diff --git a/README.md b/README.md index 0a057ba..b970439 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,13 @@ It works through Obsidian's Vault, HTTP, IndexedDB, and SecretStorage APIs. The production bundle has no Node filesystem dependency and is checked against a mobile bundle budget. +Canonical view files remain ordinary v0.3 records in this adapter. When a +collection materializes `_types/view.md` (normally referring to +`schemas/v0.3/view.schema.json`), the plugin validates their nested shared +`query` and named-view frontmatter like any other typed record. This plugin does +not execute named views or advertise the optional `view_records` feature; it +leaves execution and presentation to query-capable companion tools. + ## Collection roles ### Local collection @@ -111,10 +118,9 @@ npm run build:test enforces checked-in schema, migration-analysis, validation, and issue-render budgets. -The Connect SDK packages are vendored as exact consumer tarballs. Their source -revision and integrity hashes are recorded in -`vendor/mdbase-connect-sdk.json`; regenerate them with the Connect repository's -`package:consumer` script rather than editing the archives. +The Connect SDK and mdbase interop packages are installed from npm at exact +prerelease versions. Update `package.json` and regenerate `package-lock.json` +when advancing them. ## Compatibility diff --git a/main.js b/main.js index 3a25a8c..cd1b760 100644 --- a/main.js +++ b/main.js @@ -3,96 +3,96 @@ THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ -var $w=Object.create;var Es=Object.defineProperty;var Sw=Object.getOwnPropertyDescriptor;var Ew=Object.getOwnPropertyNames;var Aw=Object.getPrototypeOf,kw=Object.prototype.hasOwnProperty;var xw=(r,e,t)=>e in r?Es(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var E=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Pw=(r,e)=>{for(var t in e)Es(r,t,{get:e[t],enumerable:!0})},Pf=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ew(e))!kw.call(r,s)&&s!==t&&Es(r,s,{get:()=>e[s],enumerable:!(n=Sw(e,s))||n.enumerable});return r};var Zr=(r,e,t)=>(t=r!=null?$w(Aw(r)):{},Pf(e||!r||!r.__esModule?Es(t,"default",{value:r,enumerable:!0}):t,r)),Iw=r=>Pf(Es({},"__esModule",{value:!0}),r);var O=(r,e,t)=>xw(r,typeof e!="symbol"?e+"":e,t);var Ps=E(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.regexpCode=se.getEsmExportName=se.getProperty=se.safeStringify=se.stringify=se.strConcat=se.addCodeArg=se.str=se._=se.nil=se._Code=se.Name=se.IDENTIFIER=se._CodeOrName=void 0;var ks=class{};se._CodeOrName=ks;se.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var en=class extends ks{constructor(e){if(super(),!se.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};se.Name=en;var ft=class extends ks{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((t,n)=>`${t}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,n)=>(n instanceof en&&(t[n.str]=(t[n.str]||0)+1),t),{})}};se._Code=ft;se.nil=new ft("");function If(r,...e){let t=[r[0]],n=0;for(;n{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ValueScope=Xe.ValueScopeName=Xe.Scope=Xe.varKinds=Xe.UsedValueState=void 0;var Ye=Ps(),uc=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},eo;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(eo||(Xe.UsedValueState=eo={}));Xe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var to=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof Ye.Name?e:this.name(e)}name(e){return new Ye.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,n;if(!((n=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Xe.Scope=to;var ro=class extends Ye.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,Ye._)`.${new Ye.Name(t)}[${n}]`}};Xe.ValueScopeName=ro;var qw=(0,Ye._)`\n`,fc=class extends to{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?qw:Ye.nil}}get(){return this._scope}name(e){return new ro(e,this._newName(e))}value(e,t){var n;if(t.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:i}=s,o=(n=t.key)!==null&&n!==void 0?n:t.ref,a=this._values[i];if(a){let u=a.get(o);if(u)return u}else a=this._values[i]=new Map;a.set(o,s);let c=this._scope[i]||(this._scope[i]=[]),l=c.length;return c[l]=t.ref,s.setValue(t,{property:i,itemIndex:l}),s}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ye._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},t,n)}_reduceValues(e,t,n={},s){let i=Ye.nil;for(let o in e){let a=e[o];if(!a)continue;let c=n[o]=n[o]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,eo.Started);let u=t(l);if(u){let d=this.opts.es5?Xe.varKinds.var:Xe.varKinds.const;i=(0,Ye._)`${i}${d} ${l} = ${u};${this.opts._n}`}else if(u=s==null?void 0:s(l))i=(0,Ye._)`${i}${u}${this.opts._n}`;else throw new uc(l);c.set(l,eo.Completed)})}return i}};Xe.ValueScope=fc});var B=E(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.or=G.and=G.not=G.CodeGen=G.operators=G.varKinds=G.ValueScopeName=G.ValueScope=G.Scope=G.Name=G.regexpCode=G.stringify=G.getProperty=G.nil=G.strConcat=G.str=G._=void 0;var te=Ps(),At=pc(),Tr=Ps();Object.defineProperty(G,"_",{enumerable:!0,get:function(){return Tr._}});Object.defineProperty(G,"str",{enumerable:!0,get:function(){return Tr.str}});Object.defineProperty(G,"strConcat",{enumerable:!0,get:function(){return Tr.strConcat}});Object.defineProperty(G,"nil",{enumerable:!0,get:function(){return Tr.nil}});Object.defineProperty(G,"getProperty",{enumerable:!0,get:function(){return Tr.getProperty}});Object.defineProperty(G,"stringify",{enumerable:!0,get:function(){return Tr.stringify}});Object.defineProperty(G,"regexpCode",{enumerable:!0,get:function(){return Tr.regexpCode}});Object.defineProperty(G,"Name",{enumerable:!0,get:function(){return Tr.Name}});var oo=pc();Object.defineProperty(G,"Scope",{enumerable:!0,get:function(){return oo.Scope}});Object.defineProperty(G,"ValueScope",{enumerable:!0,get:function(){return oo.ValueScope}});Object.defineProperty(G,"ValueScopeName",{enumerable:!0,get:function(){return oo.ValueScopeName}});Object.defineProperty(G,"varKinds",{enumerable:!0,get:function(){return oo.varKinds}});G.operators={GT:new te._Code(">"),GTE:new te._Code(">="),LT:new te._Code("<"),LTE:new te._Code("<="),EQ:new te._Code("==="),NEQ:new te._Code("!=="),NOT:new te._Code("!"),OR:new te._Code("||"),AND:new te._Code("&&"),ADD:new te._Code("+")};var cr=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},hc=class extends cr{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?At.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=kn(this.rhs,e,t)),this}get names(){return this.rhs instanceof te._CodeOrName?this.rhs.names:{}}},no=class extends cr{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof te.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=kn(this.rhs,e,t),this}get names(){let e=this.lhs instanceof te.Name?{}:{...this.lhs.names};return io(e,this.rhs)}},mc=class extends no{constructor(e,t,n,s){super(e,n,s),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},yc=class extends cr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},gc=class extends cr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},bc=class extends cr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},wc=class extends cr{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=kn(this.code,e,t),this}get names(){return this.code instanceof te._CodeOrName?this.code.names:{}}},Is=class extends cr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,s=n.length;for(;s--;){let i=n[s];i.optimizeNames(e,t)||(jw(e,i.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>nn(e,t.names),{})}},lr=class extends Is{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},_c=class extends Is{},An=class extends lr{};An.kind="else";var tn=class r extends lr{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let n=t.optimizeNodes();t=this.else=Array.isArray(n)?new An(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(Of(e),t instanceof r?[t]:t.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,t){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,t),!!(super.optimizeNames(e,t)||this.else))return this.condition=kn(this.condition,e,t),this}get names(){let e=super.names;return io(e,this.condition),this.else&&nn(e,this.else.names),e}};tn.kind="if";var rn=class extends lr{};rn.kind="for";var vc=class extends rn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=kn(this.iteration,e,t),this}get names(){return nn(super.names,this.iteration.names)}},$c=class extends rn{constructor(e,t,n,s){super(),this.varKind=e,this.name=t,this.from=n,this.to=s}render(e){let t=e.es5?At.varKinds.var:this.varKind,{name:n,from:s,to:i}=this;return`for(${t} ${n}=${s}; ${n}<${i}; ${n}++)`+super.render(e)}get names(){let e=io(super.names,this.from);return io(e,this.to)}},so=class extends rn{constructor(e,t,n,s){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=kn(this.iterable,e,t),this}get names(){return nn(super.names,this.iterable.names)}},Ts=class extends lr{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Ts.kind="func";var Os=class extends Is{render(e){return"return "+super.render(e)}};Os.kind="return";var Sc=class extends lr{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var n,s;return super.optimizeNames(e,t),(n=this.catch)===null||n===void 0||n.optimizeNames(e,t),(s=this.finally)===null||s===void 0||s.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&nn(e,this.catch.names),this.finally&&nn(e,this.finally.names),e}},Rs=class extends lr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Rs.kind="catch";var Ms=class extends lr{render(e){return"finally"+super.render(e)}};Ms.kind="finally";var Ec=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` -`:""},this._extScope=e,this._scope=new At.Scope({parent:e}),this._nodes=[new _c]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,s){let i=this._scope.toName(t);return n!==void 0&&s&&(this._constants[i.str]=n),this._leafNode(new hc(e,i,n)),i}const(e,t,n){return this._def(At.varKinds.const,e,t,n)}let(e,t,n){return this._def(At.varKinds.let,e,t,n)}var(e,t,n){return this._def(At.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new no(e,t,n))}add(e,t){return this._leafNode(new mc(e,G.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==te.nil&&this._leafNode(new wc(e)),this}object(...e){let t=["{"];for(let[n,s]of e)t.length>1&&t.push(","),t.push(n),(n!==s||this.opts.es5)&&(t.push(":"),(0,te.addCodeArg)(t,s));return t.push("}"),new te._Code(t)}if(e,t,n){if(this._blockNode(new tn(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new tn(e))}else(){return this._elseNode(new An)}endIf(){return this._endBlockNode(tn,An)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new vc(e),t)}forRange(e,t,n,s,i=this.opts.es5?At.varKinds.var:At.varKinds.let){let o=this._scope.toName(e);return this._for(new $c(i,o,t,n),()=>s(o))}forOf(e,t,n,s=At.varKinds.const){let i=this._scope.toName(e);if(this.opts.es5){let o=t instanceof te.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,te._)`${o}.length`,a=>{this.var(i,(0,te._)`${o}[${a}]`),n(i)})}return this._for(new so("of",s,i,t),()=>n(i))}forIn(e,t,n,s=this.opts.es5?At.varKinds.var:At.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,te._)`Object.keys(${t})`,n);let i=this._scope.toName(e);return this._for(new so("in",s,i,t),()=>n(i))}endFor(){return this._endBlockNode(rn)}label(e){return this._leafNode(new yc(e))}break(e){return this._leafNode(new gc(e))}return(e){let t=new Os;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Os)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Sc;if(this._blockNode(s),this.code(e),t){let i=this.name("e");this._currNode=s.catch=new Rs(i),t(i)}return n&&(this._currNode=s.finally=new Ms,this.code(n)),this._endBlockNode(Rs,Ms)}throw(e){return this._leafNode(new bc(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=te.nil,n,s){return this._blockNode(new Ts(e,t,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Ts)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof tn))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};G.CodeGen=Ec;function nn(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function io(r,e){return e instanceof te._CodeOrName?nn(r,e.names):r}function kn(r,e,t){if(r instanceof te.Name)return n(r);if(!s(r))return r;return new te._Code(r._items.reduce((i,o)=>(o instanceof te.Name&&(o=n(o)),o instanceof te._Code?i.push(...o._items):i.push(o),i),[]));function n(i){let o=t[i.str];return o===void 0||e[i.str]!==1?i:(delete e[i.str],o)}function s(i){return i instanceof te._Code&&i._items.some(o=>o instanceof te.Name&&e[o.str]===1&&t[o.str]!==void 0)}}function jw(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function Of(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,te._)`!${Ac(r)}`}G.not=Of;var Fw=Rf(G.operators.AND);function Vw(...r){return r.reduce(Fw)}G.and=Vw;var Uw=Rf(G.operators.OR);function Hw(...r){return r.reduce(Uw)}G.or=Hw;function Rf(r){return(e,t)=>e===te.nil?t:t===te.nil?e:(0,te._)`${Ac(e)} ${r} ${Ac(t)}`}function Ac(r){return r instanceof te.Name?r:(0,te._)`(${r})`}});var Y=E(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.checkStrictMode=J.getErrorPath=J.Type=J.useFunc=J.setEvaluated=J.evaluatedPropsToName=J.mergeEvaluated=J.eachItem=J.unescapeJsonPointer=J.escapeJsonPointer=J.escapeFragment=J.unescapeFragment=J.schemaRefOrVal=J.schemaHasRulesButRef=J.schemaHasRules=J.checkUnknownRules=J.alwaysValidSchema=J.toHash=void 0;var de=B(),Bw=Ps();function zw(r){let e={};for(let t of r)e[t]=!0;return e}J.toHash=zw;function Kw(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Nf(r,e),!Lf(e,r.self.RULES.all))}J.alwaysValidSchema=Kw;function Nf(r,e=r.schema){let{opts:t,self:n}=r;if(!t.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let i in e)s[i]||jf(r,`unknown keyword: "${i}"`)}J.checkUnknownRules=Nf;function Lf(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}J.schemaHasRules=Lf;function Ww(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(t!=="$ref"&&e.all[t])return!0;return!1}J.schemaHasRulesButRef=Ww;function Gw({topSchemaRef:r,schemaPath:e},t,n,s){if(!s){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,de._)`${t}`}return(0,de._)`${r}${e}${(0,de.getProperty)(n)}`}J.schemaRefOrVal=Gw;function Jw(r){return Df(decodeURIComponent(r))}J.unescapeFragment=Jw;function Yw(r){return encodeURIComponent(xc(r))}J.escapeFragment=Yw;function xc(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}J.escapeJsonPointer=xc;function Df(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}J.unescapeJsonPointer=Df;function Xw(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}J.eachItem=Xw;function Mf({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(s,i,o,a)=>{let c=o===void 0?i:o instanceof de.Name?(i instanceof de.Name?r(s,i,o):e(s,i,o),o):i instanceof de.Name?(e(s,o,i),i):t(i,o);return a===de.Name&&!(c instanceof de.Name)?n(s,c):c}}J.mergeEvaluated={props:Mf({mergeNames:(r,e,t)=>r.if((0,de._)`${t} !== true && ${e} !== undefined`,()=>{r.if((0,de._)`${e} === true`,()=>r.assign(t,!0),()=>r.assign(t,(0,de._)`${t} || {}`).code((0,de._)`Object.assign(${t}, ${e})`))}),mergeToName:(r,e,t)=>r.if((0,de._)`${t} !== true`,()=>{e===!0?r.assign(t,!0):(r.assign(t,(0,de._)`${t} || {}`),Pc(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:qf}),items:Mf({mergeNames:(r,e,t)=>r.if((0,de._)`${t} !== true && ${e} !== undefined`,()=>r.assign(t,(0,de._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(r,e,t)=>r.if((0,de._)`${t} !== true`,()=>r.assign(t,e===!0?!0:(0,de._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(r,e)=>r===!0?!0:Math.max(r,e),resultToName:(r,e)=>r.var("items",e)})};function qf(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,de._)`{}`);return e!==void 0&&Pc(r,t,e),t}J.evaluatedPropsToName=qf;function Pc(r,e,t){Object.keys(t).forEach(n=>r.assign((0,de._)`${e}${(0,de.getProperty)(n)}`,!0))}J.setEvaluated=Pc;var Cf={};function Qw(r,e){return r.scopeValue("func",{ref:e,code:Cf[e.code]||(Cf[e.code]=new Bw._Code(e.code))})}J.useFunc=Qw;var kc;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(kc||(J.Type=kc={}));function Zw(r,e,t){if(r instanceof de.Name){let n=e===kc.Num;return t?n?(0,de._)`"[" + ${r} + "]"`:(0,de._)`"['" + ${r} + "']"`:n?(0,de._)`"/" + ${r}`:(0,de._)`"/" + ${r}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,de.getProperty)(r).toString():"/"+xc(r)}J.getErrorPath=Zw;function jf(r,e,t=r.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===!0)throw new Error(e);r.self.logger.warn(e)}}J.checkStrictMode=jf});var pt=E(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var qe=B(),e_={data:new qe.Name("data"),valCxt:new qe.Name("valCxt"),instancePath:new qe.Name("instancePath"),parentData:new qe.Name("parentData"),parentDataProperty:new qe.Name("parentDataProperty"),rootData:new qe.Name("rootData"),dynamicAnchors:new qe.Name("dynamicAnchors"),vErrors:new qe.Name("vErrors"),errors:new qe.Name("errors"),this:new qe.Name("this"),self:new qe.Name("self"),scope:new qe.Name("scope"),json:new qe.Name("json"),jsonPos:new qe.Name("jsonPos"),jsonLen:new qe.Name("jsonLen"),jsonPart:new qe.Name("jsonPart")};Ic.default=e_});var Cs=E(je=>{"use strict";Object.defineProperty(je,"__esModule",{value:!0});je.extendErrors=je.resetErrorsCount=je.reportExtraError=je.reportError=je.keyword$DataError=je.keywordError=void 0;var ne=B(),ao=Y(),Be=pt();je.keywordError={message:({keyword:r})=>(0,ne.str)`must pass "${r}" keyword validation`};je.keyword$DataError={message:({keyword:r,schemaType:e})=>e?(0,ne.str)`"${r}" keyword must be ${e} ($data)`:(0,ne.str)`"${r}" keyword is invalid ($data)`};function t_(r,e=je.keywordError,t,n){let{it:s}=r,{gen:i,compositeRule:o,allErrors:a}=s,c=Uf(r,e,t);(n!=null?n:o||a)?Ff(i,c):Vf(s,(0,ne._)`[${c}]`)}je.reportError=t_;function r_(r,e=je.keywordError,t){let{it:n}=r,{gen:s,compositeRule:i,allErrors:o}=n,a=Uf(r,e,t);Ff(s,a),i||o||Vf(n,Be.default.vErrors)}je.reportExtraError=r_;function n_(r,e){r.assign(Be.default.errors,e),r.if((0,ne._)`${Be.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,ne._)`${Be.default.vErrors}.length`,e),()=>r.assign(Be.default.vErrors,null)))}je.resetErrorsCount=n_;function s_({gen:r,keyword:e,schemaValue:t,data:n,errsCount:s,it:i}){if(s===void 0)throw new Error("ajv implementation error");let o=r.name("err");r.forRange("i",s,Be.default.errors,a=>{r.const(o,(0,ne._)`${Be.default.vErrors}[${a}]`),r.if((0,ne._)`${o}.instancePath === undefined`,()=>r.assign((0,ne._)`${o}.instancePath`,(0,ne.strConcat)(Be.default.instancePath,i.errorPath))),r.assign((0,ne._)`${o}.schemaPath`,(0,ne.str)`${i.errSchemaPath}/${e}`),i.opts.verbose&&(r.assign((0,ne._)`${o}.schema`,t),r.assign((0,ne._)`${o}.data`,n))})}je.extendErrors=s_;function Ff(r,e){let t=r.const("err",e);r.if((0,ne._)`${Be.default.vErrors} === null`,()=>r.assign(Be.default.vErrors,(0,ne._)`[${t}]`),(0,ne._)`${Be.default.vErrors}.push(${t})`),r.code((0,ne._)`${Be.default.errors}++`)}function Vf(r,e){let{gen:t,validateName:n,schemaEnv:s}=r;s.$async?t.throw((0,ne._)`new ${r.ValidationError}(${e})`):(t.assign((0,ne._)`${n}.errors`,e),t.return(!1))}var sn={keyword:new ne.Name("keyword"),schemaPath:new ne.Name("schemaPath"),params:new ne.Name("params"),propertyName:new ne.Name("propertyName"),message:new ne.Name("message"),schema:new ne.Name("schema"),parentSchema:new ne.Name("parentSchema")};function Uf(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,ne._)`{}`:i_(r,e,t)}function i_(r,e,t={}){let{gen:n,it:s}=r,i=[o_(s,t),a_(r,t)];return c_(r,e,i),n.object(...i)}function o_({errorPath:r},{instancePath:e}){let t=e?(0,ne.str)`${r}${(0,ao.getErrorPath)(e,ao.Type.Str)}`:r;return[Be.default.instancePath,(0,ne.strConcat)(Be.default.instancePath,t)]}function a_({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let s=n?e:(0,ne.str)`${e}/${r}`;return t&&(s=(0,ne.str)`${s}${(0,ao.getErrorPath)(t,ao.Type.Str)}`),[sn.schemaPath,s]}function c_(r,{params:e,message:t},n){let{keyword:s,data:i,schemaValue:o,it:a}=r,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([sn.keyword,s],[sn.params,typeof e=="function"?e(r):e||(0,ne._)`{}`]),c.messages&&n.push([sn.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([sn.schema,o],[sn.parentSchema,(0,ne._)`${u}${d}`],[Be.default.data,i]),l&&n.push([sn.propertyName,l])}});var Bf=E(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.boolOrEmptySchema=xn.topBoolOrEmptySchema=void 0;var l_=Cs(),d_=B(),u_=pt(),f_={message:"boolean schema is false"};function p_(r){let{gen:e,schema:t,validateName:n}=r;t===!1?Hf(r,!1):typeof t=="object"&&t.$async===!0?e.return(u_.default.data):(e.assign((0,d_._)`${n}.errors`,null),e.return(!0))}xn.topBoolOrEmptySchema=p_;function h_(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),Hf(r)):t.var(e,!0)}xn.boolOrEmptySchema=h_;function Hf(r,e){let{gen:t,data:n}=r,s={gen:t,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:r};(0,l_.reportError)(s,f_,void 0,e)}});var Tc=E(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.getRules=Pn.isJSONType=void 0;var m_=["string","number","integer","boolean","null","object","array"],y_=new Set(m_);function g_(r){return typeof r=="string"&&y_.has(r)}Pn.isJSONType=g_;function b_(){let r={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...r,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},r.number,r.string,r.array,r.object],post:{rules:[]},all:{},keywords:{}}}Pn.getRules=b_});var Oc=E(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.shouldUseRule=Or.shouldUseGroup=Or.schemaHasRulesForType=void 0;function w_({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&zf(r,n)}Or.schemaHasRulesForType=w_;function zf(r,e){return e.rules.some(t=>Kf(r,t))}Or.shouldUseGroup=zf;function Kf(r,e){var t;return r[e.keyword]!==void 0||((t=e.definition.implements)===null||t===void 0?void 0:t.some(n=>r[n]!==void 0))}Or.shouldUseRule=Kf});var Ns=E(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.reportTypeError=Fe.checkDataTypes=Fe.checkDataType=Fe.coerceAndCheckDataType=Fe.getJSONTypes=Fe.getSchemaTypes=Fe.DataType=void 0;var __=Tc(),v_=Oc(),$_=Cs(),K=B(),Wf=Y(),In;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(In||(Fe.DataType=In={}));function S_(r){let e=Gf(r.type);if(e.includes("null")){if(r.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&r.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');r.nullable===!0&&e.push("null")}return e}Fe.getSchemaTypes=S_;function Gf(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(__.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Fe.getJSONTypes=Gf;function E_(r,e){let{gen:t,data:n,opts:s}=r,i=A_(e,s.coerceTypes),o=e.length>0&&!(i.length===0&&e.length===1&&(0,v_.schemaHasRulesForType)(r,e[0]));if(o){let a=Mc(e,n,s.strictNumbers,In.Wrong);t.if(a,()=>{i.length?k_(r,e,i):Cc(r)})}return o}Fe.coerceAndCheckDataType=E_;var Jf=new Set(["string","number","integer","boolean","null"]);function A_(r,e){return e?r.filter(t=>Jf.has(t)||e==="array"&&t==="array"):[]}function k_(r,e,t){let{gen:n,data:s,opts:i}=r,o=n.let("dataType",(0,K._)`typeof ${s}`),a=n.let("coerced",(0,K._)`undefined`);i.coerceTypes==="array"&&n.if((0,K._)`${o} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,K._)`${s}[0]`).assign(o,(0,K._)`typeof ${s}`).if(Mc(e,s,i.strictNumbers),()=>n.assign(a,s))),n.if((0,K._)`${a} !== undefined`);for(let l of t)(Jf.has(l)||l==="array"&&i.coerceTypes==="array")&&c(l);n.else(),Cc(r),n.endIf(),n.if((0,K._)`${a} !== undefined`,()=>{n.assign(s,a),x_(r,a)});function c(l){switch(l){case"string":n.elseIf((0,K._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,K._)`"" + ${s}`).elseIf((0,K._)`${s} === null`).assign(a,(0,K._)`""`);return;case"number":n.elseIf((0,K._)`${o} == "boolean" || ${s} === null - || (${o} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,K._)`+${s}`);return;case"integer":n.elseIf((0,K._)`${o} === "boolean" || ${s} === null - || (${o} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,K._)`+${s}`);return;case"boolean":n.elseIf((0,K._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,K._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":n.elseIf((0,K._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(a,null);return;case"array":n.elseIf((0,K._)`${o} === "string" || ${o} === "number" - || ${o} === "boolean" || ${s} === null`).assign(a,(0,K._)`[${s}]`)}}}function x_({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,K._)`${e} !== undefined`,()=>r.assign((0,K._)`${e}[${t}]`,n))}function Rc(r,e,t,n=In.Correct){let s=n===In.Correct?K.operators.EQ:K.operators.NEQ,i;switch(r){case"null":return(0,K._)`${e} ${s} null`;case"array":i=(0,K._)`Array.isArray(${e})`;break;case"object":i=(0,K._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":i=o((0,K._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":i=o();break;default:return(0,K._)`typeof ${e} ${s} ${r}`}return n===In.Correct?i:(0,K.not)(i);function o(a=K.nil){return(0,K.and)((0,K._)`typeof ${e} == "number"`,a,t?(0,K._)`isFinite(${e})`:K.nil)}}Fe.checkDataType=Rc;function Mc(r,e,t,n){if(r.length===1)return Rc(r[0],e,t,n);let s,i=(0,Wf.toHash)(r);if(i.array&&i.object){let o=(0,K._)`typeof ${e} != "object"`;s=i.null?o:(0,K._)`!${e} || ${o}`,delete i.null,delete i.array,delete i.object}else s=K.nil;i.number&&delete i.integer;for(let o in i)s=(0,K.and)(s,Rc(o,e,t,n));return s}Fe.checkDataTypes=Mc;var P_={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,K._)`{type: ${r}}`:(0,K._)`{type: ${e}}`};function Cc(r){let e=I_(r);(0,$_.reportError)(e,P_)}Fe.reportTypeError=Cc;function I_(r){let{gen:e,data:t,schema:n}=r,s=(0,Wf.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:r}}});var Xf=E(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.assignDefaults=void 0;var Tn=B(),T_=Y();function O_(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let s in t)Yf(r,s,t[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,i)=>Yf(r,i,s.default))}co.assignDefaults=O_;function Yf(r,e,t){let{gen:n,compositeRule:s,data:i,opts:o}=r;if(t===void 0)return;let a=(0,Tn._)`${i}${(0,Tn.getProperty)(e)}`;if(s){(0,T_.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,Tn._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,Tn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Tn._)`${a} = ${(0,Tn.stringify)(t)}`)}});var ht=E(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.validateUnion=ce.validateArray=ce.usePattern=ce.callValidateCode=ce.schemaProperties=ce.allSchemaProperties=ce.noPropertyInData=ce.propertyInData=ce.isOwnProperty=ce.hasPropFunc=ce.reportMissingProp=ce.checkMissingProp=ce.checkReportMissingProp=void 0;var me=B(),Nc=Y(),Rr=pt(),R_=Y();function M_(r,e){let{gen:t,data:n,it:s}=r;t.if(Dc(t,n,e,s.opts.ownProperties),()=>{r.setParams({missingProperty:(0,me._)`${e}`},!0),r.error()})}ce.checkReportMissingProp=M_;function C_({gen:r,data:e,it:{opts:t}},n,s){return(0,me.or)(...n.map(i=>(0,me.and)(Dc(r,e,i,t.ownProperties),(0,me._)`${s} = ${i}`)))}ce.checkMissingProp=C_;function N_(r,e){r.setParams({missingProperty:e},!0),r.error()}ce.reportMissingProp=N_;function Qf(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,me._)`Object.prototype.hasOwnProperty`})}ce.hasPropFunc=Qf;function Lc(r,e,t){return(0,me._)`${Qf(r)}.call(${e}, ${t})`}ce.isOwnProperty=Lc;function L_(r,e,t,n){let s=(0,me._)`${e}${(0,me.getProperty)(t)} !== undefined`;return n?(0,me._)`${s} && ${Lc(r,e,t)}`:s}ce.propertyInData=L_;function Dc(r,e,t,n){let s=(0,me._)`${e}${(0,me.getProperty)(t)} === undefined`;return n?(0,me.or)(s,(0,me.not)(Lc(r,e,t))):s}ce.noPropertyInData=Dc;function Zf(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}ce.allSchemaProperties=Zf;function D_(r,e){return Zf(e).filter(t=>!(0,Nc.alwaysValidSchema)(r,e[t]))}ce.schemaProperties=D_;function q_({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:s,errorPath:i},it:o},a,c,l){let u=l?(0,me._)`${r}, ${e}, ${n}${s}`:e,d=[[Rr.default.instancePath,(0,me.strConcat)(Rr.default.instancePath,i)],[Rr.default.parentData,o.parentData],[Rr.default.parentDataProperty,o.parentDataProperty],[Rr.default.rootData,Rr.default.rootData]];o.opts.dynamicRef&&d.push([Rr.default.dynamicAnchors,Rr.default.dynamicAnchors]);let f=(0,me._)`${u}, ${t.object(...d)}`;return c!==me.nil?(0,me._)`${a}.call(${c}, ${f})`:(0,me._)`${a}(${f})`}ce.callValidateCode=q_;var j_=(0,me._)`new RegExp`;function F_({gen:r,it:{opts:e}},t){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,i=s(t,n);return r.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,me._)`${s.code==="new RegExp"?j_:(0,R_.useFunc)(r,s)}(${t}, ${n})`})}ce.usePattern=F_;function V_(r){let{gen:e,data:t,keyword:n,it:s}=r,i=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return o(()=>e.assign(a,!1)),a}return e.var(i,!0),o(()=>e.break()),i;function o(a){let c=e.const("len",(0,me._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:Nc.Type.Num},i),e.if((0,me.not)(i),a)})}}ce.validateArray=V_;function U_(r){let{gen:e,schema:t,keyword:n,it:s}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(c=>(0,Nc.alwaysValidSchema)(s,c))&&!s.opts.unevaluated)return;let o=e.let("valid",!1),a=e.name("_valid");e.block(()=>t.forEach((c,l)=>{let u=r.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(o,(0,me._)`${o} || ${a}`),r.mergeValidEvaluated(u,a)||e.if((0,me.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}ce.validateUnion=U_});var rp=E(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.validateKeywordUsage=Kt.validSchemaType=Kt.funcKeywordCode=Kt.macroKeywordCode=void 0;var ze=B(),on=pt(),H_=ht(),B_=Cs();function z_(r,e){let{gen:t,keyword:n,schema:s,parentSchema:i,it:o}=r,a=e.macro.call(o.self,s,i,o),c=tp(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:ze.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}Kt.macroKeywordCode=z_;function K_(r,e){var t;let{gen:n,keyword:s,schema:i,parentSchema:o,$data:a,it:c}=r;G_(c,e);let l=!a&&e.compile?e.compile.call(c.self,i,o,c):e.validate,u=tp(n,s,l),d=n.let("valid");r.block$data(d,f),r.ok((t=e.valid)!==null&&t!==void 0?t:d);function f(){if(e.errors===!1)h(),e.modifying&&ep(r),y(()=>r.error());else{let b=e.async?p():m();e.modifying&&ep(r),y(()=>W_(r,b))}}function p(){let b=n.let("ruleErrs",null);return n.try(()=>h((0,ze._)`await `),g=>n.assign(d,!1).if((0,ze._)`${g} instanceof ${c.ValidationError}`,()=>n.assign(b,(0,ze._)`${g}.errors`),()=>n.throw(g))),b}function m(){let b=(0,ze._)`${u}.errors`;return n.assign(b,null),h(ze.nil),b}function h(b=e.async?(0,ze._)`await `:ze.nil){let g=c.opts.passContext?on.default.this:on.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,ze._)`${b}${(0,H_.callValidateCode)(r,u,g,_)}`,e.modifying)}function y(b){var g;n.if((0,ze.not)((g=e.valid)!==null&&g!==void 0?g:d),b)}}Kt.funcKeywordCode=K_;function ep(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,ze._)`${n.parentData}[${n.parentDataProperty}]`))}function W_(r,e){let{gen:t}=r;t.if((0,ze._)`Array.isArray(${e})`,()=>{t.assign(on.default.vErrors,(0,ze._)`${on.default.vErrors} === null ? ${e} : ${on.default.vErrors}.concat(${e})`).assign(on.default.errors,(0,ze._)`${on.default.vErrors}.length`),(0,B_.extendErrors)(r)},()=>r.error())}function G_({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function tp(r,e,t){if(t===void 0)throw new Error(`keyword "${e}" failed to compile`);return r.scopeValue("keyword",typeof t=="function"?{ref:t}:{ref:t,code:(0,ze.stringify)(t)})}function J_(r,e,t=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(r):n==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==n||t&&typeof r=="undefined")}Kt.validSchemaType=J_;function Y_({schema:r,opts:e,self:t,errSchemaPath:n},s,i){if(Array.isArray(s.keyword)?!s.keyword.includes(i):s.keyword!==i)throw new Error("ajv implementation error");let o=s.dependencies;if(o!=null&&o.some(a=>!Object.prototype.hasOwnProperty.call(r,a)))throw new Error(`parent schema must have dependencies of ${i}: ${o.join(",")}`);if(s.validateSchema&&!s.validateSchema(r[i])){let c=`keyword "${i}" value is invalid at path "${n}": `+t.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(c);else throw new Error(c)}}Kt.validateKeywordUsage=Y_});var sp=E(Mr=>{"use strict";Object.defineProperty(Mr,"__esModule",{value:!0});Mr.extendSubschemaMode=Mr.extendSubschemaData=Mr.getSubschema=void 0;var Wt=B(),np=Y();function X_(r,{keyword:e,schemaProp:t,schema:n,schemaPath:s,errSchemaPath:i,topSchemaRef:o}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=r.schema[e];return t===void 0?{schema:a,schemaPath:(0,Wt._)`${r.schemaPath}${(0,Wt.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,Wt._)`${r.schemaPath}${(0,Wt.getProperty)(e)}${(0,Wt.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,np.escapeFragment)(t)}`}}if(n!==void 0){if(s===void 0||i===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:s,topSchemaRef:o,errSchemaPath:i}}throw new Error('either "keyword" or "schema" must be passed')}Mr.getSubschema=X_;function Q_(r,e,{dataProp:t,dataPropType:n,data:s,dataTypes:i,propertyName:o}){if(s!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(t!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,f=a.let("data",(0,Wt._)`${e.data}${(0,Wt.getProperty)(t)}`,!0);c(f),r.errorPath=(0,Wt.str)`${l}${(0,np.getErrorPath)(t,n,d.jsPropertySyntax)}`,r.parentDataProperty=(0,Wt._)`${t}`,r.dataPathArr=[...u,r.parentDataProperty]}if(s!==void 0){let l=s instanceof Wt.Name?s:a.let("data",s,!0);c(l),o!==void 0&&(r.propertyName=o)}i&&(r.dataTypes=i);function c(l){r.data=l,r.dataLevel=e.dataLevel+1,r.dataTypes=[],e.definedProperties=new Set,r.parentData=e.data,r.dataNames=[...e.dataNames,l]}}Mr.extendSubschemaData=Q_;function Z_(r,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:n,createErrors:s,allErrors:i}){n!==void 0&&(r.compositeRule=n),s!==void 0&&(r.createErrors=s),i!==void 0&&(r.allErrors=i),r.jtdDiscriminator=e,r.jtdMetadata=t}Mr.extendSubschemaMode=Z_});var qc=E((RR,ip)=>{"use strict";ip.exports=function r(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var n,s,i;if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(s=n;s--!==0;)if(!r(e[s],t[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(t,i[s]))return!1;for(s=n;s--!==0;){var o=i[s];if(!r(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}});var ap=E((MR,op)=>{"use strict";var Cr=op.exports=function(r,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var n=typeof t=="function"?t:t.pre||function(){},s=t.post||function(){};lo(e,n,s,r,"",r)};Cr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Cr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Cr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Cr.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 lo(r,e,t,n,s,i,o,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,i,o,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in Cr.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.getSchemaRefs=Qe.resolveUrl=Qe.normalizeId=Qe._getFullPath=Qe.getFullPath=Qe.inlineRef=void 0;var tv=Y(),rv=qc(),nv=ap(),sv=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function iv(r,e=!0){return typeof r=="boolean"?!0:e===!0?!jc(r):e?cp(r)<=e:!1}Qe.inlineRef=iv;var ov=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function jc(r){for(let e in r){if(ov.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(jc)||typeof t=="object"&&jc(t))return!0}return!1}function cp(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!sv.has(t)&&(typeof r[t]=="object"&&(0,tv.eachItem)(r[t],n=>e+=cp(n)),e===1/0))return 1/0}return e}function lp(r,e="",t){t!==!1&&(e=On(e));let n=r.parse(e);return dp(r,n)}Qe.getFullPath=lp;function dp(r,e){return r.serialize(e).split("#")[0]+"#"}Qe._getFullPath=dp;var av=/#\/?$/;function On(r){return r?r.replace(av,""):""}Qe.normalizeId=On;function cv(r,e,t){return t=On(t),r.resolve(e,t)}Qe.resolveUrl=cv;var lv=/^[a-z_][-a-z0-9._]*$/i;function dv(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,s=On(r[t]||e),i={"":s},o=lp(n,s,!1),a={},c=new Set;return nv(r,{allKeys:!0},(d,f,p,m)=>{if(m===void 0)return;let h=o+f,y=i[m];typeof d[t]=="string"&&(y=b.call(this,d[t])),g.call(this,d.$anchor),g.call(this,d.$dynamicAnchor),i[f]=y;function b(_){let I=this.opts.uriResolver.resolve;if(_=On(y?I(y,_):_),c.has(_))throw u(_);c.add(_);let v=this.refs[_];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?l(d,v.schema,_):_!==On(h)&&(_[0]==="#"?(l(d,a[_],_),a[_]=d):this.refs[_]=h),_}function g(_){if(typeof _=="string"){if(!lv.test(_))throw new Error(`invalid anchor "${_}"`);b.call(this,`#${_}`)}}}),a;function l(d,f,p){if(f!==void 0&&!rv(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Qe.getSchemaRefs=dv});var Rn=E(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.getData=Nr.KeywordCxt=Nr.validateFunctionCode=void 0;var mp=Bf(),up=Ns(),Vc=Oc(),uo=Ns(),uv=Xf(),qs=rp(),Fc=sp(),V=B(),U=pt(),fv=Ls(),dr=Y(),Ds=Cs();function pv(r){if(bp(r)&&(wp(r),gp(r))){yv(r);return}yp(r,()=>(0,mp.topBoolOrEmptySchema)(r))}Nr.validateFunctionCode=pv;function yp({gen:r,validateName:e,schema:t,schemaEnv:n,opts:s},i){s.code.es5?r.func(e,(0,V._)`${U.default.data}, ${U.default.valCxt}`,n.$async,()=>{r.code((0,V._)`"use strict"; ${fp(t,s)}`),mv(r,s),r.code(i)}):r.func(e,(0,V._)`${U.default.data}, ${hv(s)}`,n.$async,()=>r.code(fp(t,s)).code(i))}function hv(r){return(0,V._)`{${U.default.instancePath}="", ${U.default.parentData}, ${U.default.parentDataProperty}, ${U.default.rootData}=${U.default.data}${r.dynamicRef?(0,V._)`, ${U.default.dynamicAnchors}={}`:V.nil}}={}`}function mv(r,e){r.if(U.default.valCxt,()=>{r.var(U.default.instancePath,(0,V._)`${U.default.valCxt}.${U.default.instancePath}`),r.var(U.default.parentData,(0,V._)`${U.default.valCxt}.${U.default.parentData}`),r.var(U.default.parentDataProperty,(0,V._)`${U.default.valCxt}.${U.default.parentDataProperty}`),r.var(U.default.rootData,(0,V._)`${U.default.valCxt}.${U.default.rootData}`),e.dynamicRef&&r.var(U.default.dynamicAnchors,(0,V._)`${U.default.valCxt}.${U.default.dynamicAnchors}`)},()=>{r.var(U.default.instancePath,(0,V._)`""`),r.var(U.default.parentData,(0,V._)`undefined`),r.var(U.default.parentDataProperty,(0,V._)`undefined`),r.var(U.default.rootData,U.default.data),e.dynamicRef&&r.var(U.default.dynamicAnchors,(0,V._)`{}`)})}function yv(r){let{schema:e,opts:t,gen:n}=r;yp(r,()=>{t.$comment&&e.$comment&&vp(r),vv(r),n.let(U.default.vErrors,null),n.let(U.default.errors,0),t.unevaluated&&gv(r),_p(r),Ev(r)})}function gv(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,V._)`${t}.evaluated`),e.if((0,V._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,V._)`${r.evaluated}.props`,(0,V._)`undefined`)),e.if((0,V._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,V._)`${r.evaluated}.items`,(0,V._)`undefined`))}function fp(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,V._)`/*# sourceURL=${t} */`:V.nil}function bv(r,e){if(bp(r)&&(wp(r),gp(r))){wv(r,e);return}(0,mp.boolOrEmptySchema)(r,e)}function gp({schema:r,self:e}){if(typeof r=="boolean")return!r;for(let t in r)if(e.RULES.all[t])return!0;return!1}function bp(r){return typeof r.schema!="boolean"}function wv(r,e){let{schema:t,gen:n,opts:s}=r;s.$comment&&t.$comment&&vp(r),$v(r),Sv(r);let i=n.const("_errs",U.default.errors);_p(r,i),n.var(e,(0,V._)`${i} === ${U.default.errors}`)}function wp(r){(0,dr.checkUnknownRules)(r),_v(r)}function _p(r,e){if(r.opts.jtd)return pp(r,[],!1,e);let t=(0,up.getSchemaTypes)(r.schema),n=(0,up.coerceAndCheckDataType)(r,t);pp(r,t,!n,e)}function _v(r){let{schema:e,errSchemaPath:t,opts:n,self:s}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,dr.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function vv(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,dr.checkStrictMode)(r,"default is ignored in the schema root")}function $v(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,fv.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function Sv(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function vp({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:s}){let i=t.$comment;if(s.$comment===!0)r.code((0,V._)`${U.default.self}.logger.log(${i})`);else if(typeof s.$comment=="function"){let o=(0,V.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,V._)`${U.default.self}.opts.$comment(${i}, ${o}, ${a}.schema)`)}}function Ev(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:s,opts:i}=r;t.$async?e.if((0,V._)`${U.default.errors} === 0`,()=>e.return(U.default.data),()=>e.throw((0,V._)`new ${s}(${U.default.vErrors})`)):(e.assign((0,V._)`${n}.errors`,U.default.vErrors),i.unevaluated&&Av(r),e.return((0,V._)`${U.default.errors} === 0`))}function Av({gen:r,evaluated:e,props:t,items:n}){t instanceof V.Name&&r.assign((0,V._)`${e}.props`,t),n instanceof V.Name&&r.assign((0,V._)`${e}.items`,n)}function pp(r,e,t,n){let{gen:s,schema:i,data:o,allErrors:a,opts:c,self:l}=r,{RULES:u}=l;if(i.$ref&&(c.ignoreKeywordsWithRef||!(0,dr.schemaHasRulesButRef)(i,u))){s.block(()=>Sp(r,"$ref",u.all.$ref.definition));return}c.jtd||kv(r,e),s.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,Vc.shouldUseGroup)(i,f)&&(f.type?(s.if((0,uo.checkDataType)(f.type,o,c.strictNumbers)),hp(r,f),e.length===1&&e[0]===f.type&&t&&(s.else(),(0,uo.reportTypeError)(r)),s.endIf()):hp(r,f),a||s.if((0,V._)`${U.default.errors} === ${n||0}`))}}function hp(r,e){let{gen:t,schema:n,opts:{useDefaults:s}}=r;s&&(0,uv.assignDefaults)(r,e.type),t.block(()=>{for(let i of e.rules)(0,Vc.shouldUseRule)(n,i)&&Sp(r,i.keyword,i.definition,e.type)})}function kv(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(xv(r,e),r.opts.allowUnionTypes||Pv(r,e),Iv(r,r.dataTypes))}function xv(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{$p(r.dataTypes,t)||Uc(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),Ov(r,e)}}function Pv(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Uc(r,"use allowUnionTypes to allow union type keyword")}function Iv(r,e){let t=r.self.RULES.all;for(let n in t){let s=t[n];if(typeof s=="object"&&(0,Vc.shouldUseRule)(r.schema,s)){let{type:i}=s.definition;i.length&&!i.some(o=>Tv(e,o))&&Uc(r,`missing type "${i.join(",")}" for keyword "${n}"`)}}}function Tv(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function $p(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function Ov(r,e){let t=[];for(let n of r.dataTypes)$p(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function Uc(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,dr.checkStrictMode)(r,e,r.opts.strictTypes)}var fo=class{constructor(e,t,n){if((0,qs.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,dr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",Ep(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,qs.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const("_errs",U.default.errors))}result(e,t,n){this.failResult((0,V.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,V.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,V._)`${t} !== undefined && (${(0,V.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?Ds.reportExtraError:Ds.reportError)(this,this.def.error,t)}$dataError(){(0,Ds.reportError)(this,this.def.$dataError||Ds.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ds.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=V.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=V.nil,t=V.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:i,def:o}=this;n.if((0,V.or)((0,V._)`${s} === undefined`,t)),e!==V.nil&&n.assign(e,!0),(i.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==V.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:s,it:i}=this;return(0,V.or)(o(),a());function o(){if(n.length){if(!(t instanceof V.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,V._)`${(0,uo.checkDataTypes)(c,t,i.opts.strictNumbers,uo.DataType.Wrong)}`}return V.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,V._)`!${c}(${t})`}return V.nil}}subschema(e,t){let n=(0,Fc.getSubschema)(this.it,e);(0,Fc.extendSubschemaData)(n,this.it,e),(0,Fc.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return bv(s,t),s}mergeEvaluated(e,t){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=dr.mergeEvaluated.props(s,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=dr.mergeEvaluated.items(s,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(t,()=>this.mergeEvaluated(e,V.Name)),!0}};Nr.KeywordCxt=fo;function Sp(r,e,t,n){let s=new fo(r,t,e);"code"in t?t.code(s,n):s.$data&&t.validate?(0,qs.funcKeywordCode)(s,t):"macro"in t?(0,qs.macroKeywordCode)(s,t):(t.compile||t.validate)&&(0,qs.funcKeywordCode)(s,t)}var Rv=/^\/(?:[^~]|~0|~1)*$/,Mv=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Ep(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let s,i;if(r==="")return U.default.rootData;if(r[0]==="/"){if(!Rv.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);s=r,i=U.default.rootData}else{let l=Mv.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let u=+l[1];if(s=l[2],s==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(i=t[e-u],!s)return i}let o=i,a=s.split("/");for(let l of a)l&&(i=(0,V._)`${i}${(0,V.getProperty)((0,dr.unescapeJsonPointer)(l))}`,o=(0,V._)`${o} && ${i}`);return o;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Nr.getData=Ep});var js=E(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var Hc=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Bc.default=Hc});var Mn=E(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var zc=Ls(),Kc=class extends Error{constructor(e,t,n,s){super(s||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,zc.resolveUrl)(e,t,n),this.missingSchema=(0,zc.normalizeId)((0,zc.getFullPath)(e,this.missingRef))}};Wc.default=Kc});var Fs=E(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.resolveSchema=mt.getCompilingSchema=mt.resolveRef=mt.compileSchema=mt.SchemaEnv=void 0;var kt=B(),Cv=js(),an=pt(),xt=Ls(),Ap=Y(),Nv=Rn(),Cn=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,xt.normalizeId)(n==null?void 0:n[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n==null?void 0:n.$async,this.refs={}}};mt.SchemaEnv=Cn;function Jc(r){let e=kp.call(this,r);if(e)return e;let t=(0,xt.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:i}=this.opts,o=new kt.CodeGen(this.scope,{es5:n,lines:s,ownProperties:i}),a;r.$async&&(a=o.scopeValue("Error",{ref:Cv.default,code:(0,kt._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");r.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:an.default.data,parentData:an.default.parentData,parentDataProperty:an.default.parentDataProperty,dataNames:[an.default.data],dataPathArr:[kt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,kt.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:kt.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,kt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(r),(0,Nv.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let d=o.toString();u=`${o.scopeRefs(an.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,r));let p=new Function(`${an.default.self}`,`${an.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=r.schema,p.schemaEnv=r,r.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:o._values}),this.opts.unevaluated){let{props:m,items:h}=l;p.evaluated={props:m instanceof kt.Name?void 0:m,items:h instanceof kt.Name?void 0:h,dynamicProps:m instanceof kt.Name,dynamicItems:h instanceof kt.Name},p.source&&(p.source.evaluated=(0,kt.stringify)(p.evaluated))}return r.validate=p,r}catch(d){throw delete r.validate,delete r.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(r)}}mt.compileSchema=Jc;function Lv(r,e,t){var n;t=(0,xt.resolveUrl)(this.opts.uriResolver,e,t);let s=r.refs[t];if(s)return s;let i=jv.call(this,r,t);if(i===void 0){let o=(n=r.localRefs)===null||n===void 0?void 0:n[t],{schemaId:a}=this.opts;o&&(i=new Cn({schema:o,schemaId:a,root:r,baseId:e}))}if(i!==void 0)return r.refs[t]=Dv.call(this,i)}mt.resolveRef=Lv;function Dv(r){return(0,xt.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:Jc.call(this,r)}function kp(r){for(let e of this._compilations)if(qv(e,r))return e}mt.getCompilingSchema=kp;function qv(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function jv(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||po.call(this,r,e)}function po(r,e){let t=this.opts.uriResolver.parse(e),n=(0,xt._getFullPath)(this.opts.uriResolver,t),s=(0,xt.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===s)return Gc.call(this,t,r);let i=(0,xt.normalizeId)(n),o=this.refs[i]||this.schemas[i];if(typeof o=="string"){let a=po.call(this,r,o);return typeof(a==null?void 0:a.schema)!="object"?void 0:Gc.call(this,t,a)}if(typeof(o==null?void 0:o.schema)=="object"){if(o.validate||Jc.call(this,o),i===(0,xt.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(s=(0,xt.resolveUrl)(this.opts.uriResolver,s,l)),new Cn({schema:a,schemaId:c,root:r,baseId:s})}return Gc.call(this,t,o)}}mt.resolveSchema=po;var Fv=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Gc(r,{baseId:e,schema:t,root:n}){var s;if(((s=r.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of r.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let c=t[(0,Ap.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!Fv.has(a)&&l&&(e=(0,xt.resolveUrl)(this.opts.uriResolver,e,l))}let i;if(typeof t!="boolean"&&t.$ref&&!(0,Ap.schemaHasRulesButRef)(t,this.RULES)){let a=(0,xt.resolveUrl)(this.opts.uriResolver,e,t.$ref);i=po.call(this,n,a)}let{schemaId:o}=this.opts;if(i=i||new Cn({schema:t,schemaId:o,root:n,baseId:e}),i.schema!==i.root.schema)return i}});var xp=E((jR,Vv)=>{Vv.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 Qc=E((FR,Mp)=>{"use strict";var Uv=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ip=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),Yc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Tp=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Hv=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Xc(r){let e="",t=0,n=0;for(n=0;n=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[n];break}for(n+=1;n=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[n]}return e}var Bv=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Pp(r){return r.length=0,!0}function zv(r,e,t){if(r.length){let n=Xc(r);if(n!=="")e.push(n);else return t.error=!0,!1;r.length=0}return!0}function Kv(r){let e=0,t={error:!1,address:"",zone:""},n=[],s=[],i=!1,o=!1,a=zv;for(let c=0;c7){t.error=!0;break}c>0&&r[c-1]===":"&&(i=!0),n.push(":");continue}else if(l==="%"){if(!a(s,n,t))break;a=Pp}else{s.push(l);continue}}return s.length&&(a===Pp?t.zone=s.join(""):o?n.push(s.join("")):n.push(Xc(s))),t.address=n.join(""),t}function Op(r){if(Wv(r,":")<2)return{host:r,isIPV6:!1};let e=Kv(r);if(e.error)return{host:r,isIPV6:!1};{let t=e.address,n=e.address;return e.zone&&(t+="%"+e.zone,n+="%25"+e.zone),{host:t,isIPV6:!0,escapedHost:n}}}function Wv(r,e){let t=0;for(let n=0;nJv[n])}function Qv(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n{"use strict";var{isUUID:r$}=Qc(),n$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,s$=["http","https","ws","wss","urn","urn:uuid"];function i$(r){return s$.indexOf(r)!==-1}function Zc(r){return r.secure===!0?!0:r.secure===!1?!1:r.scheme?r.scheme.length===3&&(r.scheme[0]==="w"||r.scheme[0]==="W")&&(r.scheme[1]==="s"||r.scheme[1]==="S")&&(r.scheme[2]==="s"||r.scheme[2]==="S"):!1}function Cp(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function Np(r){let e=String(r.scheme).toLowerCase()==="https";return(r.port===(e?443:80)||r.port==="")&&(r.port=void 0),r.path||(r.path="/"),r}function o$(r){return r.secure=Zc(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function a$(r){if((r.port===(Zc(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let[e,t]=r.resourceName.split("?");r.path=e&&e!=="/"?e:void 0,r.query=t,r.resourceName=void 0}return r.fragment=void 0,r}function c$(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(n$);if(t){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let s=`${n}:${e.nid||r.nid}`,i=el(s);r.path=void 0,i&&(r=i.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function l$(r,e){if(r.nid===void 0)throw new Error("URN without nid cannot be serialized");let t=e.scheme||r.scheme||"urn",n=r.nid.toLowerCase(),s=`${t}:${e.nid||n}`,i=el(s);i&&(r=i.serialize(r,e));let o=r,a=r.nss;return o.path=`${n||e.nid}:${a}`,e.skipEscape=!0,o}function d$(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!r$(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function u$(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var Lp={scheme:"http",domainHost:!0,parse:Cp,serialize:Np},f$={scheme:"https",domainHost:Lp.domainHost,parse:Cp,serialize:Np},ho={scheme:"ws",domainHost:!0,parse:o$,serialize:a$},p$={scheme:"wss",domainHost:ho.domainHost,parse:ho.parse,serialize:ho.serialize},h$={scheme:"urn",parse:c$,serialize:l$,skipNormalize:!0},m$={scheme:"urn:uuid",parse:d$,serialize:u$,skipNormalize:!0},mo={http:Lp,https:f$,ws:ho,wss:p$,urn:h$,"urn:uuid":m$};Object.setPrototypeOf(mo,null);function el(r){return r&&(mo[r]||mo[r.toLowerCase()])||void 0}Dp.exports={wsIsSecure:Zc,SCHEMES:mo,isValidSchemeName:i$,getSchemeHandler:el}});var Bp=E((UR,yo)=>{"use strict";var{normalizeIPv6:y$,removeDotSegments:Vs,recomposeAuthority:g$,normalizePercentEncoding:b$,normalizePathEncoding:w$,escapePreservingEscapes:_$,reescapeHostDelimiters:v$,isIPv4:$$,nonSimpleDomain:S$}=Qc(),{SCHEMES:E$,getSchemeHandler:Fp}=qp();function A$(r,e){return typeof r=="string"?r=O$(r,e):typeof r=="object"&&(r=Nn(cn(r,e),e)),r}function k$(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},s=Vp(Nn(r,n),Nn(e,n),n,!0);return n.skipEscape=!0,cn(s,n)}function Vp(r,e,t,n){let s={};return n||(r=Nn(cn(r,t),t),e=Nn(cn(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Vs(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=Vs(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=Vs(e.path):((r.userinfo!==void 0||r.host!==void 0||r.port!==void 0)&&!r.path?s.path="/"+e.path:r.path?s.path=r.path.slice(0,r.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=Vs(s.path)),s.query=e.query):(s.path=r.path,e.query!==void 0?s.query=e.query:s.query=r.query),s.userinfo=r.userinfo,s.host=r.host,s.port=r.port),s.scheme=r.scheme),s.fragment=e.fragment,s}function x$(r,e,t){let n=jp(r,t),s=jp(e,t);return n!==void 0&&s!==void 0&&n.toLowerCase()===s.toLowerCase()}function cn(r,e){let t={host:r.host,scheme:r.scheme,userinfo:r.userinfo,port:r.port,path:r.path,query:r.query,nid:r.nid,nss:r.nss,uuid:r.uuid,fragment:r.fragment,reference:r.reference,resourceName:r.resourceName,secure:r.secure,error:""},n=Object.assign({},e),s=[],i=Fp(n.scheme||t.scheme);i&&i.serialize&&i.serialize(t,n),t.path!==void 0&&(n.skipEscape?t.path=b$(t.path):(t.path=_$(t.path),t.scheme!==void 0&&(t.path=t.path.split("%3A").join(":")))),n.reference!=="suffix"&&t.scheme&&s.push(t.scheme,":");let o=g$(t);if(o!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(o),t.path&&t.path[0]!=="/"&&s.push("/")),t.path!==void 0){let a=t.path;!n.absolutePath&&(!i||!i.absolutePath)&&(a=Vs(a)),o===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),s.push(a)}return t.query!==void 0&&s.push("?",t.query),t.fragment!==void 0&&s.push("#",t.fragment),s.join("")}var P$=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,I$=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function T$(r,e){if(e[2]!==void 0&&r.path&&r.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof r.port=="number"&&(r.port<0||r.port>65535))return"URI port is malformed."}function Up(r,e){let t=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1,i=!1;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let o=r.match(I$);o!==null&&o[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",s=!0);let a=r.match(P$);if(a){n.scheme=a[1],n.userinfo=a[3],n.host=a[4],n.port=parseInt(a[5],10),n.path=a[6]||"",n.query=a[7],n.fragment=a[8],isNaN(n.port)&&(n.port=a[5]);let c=T$(n,a);if(c!==void 0&&(n.error=n.error||c,s=!0),n.host)if($$(n.host)===!1){let d=y$(n.host);n.host=d.host.toLowerCase(),i=d.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",t.reference&&t.reference!=="suffix"&&t.reference!==n.reference&&(n.error=n.error||"URI is not a "+t.reference+" reference.");let l=Fp(t.scheme||n.scheme);if(!t.unicodeSupport&&(!l||!l.unicodeSupport)&&n.host&&(t.domainHost||l&&l.domainHost)&&i===!1&&S$(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(u){n.error=n.error||"Host's domain name can not be converted to ASCII: "+u}if((!l||l&&!l.skipNormalize)&&(r.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=v$(unescape(n.host),i))),n.path&&(n.path=w$(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch(u){n.error=n.error||"URI malformed"}l&&l.parse&&l.parse(n,t)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:s}}function Nn(r,e){return Up(r,e).parsed}function O$(r,e){return Hp(r,e).normalized}function Hp(r,e){let{parsed:t,malformedAuthorityOrPort:n}=Up(r,e);return{normalized:n?r:cn(t,e),malformedAuthorityOrPort:n}}function jp(r,e){if(typeof r=="string"){let{normalized:t,malformedAuthorityOrPort:n}=Hp(r,e);return n?void 0:t}if(typeof r=="object")return cn(r,e)}var tl={SCHEMES:E$,normalize:A$,resolve:k$,resolveComponent:Vp,equal:x$,serialize:cn,parse:Nn};yo.exports=tl;yo.exports.default=tl;yo.exports.fastUri=tl});var Kp=E(rl=>{"use strict";Object.defineProperty(rl,"__esModule",{value:!0});var zp=Bp();zp.code='require("ajv/dist/runtime/uri").default';rl.default=zp});var il=E(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.CodeGen=Ce.Name=Ce.nil=Ce.stringify=Ce.str=Ce._=Ce.KeywordCxt=void 0;var R$=Rn();Object.defineProperty(Ce,"KeywordCxt",{enumerable:!0,get:function(){return R$.KeywordCxt}});var Ln=B();Object.defineProperty(Ce,"_",{enumerable:!0,get:function(){return Ln._}});Object.defineProperty(Ce,"str",{enumerable:!0,get:function(){return Ln.str}});Object.defineProperty(Ce,"stringify",{enumerable:!0,get:function(){return Ln.stringify}});Object.defineProperty(Ce,"nil",{enumerable:!0,get:function(){return Ln.nil}});Object.defineProperty(Ce,"Name",{enumerable:!0,get:function(){return Ln.Name}});Object.defineProperty(Ce,"CodeGen",{enumerable:!0,get:function(){return Ln.CodeGen}});var M$=js(),Xp=Mn(),C$=Tc(),Us=Fs(),N$=B(),Hs=Ls(),go=Ns(),sl=Y(),Wp=xp(),L$=Kp(),Qp=(r,e)=>new RegExp(r,e);Qp.code="new RegExp";var D$=["removeAdditional","useDefaults","coerceTypes"],q$=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),j$={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."},F$={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Gp=200;function V$(r){var e,t,n,s,i,o,a,c,l,u,d,f,p,m,h,y,b,g,_,I,v,S,k,$,P;let w=r.strict,N=(e=r.code)===null||e===void 0?void 0:e.optimize,j=N===!0||N===void 0?1:N||0,H=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:Qp,A=(s=r.uriResolver)!==null&&s!==void 0?s:L$.default;return{strictSchema:(o=(i=r.strictSchema)!==null&&i!==void 0?i:w)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=r.strictNumbers)!==null&&a!==void 0?a:w)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=r.strictTypes)!==null&&l!==void 0?l:w)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=r.strictTuples)!==null&&d!==void 0?d:w)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=r.strictRequired)!==null&&p!==void 0?p:w)!==null&&m!==void 0?m:!1,code:r.code?{...r.code,optimize:j,regExp:H}:{optimize:j,regExp:H},loopRequired:(h=r.loopRequired)!==null&&h!==void 0?h:Gp,loopEnum:(y=r.loopEnum)!==null&&y!==void 0?y:Gp,meta:(b=r.meta)!==null&&b!==void 0?b:!0,messages:(g=r.messages)!==null&&g!==void 0?g:!0,inlineRefs:(_=r.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(I=r.schemaId)!==null&&I!==void 0?I:"$id",addUsedSchema:(v=r.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(S=r.validateSchema)!==null&&S!==void 0?S:!0,validateFormats:(k=r.validateFormats)!==null&&k!==void 0?k:!0,unicodeRegExp:($=r.unicodeRegExp)!==null&&$!==void 0?$:!0,int32range:(P=r.int32range)!==null&&P!==void 0?P:!0,uriResolver:A}}var Bs=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...V$(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new N$.ValueScope({scope:{},prefixes:q$,es5:t,lines:n}),this.logger=W$(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,C$.getRules)(),Jp.call(this,j$,e,"NOT SUPPORTED"),Jp.call(this,F$,e,"DEPRECATED","warn"),this._metaOpts=z$.call(this),e.formats&&H$.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&B$.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),U$.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,s=Wp;n==="id"&&(s={...Wp},s.id=s.$id,delete s.$id),t&&e&&this.addMetaSchema(s,s[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let s=n(t);return"$async"in n||(this.errors=n.errors),s}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return s.call(this,e,t);async function s(u,d){await i.call(this,u.$schema);let f=this._addSchema(u,d);return f.validate||o.call(this,f)}async function i(u){u&&!this.getSchema(u)&&await s.call(this,{$ref:u},!0)}async function o(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Xp.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),o.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await i.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,t)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,t,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(let o of e)this.addSchema(o,void 0,n,s);return this}let i;if(typeof e=="object"){let{schemaId:o}=this.opts;if(i=e[o],i!==void 0&&typeof i!="string")throw new Error(`schema ${o} must be string`)}return t=(0,Hs.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,s,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw 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 s=this.validate(n,e);if(!s&&t){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw new Error(i)}return s}getSchema(e){let t;for(;typeof(t=Yp.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,s=new Us.SchemaEnv({schema:{},schemaId:n});if(t=Us.resolveSchema.call(this,s,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let t=Yp.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,Hs.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e=="string")n=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else if(typeof e=="object"&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(J$.call(this,n,t),!t)return(0,sl.eachItem)(n,i=>nl.call(this,i)),this;X$.call(this,t);let s={...t,type:(0,go.getJSONTypes)(t.type),schemaType:(0,go.getJSONTypes)(t.schemaType)};return(0,sl.eachItem)(n,s.type.length===0?i=>nl.call(this,i,s):i=>s.type.forEach(o=>nl.call(this,i,s,o))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let s=n.rules.findIndex(i=>i.keyword===e);s>=0&&n.rules.splice(s,1)}return this}addFormat(e,t){return typeof t=="string"&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,i)=>s+t+i)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of t){let i=s.split("/").slice(1),o=e;for(let a of i)o=o[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=o[a];l&&u&&(o[a]=Zp(u))}}return e}_removeAllSchemas(e,t){for(let n in e){let s=e[n];(!t||t.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,t,n,s=this.opts.validateSchema,i=this.opts.addUsedSchema){let o,{schemaId:a}=this.opts;if(typeof e=="object")o=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Hs.normalizeId)(o||n);let l=Hs.getSchemaRefs.call(this,e,n);return c=new Us.SchemaEnv({schema:e,schemaId:a,meta:t,baseId:n,localRefs:l}),this._cache.set(c.schema,c),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),s&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Us.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{Us.compileSchema.call(this,e)}finally{this.opts=t}}};Bs.ValidationError=M$.default;Bs.MissingRefError=Xp.default;Ce.default=Bs;function Jp(r,e,t,n="error"){for(let s in r){let i=s;i in e&&this.logger[n](`${t}: option ${s}. ${r[i]}`)}}function Yp(r){return r=(0,Hs.normalizeId)(r),this.schemas[r]||this.refs[r]}function U$(){let r=this.opts.schemas;if(r)if(Array.isArray(r))this.addSchema(r);else for(let e in r)this.addSchema(r[e],e)}function H$(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function B$(r){if(Array.isArray(r)){this.addVocabulary(r);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in r){let t=r[e];t.keyword||(t.keyword=e),this.addKeyword(t)}}function z$(){let r={...this.opts};for(let e of D$)delete r[e];return r}var K$={log(){},warn(){},error(){}};function W$(r){if(r===!1)return K$;if(r===void 0)return console;if(r.log&&r.warn&&r.error)return r;throw new Error("logger must implement log, warn and error methods")}var G$=/^[a-z_$][a-z0-9_$:-]*$/i;function J$(r,e){let{RULES:t}=this;if((0,sl.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!G$.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function nl(r,e,t){var n;let s=e==null?void 0:e.post;if(t&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,o=s?i.post:i.rules.find(({type:c})=>c===t);if(o||(o={type:t,rules:[]},i.rules.push(o)),i.keywords[r]=!0,!e)return;let a={keyword:r,definition:{...e,type:(0,go.getJSONTypes)(e.type),schemaType:(0,go.getJSONTypes)(e.schemaType)}};e.before?Y$.call(this,o,a,e.before):o.rules.push(a),i.all[r]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function Y$(r,e,t){let n=r.rules.findIndex(s=>s.keyword===t);n>=0?r.rules.splice(n,0,e):(r.rules.push(e),this.logger.warn(`rule ${t} is not defined`))}function X$(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Zp(e)),r.validateSchema=this.compile(e,!0))}var Q$={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Zp(r){return{anyOf:[r,Q$]}}});var eh=E(ol=>{"use strict";Object.defineProperty(ol,"__esModule",{value:!0});var Z$={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ol.default=Z$});var _o=E(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.callRef=ln.getValidate=void 0;var eS=Mn(),th=ht(),Ze=B(),Dn=pt(),rh=Fs(),bo=Y(),tS={keyword:"$ref",schemaType:"string",code(r){let{gen:e,schema:t,it:n}=r,{baseId:s,schemaEnv:i,validateName:o,opts:a,self:c}=n,{root:l}=i;if((t==="#"||t==="#/")&&s===l.baseId)return d();let u=rh.resolveRef.call(c,l,s,t);if(u===void 0)throw new eS.default(n.opts.uriResolver,s,t);if(u instanceof rh.SchemaEnv)return f(u);return p(u);function d(){if(i===l)return wo(r,o,i,i.$async);let m=e.scopeValue("root",{ref:l});return wo(r,(0,Ze._)`${m}.validate`,l,l.$async)}function f(m){let h=nh(r,m);wo(r,h,m,m.$async)}function p(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Ze.stringify)(m)}:{ref:m}),y=e.name("valid"),b=r.subschema({schema:m,dataTypes:[],schemaPath:Ze.nil,topSchemaRef:h,errSchemaPath:t},y);r.mergeEvaluated(b),r.ok(y)}}};function nh(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,Ze._)`${t.scopeValue("wrapper",{ref:e})}.validate`}ln.getValidate=nh;function wo(r,e,t,n){let{gen:s,it:i}=r,{allErrors:o,schemaEnv:a,opts:c}=i,l=c.passContext?Dn.default.this:Ze.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=s.let("valid");s.try(()=>{s.code((0,Ze._)`await ${(0,th.callValidateCode)(r,e,l)}`),p(e),o||s.assign(m,!0)},h=>{s.if((0,Ze._)`!(${h} instanceof ${i.ValidationError})`,()=>s.throw(h)),f(h),o||s.assign(m,!1)}),r.ok(m)}function d(){r.result((0,th.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(m){let h=(0,Ze._)`${m}.errors`;s.assign(Dn.default.vErrors,(0,Ze._)`${Dn.default.vErrors} === null ? ${h} : ${Dn.default.vErrors}.concat(${h})`),s.assign(Dn.default.errors,(0,Ze._)`${Dn.default.vErrors}.length`)}function p(m){var h;if(!i.opts.unevaluated)return;let y=(h=t==null?void 0:t.validate)===null||h===void 0?void 0:h.evaluated;if(i.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(i.props=bo.mergeEvaluated.props(s,y.props,i.props));else{let b=s.var("props",(0,Ze._)`${m}.evaluated.props`);i.props=bo.mergeEvaluated.props(s,b,i.props,Ze.Name)}if(i.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(i.items=bo.mergeEvaluated.items(s,y.items,i.items));else{let b=s.var("items",(0,Ze._)`${m}.evaluated.items`);i.items=bo.mergeEvaluated.items(s,b,i.items,Ze.Name)}}}ln.callRef=wo;ln.default=tS});var cl=E(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});var rS=eh(),nS=_o(),sS=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",rS.default,nS.default];al.default=sS});var sh=E(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});var vo=B(),Lr=vo.operators,$o={maximum:{okStr:"<=",ok:Lr.LTE,fail:Lr.GT},minimum:{okStr:">=",ok:Lr.GTE,fail:Lr.LT},exclusiveMaximum:{okStr:"<",ok:Lr.LT,fail:Lr.GTE},exclusiveMinimum:{okStr:">",ok:Lr.GT,fail:Lr.LTE}},iS={message:({keyword:r,schemaCode:e})=>(0,vo.str)`must be ${$o[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,vo._)`{comparison: ${$o[r].okStr}, limit: ${e}}`},oS={keyword:Object.keys($o),type:"number",schemaType:"number",$data:!0,error:iS,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,vo._)`${t} ${$o[e].fail} ${n} || isNaN(${t})`)}};ll.default=oS});var ih=E(dl=>{"use strict";Object.defineProperty(dl,"__esModule",{value:!0});var zs=B(),aS={message:({schemaCode:r})=>(0,zs.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,zs._)`{multipleOf: ${r}}`},cS={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:aS,code(r){let{gen:e,data:t,schemaCode:n,it:s}=r,i=s.opts.multipleOfPrecision,o=e.let("res"),a=i?(0,zs._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${i}`:(0,zs._)`${o} !== parseInt(${o})`;r.fail$data((0,zs._)`(${n} === 0 || (${o} = ${t}/${n}, ${a}))`)}};dl.default=cS});var ah=E(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});function oh(r){let e=r.length,t=0,n=0,s;for(;n=55296&&s<=56319&&n{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});var dn=B(),lS=Y(),dS=ah(),uS={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,dn.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,dn._)`{limit: ${r}}`},fS={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:uS,code(r){let{keyword:e,data:t,schemaCode:n,it:s}=r,i=e==="maxLength"?dn.operators.GT:dn.operators.LT,o=s.opts.unicode===!1?(0,dn._)`${t}.length`:(0,dn._)`${(0,lS.useFunc)(r.gen,dS.default)}(${t})`;r.fail$data((0,dn._)`${o} ${i} ${n}`)}};fl.default=fS});var lh=E(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});var pS=ht(),hS=Y(),qn=B(),mS={message:({schemaCode:r})=>(0,qn.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,qn._)`{pattern: ${r}}`},yS={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:mS,code(r){let{gen:e,data:t,$data:n,schema:s,schemaCode:i,it:o}=r,a=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=o.opts.code,l=c.code==="new RegExp"?(0,qn._)`new RegExp`:(0,hS.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,qn._)`${l}(${i}, ${a}).test(${t})`),()=>e.assign(u,!1)),r.fail$data((0,qn._)`!${u}`)}else{let c=(0,pS.usePattern)(r,s);r.fail$data((0,qn._)`!${c}.test(${t})`)}}};pl.default=yS});var dh=E(hl=>{"use strict";Object.defineProperty(hl,"__esModule",{value:!0});var Ks=B(),gS={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,Ks.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,Ks._)`{limit: ${r}}`},bS={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:gS,code(r){let{keyword:e,data:t,schemaCode:n}=r,s=e==="maxProperties"?Ks.operators.GT:Ks.operators.LT;r.fail$data((0,Ks._)`Object.keys(${t}).length ${s} ${n}`)}};hl.default=bS});var uh=E(ml=>{"use strict";Object.defineProperty(ml,"__esModule",{value:!0});var Ws=ht(),Gs=B(),wS=Y(),_S={message:({params:{missingProperty:r}})=>(0,Gs.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,Gs._)`{missingProperty: ${r}}`},vS={keyword:"required",type:"object",schemaType:"array",$data:!0,error:_S,code(r){let{gen:e,schema:t,schemaCode:n,data:s,$data:i,it:o}=r,{opts:a}=o;if(!i&&t.length===0)return;let c=t.length>=a.loopRequired;if(o.allErrors?l():u(),a.strictRequired){let p=r.parentSchema.properties,{definedProperties:m}=r.it;for(let h of t)if((p==null?void 0:p[h])===void 0&&!m.has(h)){let y=o.schemaEnv.baseId+o.errSchemaPath,b=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,wS.checkStrictMode)(o,b,o.opts.strictRequired)}}function l(){if(c||i)r.block$data(Gs.nil,d);else for(let p of t)(0,Ws.checkReportMissingProp)(r,p)}function u(){let p=e.let("missing");if(c||i){let m=e.let("valid",!0);r.block$data(m,()=>f(p,m)),r.ok(m)}else e.if((0,Ws.checkMissingProp)(r,t,p)),(0,Ws.reportMissingProp)(r,p),e.else()}function d(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,Ws.noPropertyInData)(e,s,p,a.ownProperties),()=>r.error())})}function f(p,m){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(m,(0,Ws.propertyInData)(e,s,p,a.ownProperties)),e.if((0,Gs.not)(m),()=>{r.error(),e.break()})},Gs.nil)}}};ml.default=vS});var fh=E(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});var Js=B(),$S={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,Js.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,Js._)`{limit: ${r}}`},SS={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:$S,code(r){let{keyword:e,data:t,schemaCode:n}=r,s=e==="maxItems"?Js.operators.GT:Js.operators.LT;r.fail$data((0,Js._)`${t}.length ${s} ${n}`)}};yl.default=SS});var So=E(gl=>{"use strict";Object.defineProperty(gl,"__esModule",{value:!0});var ph=qc();ph.code='require("ajv/dist/runtime/equal").default';gl.default=ph});var hh=E(wl=>{"use strict";Object.defineProperty(wl,"__esModule",{value:!0});var bl=Ns(),Ne=B(),ES=Y(),AS=So(),kS={message:({params:{i:r,j:e}})=>(0,Ne.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,Ne._)`{i: ${r}, j: ${e}}`},xS={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:kS,code(r){let{gen:e,data:t,$data:n,schema:s,parentSchema:i,schemaCode:o,it:a}=r;if(!n&&!s)return;let c=e.let("valid"),l=i.items?(0,bl.getSchemaTypes)(i.items):[];r.block$data(c,u,(0,Ne._)`${o} === false`),r.ok(c);function u(){let m=e.let("i",(0,Ne._)`${t}.length`),h=e.let("j");r.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,Ne._)`${m} > 1`,()=>(d()?f:p)(m,h))}function d(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function f(m,h){let y=e.name("item"),b=(0,bl.checkDataTypes)(l,y,a.opts.strictNumbers,bl.DataType.Wrong),g=e.const("indices",(0,Ne._)`{}`);e.for((0,Ne._)`;${m}--;`,()=>{e.let(y,(0,Ne._)`${t}[${m}]`),e.if(b,(0,Ne._)`continue`),l.length>1&&e.if((0,Ne._)`typeof ${y} == "string"`,(0,Ne._)`${y} += "_"`),e.if((0,Ne._)`typeof ${g}[${y}] == "number"`,()=>{e.assign(h,(0,Ne._)`${g}[${y}]`),r.error(),e.assign(c,!1).break()}).code((0,Ne._)`${g}[${y}] = ${m}`)})}function p(m,h){let y=(0,ES.useFunc)(e,AS.default),b=e.name("outer");e.label(b).for((0,Ne._)`;${m}--;`,()=>e.for((0,Ne._)`${h} = ${m}; ${h}--;`,()=>e.if((0,Ne._)`${y}(${t}[${m}], ${t}[${h}])`,()=>{r.error(),e.assign(c,!1).break(b)})))}}};wl.default=xS});var mh=E(vl=>{"use strict";Object.defineProperty(vl,"__esModule",{value:!0});var _l=B(),PS=Y(),IS=So(),TS={message:"must be equal to constant",params:({schemaCode:r})=>(0,_l._)`{allowedValue: ${r}}`},OS={keyword:"const",$data:!0,error:TS,code(r){let{gen:e,data:t,$data:n,schemaCode:s,schema:i}=r;n||i&&typeof i=="object"?r.fail$data((0,_l._)`!${(0,PS.useFunc)(e,IS.default)}(${t}, ${s})`):r.fail((0,_l._)`${i} !== ${t}`)}};vl.default=OS});var yh=E($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});var Ys=B(),RS=Y(),MS=So(),CS={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,Ys._)`{allowedValues: ${r}}`},NS={keyword:"enum",schemaType:"array",$data:!0,error:CS,code(r){let{gen:e,data:t,$data:n,schema:s,schemaCode:i,it:o}=r;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=o.opts.loopEnum,c,l=()=>c!=null?c:c=(0,RS.useFunc)(e,MS.default),u;if(a||n)u=e.let("valid"),r.block$data(u,d);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let p=e.const("vSchema",i);u=(0,Ys.or)(...s.map((m,h)=>f(p,h)))}r.pass(u);function d(){e.assign(u,!1),e.forOf("v",i,p=>e.if((0,Ys._)`${l()}(${t}, ${p})`,()=>e.assign(u,!0).break()))}function f(p,m){let h=s[m];return typeof h=="object"&&h!==null?(0,Ys._)`${l()}(${t}, ${p}[${m}])`:(0,Ys._)`${t} === ${h}`}}};$l.default=NS});var El=E(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});var LS=sh(),DS=ih(),qS=ch(),jS=lh(),FS=dh(),VS=uh(),US=fh(),HS=hh(),BS=mh(),zS=yh(),KS=[LS.default,DS.default,qS.default,jS.default,FS.default,VS.default,US.default,HS.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},BS.default,zS.default];Sl.default=KS});var kl=E(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.validateAdditionalItems=void 0;var un=B(),Al=Y(),WS={message:({params:{len:r}})=>(0,un.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,un._)`{limit: ${r}}`},GS={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:WS,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,Al.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}gh(r,n)}};function gh(r,e){let{gen:t,schema:n,data:s,keyword:i,it:o}=r;o.items=!0;let a=t.const("len",(0,un._)`${s}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,un._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Al.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,un._)`${a} <= ${e.length}`);t.if((0,un.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,u=>{r.subschema({keyword:i,dataProp:u,dataPropType:Al.Type.Num},l),o.allErrors||t.if((0,un.not)(l),()=>t.break())})}}Xs.validateAdditionalItems=gh;Xs.default=GS});var xl=E(Qs=>{"use strict";Object.defineProperty(Qs,"__esModule",{value:!0});Qs.validateTuple=void 0;var bh=B(),Eo=Y(),JS=ht(),YS={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return wh(r,"additionalItems",e);t.items=!0,!(0,Eo.alwaysValidSchema)(t,e)&&r.ok((0,JS.validateArray)(r))}};function wh(r,e,t=r.schema){let{gen:n,parentSchema:s,data:i,keyword:o,it:a}=r;u(s),a.opts.unevaluated&&t.length&&a.items!==!0&&(a.items=Eo.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,bh._)`${i}.length`);t.forEach((d,f)=>{(0,Eo.alwaysValidSchema)(a,d)||(n.if((0,bh._)`${l} > ${f}`,()=>r.subschema({keyword:o,schemaProp:f,dataProp:f},c)),r.ok(c))});function u(d){let{opts:f,errSchemaPath:p}=a,m=t.length,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(f.strictTuples&&!h){let y=`"${o}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,Eo.checkStrictMode)(a,y,f.strictTuples)}}}Qs.validateTuple=wh;Qs.default=YS});var _h=E(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});var XS=xl(),QS={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,XS.validateTuple)(r,"items")};Pl.default=QS});var $h=E(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});var vh=B(),ZS=Y(),eE=ht(),tE=kl(),rE={message:({params:{len:r}})=>(0,vh.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,vh._)`{limit: ${r}}`},nE={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:rE,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:s}=t;n.items=!0,!(0,ZS.alwaysValidSchema)(n,e)&&(s?(0,tE.validateAdditionalItems)(r,s):r.ok((0,eE.validateArray)(r)))}};Il.default=nE});var Sh=E(Tl=>{"use strict";Object.defineProperty(Tl,"__esModule",{value:!0});var yt=B(),Ao=Y(),sE={message:({params:{min:r,max:e}})=>e===void 0?(0,yt.str)`must contain at least ${r} valid item(s)`:(0,yt.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,yt._)`{minContains: ${r}}`:(0,yt._)`{minContains: ${r}, maxContains: ${e}}`},iE={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:sE,code(r){let{gen:e,schema:t,parentSchema:n,data:s,it:i}=r,o,a,{minContains:c,maxContains:l}=n;i.opts.next?(o=c===void 0?1:c,a=l):o=1;let u=e.const("len",(0,yt._)`${s}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,Ao.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,Ao.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,Ao.alwaysValidSchema)(i,t)){let h=(0,yt._)`${u} >= ${o}`;a!==void 0&&(h=(0,yt._)`${h} && ${u} <= ${a}`),r.pass(h);return}i.items=!0;let d=e.name("valid");a===void 0&&o===1?p(d,()=>e.if(d,()=>e.break())):o===0?(e.let(d,!0),a!==void 0&&e.if((0,yt._)`${s}.length > 0`,f)):(e.let(d,!1),f()),r.result(d,()=>r.reset());function f(){let h=e.name("_valid"),y=e.let("count",0);p(h,()=>e.if(h,()=>m(y)))}function p(h,y){e.forRange("i",0,u,b=>{r.subschema({keyword:"contains",dataProp:b,dataPropType:Ao.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,yt._)`${h}++`),a===void 0?e.if((0,yt._)`${h} >= ${o}`,()=>e.assign(d,!0).break()):(e.if((0,yt._)`${h} > ${a}`,()=>e.assign(d,!1).break()),o===1?e.assign(d,!0):e.if((0,yt._)`${h} >= ${o}`,()=>e.assign(d,!0)))}}};Tl.default=iE});var ko=E(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.validateSchemaDeps=Gt.validatePropertyDeps=Gt.error=void 0;var Ol=B(),oE=Y(),Zs=ht();Gt.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,Ol.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,Ol._)`{property: ${r}, +var Qw=Object.create;var Ni=Object.defineProperty;var Zw=Object.getOwnPropertyDescriptor;var e0=Object.getOwnPropertyNames;var t0=Object.getPrototypeOf,r0=Object.prototype.hasOwnProperty;var n0=(r,e,t)=>e in r?Ni(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var A=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),i0=(r,e)=>{for(var t in e)Ni(r,t,{get:e[t],enumerable:!0})},tp=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of e0(e))!r0.call(r,i)&&i!==t&&Ni(r,i,{get:()=>e[i],enumerable:!(n=Zw(e,i))||n.enumerable});return r};var ln=(r,e,t)=>(t=r!=null?Qw(t0(r)):{},tp(e||!r||!r.__esModule?Ni(t,"default",{value:r,enumerable:!0}):t,r)),s0=r=>tp(Ni({},"__esModule",{value:!0}),r);var T=(r,e,t)=>n0(r,typeof e!="symbol"?e+"":e,t);var ji=A(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.regexpCode=le.getEsmExportName=le.getProperty=le.safeStringify=le.stringify=le.strConcat=le.addCodeArg=le.str=le._=le.nil=le._Code=le.Name=le.IDENTIFIER=le._CodeOrName=void 0;var Di=class{};le._CodeOrName=Di;le.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var dn=class extends Di{constructor(e){if(super(),!le.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};le.Name=dn;var At=class extends Di{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((t,n)=>`${t}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,n)=>(n instanceof dn&&(t[n.str]=(t[n.str]||0)+1),t),{})}};le._Code=At;le.nil=new At("");function rp(r,...e){let t=[r[0]],n=0;for(;n{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.ValueScope=dt.ValueScopeName=dt.Scope=dt.varKinds=dt.UsedValueState=void 0;var lt=ji(),Mc=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},po;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(po||(dt.UsedValueState=po={}));dt.varKinds={const:new lt.Name("const"),let:new lt.Name("let"),var:new lt.Name("var")};var ho=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof lt.Name?e:this.name(e)}name(e){return new lt.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,n;if(!((n=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};dt.Scope=ho;var mo=class extends lt.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,lt._)`.${new lt.Name(t)}[${n}]`}};dt.ValueScopeName=mo;var h0=(0,lt._)`\n`,Nc=class extends ho{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?h0:lt.nil}}get(){return this._scope}name(e){return new mo(e,this._newName(e))}value(e,t){var n;if(t.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let i=this.toName(e),{prefix:s}=i,o=(n=t.key)!==null&&n!==void 0?n:t.ref,a=this._values[s];if(a){let u=a.get(o);if(u)return u}else a=this._values[s]=new Map;a.set(o,i);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=t.ref,i.setValue(t,{property:s,itemIndex:l}),i}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,lt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,i=>{if(i.value===void 0)throw new Error(`CodeGen: name "${i}" has no value`);return i.value.code},t,n)}_reduceValues(e,t,n={},i){let s=lt.nil;for(let o in e){let a=e[o];if(!a)continue;let c=n[o]=n[o]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,po.Started);let u=t(l);if(u){let d=this.opts.es5?dt.varKinds.var:dt.varKinds.const;s=(0,lt._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=i==null?void 0:i(l))s=(0,lt._)`${s}${u}${this.opts._n}`;else throw new Mc(l);c.set(l,po.Completed)})}return s}};dt.ValueScope=Nc});var K=A(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.or=Q.and=Q.not=Q.CodeGen=Q.operators=Q.varKinds=Q.ValueScopeName=Q.ValueScope=Q.Scope=Q.Name=Q.regexpCode=Q.stringify=Q.getProperty=Q.nil=Q.strConcat=Q.str=Q._=void 0;var ie=ji(),Dt=Lc(),qr=ji();Object.defineProperty(Q,"_",{enumerable:!0,get:function(){return qr._}});Object.defineProperty(Q,"str",{enumerable:!0,get:function(){return qr.str}});Object.defineProperty(Q,"strConcat",{enumerable:!0,get:function(){return qr.strConcat}});Object.defineProperty(Q,"nil",{enumerable:!0,get:function(){return qr.nil}});Object.defineProperty(Q,"getProperty",{enumerable:!0,get:function(){return qr.getProperty}});Object.defineProperty(Q,"stringify",{enumerable:!0,get:function(){return qr.stringify}});Object.defineProperty(Q,"regexpCode",{enumerable:!0,get:function(){return qr.regexpCode}});Object.defineProperty(Q,"Name",{enumerable:!0,get:function(){return qr.Name}});var _o=Lc();Object.defineProperty(Q,"Scope",{enumerable:!0,get:function(){return _o.Scope}});Object.defineProperty(Q,"ValueScope",{enumerable:!0,get:function(){return _o.ValueScope}});Object.defineProperty(Q,"ValueScopeName",{enumerable:!0,get:function(){return _o.ValueScopeName}});Object.defineProperty(Q,"varKinds",{enumerable:!0,get:function(){return _o.varKinds}});Q.operators={GT:new ie._Code(">"),GTE:new ie._Code(">="),LT:new ie._Code("<"),LTE:new ie._Code("<="),EQ:new ie._Code("==="),NEQ:new ie._Code("!=="),NOT:new ie._Code("!"),OR:new ie._Code("||"),AND:new ie._Code("&&"),ADD:new ie._Code("+")};var _r=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},Dc=class extends _r{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?Dt.varKinds.var:this.varKind,i=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&(this.rhs=Ln(this.rhs,e,t)),this}get names(){return this.rhs instanceof ie._CodeOrName?this.rhs.names:{}}},yo=class extends _r{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(!(this.lhs instanceof ie.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Ln(this.rhs,e,t),this}get names(){let e=this.lhs instanceof ie.Name?{}:{...this.lhs.names};return bo(e,this.rhs)}},qc=class extends yo{constructor(e,t,n,i){super(e,n,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},jc=class extends _r{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Fc=class extends _r{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Vc=class extends _r{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Uc=class extends _r{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=Ln(this.code,e,t),this}get names(){return this.code instanceof ie._CodeOrName?this.code.names:{}}},Fi=class extends _r{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,i=n.length;for(;i--;){let s=n[i];s.optimizeNames(e,t)||(m0(e,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>pn(e,t.names),{})}},wr=class extends Fi{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Bc=class extends Fi{},Nn=class extends wr{};Nn.kind="else";var un=class r extends wr{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+="else "+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let n=t.optimizeNodes();t=this.else=Array.isArray(n)?new Nn(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(ip(e),t instanceof r?[t]:t.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,t){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,t),!!(super.optimizeNames(e,t)||this.else))return this.condition=Ln(this.condition,e,t),this}get names(){let e=super.names;return bo(e,this.condition),this.else&&pn(e,this.else.names),e}};un.kind="if";var fn=class extends wr{};fn.kind="for";var zc=class extends fn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=Ln(this.iteration,e,t),this}get names(){return pn(super.names,this.iteration.names)}},Hc=class extends fn{constructor(e,t,n,i){super(),this.varKind=e,this.name=t,this.from=n,this.to=i}render(e){let t=e.es5?Dt.varKinds.var:this.varKind,{name:n,from:i,to:s}=this;return`for(${t} ${n}=${i}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=bo(super.names,this.from);return bo(e,this.to)}},go=class extends fn{constructor(e,t,n,i){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=i}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=Ln(this.iterable,e,t),this}get names(){return pn(super.names,this.iterable.names)}},Vi=class extends wr{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Vi.kind="func";var Ui=class extends Fi{render(e){return"return "+super.render(e)}};Ui.kind="return";var Kc=class extends wr{render(e){let t="try"+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var n,i;return super.optimizeNames(e,t),(n=this.catch)===null||n===void 0||n.optimizeNames(e,t),(i=this.finally)===null||i===void 0||i.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&pn(e,this.catch.names),this.finally&&pn(e,this.finally.names),e}},Bi=class extends wr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Bi.kind="catch";var zi=class extends wr{render(e){return"finally"+super.render(e)}};zi.kind="finally";var Wc=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` +`:""},this._extScope=e,this._scope=new Dt.Scope({parent:e}),this._nodes=[new Bc]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,i){let s=this._scope.toName(t);return n!==void 0&&i&&(this._constants[s.str]=n),this._leafNode(new Dc(e,s,n)),s}const(e,t,n){return this._def(Dt.varKinds.const,e,t,n)}let(e,t,n){return this._def(Dt.varKinds.let,e,t,n)}var(e,t,n){return this._def(Dt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new yo(e,t,n))}add(e,t){return this._leafNode(new qc(e,Q.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==ie.nil&&this._leafNode(new Uc(e)),this}object(...e){let t=["{"];for(let[n,i]of e)t.length>1&&t.push(","),t.push(n),(n!==i||this.opts.es5)&&(t.push(":"),(0,ie.addCodeArg)(t,i));return t.push("}"),new ie._Code(t)}if(e,t,n){if(this._blockNode(new un(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new un(e))}else(){return this._elseNode(new Nn)}endIf(){return this._endBlockNode(un,Nn)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new zc(e),t)}forRange(e,t,n,i,s=this.opts.es5?Dt.varKinds.var:Dt.varKinds.let){let o=this._scope.toName(e);return this._for(new Hc(s,o,t,n),()=>i(o))}forOf(e,t,n,i=Dt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let o=t instanceof ie.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,ie._)`${o}.length`,a=>{this.var(s,(0,ie._)`${o}[${a}]`),n(s)})}return this._for(new go("of",i,s,t),()=>n(s))}forIn(e,t,n,i=this.opts.es5?Dt.varKinds.var:Dt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ie._)`Object.keys(${t})`,n);let s=this._scope.toName(e);return this._for(new go("in",i,s,t),()=>n(s))}endFor(){return this._endBlockNode(fn)}label(e){return this._leafNode(new jc(e))}break(e){return this._leafNode(new Fc(e))}return(e){let t=new Ui;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Ui)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new Kc;if(this._blockNode(i),this.code(e),t){let s=this.name("e");this._currNode=i.catch=new Bi(s),t(s)}return n&&(this._currNode=i.finally=new zi,this.code(n)),this._endBlockNode(Bi,zi)}throw(e){return this._leafNode(new Vc(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=ie.nil,n,i){return this._blockNode(new Vi(e,t,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(Vi)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof un))throw new Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};Q.CodeGen=Wc;function pn(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function bo(r,e){return e instanceof ie._CodeOrName?pn(r,e.names):r}function Ln(r,e,t){if(r instanceof ie.Name)return n(r);if(!i(r))return r;return new ie._Code(r._items.reduce((s,o)=>(o instanceof ie.Name&&(o=n(o)),o instanceof ie._Code?s.push(...o._items):s.push(o),s),[]));function n(s){let o=t[s.str];return o===void 0||e[s.str]!==1?s:(delete e[s.str],o)}function i(s){return s instanceof ie._Code&&s._items.some(o=>o instanceof ie.Name&&e[o.str]===1&&t[o.str]!==void 0)}}function m0(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function ip(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,ie._)`!${Gc(r)}`}Q.not=ip;var y0=sp(Q.operators.AND);function g0(...r){return r.reduce(y0)}Q.and=g0;var b0=sp(Q.operators.OR);function _0(...r){return r.reduce(b0)}Q.or=_0;function sp(r){return(e,t)=>e===ie.nil?t:t===ie.nil?e:(0,ie._)`${Gc(e)} ${r} ${Gc(t)}`}function Gc(r){return r instanceof ie.Name?r:(0,ie._)`(${r})`}});var ee=A(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.checkStrictMode=Z.getErrorPath=Z.Type=Z.useFunc=Z.setEvaluated=Z.evaluatedPropsToName=Z.mergeEvaluated=Z.eachItem=Z.unescapeJsonPointer=Z.escapeJsonPointer=Z.escapeFragment=Z.unescapeFragment=Z.schemaRefOrVal=Z.schemaHasRulesButRef=Z.schemaHasRules=Z.checkUnknownRules=Z.alwaysValidSchema=Z.toHash=void 0;var me=K(),w0=ji();function v0(r){let e={};for(let t of r)e[t]=!0;return e}Z.toHash=v0;function $0(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(cp(r,e),!lp(e,r.self.RULES.all))}Z.alwaysValidSchema=$0;function cp(r,e=r.schema){let{opts:t,self:n}=r;if(!t.strictSchema||typeof e=="boolean")return;let i=n.RULES.keywords;for(let s in e)i[s]||fp(r,`unknown keyword: "${s}"`)}Z.checkUnknownRules=cp;function lp(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}Z.schemaHasRules=lp;function S0(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(t!=="$ref"&&e.all[t])return!0;return!1}Z.schemaHasRulesButRef=S0;function E0({topSchemaRef:r,schemaPath:e},t,n,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,me._)`${t}`}return(0,me._)`${r}${e}${(0,me.getProperty)(n)}`}Z.schemaRefOrVal=E0;function A0(r){return dp(decodeURIComponent(r))}Z.unescapeFragment=A0;function k0(r){return encodeURIComponent(Yc(r))}Z.escapeFragment=k0;function Yc(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}Z.escapeJsonPointer=Yc;function dp(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}Z.unescapeJsonPointer=dp;function x0(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}Z.eachItem=x0;function op({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(i,s,o,a)=>{let c=o===void 0?s:o instanceof me.Name?(s instanceof me.Name?r(i,s,o):e(i,s,o),o):s instanceof me.Name?(e(i,o,s),s):t(s,o);return a===me.Name&&!(c instanceof me.Name)?n(i,c):c}}Z.mergeEvaluated={props:op({mergeNames:(r,e,t)=>r.if((0,me._)`${t} !== true && ${e} !== undefined`,()=>{r.if((0,me._)`${e} === true`,()=>r.assign(t,!0),()=>r.assign(t,(0,me._)`${t} || {}`).code((0,me._)`Object.assign(${t}, ${e})`))}),mergeToName:(r,e,t)=>r.if((0,me._)`${t} !== true`,()=>{e===!0?r.assign(t,!0):(r.assign(t,(0,me._)`${t} || {}`),Xc(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:up}),items:op({mergeNames:(r,e,t)=>r.if((0,me._)`${t} !== true && ${e} !== undefined`,()=>r.assign(t,(0,me._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(r,e,t)=>r.if((0,me._)`${t} !== true`,()=>r.assign(t,e===!0?!0:(0,me._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(r,e)=>r===!0?!0:Math.max(r,e),resultToName:(r,e)=>r.var("items",e)})};function up(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,me._)`{}`);return e!==void 0&&Xc(r,t,e),t}Z.evaluatedPropsToName=up;function Xc(r,e,t){Object.keys(t).forEach(n=>r.assign((0,me._)`${e}${(0,me.getProperty)(n)}`,!0))}Z.setEvaluated=Xc;var ap={};function P0(r,e){return r.scopeValue("func",{ref:e,code:ap[e.code]||(ap[e.code]=new w0._Code(e.code))})}Z.useFunc=P0;var Jc;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(Jc||(Z.Type=Jc={}));function I0(r,e,t){if(r instanceof me.Name){let n=e===Jc.Num;return t?n?(0,me._)`"[" + ${r} + "]"`:(0,me._)`"['" + ${r} + "']"`:n?(0,me._)`"/" + ${r}`:(0,me._)`"/" + ${r}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,me.getProperty)(r).toString():"/"+Yc(r)}Z.getErrorPath=I0;function fp(r,e,t=r.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===!0)throw new Error(e);r.self.logger.warn(e)}}Z.checkStrictMode=fp});var kt=A(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var He=K(),O0={data:new He.Name("data"),valCxt:new He.Name("valCxt"),instancePath:new He.Name("instancePath"),parentData:new He.Name("parentData"),parentDataProperty:new He.Name("parentDataProperty"),rootData:new He.Name("rootData"),dynamicAnchors:new He.Name("dynamicAnchors"),vErrors:new He.Name("vErrors"),errors:new He.Name("errors"),this:new He.Name("this"),self:new He.Name("self"),scope:new He.Name("scope"),json:new He.Name("json"),jsonPos:new He.Name("jsonPos"),jsonLen:new He.Name("jsonLen"),jsonPart:new He.Name("jsonPart")};Qc.default=O0});var Hi=A(Ke=>{"use strict";Object.defineProperty(Ke,"__esModule",{value:!0});Ke.extendErrors=Ke.resetErrorsCount=Ke.reportExtraError=Ke.reportError=Ke.keyword$DataError=Ke.keywordError=void 0;var oe=K(),wo=ee(),tt=kt();Ke.keywordError={message:({keyword:r})=>(0,oe.str)`must pass "${r}" keyword validation`};Ke.keyword$DataError={message:({keyword:r,schemaType:e})=>e?(0,oe.str)`"${r}" keyword must be ${e} ($data)`:(0,oe.str)`"${r}" keyword is invalid ($data)`};function T0(r,e=Ke.keywordError,t,n){let{it:i}=r,{gen:s,compositeRule:o,allErrors:a}=i,c=mp(r,e,t);(n!=null?n:o||a)?pp(s,c):hp(i,(0,oe._)`[${c}]`)}Ke.reportError=T0;function R0(r,e=Ke.keywordError,t){let{it:n}=r,{gen:i,compositeRule:s,allErrors:o}=n,a=mp(r,e,t);pp(i,a),s||o||hp(n,tt.default.vErrors)}Ke.reportExtraError=R0;function C0(r,e){r.assign(tt.default.errors,e),r.if((0,oe._)`${tt.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,oe._)`${tt.default.vErrors}.length`,e),()=>r.assign(tt.default.vErrors,null)))}Ke.resetErrorsCount=C0;function M0({gen:r,keyword:e,schemaValue:t,data:n,errsCount:i,it:s}){if(i===void 0)throw new Error("ajv implementation error");let o=r.name("err");r.forRange("i",i,tt.default.errors,a=>{r.const(o,(0,oe._)`${tt.default.vErrors}[${a}]`),r.if((0,oe._)`${o}.instancePath === undefined`,()=>r.assign((0,oe._)`${o}.instancePath`,(0,oe.strConcat)(tt.default.instancePath,s.errorPath))),r.assign((0,oe._)`${o}.schemaPath`,(0,oe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(r.assign((0,oe._)`${o}.schema`,t),r.assign((0,oe._)`${o}.data`,n))})}Ke.extendErrors=M0;function pp(r,e){let t=r.const("err",e);r.if((0,oe._)`${tt.default.vErrors} === null`,()=>r.assign(tt.default.vErrors,(0,oe._)`[${t}]`),(0,oe._)`${tt.default.vErrors}.push(${t})`),r.code((0,oe._)`${tt.default.errors}++`)}function hp(r,e){let{gen:t,validateName:n,schemaEnv:i}=r;i.$async?t.throw((0,oe._)`new ${r.ValidationError}(${e})`):(t.assign((0,oe._)`${n}.errors`,e),t.return(!1))}var hn={keyword:new oe.Name("keyword"),schemaPath:new oe.Name("schemaPath"),params:new oe.Name("params"),propertyName:new oe.Name("propertyName"),message:new oe.Name("message"),schema:new oe.Name("schema"),parentSchema:new oe.Name("parentSchema")};function mp(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,oe._)`{}`:N0(r,e,t)}function N0(r,e,t={}){let{gen:n,it:i}=r,s=[L0(i,t),D0(r,t)];return q0(r,e,s),n.object(...s)}function L0({errorPath:r},{instancePath:e}){let t=e?(0,oe.str)`${r}${(0,wo.getErrorPath)(e,wo.Type.Str)}`:r;return[tt.default.instancePath,(0,oe.strConcat)(tt.default.instancePath,t)]}function D0({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let i=n?e:(0,oe.str)`${e}/${r}`;return t&&(i=(0,oe.str)`${i}${(0,wo.getErrorPath)(t,wo.Type.Str)}`),[hn.schemaPath,i]}function q0(r,{params:e,message:t},n){let{keyword:i,data:s,schemaValue:o,it:a}=r,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:d}=a;n.push([hn.keyword,i],[hn.params,typeof e=="function"?e(r):e||(0,oe._)`{}`]),c.messages&&n.push([hn.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([hn.schema,o],[hn.parentSchema,(0,oe._)`${u}${d}`],[tt.default.data,s]),l&&n.push([hn.propertyName,l])}});var gp=A(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.boolOrEmptySchema=Dn.topBoolOrEmptySchema=void 0;var j0=Hi(),F0=K(),V0=kt(),U0={message:"boolean schema is false"};function B0(r){let{gen:e,schema:t,validateName:n}=r;t===!1?yp(r,!1):typeof t=="object"&&t.$async===!0?e.return(V0.default.data):(e.assign((0,F0._)`${n}.errors`,null),e.return(!0))}Dn.topBoolOrEmptySchema=B0;function z0(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),yp(r)):t.var(e,!0)}Dn.boolOrEmptySchema=z0;function yp(r,e){let{gen:t,data:n}=r,i={gen:t,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:r};(0,j0.reportError)(i,U0,void 0,e)}});var Zc=A(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.getRules=qn.isJSONType=void 0;var H0=["string","number","integer","boolean","null","object","array"],K0=new Set(H0);function W0(r){return typeof r=="string"&&K0.has(r)}qn.isJSONType=W0;function G0(){let r={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...r,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},r.number,r.string,r.array,r.object],post:{rules:[]},all:{},keywords:{}}}qn.getRules=G0});var el=A(jr=>{"use strict";Object.defineProperty(jr,"__esModule",{value:!0});jr.shouldUseRule=jr.shouldUseGroup=jr.schemaHasRulesForType=void 0;function J0({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&bp(r,n)}jr.schemaHasRulesForType=J0;function bp(r,e){return e.rules.some(t=>_p(r,t))}jr.shouldUseGroup=bp;function _p(r,e){var t;return r[e.keyword]!==void 0||((t=e.definition.implements)===null||t===void 0?void 0:t.some(n=>r[n]!==void 0))}jr.shouldUseRule=_p});var Ki=A(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.reportTypeError=We.checkDataTypes=We.checkDataType=We.coerceAndCheckDataType=We.getJSONTypes=We.getSchemaTypes=We.DataType=void 0;var Y0=Zc(),X0=el(),Q0=Hi(),G=K(),wp=ee(),jn;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(jn||(We.DataType=jn={}));function Z0(r){let e=vp(r.type);if(e.includes("null")){if(r.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&r.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');r.nullable===!0&&e.push("null")}return e}We.getSchemaTypes=Z0;function vp(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(Y0.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}We.getJSONTypes=vp;function ev(r,e){let{gen:t,data:n,opts:i}=r,s=tv(e,i.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,X0.schemaHasRulesForType)(r,e[0]));if(o){let a=rl(e,n,i.strictNumbers,jn.Wrong);t.if(a,()=>{s.length?rv(r,e,s):nl(r)})}return o}We.coerceAndCheckDataType=ev;var $p=new Set(["string","number","integer","boolean","null"]);function tv(r,e){return e?r.filter(t=>$p.has(t)||e==="array"&&t==="array"):[]}function rv(r,e,t){let{gen:n,data:i,opts:s}=r,o=n.let("dataType",(0,G._)`typeof ${i}`),a=n.let("coerced",(0,G._)`undefined`);s.coerceTypes==="array"&&n.if((0,G._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,G._)`${i}[0]`).assign(o,(0,G._)`typeof ${i}`).if(rl(e,i,s.strictNumbers),()=>n.assign(a,i))),n.if((0,G._)`${a} !== undefined`);for(let l of t)($p.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),nl(r),n.endIf(),n.if((0,G._)`${a} !== undefined`,()=>{n.assign(i,a),nv(r,a)});function c(l){switch(l){case"string":n.elseIf((0,G._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,G._)`"" + ${i}`).elseIf((0,G._)`${i} === null`).assign(a,(0,G._)`""`);return;case"number":n.elseIf((0,G._)`${o} == "boolean" || ${i} === null + || (${o} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,G._)`+${i}`);return;case"integer":n.elseIf((0,G._)`${o} === "boolean" || ${i} === null + || (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,G._)`+${i}`);return;case"boolean":n.elseIf((0,G._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,G._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,G._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,G._)`${o} === "string" || ${o} === "number" + || ${o} === "boolean" || ${i} === null`).assign(a,(0,G._)`[${i}]`)}}}function nv({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,G._)`${e} !== undefined`,()=>r.assign((0,G._)`${e}[${t}]`,n))}function tl(r,e,t,n=jn.Correct){let i=n===jn.Correct?G.operators.EQ:G.operators.NEQ,s;switch(r){case"null":return(0,G._)`${e} ${i} null`;case"array":s=(0,G._)`Array.isArray(${e})`;break;case"object":s=(0,G._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,G._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,G._)`typeof ${e} ${i} ${r}`}return n===jn.Correct?s:(0,G.not)(s);function o(a=G.nil){return(0,G.and)((0,G._)`typeof ${e} == "number"`,a,t?(0,G._)`isFinite(${e})`:G.nil)}}We.checkDataType=tl;function rl(r,e,t,n){if(r.length===1)return tl(r[0],e,t,n);let i,s=(0,wp.toHash)(r);if(s.array&&s.object){let o=(0,G._)`typeof ${e} != "object"`;i=s.null?o:(0,G._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=G.nil;s.number&&delete s.integer;for(let o in s)i=(0,G.and)(i,tl(o,e,t,n));return i}We.checkDataTypes=rl;var iv={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,G._)`{type: ${r}}`:(0,G._)`{type: ${e}}`};function nl(r){let e=sv(r);(0,Q0.reportError)(e,iv)}We.reportTypeError=nl;function sv(r){let{gen:e,data:t,schema:n}=r,i=(0,wp.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var Ep=A(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.assignDefaults=void 0;var Fn=K(),ov=ee();function av(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)Sp(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>Sp(r,s,i.default))}vo.assignDefaults=av;function Sp(r,e,t){let{gen:n,compositeRule:i,data:s,opts:o}=r;if(t===void 0)return;let a=(0,Fn._)`${s}${(0,Fn.getProperty)(e)}`;if(i){(0,ov.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,Fn._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,Fn._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Fn._)`${a} = ${(0,Fn.stringify)(t)}`)}});var xt=A(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.validateUnion=he.validateArray=he.usePattern=he.callValidateCode=he.schemaProperties=he.allSchemaProperties=he.noPropertyInData=he.propertyInData=he.isOwnProperty=he.hasPropFunc=he.reportMissingProp=he.checkMissingProp=he.checkReportMissingProp=void 0;var _e=K(),il=ee(),Fr=kt(),cv=ee();function lv(r,e){let{gen:t,data:n,it:i}=r;t.if(ol(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,_e._)`${e}`},!0),r.error()})}he.checkReportMissingProp=lv;function dv({gen:r,data:e,it:{opts:t}},n,i){return(0,_e.or)(...n.map(s=>(0,_e.and)(ol(r,e,s,t.ownProperties),(0,_e._)`${i} = ${s}`)))}he.checkMissingProp=dv;function uv(r,e){r.setParams({missingProperty:e},!0),r.error()}he.reportMissingProp=uv;function Ap(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,_e._)`Object.prototype.hasOwnProperty`})}he.hasPropFunc=Ap;function sl(r,e,t){return(0,_e._)`${Ap(r)}.call(${e}, ${t})`}he.isOwnProperty=sl;function fv(r,e,t,n){let i=(0,_e._)`${e}${(0,_e.getProperty)(t)} !== undefined`;return n?(0,_e._)`${i} && ${sl(r,e,t)}`:i}he.propertyInData=fv;function ol(r,e,t,n){let i=(0,_e._)`${e}${(0,_e.getProperty)(t)} === undefined`;return n?(0,_e.or)(i,(0,_e.not)(sl(r,e,t))):i}he.noPropertyInData=ol;function kp(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}he.allSchemaProperties=kp;function pv(r,e){return kp(e).filter(t=>!(0,il.alwaysValidSchema)(r,e[t]))}he.schemaProperties=pv;function hv({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,c,l){let u=l?(0,_e._)`${r}, ${e}, ${n}${i}`:e,d=[[Fr.default.instancePath,(0,_e.strConcat)(Fr.default.instancePath,s)],[Fr.default.parentData,o.parentData],[Fr.default.parentDataProperty,o.parentDataProperty],[Fr.default.rootData,Fr.default.rootData]];o.opts.dynamicRef&&d.push([Fr.default.dynamicAnchors,Fr.default.dynamicAnchors]);let f=(0,_e._)`${u}, ${t.object(...d)}`;return c!==_e.nil?(0,_e._)`${a}.call(${c}, ${f})`:(0,_e._)`${a}(${f})`}he.callValidateCode=hv;var mv=(0,_e._)`new RegExp`;function yv({gen:r,it:{opts:e}},t){let n=e.unicodeRegExp?"u":"",{regExp:i}=e.code,s=i(t,n);return r.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,_e._)`${i.code==="new RegExp"?mv:(0,cv.useFunc)(r,i)}(${t}, ${n})`})}he.usePattern=yv;function gv(r){let{gen:e,data:t,keyword:n,it:i}=r,s=e.name("valid");if(i.allErrors){let a=e.let("valid",!0);return o(()=>e.assign(a,!1)),a}return e.var(s,!0),o(()=>e.break()),s;function o(a){let c=e.const("len",(0,_e._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:il.Type.Num},s),e.if((0,_e.not)(s),a)})}}he.validateArray=gv;function bv(r){let{gen:e,schema:t,keyword:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(t.some(c=>(0,il.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let o=e.let("valid",!1),a=e.name("_valid");e.block(()=>t.forEach((c,l)=>{let u=r.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(o,(0,_e._)`${o} || ${a}`),r.mergeValidEvaluated(u,a)||e.if((0,_e.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}he.validateUnion=bv});var Ip=A(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.validateKeywordUsage=sr.validSchemaType=sr.funcKeywordCode=sr.macroKeywordCode=void 0;var rt=K(),mn=kt(),_v=xt(),wv=Hi();function vv(r,e){let{gen:t,keyword:n,schema:i,parentSchema:s,it:o}=r,a=e.macro.call(o.self,i,s,o),c=Pp(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:rt.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}sr.macroKeywordCode=vv;function $v(r,e){var t;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=r;Ev(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,u=Pp(n,i,l),d=n.let("valid");r.block$data(d,f),r.ok((t=e.valid)!==null&&t!==void 0?t:d);function f(){if(e.errors===!1)h(),e.modifying&&xp(r),y(()=>r.error());else{let b=e.async?p():m();e.modifying&&xp(r),y(()=>Sv(r,b))}}function p(){let b=n.let("ruleErrs",null);return n.try(()=>h((0,rt._)`await `),g=>n.assign(d,!1).if((0,rt._)`${g} instanceof ${c.ValidationError}`,()=>n.assign(b,(0,rt._)`${g}.errors`),()=>n.throw(g))),b}function m(){let b=(0,rt._)`${u}.errors`;return n.assign(b,null),h(rt.nil),b}function h(b=e.async?(0,rt._)`await `:rt.nil){let g=c.opts.passContext?mn.default.this:mn.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,rt._)`${b}${(0,_v.callValidateCode)(r,u,g,_)}`,e.modifying)}function y(b){var g;n.if((0,rt.not)((g=e.valid)!==null&&g!==void 0?g:d),b)}}sr.funcKeywordCode=$v;function xp(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,rt._)`${n.parentData}[${n.parentDataProperty}]`))}function Sv(r,e){let{gen:t}=r;t.if((0,rt._)`Array.isArray(${e})`,()=>{t.assign(mn.default.vErrors,(0,rt._)`${mn.default.vErrors} === null ? ${e} : ${mn.default.vErrors}.concat(${e})`).assign(mn.default.errors,(0,rt._)`${mn.default.vErrors}.length`),(0,wv.extendErrors)(r)},()=>r.error())}function Ev({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function Pp(r,e,t){if(t===void 0)throw new Error(`keyword "${e}" failed to compile`);return r.scopeValue("keyword",typeof t=="function"?{ref:t}:{ref:t,code:(0,rt.stringify)(t)})}function Av(r,e,t=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(r):n==="object"?r&&typeof r=="object"&&!Array.isArray(r):typeof r==n||t&&typeof r=="undefined")}sr.validSchemaType=Av;function kv({schema:r,opts:e,self:t,errSchemaPath:n},i,s){if(Array.isArray(i.keyword)?!i.keyword.includes(s):i.keyword!==s)throw new Error("ajv implementation error");let o=i.dependencies;if(o!=null&&o.some(a=>!Object.prototype.hasOwnProperty.call(r,a)))throw new Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(i.validateSchema&&!i.validateSchema(r[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+t.errorsText(i.validateSchema.errors);if(e.validateSchema==="log")t.logger.error(c);else throw new Error(c)}}sr.validateKeywordUsage=kv});var Tp=A(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.extendSubschemaMode=Vr.extendSubschemaData=Vr.getSubschema=void 0;var or=K(),Op=ee();function xv(r,{keyword:e,schemaProp:t,schema:n,schemaPath:i,errSchemaPath:s,topSchemaRef:o}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=r.schema[e];return t===void 0?{schema:a,schemaPath:(0,or._)`${r.schemaPath}${(0,or.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,or._)`${r.schemaPath}${(0,or.getProperty)(e)}${(0,or.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,Op.escapeFragment)(t)}`}}if(n!==void 0){if(i===void 0||s===void 0||o===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:o,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Vr.getSubschema=xv;function Pv(r,e,{dataProp:t,dataPropType:n,data:i,dataTypes:s,propertyName:o}){if(i!==void 0&&t!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(t!==void 0){let{errorPath:l,dataPathArr:u,opts:d}=e,f=a.let("data",(0,or._)`${e.data}${(0,or.getProperty)(t)}`,!0);c(f),r.errorPath=(0,or.str)`${l}${(0,Op.getErrorPath)(t,n,d.jsPropertySyntax)}`,r.parentDataProperty=(0,or._)`${t}`,r.dataPathArr=[...u,r.parentDataProperty]}if(i!==void 0){let l=i instanceof or.Name?i:a.let("data",i,!0);c(l),o!==void 0&&(r.propertyName=o)}s&&(r.dataTypes=s);function c(l){r.data=l,r.dataLevel=e.dataLevel+1,r.dataTypes=[],e.definedProperties=new Set,r.parentData=e.data,r.dataNames=[...e.dataNames,l]}}Vr.extendSubschemaData=Pv;function Iv(r,{jtdDiscriminator:e,jtdMetadata:t,compositeRule:n,createErrors:i,allErrors:s}){n!==void 0&&(r.compositeRule=n),i!==void 0&&(r.createErrors=i),s!==void 0&&(r.allErrors=s),r.jtdDiscriminator=e,r.jtdMetadata=t}Vr.extendSubschemaMode=Iv});var al=A((OC,Rp)=>{"use strict";Rp.exports=function r(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var n,i,s;if(Array.isArray(e)){if(n=e.length,n!=t.length)return!1;for(i=n;i--!==0;)if(!r(e[i],t[i]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(t).length)return!1;for(i=n;i--!==0;)if(!Object.prototype.hasOwnProperty.call(t,s[i]))return!1;for(i=n;i--!==0;){var o=s[i];if(!r(e[o],t[o]))return!1}return!0}return e!==e&&t!==t}});var Mp=A((TC,Cp)=>{"use strict";var Ur=Cp.exports=function(r,e,t){typeof e=="function"&&(t=e,e={}),t=e.cb||t;var n=typeof t=="function"?t:t.pre||function(){},i=t.post||function(){};$o(e,n,i,r,"",r)};Ur.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Ur.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ur.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ur.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 $o(r,e,t,n,i,s,o,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,i,s,o,a,c,l);for(var u in n){var d=n[u];if(Array.isArray(d)){if(u in Ur.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.getSchemaRefs=ut.resolveUrl=ut.normalizeId=ut._getFullPath=ut.getFullPath=ut.inlineRef=void 0;var Tv=ee(),Rv=al(),Cv=Mp(),Mv=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function Nv(r,e=!0){return typeof r=="boolean"?!0:e===!0?!cl(r):e?Np(r)<=e:!1}ut.inlineRef=Nv;var Lv=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function cl(r){for(let e in r){if(Lv.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(cl)||typeof t=="object"&&cl(t))return!0}return!1}function Np(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!Mv.has(t)&&(typeof r[t]=="object"&&(0,Tv.eachItem)(r[t],n=>e+=Np(n)),e===1/0))return 1/0}return e}function Lp(r,e="",t){t!==!1&&(e=Vn(e));let n=r.parse(e);return Dp(r,n)}ut.getFullPath=Lp;function Dp(r,e){return r.serialize(e).split("#")[0]+"#"}ut._getFullPath=Dp;var Dv=/#\/?$/;function Vn(r){return r?r.replace(Dv,""):""}ut.normalizeId=Vn;function qv(r,e,t){return t=Vn(t),r.resolve(e,t)}ut.resolveUrl=qv;var jv=/^[a-z_][-a-z0-9._]*$/i;function Fv(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=Vn(r[t]||e),s={"":i},o=Lp(n,i,!1),a={},c=new Set;return Cv(r,{allKeys:!0},(d,f,p,m)=>{if(m===void 0)return;let h=o+f,y=s[m];typeof d[t]=="string"&&(y=b.call(this,d[t])),g.call(this,d.$anchor),g.call(this,d.$dynamicAnchor),s[f]=y;function b(_){let k=this.opts.uriResolver.resolve;if(_=Vn(y?k(y,_):_),c.has(_))throw u(_);c.add(_);let v=this.refs[_];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?l(d,v.schema,_):_!==Vn(h)&&(_[0]==="#"?(l(d,a[_],_),a[_]=d):this.refs[_]=h),_}function g(_){if(typeof _=="string"){if(!jv.test(_))throw new Error(`invalid anchor "${_}"`);b.call(this,`#${_}`)}}}),a;function l(d,f,p){if(f!==void 0&&!Rv(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}ut.getSchemaRefs=Fv});var Un=A(Br=>{"use strict";Object.defineProperty(Br,"__esModule",{value:!0});Br.getData=Br.KeywordCxt=Br.validateFunctionCode=void 0;var Up=gp(),qp=Ki(),dl=el(),So=Ki(),Vv=Ep(),Ji=Ip(),ll=Tp(),B=K(),H=kt(),Uv=Wi(),vr=ee(),Gi=Hi();function Bv(r){if(Hp(r)&&(Kp(r),zp(r))){Kv(r);return}Bp(r,()=>(0,Up.topBoolOrEmptySchema)(r))}Br.validateFunctionCode=Bv;function Bp({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},s){i.code.es5?r.func(e,(0,B._)`${H.default.data}, ${H.default.valCxt}`,n.$async,()=>{r.code((0,B._)`"use strict"; ${jp(t,i)}`),Hv(r,i),r.code(s)}):r.func(e,(0,B._)`${H.default.data}, ${zv(i)}`,n.$async,()=>r.code(jp(t,i)).code(s))}function zv(r){return(0,B._)`{${H.default.instancePath}="", ${H.default.parentData}, ${H.default.parentDataProperty}, ${H.default.rootData}=${H.default.data}${r.dynamicRef?(0,B._)`, ${H.default.dynamicAnchors}={}`:B.nil}}={}`}function Hv(r,e){r.if(H.default.valCxt,()=>{r.var(H.default.instancePath,(0,B._)`${H.default.valCxt}.${H.default.instancePath}`),r.var(H.default.parentData,(0,B._)`${H.default.valCxt}.${H.default.parentData}`),r.var(H.default.parentDataProperty,(0,B._)`${H.default.valCxt}.${H.default.parentDataProperty}`),r.var(H.default.rootData,(0,B._)`${H.default.valCxt}.${H.default.rootData}`),e.dynamicRef&&r.var(H.default.dynamicAnchors,(0,B._)`${H.default.valCxt}.${H.default.dynamicAnchors}`)},()=>{r.var(H.default.instancePath,(0,B._)`""`),r.var(H.default.parentData,(0,B._)`undefined`),r.var(H.default.parentDataProperty,(0,B._)`undefined`),r.var(H.default.rootData,H.default.data),e.dynamicRef&&r.var(H.default.dynamicAnchors,(0,B._)`{}`)})}function Kv(r){let{schema:e,opts:t,gen:n}=r;Bp(r,()=>{t.$comment&&e.$comment&&Gp(r),Xv(r),n.let(H.default.vErrors,null),n.let(H.default.errors,0),t.unevaluated&&Wv(r),Wp(r),e$(r)})}function Wv(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,B._)`${t}.evaluated`),e.if((0,B._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,B._)`${r.evaluated}.props`,(0,B._)`undefined`)),e.if((0,B._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,B._)`${r.evaluated}.items`,(0,B._)`undefined`))}function jp(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,B._)`/*# sourceURL=${t} */`:B.nil}function Gv(r,e){if(Hp(r)&&(Kp(r),zp(r))){Jv(r,e);return}(0,Up.boolOrEmptySchema)(r,e)}function zp({schema:r,self:e}){if(typeof r=="boolean")return!r;for(let t in r)if(e.RULES.all[t])return!0;return!1}function Hp(r){return typeof r.schema!="boolean"}function Jv(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&Gp(r),Qv(r),Zv(r);let s=n.const("_errs",H.default.errors);Wp(r,s),n.var(e,(0,B._)`${s} === ${H.default.errors}`)}function Kp(r){(0,vr.checkUnknownRules)(r),Yv(r)}function Wp(r,e){if(r.opts.jtd)return Fp(r,[],!1,e);let t=(0,qp.getSchemaTypes)(r.schema),n=(0,qp.coerceAndCheckDataType)(r,t);Fp(r,t,!n,e)}function Yv(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,vr.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function Xv(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,vr.checkStrictMode)(r,"default is ignored in the schema root")}function Qv(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,Uv.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function Zv(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function Gp({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let s=t.$comment;if(i.$comment===!0)r.code((0,B._)`${H.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,B.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,B._)`${H.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function e$(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:i,opts:s}=r;t.$async?e.if((0,B._)`${H.default.errors} === 0`,()=>e.return(H.default.data),()=>e.throw((0,B._)`new ${i}(${H.default.vErrors})`)):(e.assign((0,B._)`${n}.errors`,H.default.vErrors),s.unevaluated&&t$(r),e.return((0,B._)`${H.default.errors} === 0`))}function t$({gen:r,evaluated:e,props:t,items:n}){t instanceof B.Name&&r.assign((0,B._)`${e}.props`,t),n instanceof B.Name&&r.assign((0,B._)`${e}.items`,n)}function Fp(r,e,t,n){let{gen:i,schema:s,data:o,allErrors:a,opts:c,self:l}=r,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,vr.schemaHasRulesButRef)(s,u))){i.block(()=>Yp(r,"$ref",u.all.$ref.definition));return}c.jtd||r$(r,e),i.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,dl.shouldUseGroup)(s,f)&&(f.type?(i.if((0,So.checkDataType)(f.type,o,c.strictNumbers)),Vp(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,So.reportTypeError)(r)),i.endIf()):Vp(r,f),a||i.if((0,B._)`${H.default.errors} === ${n||0}`))}}function Vp(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,Vv.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,dl.shouldUseRule)(n,s)&&Yp(r,s.keyword,s.definition,e.type)})}function r$(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(n$(r,e),r.opts.allowUnionTypes||i$(r,e),s$(r,r.dataTypes))}function n$(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{Jp(r.dataTypes,t)||ul(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),a$(r,e)}}function i$(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&ul(r,"use allowUnionTypes to allow union type keyword")}function s$(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,dl.shouldUseRule)(r.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>o$(e,o))&&ul(r,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function o$(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function Jp(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function a$(r,e){let t=[];for(let n of r.dataTypes)Jp(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function ul(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,vr.checkStrictMode)(r,e,r.opts.strictTypes)}var Eo=class{constructor(e,t,n){if((0,Ji.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,vr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",Xp(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ji.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);("code"in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const("_errs",H.default.errors))}result(e,t,n){this.failResult((0,B.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,B.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,B._)`${t} !== undefined && (${(0,B.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?Gi.reportExtraError:Gi.reportError)(this,this.def.error,t)}$dataError(){(0,Gi.reportError)(this,this.def.$dataError||Gi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Gi.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=B.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=B.nil,t=B.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:s,def:o}=this;n.if((0,B.or)((0,B._)`${i} === undefined`,t)),e!==B.nil&&n.assign(e,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==B.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:i,it:s}=this;return(0,B.or)(o(),a());function o(){if(n.length){if(!(t instanceof B.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,B._)`${(0,So.checkDataTypes)(c,t,s.opts.strictNumbers,So.DataType.Wrong)}`}return B.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,B._)`!${c}(${t})`}return B.nil}}subschema(e,t){let n=(0,ll.getSubschema)(this.it,e);(0,ll.extendSubschemaData)(n,this.it,e),(0,ll.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return Gv(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=vr.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=vr.mergeEvaluated.items(i,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:i}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return i.if(t,()=>this.mergeEvaluated(e,B.Name)),!0}};Br.KeywordCxt=Eo;function Yp(r,e,t,n){let i=new Eo(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,Ji.funcKeywordCode)(i,t):"macro"in t?(0,Ji.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,Ji.funcKeywordCode)(i,t)}var c$=/^\/(?:[^~]|~0|~1)*$/,l$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Xp(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,s;if(r==="")return H.default.rootData;if(r[0]==="/"){if(!c$.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,s=H.default.rootData}else{let l=l$.exec(r);if(!l)throw new Error(`Invalid JSON-pointer: ${r}`);let u=+l[1];if(i=l[2],i==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(s=t[e-u],!i)return s}let o=s,a=i.split("/");for(let l of a)l&&(s=(0,B._)`${s}${(0,B.getProperty)((0,vr.unescapeJsonPointer)(l))}`,o=(0,B._)`${o} && ${s}`);return o;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Br.getData=Xp});var Yi=A(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});var fl=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};pl.default=fl});var Bn=A(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});var hl=Wi(),ml=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,hl.resolveUrl)(e,t,n),this.missingSchema=(0,hl.normalizeId)((0,hl.getFullPath)(e,this.missingRef))}};yl.default=ml});var Xi=A(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.resolveSchema=Pt.getCompilingSchema=Pt.resolveRef=Pt.compileSchema=Pt.SchemaEnv=void 0;var qt=K(),d$=Yi(),yn=kt(),jt=Wi(),Qp=ee(),u$=Un(),zn=class{constructor(e){var t;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,jt.normalizeId)(n==null?void 0:n[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n==null?void 0:n.$async,this.refs={}}};Pt.SchemaEnv=zn;function bl(r){let e=Zp.call(this,r);if(e)return e;let t=(0,jt.getFullPath)(this.opts.uriResolver,r.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new qt.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;r.$async&&(a=o.scopeValue("Error",{ref:d$.default,code:(0,qt._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");r.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:yn.default.data,parentData:yn.default.parentData,parentDataProperty:yn.default.parentDataProperty,dataNames:[yn.default.data],dataPathArr:[qt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,qt.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:qt.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,qt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(r),(0,u$.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let d=o.toString();u=`${o.scopeRefs(yn.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,r));let p=new Function(`${yn.default.self}`,`${yn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=r.schema,p.schemaEnv=r,r.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:d,scopeValues:o._values}),this.opts.unevaluated){let{props:m,items:h}=l;p.evaluated={props:m instanceof qt.Name?void 0:m,items:h instanceof qt.Name?void 0:h,dynamicProps:m instanceof qt.Name,dynamicItems:h instanceof qt.Name},p.source&&(p.source.evaluated=(0,qt.stringify)(p.evaluated))}return r.validate=p,r}catch(d){throw delete r.validate,delete r.validateName,u&&this.logger.error("Error compiling schema, function code:",u),d}finally{this._compilations.delete(r)}}Pt.compileSchema=bl;function f$(r,e,t){var n;t=(0,jt.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let s=m$.call(this,r,t);if(s===void 0){let o=(n=r.localRefs)===null||n===void 0?void 0:n[t],{schemaId:a}=this.opts;o&&(s=new zn({schema:o,schemaId:a,root:r,baseId:e}))}if(s!==void 0)return r.refs[t]=p$.call(this,s)}Pt.resolveRef=f$;function p$(r){return(0,jt.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:bl.call(this,r)}function Zp(r){for(let e of this._compilations)if(h$(e,r))return e}Pt.getCompilingSchema=Zp;function h$(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function m$(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Ao.call(this,r,e)}function Ao(r,e){let t=this.opts.uriResolver.parse(e),n=(0,jt._getFullPath)(this.opts.uriResolver,t),i=(0,jt.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return gl.call(this,t,r);let s=(0,jt.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=Ao.call(this,r,o);return typeof(a==null?void 0:a.schema)!="object"?void 0:gl.call(this,t,a)}if(typeof(o==null?void 0:o.schema)=="object"){if(o.validate||bl.call(this,o),s===(0,jt.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,jt.resolveUrl)(this.opts.uriResolver,i,l)),new zn({schema:a,schemaId:c,root:r,baseId:i})}return gl.call(this,t,o)}}Pt.resolveSchema=Ao;var y$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function gl(r,{baseId:e,schema:t,root:n}){var i;if(((i=r.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of r.fragment.slice(1).split("/")){if(typeof t=="boolean")return;let c=t[(0,Qp.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!y$.has(a)&&l&&(e=(0,jt.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,Qp.schemaHasRulesButRef)(t,this.RULES)){let a=(0,jt.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=Ao.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new zn({schema:t,schemaId:o,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var eh=A((DC,g$)=>{g$.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 vl=A((qC,oh)=>{"use strict";var b$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),rh=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),_l=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),nh=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),_$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function wl(r){let e="",t=0,n=0;for(n=0;n=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[n];break}for(n+=1;n=48&&t<=57||t>=65&&t<=70||t>=97&&t<=102))return"";e+=r[n]}return e}var w$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function th(r){return r.length=0,!0}function v$(r,e,t){if(r.length){let n=wl(r);if(n!=="")e.push(n);else return t.error=!0,!1;r.length=0}return!0}function $$(r){let e=0,t={error:!1,address:"",zone:""},n=[],i=[],s=!1,o=!1,a=v$;for(let c=0;c7){t.error=!0;break}c>0&&r[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(i,n,t))break;a=th}else{i.push(l);continue}}return i.length&&(a===th?t.zone=i.join(""):o?n.push(i.join("")):n.push(wl(i))),t.address=n.join(""),t}function ih(r){if(S$(r,":")<2)return{host:r,isIPV6:!1};let e=$$(r);if(e.error)return{host:r,isIPV6:!1};{let t=e.address,n=e.address;return e.zone&&(t+="%"+e.zone,n+="%25"+e.zone),{host:t,isIPV6:!0,escapedHost:n}}}function S$(r,e){let t=0;for(let n=0;nA$[n])}function P$(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n{"use strict";var{isUUID:R$}=vl(),C$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,M$=["http","https","ws","wss","urn","urn:uuid"];function N$(r){return M$.indexOf(r)!==-1}function $l(r){return r.secure===!0?!0:r.secure===!1?!1:r.scheme?r.scheme.length===3&&(r.scheme[0]==="w"||r.scheme[0]==="W")&&(r.scheme[1]==="s"||r.scheme[1]==="S")&&(r.scheme[2]==="s"||r.scheme[2]==="S"):!1}function ah(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function ch(r){let e=String(r.scheme).toLowerCase()==="https";return(r.port===(e?443:80)||r.port==="")&&(r.port=void 0),r.path||(r.path="/"),r}function L$(r){return r.secure=$l(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function D$(r){if((r.port===($l(r)?443:80)||r.port==="")&&(r.port=void 0),typeof r.secure=="boolean"&&(r.scheme=r.secure?"wss":"ws",r.secure=void 0),r.resourceName){let[e,t]=r.resourceName.split("?");r.path=e&&e!=="/"?e:void 0,r.query=t,r.resourceName=void 0}return r.fragment=void 0,r}function q$(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(C$);if(t){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let i=`${n}:${e.nid||r.nid}`,s=Sl(i);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function j$(r,e){if(r.nid===void 0)throw new Error("URN without nid cannot be serialized");let t=e.scheme||r.scheme||"urn",n=r.nid.toLowerCase(),i=`${t}:${e.nid||n}`,s=Sl(i);s&&(r=s.serialize(r,e));let o=r,a=r.nss;return o.path=`${n||e.nid}:${a}`,e.skipEscape=!0,o}function F$(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!R$(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function V$(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var lh={scheme:"http",domainHost:!0,parse:ah,serialize:ch},U$={scheme:"https",domainHost:lh.domainHost,parse:ah,serialize:ch},ko={scheme:"ws",domainHost:!0,parse:L$,serialize:D$},B$={scheme:"wss",domainHost:ko.domainHost,parse:ko.parse,serialize:ko.serialize},z$={scheme:"urn",parse:q$,serialize:j$,skipNormalize:!0},H$={scheme:"urn:uuid",parse:F$,serialize:V$,skipNormalize:!0},xo={http:lh,https:U$,ws:ko,wss:B$,urn:z$,"urn:uuid":H$};Object.setPrototypeOf(xo,null);function Sl(r){return r&&(xo[r]||xo[r.toLowerCase()])||void 0}dh.exports={wsIsSecure:$l,SCHEMES:xo,isValidSchemeName:N$,getSchemeHandler:Sl}});var yh=A((FC,Oo)=>{"use strict";var{normalizeIPv6:K$,removeDotSegments:Qi,recomposeAuthority:W$,normalizePercentEncoding:G$,normalizePathEncoding:J$,escapePreservingEscapes:Y$,reescapeHostDelimiters:X$,isIPv4:Q$,nonSimpleDomain:Z$}=vl(),{SCHEMES:eS,getSchemeHandler:ph}=uh();function tS(r,e){return typeof r=="string"?r=cS(r,e):typeof r=="object"&&(r=Io(gn(r,e),e)),r}function rS(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:s}=Po(r,n),{parsed:o,malformedAuthorityOrPort:a}=Po(e,n);if(s||a)throw new Error(i.error||o.error||"URI is malformed.");let c=hh(i,o,n,!0);return n.skipEscape=!0,gn(c,n)}function hh(r,e,t,n){let i={};return n||(r=Io(gn(r,t),t),e=Io(gn(e,t),t)),t=t||{},!t.tolerant&&e.scheme?(i.scheme=e.scheme,i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=Qi(e.path||""),i.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(i.userinfo=e.userinfo,i.host=e.host,i.port=e.port,i.path=Qi(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=Qi(e.path):((r.userinfo!==void 0||r.host!==void 0||r.port!==void 0)&&!r.path?i.path="/"+e.path:r.path?i.path=r.path.slice(0,r.path.lastIndexOf("/")+1)+e.path:i.path=e.path,i.path=Qi(i.path)),i.query=e.query):(i.path=r.path,e.query!==void 0?i.query=e.query:i.query=r.query),i.userinfo=r.userinfo,i.host=r.host,i.port=r.port),i.scheme=r.scheme),i.fragment=e.fragment,i}function nS(r,e,t){let n=fh(r,t),i=fh(e,t);return n!==void 0&&i!==void 0&&n.toLowerCase()===i.toLowerCase()}function gn(r,e){let t={host:r.host,scheme:r.scheme,userinfo:r.userinfo,port:r.port,path:r.path,query:r.query,nid:r.nid,nss:r.nss,uuid:r.uuid,fragment:r.fragment,reference:r.reference,resourceName:r.resourceName,secure:r.secure,error:""},n=Object.assign({},e),i=[],s=ph(n.scheme||t.scheme);s&&s.serialize&&s.serialize(t,n),t.path!==void 0&&(n.skipEscape?t.path=G$(t.path):(t.path=Y$(t.path),t.scheme!==void 0&&(t.path=t.path.split("%3A").join(":")))),n.reference!=="suffix"&&t.scheme&&i.push(t.scheme,":");let o=W$(t);if(o!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(o),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let a=t.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Qi(a)),o===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),i.push(a)}return t.query!==void 0&&i.push("?",t.query),t.fragment!==void 0&&i.push("#",t.fragment),i.join("")}var iS=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,sS=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,oS=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function aS(r,e){if(e[2]!==void 0&&r.path&&r.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof r.port=="number"&&(r.port<0||r.port>65535))return"URI port is malformed."}function Po(r,e){let t=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},i=!1,s=!1;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let o=r.match(sS);o!==null&&o[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let a=r.match(oS);if(a!==null){let l=a[1],u=l.replace(/[\t\n\r]/g,"");u.length>=2&&(u.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):l.length!==u.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let c=r.match(iS);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 l=aS(n,c);if(l!==void 0&&(n.error=n.error||l,i=!0),n.host)if(Q$(n.host)===!1){let f=K$(n.host);n.host=f.host.toLowerCase(),s=f.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",t.reference&&t.reference!=="suffix"&&t.reference!==n.reference&&(n.error=n.error||"URI is not a "+t.reference+" reference.");let u=ph(t.scheme||n.scheme);if(!t.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(t.domainHost||u&&u.domainHost)&&s===!1&&Z$(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(d){n.error=n.error||"Host's domain name can not be converted to ASCII: "+d}if((!u||u&&!u.skipNormalize)&&(r.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=X$(unescape(n.host),s))),n.path&&(n.path=J$(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch(d){n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,t)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i}}function Io(r,e){return Po(r,e).parsed}function cS(r,e){return mh(r,e).normalized}function mh(r,e){let{parsed:t,malformedAuthorityOrPort:n}=Po(r,e);return{normalized:n?r:gn(t,e),malformedAuthorityOrPort:n}}function fh(r,e){if(typeof r=="string"){let{normalized:t,malformedAuthorityOrPort:n}=mh(r,e);return n?void 0:t}if(typeof r=="object")return gn(r,e)}var El={SCHEMES:eS,normalize:tS,resolve:rS,resolveComponent:hh,equal:nS,serialize:gn,parse:Io};Oo.exports=El;Oo.exports.default=El;Oo.exports.fastUri=El});var bh=A(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});var gh=yh();gh.code='require("ajv/dist/runtime/uri").default';Al.default=gh});var Pl=A(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.CodeGen=Fe.Name=Fe.nil=Fe.stringify=Fe.str=Fe._=Fe.KeywordCxt=void 0;var lS=Un();Object.defineProperty(Fe,"KeywordCxt",{enumerable:!0,get:function(){return lS.KeywordCxt}});var Hn=K();Object.defineProperty(Fe,"_",{enumerable:!0,get:function(){return Hn._}});Object.defineProperty(Fe,"str",{enumerable:!0,get:function(){return Hn.str}});Object.defineProperty(Fe,"stringify",{enumerable:!0,get:function(){return Hn.stringify}});Object.defineProperty(Fe,"nil",{enumerable:!0,get:function(){return Hn.nil}});Object.defineProperty(Fe,"Name",{enumerable:!0,get:function(){return Hn.Name}});Object.defineProperty(Fe,"CodeGen",{enumerable:!0,get:function(){return Hn.CodeGen}});var dS=Yi(),Sh=Bn(),uS=Zc(),Zi=Xi(),fS=K(),es=Wi(),To=Ki(),xl=ee(),_h=eh(),pS=bh(),Eh=(r,e)=>new RegExp(r,e);Eh.code="new RegExp";var hS=["removeAdditional","useDefaults","coerceTypes"],mS=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),yS={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."},gS={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},wh=200;function bS(r){var e,t,n,i,s,o,a,c,l,u,d,f,p,m,h,y,b,g,_,k,v,E,O,w,x;let $=r.strict,L=(e=r.code)===null||e===void 0?void 0:e.optimize,F=L===!0||L===void 0?1:L||0,z=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:Eh,P=(i=r.uriResolver)!==null&&i!==void 0?i:pS.default;return{strictSchema:(o=(s=r.strictSchema)!==null&&s!==void 0?s:$)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=r.strictNumbers)!==null&&a!==void 0?a:$)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=r.strictTypes)!==null&&l!==void 0?l:$)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=r.strictTuples)!==null&&d!==void 0?d:$)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=r.strictRequired)!==null&&p!==void 0?p:$)!==null&&m!==void 0?m:!1,code:r.code?{...r.code,optimize:F,regExp:z}:{optimize:F,regExp:z},loopRequired:(h=r.loopRequired)!==null&&h!==void 0?h:wh,loopEnum:(y=r.loopEnum)!==null&&y!==void 0?y:wh,meta:(b=r.meta)!==null&&b!==void 0?b:!0,messages:(g=r.messages)!==null&&g!==void 0?g:!0,inlineRefs:(_=r.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(k=r.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(v=r.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(E=r.validateSchema)!==null&&E!==void 0?E:!0,validateFormats:(O=r.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(w=r.unicodeRegExp)!==null&&w!==void 0?w:!0,int32range:(x=r.int32range)!==null&&x!==void 0?x:!0,uriResolver:P}}var ts=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...bS(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new fS.ValueScope({scope:{},prefixes:mS,es5:t,lines:n}),this.logger=ES(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,uS.getRules)(),vh.call(this,yS,e,"NOT SUPPORTED"),vh.call(this,gS,e,"DEPRECATED","warn"),this._metaOpts=$S.call(this),e.formats&&wS.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&vS.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),_S.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=_h;n==="id"&&(i={..._h},i.id=i.$id,delete i.$id),t&&e&&this.addMetaSchema(i,i[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let i=n(t);return"$async"in n||(this.errors=n.errors),i}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return i.call(this,e,t);async function i(u,d){await s.call(this,u.$schema);let f=this._addSchema(u,d);return f.validate||o.call(this,f)}async function s(u){u&&!this.getSchema(u)&&await i.call(this,{$ref:u},!0)}async function o(u){try{return this._compileSchemaEnv(u)}catch(d){if(!(d instanceof Sh.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),o.call(this,u)}}function a({missingSchema:u,missingRef:d}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${d} cannot be resolved`)}async function c(u){let d=await l.call(this,u);this.refs[u]||await s.call(this,d.$schema),this.refs[u]||this.addSchema(d,u,t)}async function l(u){let d=this._loading[u];if(d)return d;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,t,n,i=this.opts.validateSchema){if(Array.isArray(e)){for(let o of e)this.addSchema(o,void 0,n,i);return this}let s;if(typeof e=="object"){let{schemaId:o}=this.opts;if(s=e[o],s!==void 0&&typeof s!="string")throw new Error(`schema ${o} must be string`)}return t=(0,es.normalizeId)(t||s),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,i,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw 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 i=this.validate(n,e);if(!i&&t){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return i}getSchema(e){let t;for(;typeof(t=$h.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new Zi.SchemaEnv({schema:{},schemaId:n});if(t=Zi.resolveSchema.call(this,i,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let t=$h.call(this,e);return typeof t=="object"&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,es.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e=="string")n=e,typeof t=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=n);else if(typeof e=="object"&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(kS.call(this,n,t),!t)return(0,xl.eachItem)(n,s=>kl.call(this,s)),this;PS.call(this,t);let i={...t,type:(0,To.getJSONTypes)(t.type),schemaType:(0,To.getJSONTypes)(t.schemaType)};return(0,xl.eachItem)(n,i.type.length===0?s=>kl.call(this,s,i):s=>i.type.forEach(o=>kl.call(this,s,i,o))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let i=n.rules.findIndex(s=>s.keyword===e);i>=0&&n.rules.splice(i,1)}return this}addFormat(e,t){return typeof t=="string"&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(i=>`${n}${i.instancePath} ${i.message}`).reduce((i,s)=>i+t+s)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let i of t){let s=i.split("/").slice(1),o=e;for(let a of s)o=o[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=o[a];l&&u&&(o[a]=Ah(u))}}return e}_removeAllSchemas(e,t){for(let n in e){let i=e[n];(!t||t.test(n))&&(typeof i=="string"?delete e[n]:i&&!i.meta&&(this._cache.delete(i.schema),delete e[n]))}}_addSchema(e,t,n,i=this.opts.validateSchema,s=this.opts.addUsedSchema){let o,{schemaId:a}=this.opts;if(typeof e=="object")o=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,es.normalizeId)(o||n);let l=es.getSchemaRefs.call(this,e,n);return c=new Zi.SchemaEnv({schema:e,schemaId:a,meta:t,baseId:n,localRefs:l}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),i&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Zi.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{Zi.compileSchema.call(this,e)}finally{this.opts=t}}};ts.ValidationError=dS.default;ts.MissingRefError=Sh.default;Fe.default=ts;function vh(r,e,t,n="error"){for(let i in r){let s=i;s in e&&this.logger[n](`${t}: option ${i}. ${r[s]}`)}}function $h(r){return r=(0,es.normalizeId)(r),this.schemas[r]||this.refs[r]}function _S(){let r=this.opts.schemas;if(r)if(Array.isArray(r))this.addSchema(r);else for(let e in r)this.addSchema(r[e],e)}function wS(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function vS(r){if(Array.isArray(r)){this.addVocabulary(r);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in r){let t=r[e];t.keyword||(t.keyword=e),this.addKeyword(t)}}function $S(){let r={...this.opts};for(let e of hS)delete r[e];return r}var SS={log(){},warn(){},error(){}};function ES(r){if(r===!1)return SS;if(r===void 0)return console;if(r.log&&r.warn&&r.error)return r;throw new Error("logger must implement log, warn and error methods")}var AS=/^[a-z_$][a-z0-9_$:-]*$/i;function kS(r,e){let{RULES:t}=this;if((0,xl.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!AS.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function kl(r,e,t){var n;let i=e==null?void 0:e.post;if(t&&i)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=i?s.post:s.rules.find(({type:c})=>c===t);if(o||(o={type:t,rules:[]},s.rules.push(o)),s.keywords[r]=!0,!e)return;let a={keyword:r,definition:{...e,type:(0,To.getJSONTypes)(e.type),schemaType:(0,To.getJSONTypes)(e.schemaType)}};e.before?xS.call(this,o,a,e.before):o.rules.push(a),s.all[r]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function xS(r,e,t){let n=r.rules.findIndex(i=>i.keyword===t);n>=0?r.rules.splice(n,0,e):(r.rules.push(e),this.logger.warn(`rule ${t} is not defined`))}function PS(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Ah(e)),r.validateSchema=this.compile(e,!0))}var IS={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Ah(r){return{anyOf:[r,IS]}}});var kh=A(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});var OS={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Il.default=OS});var Mo=A(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.callRef=bn.getValidate=void 0;var TS=Bn(),xh=xt(),ft=K(),Kn=kt(),Ph=Xi(),Ro=ee(),RS={keyword:"$ref",schemaType:"string",code(r){let{gen:e,schema:t,it:n}=r,{baseId:i,schemaEnv:s,validateName:o,opts:a,self:c}=n,{root:l}=s;if((t==="#"||t==="#/")&&i===l.baseId)return d();let u=Ph.resolveRef.call(c,l,i,t);if(u===void 0)throw new TS.default(n.opts.uriResolver,i,t);if(u instanceof Ph.SchemaEnv)return f(u);return p(u);function d(){if(s===l)return Co(r,o,s,s.$async);let m=e.scopeValue("root",{ref:l});return Co(r,(0,ft._)`${m}.validate`,l,l.$async)}function f(m){let h=Ih(r,m);Co(r,h,m,m.$async)}function p(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,ft.stringify)(m)}:{ref:m}),y=e.name("valid"),b=r.subschema({schema:m,dataTypes:[],schemaPath:ft.nil,topSchemaRef:h,errSchemaPath:t},y);r.mergeEvaluated(b),r.ok(y)}}};function Ih(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,ft._)`${t.scopeValue("wrapper",{ref:e})}.validate`}bn.getValidate=Ih;function Co(r,e,t,n){let{gen:i,it:s}=r,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?Kn.default.this:ft.nil;n?u():d();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=i.let("valid");i.try(()=>{i.code((0,ft._)`await ${(0,xh.callValidateCode)(r,e,l)}`),p(e),o||i.assign(m,!0)},h=>{i.if((0,ft._)`!(${h} instanceof ${s.ValidationError})`,()=>i.throw(h)),f(h),o||i.assign(m,!1)}),r.ok(m)}function d(){r.result((0,xh.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(m){let h=(0,ft._)`${m}.errors`;i.assign(Kn.default.vErrors,(0,ft._)`${Kn.default.vErrors} === null ? ${h} : ${Kn.default.vErrors}.concat(${h})`),i.assign(Kn.default.errors,(0,ft._)`${Kn.default.vErrors}.length`)}function p(m){var h;if(!s.opts.unevaluated)return;let y=(h=t==null?void 0:t.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Ro.mergeEvaluated.props(i,y.props,s.props));else{let b=i.var("props",(0,ft._)`${m}.evaluated.props`);s.props=Ro.mergeEvaluated.props(i,b,s.props,ft.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Ro.mergeEvaluated.items(i,y.items,s.items));else{let b=i.var("items",(0,ft._)`${m}.evaluated.items`);s.items=Ro.mergeEvaluated.items(i,b,s.items,ft.Name)}}}bn.callRef=Co;bn.default=RS});var Tl=A(Ol=>{"use strict";Object.defineProperty(Ol,"__esModule",{value:!0});var CS=kh(),MS=Mo(),NS=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",CS.default,MS.default];Ol.default=NS});var Oh=A(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});var No=K(),zr=No.operators,Lo={maximum:{okStr:"<=",ok:zr.LTE,fail:zr.GT},minimum:{okStr:">=",ok:zr.GTE,fail:zr.LT},exclusiveMaximum:{okStr:"<",ok:zr.LT,fail:zr.GTE},exclusiveMinimum:{okStr:">",ok:zr.GT,fail:zr.LTE}},LS={message:({keyword:r,schemaCode:e})=>(0,No.str)`must be ${Lo[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,No._)`{comparison: ${Lo[r].okStr}, limit: ${e}}`},DS={keyword:Object.keys(Lo),type:"number",schemaType:"number",$data:!0,error:LS,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,No._)`${t} ${Lo[e].fail} ${n} || isNaN(${t})`)}};Rl.default=DS});var Th=A(Cl=>{"use strict";Object.defineProperty(Cl,"__esModule",{value:!0});var rs=K(),qS={message:({schemaCode:r})=>(0,rs.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,rs._)`{multipleOf: ${r}}`},jS={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:qS,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,s=i.opts.multipleOfPrecision,o=e.let("res"),a=s?(0,rs._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,rs._)`${o} !== parseInt(${o})`;r.fail$data((0,rs._)`(${n} === 0 || (${o} = ${t}/${n}, ${a}))`)}};Cl.default=jS});var Ch=A(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});function Rh(r){let e=r.length,t=0,n=0,i;for(;n=55296&&i<=56319&&n{"use strict";Object.defineProperty(Nl,"__esModule",{value:!0});var _n=K(),FS=ee(),VS=Ch(),US={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,_n.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,_n._)`{limit: ${r}}`},BS={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:US,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,s=e==="maxLength"?_n.operators.GT:_n.operators.LT,o=i.opts.unicode===!1?(0,_n._)`${t}.length`:(0,_n._)`${(0,FS.useFunc)(r.gen,VS.default)}(${t})`;r.fail$data((0,_n._)`${o} ${s} ${n}`)}};Nl.default=BS});var Nh=A(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});var zS=xt(),HS=ee(),Wn=K(),KS={message:({schemaCode:r})=>(0,Wn.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,Wn._)`{pattern: ${r}}`},WS={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:KS,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:s,it:o}=r,a=o.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=o.opts.code,l=c.code==="new RegExp"?(0,Wn._)`new RegExp`:(0,HS.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Wn._)`${l}(${s}, ${a}).test(${t})`),()=>e.assign(u,!1)),r.fail$data((0,Wn._)`!${u}`)}else{let c=(0,zS.usePattern)(r,i);r.fail$data((0,Wn._)`!${c}.test(${t})`)}}};Ll.default=WS});var Lh=A(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var ns=K(),GS={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,ns.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,ns._)`{limit: ${r}}`},JS={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:GS,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?ns.operators.GT:ns.operators.LT;r.fail$data((0,ns._)`Object.keys(${t}).length ${i} ${n}`)}};Dl.default=JS});var Dh=A(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var is=xt(),ss=K(),YS=ee(),XS={message:({params:{missingProperty:r}})=>(0,ss.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,ss._)`{missingProperty: ${r}}`},QS={keyword:"required",type:"object",schemaType:"array",$data:!0,error:XS,code(r){let{gen:e,schema:t,schemaCode:n,data:i,$data:s,it:o}=r,{opts:a}=o;if(!s&&t.length===0)return;let c=t.length>=a.loopRequired;if(o.allErrors?l():u(),a.strictRequired){let p=r.parentSchema.properties,{definedProperties:m}=r.it;for(let h of t)if((p==null?void 0:p[h])===void 0&&!m.has(h)){let y=o.schemaEnv.baseId+o.errSchemaPath,b=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,YS.checkStrictMode)(o,b,o.opts.strictRequired)}}function l(){if(c||s)r.block$data(ss.nil,d);else for(let p of t)(0,is.checkReportMissingProp)(r,p)}function u(){let p=e.let("missing");if(c||s){let m=e.let("valid",!0);r.block$data(m,()=>f(p,m)),r.ok(m)}else e.if((0,is.checkMissingProp)(r,t,p)),(0,is.reportMissingProp)(r,p),e.else()}function d(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,is.noPropertyInData)(e,i,p,a.ownProperties),()=>r.error())})}function f(p,m){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(m,(0,is.propertyInData)(e,i,p,a.ownProperties)),e.if((0,ss.not)(m),()=>{r.error(),e.break()})},ss.nil)}}};ql.default=QS});var qh=A(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});var os=K(),ZS={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,os.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,os._)`{limit: ${r}}`},eE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:ZS,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?os.operators.GT:os.operators.LT;r.fail$data((0,os._)`${t}.length ${i} ${n}`)}};jl.default=eE});var Do=A(Fl=>{"use strict";Object.defineProperty(Fl,"__esModule",{value:!0});var jh=al();jh.code='require("ajv/dist/runtime/equal").default';Fl.default=jh});var Fh=A(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});var Vl=Ki(),Ve=K(),tE=ee(),rE=Do(),nE={message:({params:{i:r,j:e}})=>(0,Ve.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,Ve._)`{i: ${r}, j: ${e}}`},iE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:nE,code(r){let{gen:e,data:t,$data:n,schema:i,parentSchema:s,schemaCode:o,it:a}=r;if(!n&&!i)return;let c=e.let("valid"),l=s.items?(0,Vl.getSchemaTypes)(s.items):[];r.block$data(c,u,(0,Ve._)`${o} === false`),r.ok(c);function u(){let m=e.let("i",(0,Ve._)`${t}.length`),h=e.let("j");r.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,Ve._)`${m} > 1`,()=>(d()?f:p)(m,h))}function d(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function f(m,h){let y=e.name("item"),b=(0,Vl.checkDataTypes)(l,y,a.opts.strictNumbers,Vl.DataType.Wrong),g=e.const("indices",(0,Ve._)`{}`);e.for((0,Ve._)`;${m}--;`,()=>{e.let(y,(0,Ve._)`${t}[${m}]`),e.if(b,(0,Ve._)`continue`),l.length>1&&e.if((0,Ve._)`typeof ${y} == "string"`,(0,Ve._)`${y} += "_"`),e.if((0,Ve._)`typeof ${g}[${y}] == "number"`,()=>{e.assign(h,(0,Ve._)`${g}[${y}]`),r.error(),e.assign(c,!1).break()}).code((0,Ve._)`${g}[${y}] = ${m}`)})}function p(m,h){let y=(0,tE.useFunc)(e,rE.default),b=e.name("outer");e.label(b).for((0,Ve._)`;${m}--;`,()=>e.for((0,Ve._)`${h} = ${m}; ${h}--;`,()=>e.if((0,Ve._)`${y}(${t}[${m}], ${t}[${h}])`,()=>{r.error(),e.assign(c,!1).break(b)})))}}};Ul.default=iE});var Vh=A(zl=>{"use strict";Object.defineProperty(zl,"__esModule",{value:!0});var Bl=K(),sE=ee(),oE=Do(),aE={message:"must be equal to constant",params:({schemaCode:r})=>(0,Bl._)`{allowedValue: ${r}}`},cE={keyword:"const",$data:!0,error:aE,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:s}=r;n||s&&typeof s=="object"?r.fail$data((0,Bl._)`!${(0,sE.useFunc)(e,oE.default)}(${t}, ${i})`):r.fail((0,Bl._)`${s} !== ${t}`)}};zl.default=cE});var Uh=A(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var as=K(),lE=ee(),dE=Do(),uE={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,as._)`{allowedValues: ${r}}`},fE={keyword:"enum",schemaType:"array",$data:!0,error:uE,code(r){let{gen:e,data:t,$data:n,schema:i,schemaCode:s,it:o}=r;if(!n&&i.length===0)throw new Error("enum must have non-empty array");let a=i.length>=o.opts.loopEnum,c,l=()=>c!=null?c:c=(0,lE.useFunc)(e,dE.default),u;if(a||n)u=e.let("valid"),r.block$data(u,d);else{if(!Array.isArray(i))throw new Error("ajv implementation error");let p=e.const("vSchema",s);u=(0,as.or)(...i.map((m,h)=>f(p,h)))}r.pass(u);function d(){e.assign(u,!1),e.forOf("v",s,p=>e.if((0,as._)`${l()}(${t}, ${p})`,()=>e.assign(u,!0).break()))}function f(p,m){let h=i[m];return typeof h=="object"&&h!==null?(0,as._)`${l()}(${t}, ${p}[${m}])`:(0,as._)`${t} === ${h}`}}};Hl.default=fE});var Wl=A(Kl=>{"use strict";Object.defineProperty(Kl,"__esModule",{value:!0});var pE=Oh(),hE=Th(),mE=Mh(),yE=Nh(),gE=Lh(),bE=Dh(),_E=qh(),wE=Fh(),vE=Vh(),$E=Uh(),SE=[pE.default,hE.default,mE.default,yE.default,gE.default,bE.default,_E.default,wE.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},vE.default,$E.default];Kl.default=SE});var Jl=A(cs=>{"use strict";Object.defineProperty(cs,"__esModule",{value:!0});cs.validateAdditionalItems=void 0;var wn=K(),Gl=ee(),EE={message:({params:{len:r}})=>(0,wn.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,wn._)`{limit: ${r}}`},AE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:EE,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,Gl.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}Bh(r,n)}};function Bh(r,e){let{gen:t,schema:n,data:i,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,wn._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,wn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Gl.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,wn._)`${a} <= ${e.length}`);t.if((0,wn.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,u=>{r.subschema({keyword:s,dataProp:u,dataPropType:Gl.Type.Num},l),o.allErrors||t.if((0,wn.not)(l),()=>t.break())})}}cs.validateAdditionalItems=Bh;cs.default=AE});var Yl=A(ls=>{"use strict";Object.defineProperty(ls,"__esModule",{value:!0});ls.validateTuple=void 0;var zh=K(),qo=ee(),kE=xt(),xE={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return Hh(r,"additionalItems",e);t.items=!0,!(0,qo.alwaysValidSchema)(t,e)&&r.ok((0,kE.validateArray)(r))}};function Hh(r,e,t=r.schema){let{gen:n,parentSchema:i,data:s,keyword:o,it:a}=r;u(i),a.opts.unevaluated&&t.length&&a.items!==!0&&(a.items=qo.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,zh._)`${s}.length`);t.forEach((d,f)=>{(0,qo.alwaysValidSchema)(a,d)||(n.if((0,zh._)`${l} > ${f}`,()=>r.subschema({keyword:o,schemaProp:f,dataProp:f},c)),r.ok(c))});function u(d){let{opts:f,errSchemaPath:p}=a,m=t.length,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(f.strictTuples&&!h){let y=`"${o}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${p}"`;(0,qo.checkStrictMode)(a,y,f.strictTuples)}}}ls.validateTuple=Hh;ls.default=xE});var Kh=A(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var PE=Yl(),IE={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,PE.validateTuple)(r,"items")};Xl.default=IE});var Gh=A(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});var Wh=K(),OE=ee(),TE=xt(),RE=Jl(),CE={message:({params:{len:r}})=>(0,Wh.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,Wh._)`{limit: ${r}}`},ME={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:CE,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,OE.alwaysValidSchema)(n,e)&&(i?(0,RE.validateAdditionalItems)(r,i):r.ok((0,TE.validateArray)(r)))}};Ql.default=ME});var Jh=A(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var It=K(),jo=ee(),NE={message:({params:{min:r,max:e}})=>e===void 0?(0,It.str)`must contain at least ${r} valid item(s)`:(0,It.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,It._)`{minContains: ${r}}`:(0,It._)`{minContains: ${r}, maxContains: ${e}}`},LE={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:NE,code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:s}=r,o,a,{minContains:c,maxContains:l}=n;s.opts.next?(o=c===void 0?1:c,a=l):o=1;let u=e.const("len",(0,It._)`${i}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,jo.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,jo.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,jo.alwaysValidSchema)(s,t)){let h=(0,It._)`${u} >= ${o}`;a!==void 0&&(h=(0,It._)`${h} && ${u} <= ${a}`),r.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&o===1?p(d,()=>e.if(d,()=>e.break())):o===0?(e.let(d,!0),a!==void 0&&e.if((0,It._)`${i}.length > 0`,f)):(e.let(d,!1),f()),r.result(d,()=>r.reset());function f(){let h=e.name("_valid"),y=e.let("count",0);p(h,()=>e.if(h,()=>m(y)))}function p(h,y){e.forRange("i",0,u,b=>{r.subschema({keyword:"contains",dataProp:b,dataPropType:jo.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,It._)`${h}++`),a===void 0?e.if((0,It._)`${h} >= ${o}`,()=>e.assign(d,!0).break()):(e.if((0,It._)`${h} > ${a}`,()=>e.assign(d,!1).break()),o===1?e.assign(d,!0):e.if((0,It._)`${h} >= ${o}`,()=>e.assign(d,!0)))}}};Zl.default=LE});var Fo=A(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.validateSchemaDeps=ar.validatePropertyDeps=ar.error=void 0;var ed=K(),DE=ee(),ds=xt();ar.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,ed.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,ed._)`{property: ${r}, missingProperty: ${n}, depsCount: ${e}, - deps: ${t}}`};var aE={keyword:"dependencies",type:"object",schemaType:"object",error:Gt.error,code(r){let[e,t]=cE(r);Eh(r,e),Ah(r,t)}};function cE({schema:r}){let e={},t={};for(let n in r){if(n==="__proto__")continue;let s=Array.isArray(r[n])?e:t;s[n]=r[n]}return[e,t]}function Eh(r,e=r.schema){let{gen:t,data:n,it:s}=r;if(Object.keys(e).length===0)return;let i=t.let("missing");for(let o in e){let a=e[o];if(a.length===0)continue;let c=(0,Zs.propertyInData)(t,n,o,s.opts.ownProperties);r.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),s.allErrors?t.if(c,()=>{for(let l of a)(0,Zs.checkReportMissingProp)(r,l)}):(t.if((0,Ol._)`${c} && (${(0,Zs.checkMissingProp)(r,a,i)})`),(0,Zs.reportMissingProp)(r,i),t.else())}}Gt.validatePropertyDeps=Eh;function Ah(r,e=r.schema){let{gen:t,data:n,keyword:s,it:i}=r,o=t.name("valid");for(let a in e)(0,oE.alwaysValidSchema)(i,e[a])||(t.if((0,Zs.propertyInData)(t,n,a,i.opts.ownProperties),()=>{let c=r.subschema({keyword:s,schemaProp:a},o);r.mergeValidEvaluated(c,o)},()=>t.var(o,!0)),r.ok(o))}Gt.validateSchemaDeps=Ah;Gt.default=aE});var xh=E(Rl=>{"use strict";Object.defineProperty(Rl,"__esModule",{value:!0});var kh=B(),lE=Y(),dE={message:"property name must be valid",params:({params:r})=>(0,kh._)`{propertyName: ${r.propertyName}}`},uE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:dE,code(r){let{gen:e,schema:t,data:n,it:s}=r;if((0,lE.alwaysValidSchema)(s,t))return;let i=e.name("valid");e.forIn("key",n,o=>{r.setParams({propertyName:o}),r.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},i),e.if((0,kh.not)(i),()=>{r.error(!0),s.allErrors||e.break()})}),r.ok(i)}};Rl.default=uE});var Cl=E(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});var xo=ht(),Pt=B(),fE=pt(),Po=Y(),pE={message:"must NOT have additional properties",params:({params:r})=>(0,Pt._)`{additionalProperty: ${r.additionalProperty}}`},hE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:pE,code(r){let{gen:e,schema:t,parentSchema:n,data:s,errsCount:i,it:o}=r;if(!i)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,Po.alwaysValidSchema)(o,t))return;let l=(0,xo.allSchemaProperties)(n.properties),u=(0,xo.allSchemaProperties)(n.patternProperties);d(),r.ok((0,Pt._)`${i} === ${fE.default.errors}`);function d(){e.forIn("key",s,y=>{!l.length&&!u.length?m(y):e.if(f(y),()=>m(y))})}function f(y){let b;if(l.length>8){let g=(0,Po.schemaRefOrVal)(o,n.properties,"properties");b=(0,xo.isOwnProperty)(e,g,y)}else l.length?b=(0,Pt.or)(...l.map(g=>(0,Pt._)`${y} === ${g}`)):b=Pt.nil;return u.length&&(b=(0,Pt.or)(b,...u.map(g=>(0,Pt._)`${(0,xo.usePattern)(r,g)}.test(${y})`))),(0,Pt.not)(b)}function p(y){e.code((0,Pt._)`delete ${s}[${y}]`)}function m(y){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){p(y);return}if(t===!1){r.setParams({additionalProperty:y}),r.error(),a||e.break();return}if(typeof t=="object"&&!(0,Po.alwaysValidSchema)(o,t)){let b=e.name("valid");c.removeAdditional==="failing"?(h(y,b,!1),e.if((0,Pt.not)(b),()=>{r.reset(),p(y)})):(h(y,b),a||e.if((0,Pt.not)(b),()=>e.break()))}}function h(y,b,g){let _={keyword:"additionalProperties",dataProp:y,dataPropType:Po.Type.Str};g===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(_,b)}}};Ml.default=hE});var Th=E(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});var mE=Rn(),Ph=ht(),Nl=Y(),Ih=Cl(),yE={keyword:"properties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,parentSchema:n,data:s,it:i}=r;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Ih.default.code(new mE.KeywordCxt(i,Ih.default,"additionalProperties"));let o=(0,Ph.allSchemaProperties)(t);for(let d of o)i.definedProperties.add(d);i.opts.unevaluated&&o.length&&i.props!==!0&&(i.props=Nl.mergeEvaluated.props(e,(0,Nl.toHash)(o),i.props));let a=o.filter(d=>!(0,Nl.alwaysValidSchema)(i,t[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,Ph.propertyInData)(e,s,d,i.opts.ownProperties)),u(d),i.allErrors||e.else().var(c,!0),e.endIf()),r.it.definedProperties.add(d),r.ok(c);function l(d){return i.opts.useDefaults&&!i.compositeRule&&t[d].default!==void 0}function u(d){r.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Ll.default=yE});var Ch=E(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var Oh=ht(),Io=B(),Rh=Y(),Mh=Y(),gE={keyword:"patternProperties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,data:n,parentSchema:s,it:i}=r,{opts:o}=i,a=(0,Oh.allSchemaProperties)(t),c=a.filter(h=>(0,Rh.alwaysValidSchema)(i,t[h]));if(a.length===0||c.length===a.length&&(!i.opts.unevaluated||i.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&s.properties,u=e.name("valid");i.props!==!0&&!(i.props instanceof Io.Name)&&(i.props=(0,Mh.evaluatedPropsToName)(e,i.props));let{props:d}=i;f();function f(){for(let h of a)l&&p(h),i.allErrors?m(h):(e.var(u,!0),m(h),e.if(u))}function p(h){for(let y in l)new RegExp(h).test(y)&&(0,Rh.checkStrictMode)(i,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,Io._)`${(0,Oh.usePattern)(r,h)}.test(${y})`,()=>{let b=c.includes(h);b||r.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:Mh.Type.Str},u),i.opts.unevaluated&&d!==!0?e.assign((0,Io._)`${d}[${y}]`,!0):!b&&!i.allErrors&&e.if((0,Io.not)(u),()=>e.break())})})}}};Dl.default=gE});var Nh=E(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var bE=Y(),wE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,bE.alwaysValidSchema)(n,t)){r.fail();return}let s=e.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),r.failResult(s,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};ql.default=wE});var Lh=E(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});var _E=ht(),vE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:_E.validateUnion,error:{message:"must match a schema in anyOf"}};jl.default=vE});var Dh=E(Fl=>{"use strict";Object.defineProperty(Fl,"__esModule",{value:!0});var To=B(),$E=Y(),SE={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,To._)`{passingSchemas: ${r.passing}}`},EE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:SE,code(r){let{gen:e,schema:t,parentSchema:n,it:s}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let i=t,o=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");r.setParams({passing:a}),e.block(l),r.result(o,()=>r.reset(),()=>r.error(!0));function l(){i.forEach((u,d)=>{let f;(0,$E.alwaysValidSchema)(s,u)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,To._)`${c} && ${o}`).assign(o,!1).assign(a,(0,To._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,d),f&&r.mergeEvaluated(f,To.Name)})})}}};Fl.default=EE});var qh=E(Vl=>{"use strict";Object.defineProperty(Vl,"__esModule",{value:!0});var AE=Y(),kE={keyword:"allOf",schemaType:"array",code(r){let{gen:e,schema:t,it:n}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");let s=e.name("valid");t.forEach((i,o)=>{if((0,AE.alwaysValidSchema)(n,i))return;let a=r.subschema({keyword:"allOf",schemaProp:o},s);r.ok(s),r.mergeEvaluated(a)})}};Vl.default=kE});var Vh=E(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});var Oo=B(),Fh=Y(),xE={message:({params:r})=>(0,Oo.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,Oo._)`{failingKeyword: ${r.ifClause}}`},PE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:xE,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,Fh.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=jh(n,"then"),i=jh(n,"else");if(!s&&!i)return;let o=e.let("valid",!0),a=e.name("_valid");if(c(),r.reset(),s&&i){let u=e.let("ifClause");r.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else s?e.if(a,l("then")):e.if((0,Oo.not)(a),l("else"));r.pass(o,()=>r.error(!0));function c(){let u=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);r.mergeEvaluated(u)}function l(u,d){return()=>{let f=r.subschema({keyword:u},a);e.assign(o,a),r.mergeValidEvaluated(f,o),d?e.assign(d,(0,Oo._)`${u}`):r.setParams({ifClause:u})}}}};function jh(r,e){let t=r.schema[e];return t!==void 0&&!(0,Fh.alwaysValidSchema)(r,t)}Ul.default=PE});var Uh=E(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var IE=Y(),TE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,IE.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};Hl.default=TE});var zl=E(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var OE=kl(),RE=_h(),ME=xl(),CE=$h(),NE=Sh(),LE=ko(),DE=xh(),qE=Cl(),jE=Th(),FE=Ch(),VE=Nh(),UE=Lh(),HE=Dh(),BE=qh(),zE=Vh(),KE=Uh();function WE(r=!1){let e=[VE.default,UE.default,HE.default,BE.default,zE.default,KE.default,DE.default,qE.default,LE.default,jE.default,FE.default];return r?e.push(RE.default,CE.default):e.push(OE.default,ME.default),e.push(NE.default),e}Bl.default=WE});var Wl=E(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.dynamicAnchor=void 0;var Kl=B(),GE=pt(),Hh=Fs(),JE=_o(),YE={keyword:"$dynamicAnchor",schemaType:"string",code:r=>Bh(r,r.schema)};function Bh(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let s=(0,Kl._)`${GE.default.dynamicAnchors}${(0,Kl.getProperty)(e)}`,i=n.errSchemaPath==="#"?n.validateName:XE(r);t.if((0,Kl._)`!${s}`,()=>t.assign(s,i))}ei.dynamicAnchor=Bh;function XE(r){let{schemaEnv:e,schema:t,self:n}=r.it,{root:s,baseId:i,localRefs:o,meta:a}=e.root,{schemaId:c}=n.opts,l=new Hh.SchemaEnv({schema:t,schemaId:c,root:s,baseId:i,localRefs:o,meta:a});return Hh.compileSchema.call(n,l),(0,JE.getValidate)(r,l)}ei.default=YE});var Gl=E(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.dynamicRef=void 0;var zh=B(),QE=pt(),Kh=_o(),ZE={keyword:"$dynamicRef",schemaType:"string",code:r=>Wh(r,r.schema)};function Wh(r,e){let{gen:t,keyword:n,it:s}=r;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let i=e.slice(1);if(s.allErrors)o();else{let c=t.let("valid",!1);o(c),r.ok(c)}function o(c){if(s.schemaEnv.root.dynamicAnchors[i]){let l=t.let("_v",(0,zh._)`${QE.default.dynamicAnchors}${(0,zh.getProperty)(i)}`);t.if(l,a(l,c),a(s.validateName,c))}else a(s.validateName,c)()}function a(c,l){return l?()=>t.block(()=>{(0,Kh.callRef)(r,c),t.let(l,!0)}):()=>(0,Kh.callRef)(r,c)}}ti.dynamicRef=Wh;ti.default=ZE});var Gh=E(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});var e1=Wl(),t1=Y(),r1={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,e1.dynamicAnchor)(r,""):(0,t1.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};Jl.default=r1});var Jh=E(Yl=>{"use strict";Object.defineProperty(Yl,"__esModule",{value:!0});var n1=Gl(),s1={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,n1.dynamicRef)(r,r.schema)};Yl.default=s1});var Yh=E(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var i1=Wl(),o1=Gl(),a1=Gh(),c1=Jh(),l1=[i1.default,o1.default,a1.default,c1.default];Xl.default=l1});var Qh=E(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});var Xh=ko(),d1={keyword:"dependentRequired",type:"object",schemaType:"object",error:Xh.error,code:r=>(0,Xh.validatePropertyDeps)(r)};Ql.default=d1});var Zh=E(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var u1=ko(),f1={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,u1.validateSchemaDeps)(r)};Zl.default=f1});var em=E(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var p1=Y(),h1={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,p1.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};ed.default=h1});var tm=E(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var m1=Qh(),y1=Zh(),g1=em(),b1=[m1.default,y1.default,g1.default];td.default=b1});var nm=E(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var Dr=B(),rm=Y(),w1=pt(),_1={message:"must NOT have unevaluated properties",params:({params:r})=>(0,Dr._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},v1={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:_1,code(r){let{gen:e,schema:t,data:n,errsCount:s,it:i}=r;if(!s)throw new Error("ajv implementation error");let{allErrors:o,props:a}=i;a instanceof Dr.Name?e.if((0,Dr._)`${a} !== true`,()=>e.forIn("key",n,d=>e.if(l(a,d),()=>c(d)))):a!==!0&&e.forIn("key",n,d=>a===void 0?c(d):e.if(u(a,d),()=>c(d))),i.props=!0,r.ok((0,Dr._)`${s} === ${w1.default.errors}`);function c(d){if(t===!1){r.setParams({unevaluatedProperty:d}),r.error(),o||e.break();return}if(!(0,rm.alwaysValidSchema)(i,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:rm.Type.Str},f),o||e.if((0,Dr.not)(f),()=>e.break())}}function l(d,f){return(0,Dr._)`!${d} || !${d}[${f}]`}function u(d,f){let p=[];for(let m in d)d[m]===!0&&p.push((0,Dr._)`${f} !== ${m}`);return(0,Dr.and)(...p)}}};rd.default=v1});var im=E(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});var fn=B(),sm=Y(),$1={message:({params:{len:r}})=>(0,fn.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,fn._)`{limit: ${r}}`},S1={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:$1,code(r){let{gen:e,schema:t,data:n,it:s}=r,i=s.items||0;if(i===!0)return;let o=e.const("len",(0,fn._)`${n}.length`);if(t===!1)r.setParams({len:i}),r.fail((0,fn._)`${o} > ${i}`);else if(typeof t=="object"&&!(0,sm.alwaysValidSchema)(s,t)){let c=e.var("valid",(0,fn._)`${o} <= ${i}`);e.if((0,fn.not)(c),()=>a(c,i)),r.ok(c)}s.items=!0;function a(c,l){e.forRange("i",l,o,u=>{r.subschema({keyword:"unevaluatedItems",dataProp:u,dataPropType:sm.Type.Num},c),s.allErrors||e.if((0,fn.not)(c),()=>e.break())})}}};nd.default=S1});var om=E(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var E1=nm(),A1=im(),k1=[E1.default,A1.default];sd.default=k1});var am=E(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var Ee=B(),x1={message:({schemaCode:r})=>(0,Ee.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,Ee._)`{format: ${r}}`},P1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:x1,code(r,e){let{gen:t,data:n,$data:s,schema:i,schemaCode:o,it:a}=r,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;s?f():p();function f(){let m=t.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=t.const("fDef",(0,Ee._)`${m}[${o}]`),y=t.let("fType"),b=t.let("format");t.if((0,Ee._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>t.assign(y,(0,Ee._)`${h}.type || "string"`).assign(b,(0,Ee._)`${h}.validate`),()=>t.assign(y,(0,Ee._)`"string"`).assign(b,h)),r.fail$data((0,Ee.or)(g(),_()));function g(){return c.strictSchema===!1?Ee.nil:(0,Ee._)`${o} && !${b}`}function _(){let I=u.$async?(0,Ee._)`(${h}.async ? await ${b}(${n}) : ${b}(${n}))`:(0,Ee._)`${b}(${n})`,v=(0,Ee._)`(typeof ${b} == "function" ? ${I} : ${b}.test(${n}))`;return(0,Ee._)`${b} && ${b} !== true && ${y} === ${e} && !${v}`}}function p(){let m=d.formats[i];if(!m){g();return}if(m===!0)return;let[h,y,b]=_(m);h===e&&r.pass(I());function g(){if(c.strictSchema===!1){d.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${i}" ignored in schema at path "${l}"`}}function _(v){let S=v instanceof RegExp?(0,Ee.regexpCode)(v):c.code.formats?(0,Ee._)`${c.code.formats}${(0,Ee.getProperty)(i)}`:void 0,k=t.scopeValue("formats",{key:i,ref:v,code:S});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,Ee._)`${k}.validate`]:["string",v,k]}function I(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Ee._)`await ${b}(${n})`}return typeof y=="function"?(0,Ee._)`${b}(${n})`:(0,Ee._)`${b}.test(${n})`}}}};id.default=P1});var ad=E(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var I1=am(),T1=[I1.default];od.default=T1});var cd=E(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.contentVocabulary=jn.metadataVocabulary=void 0;jn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];jn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var lm=E(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});var O1=cl(),R1=El(),M1=zl(),C1=Yh(),N1=tm(),L1=om(),D1=ad(),cm=cd(),q1=[C1.default,O1.default,R1.default,(0,M1.default)(!0),D1.default,cm.metadataVocabulary,cm.contentVocabulary,N1.default,L1.default];ld.default=q1});var um=E(Ro=>{"use strict";Object.defineProperty(Ro,"__esModule",{value:!0});Ro.DiscrError=void 0;var dm;(function(r){r.Tag="tag",r.Mapping="mapping"})(dm||(Ro.DiscrError=dm={}))});var fd=E(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var Fn=B(),dd=um(),fm=Fs(),j1=Mn(),F1=Y(),V1={message:({params:{discrError:r,tagName:e}})=>r===dd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Fn._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},U1={keyword:"discriminator",type:"object",schemaType:"object",error:V1,code(r){let{gen:e,data:t,schema:n,parentSchema:s,it:i}=r,{oneOf:o}=s;if(!i.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Fn._)`${t}${(0,Fn.getProperty)(a)}`);e.if((0,Fn._)`typeof ${l} == "string"`,()=>u(),()=>r.error(!1,{discrError:dd.DiscrError.Tag,tag:l,tagName:a})),r.ok(c);function u(){let p=f();e.if(!1);for(let m in p)e.elseIf((0,Fn._)`${l} === ${m}`),e.assign(c,d(p[m]));e.else(),r.error(!1,{discrError:dd.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(p){let m=e.name("valid"),h=r.subschema({keyword:"oneOf",schemaProp:p},m);return r.mergeEvaluated(h,Fn.Name),m}function f(){var p;let m={},h=b(s),y=!0;for(let I=0;I{H1.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 hm=E((HM,B1)=>{B1.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 mm=E((BM,z1)=>{z1.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 ym=E((zM,K1)=>{K1.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 gm=E((KM,W1)=>{W1.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 bm=E((WM,G1)=>{G1.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 wm=E((GM,J1)=>{J1.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 _m=E((JM,Y1)=>{Y1.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 vm=E(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});var X1=pm(),Q1=hm(),Z1=mm(),eA=ym(),tA=gm(),rA=bm(),nA=wm(),sA=_m(),iA=["/properties"];function oA(r){return[X1,Q1,Z1,eA,tA,e(this,rA),nA,e(this,sA)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,iA):n}}pd.default=oA});var yd=E((ye,md)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv2020=void 0;var aA=il(),cA=lm(),lA=fd(),dA=vm(),hd="https://json-schema.org/draft/2020-12/schema",Vn=class extends aA.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),cA.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(lA.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(dA.default.call(this,e),this.refs["http://json-schema.org/schema"]=hd)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(hd)?hd:void 0)}};ye.Ajv2020=Vn;md.exports=ye=Vn;md.exports.Ajv2020=Vn;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=Vn;var uA=Rn();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return uA.KeywordCxt}});var Un=B();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return Un._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return Un.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return Un.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return Un.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return Un.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return Un.CodeGen}});var fA=js();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return fA.default}});var pA=Mn();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return pA.default}})});var Im=E(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.formatNames=Yt.fastFormats=Yt.fullFormats=void 0;function Jt(r,e){return{validate:r,compare:e}}Yt.fullFormats={date:Jt(Am,_d),time:Jt(bd(!0),vd),"date-time":Jt($m(!0),xm),"iso-time":Jt(bd(),km),"iso-date-time":Jt($m(),Pm),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:wA,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:kA,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:_A,int32:{type:"number",validate:SA},int64:{type:"number",validate:EA},float:{type:"number",validate:Em},double:{type:"number",validate:Em},password:!0,binary:!0};Yt.fastFormats={...Yt.fullFormats,date:Jt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,_d),time:Jt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,vd),"date-time":Jt(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,xm),"iso-time":Jt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,km),"iso-date-time":Jt(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Pm),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Yt.formatNames=Object.keys(Yt.fullFormats);function hA(r){return r%4===0&&(r%100!==0||r%400===0)}var mA=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,yA=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Am(r){let e=mA.exec(r);if(!e)return!1;let t=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&hA(t)?29:yA[n])}function _d(r,e){if(r&&e)return r>e?1:r23||u>59||r&&!a)return!1;if(s<=23&&i<=59&&o<60)return!0;let d=i-u*c,f=s-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&o<61}}function vd(r,e){if(!(r&&e))return;let t=new Date("2020-01-01T"+r).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(t&&n)return t-n}function km(r,e){if(!(r&&e))return;let t=gd.exec(r),n=gd.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=vA}function EA(r){return Number.isInteger(r)}function Em(){return!0}var AA=/[^\\]\\Z/;function kA(r){if(AA.test(r))return!1;try{return new RegExp(r),!0}catch(e){return!1}}});var Om=E($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var xA=cl(),PA=El(),IA=zl(),TA=ad(),Tm=cd(),OA=[xA.default,PA.default,(0,IA.default)(),TA.default,Tm.metadataVocabulary,Tm.contentVocabulary];$d.default=OA});var Rm=E((ZM,RA)=>{RA.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Cm=E((ge,Sd)=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.MissingRefError=ge.ValidationError=ge.CodeGen=ge.Name=ge.nil=ge.stringify=ge.str=ge._=ge.KeywordCxt=ge.Ajv=void 0;var MA=il(),CA=Om(),NA=fd(),Mm=Rm(),LA=["/properties"],Mo="http://json-schema.org/draft-07/schema",Hn=class extends MA.default{_addVocabularies(){super._addVocabularies(),CA.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(NA.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Mm,LA):Mm;this.addMetaSchema(e,Mo,!1),this.refs["http://json-schema.org/schema"]=Mo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Mo)?Mo:void 0)}};ge.Ajv=Hn;Sd.exports=ge=Hn;Sd.exports.Ajv=Hn;Object.defineProperty(ge,"__esModule",{value:!0});ge.default=Hn;var DA=Rn();Object.defineProperty(ge,"KeywordCxt",{enumerable:!0,get:function(){return DA.KeywordCxt}});var Bn=B();Object.defineProperty(ge,"_",{enumerable:!0,get:function(){return Bn._}});Object.defineProperty(ge,"str",{enumerable:!0,get:function(){return Bn.str}});Object.defineProperty(ge,"stringify",{enumerable:!0,get:function(){return Bn.stringify}});Object.defineProperty(ge,"nil",{enumerable:!0,get:function(){return Bn.nil}});Object.defineProperty(ge,"Name",{enumerable:!0,get:function(){return Bn.Name}});Object.defineProperty(ge,"CodeGen",{enumerable:!0,get:function(){return Bn.CodeGen}});var qA=js();Object.defineProperty(ge,"ValidationError",{enumerable:!0,get:function(){return qA.default}});var jA=Mn();Object.defineProperty(ge,"MissingRefError",{enumerable:!0,get:function(){return jA.default}})});var Nm=E(zn=>{"use strict";Object.defineProperty(zn,"__esModule",{value:!0});zn.formatLimitDefinition=void 0;var FA=Cm(),It=B(),qr=It.operators,Co={formatMaximum:{okStr:"<=",ok:qr.LTE,fail:qr.GT},formatMinimum:{okStr:">=",ok:qr.GTE,fail:qr.LT},formatExclusiveMaximum:{okStr:"<",ok:qr.LT,fail:qr.GTE},formatExclusiveMinimum:{okStr:">",ok:qr.GT,fail:qr.LTE}},VA={message:({keyword:r,schemaCode:e})=>(0,It.str)`should be ${Co[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,It._)`{comparison: ${Co[r].okStr}, limit: ${e}}`};zn.formatLimitDefinition={keyword:Object.keys(Co),type:"string",schemaType:"string",$data:!0,error:VA,code(r){let{gen:e,data:t,schemaCode:n,keyword:s,it:i}=r,{opts:o,self:a}=i;if(!o.validateFormats)return;let c=new FA.KeywordCxt(i,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let f=e.scopeValue("formats",{ref:a.formats,code:o.code.formats}),p=e.const("fmt",(0,It._)`${f}[${c.schemaCode}]`);r.fail$data((0,It.or)((0,It._)`typeof ${p} != "object"`,(0,It._)`${p} instanceof RegExp`,(0,It._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${s}": format "${f}" does not define "compare" function`);let m=e.scopeValue("formats",{key:f,ref:p,code:o.code.formats?(0,It._)`${o.code.formats}${(0,It.getProperty)(f)}`:void 0});r.fail$data(d(m))}function d(f){return(0,It._)`${f}.compare(${t}, ${n}) ${Co[s].fail} 0`}},dependencies:["format"]};var UA=r=>(r.addKeyword(zn.formatLimitDefinition),r);zn.default=UA});var kd=E((ri,qm)=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});var Kn=Im(),HA=Nm(),Ed=B(),Lm=new Ed.Name("fullFormats"),BA=new Ed.Name("fastFormats"),Ad=(r,e={keywords:!0})=>{if(Array.isArray(e))return Dm(r,e,Kn.fullFormats,Lm),r;let[t,n]=e.mode==="fast"?[Kn.fastFormats,BA]:[Kn.fullFormats,Lm],s=e.formats||Kn.formatNames;return Dm(r,s,t,n),e.keywords&&(0,HA.default)(r),r};Ad.get=(r,e="full")=>{let n=(e==="fast"?Kn.fastFormats:Kn.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function Dm(r,e,t,n){var s,i;(s=(i=r.opts.code).formats)!==null&&s!==void 0||(i.formats=(0,Ed._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}qm.exports=ri=Ad;Object.defineProperty(ri,"__esModule",{value:!0});ri.default=Ad});var Jn=E((aC,zm)=>{"use strict";var WA="2.0.0",GA=Number.MAX_SAFE_INTEGER||9007199254740991,JA=16,YA=250,XA=["major","premajor","minor","preminor","patch","prepatch","prerelease"];zm.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:JA,MAX_SAFE_BUILD_LENGTH:YA,MAX_SAFE_INTEGER:GA,RELEASE_TYPES:XA,SEMVER_SPEC_VERSION:WA,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var ni=E((cC,Km)=>{"use strict";var QA=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Km.exports=QA});var Yn=E((Qt,Wm)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Td,MAX_SAFE_BUILD_LENGTH:ZA,MAX_LENGTH:ek}=Jn(),tk=ni();Qt=Wm.exports={};var rk=Qt.re=[],nk=Qt.safeRe=[],D=Qt.src=[],sk=Qt.safeSrc=[],q=Qt.t={},ik=0,Od="[a-zA-Z0-9-]",ok=[["\\s",1],["\\d",ek],[Od,ZA]],ak=r=>{for(let[e,t]of ok)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},z=(r,e,t)=>{let n=ak(e),s=ik++;tk(r,s,e),q[r]=s,D[s]=e,sk[s]=n,rk[s]=new RegExp(e,t?"g":void 0),nk[s]=new RegExp(n,t?"g":void 0)};z("NUMERICIDENTIFIER","0|[1-9]\\d*");z("NUMERICIDENTIFIERLOOSE","\\d+");z("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Od}*`);z("MAINVERSION",`(${D[q.NUMERICIDENTIFIER]})\\.(${D[q.NUMERICIDENTIFIER]})\\.(${D[q.NUMERICIDENTIFIER]})`);z("MAINVERSIONLOOSE",`(${D[q.NUMERICIDENTIFIERLOOSE]})\\.(${D[q.NUMERICIDENTIFIERLOOSE]})\\.(${D[q.NUMERICIDENTIFIERLOOSE]})`);z("PRERELEASEIDENTIFIER",`(?:${D[q.NONNUMERICIDENTIFIER]}|${D[q.NUMERICIDENTIFIER]})`);z("PRERELEASEIDENTIFIERLOOSE",`(?:${D[q.NONNUMERICIDENTIFIER]}|${D[q.NUMERICIDENTIFIERLOOSE]})`);z("PRERELEASE",`(?:-(${D[q.PRERELEASEIDENTIFIER]}(?:\\.${D[q.PRERELEASEIDENTIFIER]})*))`);z("PRERELEASELOOSE",`(?:-?(${D[q.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${D[q.PRERELEASEIDENTIFIERLOOSE]})*))`);z("BUILDIDENTIFIER",`${Od}+`);z("BUILD",`(?:\\+(${D[q.BUILDIDENTIFIER]}(?:\\.${D[q.BUILDIDENTIFIER]})*))`);z("FULLPLAIN",`v?${D[q.MAINVERSION]}${D[q.PRERELEASE]}?${D[q.BUILD]}?`);z("FULL",`^${D[q.FULLPLAIN]}$`);z("LOOSEPLAIN",`[v=\\s]*${D[q.MAINVERSIONLOOSE]}${D[q.PRERELEASELOOSE]}?${D[q.BUILD]}?`);z("LOOSE",`^${D[q.LOOSEPLAIN]}$`);z("GTLT","((?:<|>)?=?)");z("XRANGEIDENTIFIERLOOSE",`${D[q.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);z("XRANGEIDENTIFIER",`${D[q.NUMERICIDENTIFIER]}|x|X|\\*`);z("XRANGEPLAIN",`[v=\\s]*(${D[q.XRANGEIDENTIFIER]})(?:\\.(${D[q.XRANGEIDENTIFIER]})(?:\\.(${D[q.XRANGEIDENTIFIER]})(?:${D[q.PRERELEASE]})?${D[q.BUILD]}?)?)?`);z("XRANGEPLAINLOOSE",`[v=\\s]*(${D[q.XRANGEIDENTIFIERLOOSE]})(?:\\.(${D[q.XRANGEIDENTIFIERLOOSE]})(?:\\.(${D[q.XRANGEIDENTIFIERLOOSE]})(?:${D[q.PRERELEASELOOSE]})?${D[q.BUILD]}?)?)?`);z("XRANGE",`^${D[q.GTLT]}\\s*${D[q.XRANGEPLAIN]}$`);z("XRANGELOOSE",`^${D[q.GTLT]}\\s*${D[q.XRANGEPLAINLOOSE]}$`);z("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Td}})(?:\\.(\\d{1,${Td}}))?(?:\\.(\\d{1,${Td}}))?`);z("COERCE",`${D[q.COERCEPLAIN]}(?:$|[^\\d])`);z("COERCEFULL",D[q.COERCEPLAIN]+`(?:${D[q.PRERELEASE]})?(?:${D[q.BUILD]})?(?:$|[^\\d])`);z("COERCERTL",D[q.COERCE],!0);z("COERCERTLFULL",D[q.COERCEFULL],!0);z("LONETILDE","(?:~>?)");z("TILDETRIM",`(\\s*)${D[q.LONETILDE]}\\s+`,!0);Qt.tildeTrimReplace="$1~";z("TILDE",`^${D[q.LONETILDE]}${D[q.XRANGEPLAIN]}$`);z("TILDELOOSE",`^${D[q.LONETILDE]}${D[q.XRANGEPLAINLOOSE]}$`);z("LONECARET","(?:\\^)");z("CARETTRIM",`(\\s*)${D[q.LONECARET]}\\s+`,!0);Qt.caretTrimReplace="$1^";z("CARET",`^${D[q.LONECARET]}${D[q.XRANGEPLAIN]}$`);z("CARETLOOSE",`^${D[q.LONECARET]}${D[q.XRANGEPLAINLOOSE]}$`);z("COMPARATORLOOSE",`^${D[q.GTLT]}\\s*(${D[q.LOOSEPLAIN]})$|^$`);z("COMPARATOR",`^${D[q.GTLT]}\\s*(${D[q.FULLPLAIN]})$|^$`);z("COMPARATORTRIM",`(\\s*)${D[q.GTLT]}\\s*(${D[q.LOOSEPLAIN]}|${D[q.XRANGEPLAIN]})`,!0);Qt.comparatorTrimReplace="$1$2$3";z("HYPHENRANGE",`^\\s*(${D[q.XRANGEPLAIN]})\\s+-\\s+(${D[q.XRANGEPLAIN]})\\s*$`);z("HYPHENRANGELOOSE",`^\\s*(${D[q.XRANGEPLAINLOOSE]})\\s+-\\s+(${D[q.XRANGEPLAINLOOSE]})\\s*$`);z("STAR","(<|>)?=?\\s*\\*");z("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");z("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Do=E((lC,Gm)=>{"use strict";var ck=Object.freeze({loose:!0}),lk=Object.freeze({}),dk=r=>r?typeof r!="object"?ck:r:lk;Gm.exports=dk});var Rd=E((dC,Xm)=>{"use strict";var Jm=/^[0-9]+$/,Ym=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rYm(e,r);Xm.exports={compareIdentifiers:Ym,rcompareIdentifiers:uk}});var Le=E((uC,Zm)=>{"use strict";var qo=ni(),{MAX_LENGTH:Qm,MAX_SAFE_INTEGER:jo}=Jn(),{safeRe:Fo,t:Vo}=Yn(),fk=Do(),{compareIdentifiers:Md}=Rd(),pk=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nQm)throw new TypeError(`version is longer than ${Qm} characters`);qo("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Fo[Vo.LOOSE]:Fo[Vo.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>jo||this.major<0)throw new TypeError("Invalid major version");if(this.minor>jo||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>jo||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let i=+s;if(i>=0&&ie.major?1:this.minore.minor?1:this.patche.patch?1:0}comparePre(e){if(e instanceof r||(e=new r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let n=this.prerelease[t],s=e.prerelease[t];if(qo("prerelease compare",t,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Md(n,s)}while(++t)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let t=0;do{let n=this.build[t],s=e.build[t];if(qo("build compare",t,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Md(n,s)}while(++t)}inc(e,t,n){if(e.startsWith("pre")){if(!t&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(t){let s=`-${t}`.match(this.options.loose?Fo[Vo.PRERELEASELOOSE]:Fo[Vo.PRERELEASE]);if(!s||s[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,n),this.inc("pre",t,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,n),this.inc("pre",t,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let i=this.prerelease.length;for(;--i>=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);if(i===-1){if(t===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(t){let i=[t,s];if(n===!1&&(i=[t]),pk(this.prerelease,t)){let o=this.prerelease[t.split(".").length];isNaN(o)&&(this.prerelease=i)}else this.prerelease=i}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Zm.exports=Cd});var Fr=E((fC,ty)=>{"use strict";var ey=Le(),hk=(r,e,t=!1)=>{if(r instanceof ey)return r;try{return new ey(r,e)}catch(n){if(!t)return null;throw n}};ty.exports=hk});var ny=E((pC,ry)=>{"use strict";var mk=Fr(),yk=(r,e)=>{let t=mk(r,e);return t?t.version:null};ry.exports=yk});var iy=E((hC,sy)=>{"use strict";var gk=Fr(),bk=(r,e)=>{let t=gk(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};sy.exports=bk});var cy=E((mC,ay)=>{"use strict";var oy=Le(),wk=(r,e,t,n,s)=>{typeof t=="string"&&(s=n,n=t,t=void 0);try{return new oy(r instanceof oy?r.version:r,t).inc(e,n,s).version}catch(i){return null}};ay.exports=wk});var uy=E((yC,dy)=>{"use strict";var ly=Fr(),_k=(r,e)=>{let t=ly(r,null,!0),n=ly(e,null,!0),s=t.compare(n);if(s===0)return null;let i=s>0,o=i?t:n,a=i?n:t,c=!!o.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0)return a.minor&&!a.patch?"minor":"patch"}let u=c?"pre":"";return t.major!==n.major?u+"major":t.minor!==n.minor?u+"minor":t.patch!==n.patch?u+"patch":"prerelease"};dy.exports=_k});var py=E((gC,fy)=>{"use strict";var vk=Le(),$k=(r,e)=>new vk(r,e).major;fy.exports=$k});var my=E((bC,hy)=>{"use strict";var Sk=Le(),Ek=(r,e)=>new Sk(r,e).minor;hy.exports=Ek});var gy=E((wC,yy)=>{"use strict";var Ak=Le(),kk=(r,e)=>new Ak(r,e).patch;yy.exports=kk});var wy=E((_C,by)=>{"use strict";var xk=Fr(),Pk=(r,e)=>{let t=xk(r,e);return t&&t.prerelease.length?t.prerelease:null};by.exports=Pk});var gt=E((vC,vy)=>{"use strict";var _y=Le(),Ik=(r,e,t)=>new _y(r,t).compare(new _y(e,t));vy.exports=Ik});var Sy=E(($C,$y)=>{"use strict";var Tk=gt(),Ok=(r,e,t)=>Tk(e,r,t);$y.exports=Ok});var Ay=E((SC,Ey)=>{"use strict";var Rk=gt(),Mk=(r,e)=>Rk(r,e,!0);Ey.exports=Mk});var Uo=E((EC,xy)=>{"use strict";var ky=Le(),Ck=(r,e,t)=>{let n=new ky(r,t),s=new ky(e,t);return n.compare(s)||n.compareBuild(s)};xy.exports=Ck});var Iy=E((AC,Py)=>{"use strict";var Nk=Uo(),Lk=(r,e)=>r.sort((t,n)=>Nk(t,n,e));Py.exports=Lk});var Oy=E((kC,Ty)=>{"use strict";var Dk=Uo(),qk=(r,e)=>r.sort((t,n)=>Dk(n,t,e));Ty.exports=qk});var si=E((xC,Ry)=>{"use strict";var jk=gt(),Fk=(r,e,t)=>jk(r,e,t)>0;Ry.exports=Fk});var Ho=E((PC,My)=>{"use strict";var Vk=gt(),Uk=(r,e,t)=>Vk(r,e,t)<0;My.exports=Uk});var Nd=E((IC,Cy)=>{"use strict";var Hk=gt(),Bk=(r,e,t)=>Hk(r,e,t)===0;Cy.exports=Bk});var Ld=E((TC,Ny)=>{"use strict";var zk=gt(),Kk=(r,e,t)=>zk(r,e,t)!==0;Ny.exports=Kk});var Bo=E((OC,Ly)=>{"use strict";var Wk=gt(),Gk=(r,e,t)=>Wk(r,e,t)>=0;Ly.exports=Gk});var zo=E((RC,Dy)=>{"use strict";var Jk=gt(),Yk=(r,e,t)=>Jk(r,e,t)<=0;Dy.exports=Yk});var Dd=E((MC,qy)=>{"use strict";var Xk=Nd(),Qk=Ld(),Zk=si(),ex=Bo(),tx=Ho(),rx=zo(),nx=(r,e,t,n)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return Xk(r,t,n);case"!=":return Qk(r,t,n);case">":return Zk(r,t,n);case">=":return ex(r,t,n);case"<":return tx(r,t,n);case"<=":return rx(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};qy.exports=nx});var Fy=E((CC,jy)=>{"use strict";var sx=Le(),ix=Fr(),{safeRe:Ko,t:Wo}=Yn(),ox=(r,e)=>{if(r instanceof sx)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?Ko[Wo.COERCEFULL]:Ko[Wo.COERCE]);else{let c=e.includePrerelease?Ko[Wo.COERCERTLFULL]:Ko[Wo.COERCERTL],l;for(;(l=c.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||l.index+l[0].length!==t.index+t[0].length)&&(t=l),c.lastIndex=l.index+l[1].length+l[2].length;c.lastIndex=-1}if(t===null)return null;let n=t[2],s=t[3]||"0",i=t[4]||"0",o=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return ix(`${n}.${s}.${i}${o}${a}`,e)};jy.exports=ox});var Uy=E((NC,Vy)=>{"use strict";var ax=Fr(),cx=Jn(),lx=Le(),dx=(r,e,t)=>{if(!cx.RELEASE_TYPES.includes(e))return null;let n=ux(r,t);return n&&fx(n,e)},ux=(r,e)=>{let t=r instanceof lx?r.version:r;return ax(t,e)},fx=(r,e)=>{if(px(e))return r.version;switch(r.prerelease=[],e){case"major":r.minor=0,r.patch=0;break;case"minor":r.patch=0;break}return r.format()},px=r=>r.startsWith("pre");Vy.exports=dx});var By=E((LC,Hy)=>{"use strict";var qd=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let s=this.map.keys().next().value;this.delete(s)}this.map.set(e,t)}return this}};Hy.exports=qd});var bt=E((DC,Gy)=>{"use strict";var hx=/\s+/g,jd=class r{constructor(e,t){if(t=yx(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof Fd)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(hx," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(s=>!Ky(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&Ax(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e0&&(this.formatted+="||");let t=this.set[e];for(let n=0;n0&&(this.formatted+=" "),this.formatted+=t[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){e=e.replace(Ex,"");let n=((this.options.includePrerelease&&$x)|(this.options.loose&&Sx))+":"+e,s=zy.get(n);if(s)return s;let i=this.options.loose,o=i?Ke[De.HYPHENRANGELOOSE]:Ke[De.HYPHENRANGE];e=e.replace(o,Lx(this.options.includePrerelease)),be("hyphen replace",e),e=e.replace(Ke[De.COMPARATORTRIM],wx),be("comparator trim",e),e=e.replace(Ke[De.TILDETRIM],_x),be("tilde trim",e),e=e.replace(Ke[De.CARETTRIM],vx),be("caret trim",e);let a=e.split(" ").map(d=>kx(d,this.options)).join(" ").split(/\s+/).map(d=>Nx(d,this.options));i&&(a=a.filter(d=>(be("loose invalid filter",d,this.options),!!d.match(Ke[De.COMPARATORLOOSE])))),be("range list",a);let c=new Map,l=a.map(d=>new Fd(d,this.options));for(let d of l){if(Ky(d))return[d];c.set(d.value,d)}c.size>1&&c.has("")&&c.delete("");let u=[...c.values()];return zy.set(n,u),u}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>Wy(n,t)&&e.set.some(s=>Wy(s,t)&&n.every(i=>s.every(o=>i.intersects(o,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new gx(e,this.options)}catch(t){return!1}for(let t=0;tr.value==="<0.0.0-0",Ax=r=>r.value==="",Wy=(r,e)=>{let t=!0,n=r.slice(),s=n.pop();for(;t&&n.length;)t=n.every(i=>s.intersects(i,e)),s=n.pop();return t},kx=(r,e)=>(r=r.replace(Ke[De.BUILD],""),be("comp",r,e),r=Tx(r,e),be("caret",r),r=Px(r,e),be("tildes",r),r=Rx(r,e),be("xrange",r),r=Cx(r,e),be("stars",r),r),Ie=r=>!r||r.toLowerCase()==="x"||r==="*",xx=(r,e,t)=>Ie(r)&&!Ie(e)||Ie(e)&&t&&!Ie(t),Px=(r,e)=>r.trim().split(/\s+/).map(t=>Ix(t,e)).join(" "),Ix=(r,e)=>{let t=e.loose?Ke[De.TILDELOOSE]:Ke[De.TILDE],n=e.includePrerelease?"-0":"";return r.replace(t,(s,i,o,a,c)=>{be("tilde",r,s,i,o,a,c);let l;return Ie(i)?l="":Ie(o)?l=`>=${i}.0.0${n} <${+i+1}.0.0-0`:Ie(a)?l=`>=${i}.${o}.0${n} <${i}.${+o+1}.0-0`:c?(be("replaceTilde pr",c),l=`>=${i}.${o}.${a}-${c} <${i}.${+o+1}.0-0`):l=`>=${i}.${o}.${a} <${i}.${+o+1}.0-0`,be("tilde return",l),l})},Tx=(r,e)=>r.trim().split(/\s+/).map(t=>Ox(t,e)).join(" "),Ox=(r,e)=>{be("caret",r,e);let t=e.loose?Ke[De.CARETLOOSE]:Ke[De.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(s,i,o,a,c)=>{be("caret",r,s,i,o,a,c);let l;return Ie(i)?l="":Ie(o)?l=`>=${i}.0.0${n} <${+i+1}.0.0-0`:Ie(a)?i==="0"?l=`>=${i}.${o}.0${n} <${i}.${+o+1}.0-0`:l=`>=${i}.${o}.0${n} <${+i+1}.0.0-0`:c?(be("replaceCaret pr",c),i==="0"?o==="0"?l=`>=${i}.${o}.${a}-${c} <${i}.${o}.${+a+1}-0`:l=`>=${i}.${o}.${a}-${c} <${i}.${+o+1}.0-0`:l=`>=${i}.${o}.${a}-${c} <${+i+1}.0.0-0`):(be("no pr"),i==="0"?o==="0"?l=`>=${i}.${o}.${a} <${i}.${o}.${+a+1}-0`:l=`>=${i}.${o}.${a} <${i}.${+o+1}.0-0`:l=`>=${i}.${o}.${a} <${+i+1}.0.0-0`),be("caret return",l),l})},Rx=(r,e)=>(be("replaceXRanges",r,e),r.split(/\s+/).map(t=>Mx(t,e)).join(" ")),Mx=(r,e)=>{r=r.trim();let t=e.loose?Ke[De.XRANGELOOSE]:Ke[De.XRANGE];return r.replace(t,(n,s,i,o,a,c)=>{if(be("xRange",r,n,s,i,o,a,c),xx(i,o,a))return r;let l=Ie(i),u=l||Ie(o),d=u||Ie(a),f=d;return s==="="&&f&&(s=""),c=e.includePrerelease?"-0":"",l?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&f?(u&&(o=0),a=0,s===">"?(s=">=",u?(i=+i+1,o=0,a=0):(o=+o+1,a=0)):s==="<="&&(s="<",u?i=+i+1:o=+o+1),s==="<"&&(c="-0"),n=`${s+i}.${o}.${a}${c}`):u?n=`>=${i}.0.0${c} <${+i+1}.0.0-0`:d&&(n=`>=${i}.${o}.0${c} <${i}.${+o+1}.0-0`),be("xRange return",n),n})},Cx=(r,e)=>(be("replaceStars",r,e),r.trim().replace(Ke[De.STAR],"")),Nx=(r,e)=>(be("replaceGTE0",r,e),r.trim().replace(Ke[e.includePrerelease?De.GTE0PRE:De.GTE0],"")),Lx=r=>(e,t,n,s,i,o,a,c,l,u,d,f)=>(Ie(n)?t="":Ie(s)?t=`>=${n}.0.0${r?"-0":""}`:Ie(i)?t=`>=${n}.${s}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Ie(l)?c="":Ie(u)?c=`<${+l+1}.0.0-0`:Ie(d)?c=`<${l}.${+u+1}.0-0`:f?c=`<=${l}.${u}.${d}-${f}`:r?c=`<${l}.${u}.${+d+1}-0`:c=`<=${c}`,`${t} ${c}`.trim()),Dx=(r,e,t)=>{for(let n=0;n0){let s=r[n].semver;if(s.major===e.major&&s.minor===e.minor&&s.patch===e.patch)return!0}return!1}return!0}});var ii=E((qC,eg)=>{"use strict";var oi=Symbol("SemVer ANY"),Hd=class r{static get ANY(){return oi}constructor(e,t){if(t=Jy(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Ud("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===oi?this.value="":this.value=this.operator+this.semver.version,Ud("comp",this)}parse(e){let t=this.options.loose?Yy[Xy.COMPARATORLOOSE]:Yy[Xy.COMPARATOR],n=e.match(t);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Qy(n[2],this.options.loose):this.semver=oi}toString(){return this.value}test(e){if(Ud("Comparator.test",e,this.options.loose),this.semver===oi||e===oi)return!0;if(typeof e=="string")try{e=new Qy(e,this.options)}catch(t){return!1}return Vd(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Zy(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Zy(this.value,t).test(e.semver):(t=Jy(t),t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||Vd(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Vd(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};eg.exports=Hd;var Jy=Do(),{safeRe:Yy,t:Xy}=Yn(),Vd=Dd(),Ud=ni(),Qy=Le(),Zy=bt()});var ai=E((jC,tg)=>{"use strict";var qx=bt(),jx=(r,e,t)=>{try{e=new qx(e,t)}catch(n){return!1}return e.test(r)};tg.exports=jx});var ng=E((FC,rg)=>{"use strict";var Fx=bt(),Vx=(r,e)=>new Fx(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));rg.exports=Vx});var ig=E((VC,sg)=>{"use strict";var Ux=Le(),Hx=bt(),Bx=(r,e,t)=>{let n=null,s=null,i=null;try{i=new Hx(e,t)}catch(o){return null}return r.forEach(o=>{i.test(o)&&(!n||s.compare(o)===-1)&&(n=o,s=new Ux(n,t))}),n};sg.exports=Bx});var ag=E((UC,og)=>{"use strict";var zx=Le(),Kx=bt(),Wx=(r,e,t)=>{let n=null,s=null,i=null;try{i=new Kx(e,t)}catch(o){return null}return r.forEach(o=>{i.test(o)&&(!n||s.compare(o)===1)&&(n=o,s=new zx(n,t))}),n};og.exports=Wx});var dg=E((HC,lg)=>{"use strict";var Bd=Le(),Gx=bt(),cg=si(),Jx=(r,e)=>{r=new Gx(r,e);let t=new Bd("0.0.0");if(r.test(t)||(t=new Bd("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new Bd(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!i||cg(a,i))&&(i=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),i&&(!t||cg(t,i))&&(t=i)}return t&&r.test(t)?t:null};lg.exports=Jx});var fg=E((BC,ug)=>{"use strict";var Yx=bt(),Xx=(r,e)=>{try{return new Yx(r,e).range||"*"}catch(t){return null}};ug.exports=Xx});var Go=E((zC,yg)=>{"use strict";var Qx=Le(),mg=ii(),{ANY:Zx}=mg,eP=bt(),tP=ai(),pg=si(),hg=Ho(),rP=zo(),nP=Bo(),sP=(r,e,t,n)=>{r=new Qx(r,n),e=new eP(e,n);let s,i,o,a,c;switch(t){case">":s=pg,i=rP,o=hg,a=">",c=">=";break;case"<":s=hg,i=nP,o=pg,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(tP(r,e,n))return!1;for(let l=0;l{p.semver===Zx&&(p=new mg(">=0.0.0")),d=d||p,f=f||p,s(p.semver,d.semver,n)?d=p:o(p.semver,f.semver,n)&&(f=p)}),d.operator===a||d.operator===c||(!f.operator||f.operator===a)&&i(r,f.semver))return!1;if(f.operator===c&&o(r,f.semver))return!1}return!0};yg.exports=sP});var bg=E((KC,gg)=>{"use strict";var iP=Go(),oP=(r,e,t)=>iP(r,e,">",t);gg.exports=oP});var _g=E((WC,wg)=>{"use strict";var aP=Go(),cP=(r,e,t)=>aP(r,e,"<",t);wg.exports=cP});var Sg=E((GC,$g)=>{"use strict";var vg=bt(),lP=(r,e,t)=>(r=new vg(r,t),e=new vg(e,t),r.intersects(e,t));$g.exports=lP});var Ag=E((JC,Eg)=>{"use strict";var dP=ai(),uP=gt();Eg.exports=(r,e,t)=>{let n=[],s=null,i=null,o=r.sort((u,d)=>uP(u,d,t));for(let u of o)dP(u,e,t)?(i=u,s||(s=u)):(i&&n.push([s,i]),i=null,s=null);s&&n.push([s,null]);let a=[];for(let[u,d]of n)u===d?a.push(u):!d&&u===o[0]?a.push("*"):d?u===o[0]?a.push(`<=${d}`):a.push(`${u} - ${d}`):a.push(`>=${u}`);let c=a.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return c.length{"use strict";var kg=bt(),Wd=ii(),{ANY:zd}=Wd,Kd=ai(),Gd=gt(),fP=(r,e,t={})=>{if(r===e)return!0;r=new kg(r,t),e=new kg(e,t);let n=!1;e:for(let s of r.set){for(let i of e.set){let o=hP(s,i,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},pP=[new Wd(">=0.0.0-0")],xg=[new Wd(">=0.0.0")],hP=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===zd){if(e.length===1&&e[0].semver===zd)return!0;t.includePrerelease?r=pP:r=xg}if(e.length===1&&e[0].semver===zd){if(t.includePrerelease)return!0;e=xg}let n=new Set,s,i;for(let p of r)p.operator===">"||p.operator===">="?s=Pg(s,p,t):p.operator==="<"||p.operator==="<="?i=Ig(i,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(s&&i){if(o=Gd(s.semver,i.semver,t),o>0)return null;if(o===0&&(s.operator!==">="||i.operator!=="<="))return null}for(let p of n){if(s&&!Kd(p,String(s),t)||i&&!Kd(p,String(i),t))return null;for(let m of e)if(!Kd(p,String(m),t))return!1;return!0}let a,c,l,u,d=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1,f=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1;d&&d.prerelease.length===1&&i.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let p of e){if(u=u||p.operator===">"||p.operator===">=",l=l||p.operator==="<"||p.operator==="<=",s){if(f&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch&&(f=!1),p.operator===">"||p.operator===">="){if(a=Pg(s,p,t),a===p&&a!==s)return!1}else if(s.operator===">="&&!p.test(s.semver))return!1}if(i){if(d&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===d.major&&p.semver.minor===d.minor&&p.semver.patch===d.patch&&(d=!1),p.operator==="<"||p.operator==="<="){if(c=Ig(i,p,t),c===p&&c!==i)return!1}else if(i.operator==="<="&&!p.test(i.semver))return!1}if(!p.operator&&(i||s)&&o!==0)return!1}return!(s&&l&&!i&&o!==0||i&&u&&!s&&o!==0||f||d)},Pg=(r,e,t)=>{if(!r)return e;let n=Gd(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},Ig=(r,e,t)=>{if(!r)return e;let n=Gd(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};Tg.exports=fP});var Ng=E((XC,Cg)=>{"use strict";var Jd=Yn(),Rg=Jn(),mP=Le(),Mg=Rd(),yP=Fr(),gP=ny(),bP=iy(),wP=cy(),_P=uy(),vP=py(),$P=my(),SP=gy(),EP=wy(),AP=gt(),kP=Sy(),xP=Ay(),PP=Uo(),IP=Iy(),TP=Oy(),OP=si(),RP=Ho(),MP=Nd(),CP=Ld(),NP=Bo(),LP=zo(),DP=Dd(),qP=Fy(),jP=Uy(),FP=ii(),VP=bt(),UP=ai(),HP=ng(),BP=ig(),zP=ag(),KP=dg(),WP=fg(),GP=Go(),JP=bg(),YP=_g(),XP=Sg(),QP=Ag(),ZP=Og();Cg.exports={parse:yP,valid:gP,clean:bP,inc:wP,diff:_P,major:vP,minor:$P,patch:SP,prerelease:EP,compare:AP,rcompare:kP,compareLoose:xP,compareBuild:PP,sort:IP,rsort:TP,gt:OP,lt:RP,eq:MP,neq:CP,gte:NP,lte:LP,cmp:DP,coerce:qP,truncate:jP,Comparator:FP,Range:VP,satisfies:UP,toComparators:HP,maxSatisfying:BP,minSatisfying:zP,minVersion:KP,validRange:WP,outside:GP,gtr:JP,ltr:YP,intersects:XP,simplifyRange:QP,subset:ZP,SemVer:mP,re:Jd.re,src:Jd.src,tokens:Jd.t,SEMVER_SPEC_VERSION:Rg.SEMVER_SPEC_VERSION,RELEASE_TYPES:Rg.RELEASE_TYPES,compareIdentifiers:Mg.compareIdentifiers,rcompareIdentifiers:Mg.rcompareIdentifiers}});var li=E((mN,zg)=>{"use strict";var Vg="[^\\\\/]",cI="(?=.)",Ug="[^/]",eu="(?:\\/|$)",Hg="(?:^|\\/)",tu=`\\.{1,2}${eu}`,lI="(?!\\.)",dI=`(?!${Hg}${tu})`,uI=`(?!\\.{0,1}${eu})`,fI=`(?!${tu})`,pI="[^.\\/]",hI=`${Ug}*?`,mI="/",Bg={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:cI,QMARK:Ug,END_ANCHOR:eu,DOTS_SLASH:tu,NO_DOT:lI,NO_DOTS:dI,NO_DOT_SLASH:uI,NO_DOTS_SLASH:fI,QMARK_NO_DOT:pI,STAR:hI,START_ANCHOR:Hg,SEP:mI},yI={...Bg,SLASH_LITERAL:"[\\\\/]",QMARK:Vg,STAR:`${Vg}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},gI={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};zg.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:gI,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(r){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${r.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(r){return r===!0?yI:Bg}}});var di=E(et=>{"use strict";var{REGEX_BACKSLASH:bI,REGEX_REMOVE_BACKSLASH:wI,REGEX_SPECIAL_CHARS:_I,REGEX_SPECIAL_CHARS_GLOBAL:vI}=li();et.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);et.hasRegexChars=r=>_I.test(r);et.isRegexChar=r=>r.length===1&&et.hasRegexChars(r);et.escapeRegex=r=>r.replace(vI,"\\$1");et.toPosixSlashes=r=>r.replace(bI,"/");et.isWindows=()=>{if(typeof navigator!="undefined"&&navigator.platform){let r=navigator.platform.toLowerCase();return r==="win32"||r==="windows"}return typeof process!="undefined"&&process.platform?process.platform==="win32":!1};et.removeBackslashes=r=>r.replace(wI,e=>e==="\\"?"":e);et.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?et.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};et.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};et.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",s=t.contains?"":"$",i=`${n}(?:${r})${s}`;return e.negated===!0&&(i=`(?:^(?!${i}).*$)`),i};et.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n}});var Zg=E((gN,Qg)=>{"use strict";var Kg=di(),{CHAR_ASTERISK:ru,CHAR_AT:$I,CHAR_BACKWARD_SLASH:ui,CHAR_COMMA:SI,CHAR_DOT:nu,CHAR_EXCLAMATION_MARK:su,CHAR_FORWARD_SLASH:Xg,CHAR_LEFT_CURLY_BRACE:iu,CHAR_LEFT_PARENTHESES:ou,CHAR_LEFT_SQUARE_BRACKET:EI,CHAR_PLUS:AI,CHAR_QUESTION_MARK:Wg,CHAR_RIGHT_CURLY_BRACE:kI,CHAR_RIGHT_PARENTHESES:Gg,CHAR_RIGHT_SQUARE_BRACKET:xI}=li(),Jg=r=>r===Xg||r===ui,Yg=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},PI=(r,e)=>{let t=e||{},n=r.length-1,s=t.parts===!0||t.scanToEnd===!0,i=[],o=[],a=[],c=r,l=-1,u=0,d=0,f=!1,p=!1,m=!1,h=!1,y=!1,b=!1,g=!1,_=!1,I=!1,v=!1,S=0,k,$,P={value:"",depth:0,isGlob:!1},w=()=>l>=n,N=()=>c.charCodeAt(l+1),j=()=>(k=$,c.charCodeAt(++l));for(;l0&&(A=c.slice(0,u),c=c.slice(u),d-=u),H&&m===!0&&d>0?(H=c.slice(0,d),x=c.slice(d)):m===!0?(H="",x=c):H=c,H&&H!==""&&H!=="/"&&H!==c&&Jg(H.charCodeAt(H.length-1))&&(H=H.slice(0,-1)),t.unescape===!0&&(x&&(x=Kg.removeBackslashes(x)),H&&g===!0&&(H=Kg.removeBackslashes(H)));let _e={prefix:A,input:r,start:u,base:H,glob:x,isBrace:f,isBracket:p,isGlob:m,isExtglob:h,isGlobstar:y,negated:_,negatedExtglob:I};if(t.tokens===!0&&(_e.maxDepth=0,Jg($)||o.push(P),_e.tokens=o),t.parts===!0||t.tokens===!0){let oe;for(let ae=0;ae{"use strict";var fi=li(),ot=di(),{MAX_LENGTH:Qo,POSIX_REGEX_SOURCE:II,REGEX_NON_SPECIAL_CHARS:TI,REGEX_SPECIAL_CHARS_BACKREF:OI,REPLACEMENTS:eb}=fi,RI=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch(n){return r.map(s=>ot.escapeRegex(s)).join("..")}return t},Xn=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,tb=r=>{let e=[],t=0,n=0,s=0,i="",o=!1;for(let a of r){if(o===!0){i+=a,o=!1;continue}if(a==="\\"){i+=a,o=!0;continue}if(a==='"'){s=s===1?0:1,i+=a;continue}if(s===0){if(a==="[")t++;else if(a==="]"&&t>0)t--;else if(t===0){if(a==="(")n++;else if(a===")"&&n>0)n--;else if(a==="|"&&n===0){e.push(i),i="";continue}}}i+=a}return e.push(i),e},MI=r=>{let e=!1;for(let t of r){if(e===!0){e=!1;continue}if(t==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(t))return!1}return!0},cu=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(MI(e))return e.replace(/\\(.)/g,"$1")},CI=r=>{let e=r.map(cu).filter(Boolean);for(let t=0;t{if(r[0]!=="+"&&r[0]!=="*"||r[1]!=="(")return;let t=0,n=0,s=0,i=!1;for(let o=1;o0){t--;continue}if(!(t>0)){if(a==="("){n++;continue}if(a===")"&&(n--,n===0))return e===!0&&o!==r.length-1?void 0:{type:r[0],body:r.slice(2,o),end:o}}}}},NI=r=>`${r.length===1?ot.escapeRegex(r[0]):`[${r.map(t=>ot.escapeRegex(t)).join("")}]`}*`,LI=r=>{let e=0,t=[];for(;eo.trim());if(s.length!==1)return;let i=cu(s[0]);if(!i||i.length!==1)return;t.push(i),e+=n.end+1}if(!(t.length<1))return t},DI=r=>{let e=0,t=r.trim(),n=au(t);for(;n;)e++,t=n.body.trim(),n=au(t);return e},qI=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:fi.DEFAULT_MAX_EXTGLOB_RECURSION,n=tb(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||CI(n)))return{risky:!0};let s=[],i=!1,o=!0;for(let a of n){let c=LI(a);if(c){i=!0,s.push(...c);continue}let l=cu(a);if(l&&l.length===1){s.push(l);continue}if(o=!1,DI(a)>t)return{risky:!0}}return i?o?{risky:!0,safeOutput:NI([...new Set(s)])}:{risky:!0}:{risky:!1}},lu=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=eb[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(Qo,t.maxLength):Qo,s=r.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);let i={type:"bos",value:"",output:t.prepend||""},o=[i],a=t.capture?"":"?:",c=fi.globChars(t.windows),l=fi.extglobChars(c),{DOT_LITERAL:u,PLUS_LITERAL:d,SLASH_LITERAL:f,ONE_CHAR:p,DOTS_SLASH:m,NO_DOT:h,NO_DOT_SLASH:y,NO_DOTS_SLASH:b,QMARK:g,QMARK_NO_DOT:_,STAR:I,START_ANCHOR:v}=c,S=M=>`(${a}(?:(?!${v}${M.dot?m:u}).)*?)`,k=t.dot?"":h,$=t.dot?g:_,P=t.bash===!0?S(t):I;t.capture&&(P=`(${P})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let w={input:r,index:-1,start:0,dot:t.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};r=ot.removePrefix(r,w),s=r.length;let N=[],j=[],H=[],A=i,x,_e=()=>w.index===s-1,oe=w.peek=(M=1)=>r[w.index+M],ae=w.advance=()=>r[++w.index]||"",ar=()=>r.slice(w.index+1),ut=(M="",ve=0)=>{w.consumed+=M,w.index+=ve},Pr=M=>{w.output+=M.output!=null?M.output:M.value,ut(M.value)},_w=()=>{let M=1;for(;oe()==="!"&&(oe(2)!=="("||oe(3)==="?");)ae(),w.start++,M++;return M%2===0?!1:(w.negated=!0,w.start++,!0)},Qi=M=>{w[M]++,H.push(M)},Ir=M=>{w[M]--,H.pop()},X=M=>{if(A.type==="globstar"){let ve=w.braces>0&&(M.type==="comma"||M.type==="brace"),R=M.extglob===!0||N.length&&(M.type==="pipe"||M.type==="paren");M.type!=="slash"&&M.type!=="paren"&&!ve&&!R&&(w.output=w.output.slice(0,-A.output.length),A.type="star",A.value="*",A.output=P,w.output+=A.output)}if(N.length&&M.type!=="paren"&&(N[N.length-1].inner+=M.value),(M.value||M.output)&&Pr(M),A&&A.type==="text"&&M.type==="text"){A.output=(A.output||A.value)+M.value,A.value+=M.value;return}M.prev=A,o.push(M),A=M},Zi=(M,ve)=>{let R={...l[ve],conditions:1,inner:""};R.prev=A,R.parens=w.parens,R.output=w.output,R.startIndex=w.index,R.tokensIndex=o.length;let Q=(t.capture?"(":"")+R.open;Qi("parens"),X({type:M,value:ve,output:w.output?"":p}),X({type:"paren",extglob:!0,value:ae(),output:Q}),N.push(R)},vw=M=>{let ve=r.slice(M.startIndex,w.index+1),R=r.slice(M.startIndex+2,w.index),Q=qI(R,t);if((M.type==="plus"||M.type==="star")&&Q.risky){let fe=Q.safeOutput?(M.output?"":p)+(t.capture?`(${Q.safeOutput})`:Q.safeOutput):void 0,Bt=o[M.tokensIndex];Bt.type="text",Bt.value=ve,Bt.output=fe||ot.escapeRegex(ve);for(let zt=M.tokensIndex+1;zt1&&M.inner.includes("/")&&(fe=S(t)),(fe!==P||_e()||/^\)+$/.test(ar()))&&(he=M.close=`)$))${fe}`),M.inner.includes("*")&&(Pe=ar())&&/^\.[^\\/.]+$/.test(Pe)){let Bt=lu(Pe,{...e,fastpaths:!1}).output;he=M.close=`)${Bt})${fe})`}M.prev.type==="bos"&&(w.negatedExtglob=!0)}X({type:"paren",extglob:!0,value:x,output:he}),Ir("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let M=!1,ve=r.replace(OI,(R,Q,he,Pe,fe,Bt)=>Pe==="\\"?(M=!0,R):Pe==="?"?Q?Q+Pe+(fe?g.repeat(fe.length):""):Bt===0?$+(fe?g.repeat(fe.length):""):g.repeat(he.length):Pe==="."?u.repeat(he.length):Pe==="*"?Q?Q+Pe+(fe?P:""):P:Q?R:`\\${R}`);return M===!0&&(t.unescape===!0?ve=ve.replace(/\\/g,""):ve=ve.replace(/\\+/g,R=>R.length%2===0?"\\\\":R?"\\":"")),ve===r&&t.contains===!0?(w.output=r,w):(w.output=ot.wrapOutput(ve,w,e),w)}for(;!_e();){if(x=ae(),x==="\0")continue;if(x==="\\"){let R=oe();if(R==="/"&&t.bash!==!0||R==="."||R===";")continue;if(!R){x+="\\",X({type:"text",value:x});continue}let Q=/^\\+/.exec(ar()),he=0;if(Q&&Q[0].length>2&&(he=Q[0].length,w.index+=he,he%2!==0&&(x+="\\")),t.unescape===!0?x=ae():x+=ae(),w.brackets===0){X({type:"text",value:x});continue}}if(w.brackets>0&&(x!=="]"||A.value==="["||A.value==="[^")){if(t.posix!==!1&&x===":"){let R=A.value.slice(1);if(R.includes("[")&&(A.posix=!0,R.includes(":"))){let Q=A.value.lastIndexOf("["),he=A.value.slice(0,Q),Pe=A.value.slice(Q+2),fe=II[Pe];if(fe){A.value=he+fe,w.backtrack=!0,ae(),!i.output&&o.indexOf(A)===1&&(i.output=p);continue}}}(x==="["&&oe()!==":"||x==="-"&&oe()==="]")&&(x=`\\${x}`),x==="]"&&(A.value==="["||A.value==="[^")&&(x=`\\${x}`),t.posix===!0&&x==="!"&&A.value==="["&&(x="^"),A.value+=x,Pr({value:x});continue}if(w.quotes===1&&x!=='"'){x=ot.escapeRegex(x),A.value+=x,Pr({value:x});continue}if(x==='"'){w.quotes=w.quotes===1?0:1,t.keepQuotes===!0&&X({type:"text",value:x});continue}if(x==="("){Qi("parens"),X({type:"paren",value:x});continue}if(x===")"){if(w.parens===0&&t.strictBrackets===!0)throw new SyntaxError(Xn("opening","("));let R=N[N.length-1];if(R&&w.parens===R.parens+1){vw(N.pop());continue}X({type:"paren",value:x,output:w.parens?")":"\\)"}),Ir("parens");continue}if(x==="["){if(t.nobracket===!0||!ar().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(Xn("closing","]"));x=`\\${x}`}else Qi("brackets");X({type:"bracket",value:x});continue}if(x==="]"){if(t.nobracket===!0||A&&A.type==="bracket"&&A.value.length===1){X({type:"text",value:x,output:`\\${x}`});continue}if(w.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(Xn("opening","["));X({type:"text",value:x,output:`\\${x}`});continue}Ir("brackets");let R=A.value.slice(1);if(A.posix!==!0&&R[0]==="^"&&!R.includes("/")&&(x=`/${x}`),A.value+=x,Pr({value:x}),t.literalBrackets===!1||ot.hasRegexChars(R))continue;let Q=ot.escapeRegex(A.value);if(w.output=w.output.slice(0,-A.value.length),t.literalBrackets===!0){w.output+=Q,A.value=Q;continue}A.value=`(${a}${Q}|${A.value})`,w.output+=A.value;continue}if(x==="{"&&t.nobrace!==!0){Qi("braces");let R={type:"brace",value:x,output:"(",outputIndex:w.output.length,tokensIndex:w.tokens.length};j.push(R),X(R);continue}if(x==="}"){let R=j[j.length-1];if(t.nobrace===!0||!R){X({type:"text",value:x,output:x});continue}let Q=")";if(R.dots===!0){let he=o.slice(),Pe=[];for(let fe=he.length-1;fe>=0&&(o.pop(),he[fe].type!=="brace");fe--)he[fe].type!=="dots"&&Pe.unshift(he[fe].value);Q=RI(Pe,t),w.backtrack=!0}if(R.comma!==!0&&R.dots!==!0){let he=w.output.slice(0,R.outputIndex),Pe=w.tokens.slice(R.tokensIndex);R.value=R.output="\\{",x=Q="\\}",w.output=he;for(let fe of Pe)w.output+=fe.output||fe.value}X({type:"brace",value:x,output:Q}),Ir("braces"),j.pop();continue}if(x==="|"){N.length>0&&N[N.length-1].conditions++,X({type:"text",value:x});continue}if(x===","){let R=x,Q=j[j.length-1];Q&&H[H.length-1]==="braces"&&(Q.comma=!0,R="|"),X({type:"comma",value:x,output:R});continue}if(x==="/"){if(A.type==="dot"&&w.index===w.start+1){w.start=w.index+1,w.consumed="",w.output="",o.pop(),A=i;continue}X({type:"slash",value:x,output:f});continue}if(x==="."){if(w.braces>0&&A.type==="dot"){A.value==="."&&(A.output=u);let R=j[j.length-1];A.type="dots",A.output+=x,A.value+=x,R.dots=!0;continue}if(w.braces+w.parens===0&&A.type!=="bos"&&A.type!=="slash"){X({type:"text",value:x,output:u});continue}X({type:"dot",value:x,output:u});continue}if(x==="?"){if(!(A&&A.value==="(")&&t.noextglob!==!0&&oe()==="("&&oe(2)!=="?"){Zi("qmark",x);continue}if(A&&A.type==="paren"){let Q=oe(),he=x;(A.value==="("&&!/[!=<:]/.test(Q)||Q==="<"&&!/<([!=]|\w+>)/.test(ar()))&&(he=`\\${x}`),X({type:"text",value:x,output:he});continue}if(t.dot!==!0&&(A.type==="slash"||A.type==="bos")){X({type:"qmark",value:x,output:_});continue}X({type:"qmark",value:x,output:g});continue}if(x==="!"){if(t.noextglob!==!0&&oe()==="("&&(oe(2)!=="?"||!/[!=<:]/.test(oe(3)))){Zi("negate",x);continue}if(t.nonegate!==!0&&w.index===0){_w();continue}}if(x==="+"){if(t.noextglob!==!0&&oe()==="("&&oe(2)!=="?"){Zi("plus",x);continue}if(A&&A.value==="("||t.regex===!1){X({type:"plus",value:x,output:d});continue}if(A&&(A.type==="bracket"||A.type==="paren"||A.type==="brace")||w.parens>0){X({type:"plus",value:x});continue}X({type:"plus",value:d});continue}if(x==="@"){if(t.noextglob!==!0&&oe()==="("&&oe(2)!=="?"){X({type:"at",extglob:!0,value:x,output:""});continue}X({type:"text",value:x});continue}if(x!=="*"){(x==="$"||x==="^")&&(x=`\\${x}`);let R=TI.exec(ar());R&&(x+=R[0],w.index+=R[0].length),X({type:"text",value:x});continue}if(A&&(A.type==="globstar"||A.star===!0)){A.type="star",A.star=!0,A.value+=x,A.output=P,w.backtrack=!0,w.globstar=!0,ut(x);continue}let M=ar();if(t.noextglob!==!0&&/^\([^?]/.test(M)){Zi("star",x);continue}if(A.type==="star"){if(t.noglobstar===!0){ut(x);continue}let R=A.prev,Q=R.prev,he=R.type==="slash"||R.type==="bos",Pe=Q&&(Q.type==="star"||Q.type==="globstar");if(t.bash===!0&&(!he||M[0]&&M[0]!=="/")){X({type:"star",value:x,output:""});continue}let fe=w.braces>0&&(R.type==="comma"||R.type==="brace"),Bt=N.length&&(R.type==="pipe"||R.type==="paren");if(!he&&R.type!=="paren"&&!fe&&!Bt){X({type:"star",value:x,output:""});continue}for(;M.slice(0,3)==="/**";){let zt=r[w.index+4];if(zt&&zt!=="/")break;M=M.slice(3),ut("/**",3)}if(R.type==="bos"&&_e()){A.type="globstar",A.value+=x,A.output=S(t),w.output=A.output,w.globstar=!0,ut(x);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&!Pe&&_e()){w.output=w.output.slice(0,-(R.output+A.output).length),R.output=`(?:${R.output}`,A.type="globstar",A.output=S(t)+(t.strictSlashes?")":"|$)"),A.value+=x,w.globstar=!0,w.output+=R.output+A.output,ut(x);continue}if(R.type==="slash"&&R.prev.type!=="bos"&&M[0]==="/"){let zt=M[1]!==void 0?"|$":"";w.output=w.output.slice(0,-(R.output+A.output).length),R.output=`(?:${R.output}`,A.type="globstar",A.output=`${S(t)}${f}|${f}${zt})`,A.value+=x,w.output+=R.output+A.output,w.globstar=!0,ut(x+ae()),X({type:"slash",value:"/",output:""});continue}if(R.type==="bos"&&M[0]==="/"){A.type="globstar",A.value+=x,A.output=`(?:^|${f}|${S(t)}${f})`,w.output=A.output,w.globstar=!0,ut(x+ae()),X({type:"slash",value:"/",output:""});continue}w.output=w.output.slice(0,-A.output.length),A.type="globstar",A.output=S(t),A.value+=x,w.output+=A.output,w.globstar=!0,ut(x);continue}let ve={type:"star",value:x,output:P};if(t.bash===!0){ve.output=".*?",(A.type==="bos"||A.type==="slash")&&(ve.output=k+ve.output),X(ve);continue}if(A&&(A.type==="bracket"||A.type==="paren")&&t.regex===!0){ve.output=x,X(ve);continue}(w.index===w.start||A.type==="slash"||A.type==="dot")&&(A.type==="dot"?(w.output+=y,A.output+=y):t.dot===!0?(w.output+=b,A.output+=b):(w.output+=k,A.output+=k),oe()!=="*"&&(w.output+=p,A.output+=p)),X(ve)}for(;w.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xn("closing","]"));w.output=ot.escapeLast(w.output,"["),Ir("brackets")}for(;w.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xn("closing",")"));w.output=ot.escapeLast(w.output,"("),Ir("parens")}for(;w.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(Xn("closing","}"));w.output=ot.escapeLast(w.output,"{"),Ir("braces")}if(t.strictSlashes!==!0&&(A.type==="star"||A.type==="bracket")&&X({type:"maybe_slash",value:"",output:`${f}?`}),w.backtrack===!0){w.output="";for(let M of w.tokens)w.output+=M.output!=null?M.output:M.value,M.suffix&&(w.output+=M.suffix)}return w};lu.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(Qo,t.maxLength):Qo,s=r.length;if(s>n)throw new SyntaxError(`Input length: ${s}, exceeds maximum allowed length: ${n}`);r=eb[r]||r;let{DOT_LITERAL:i,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:c,NO_DOT:l,NO_DOTS:u,NO_DOTS_SLASH:d,STAR:f,START_ANCHOR:p}=fi.globChars(t.windows),m=t.dot?u:l,h=t.dot?d:l,y=t.capture?"":"?:",b={negated:!1,prefix:""},g=t.bash===!0?".*?":f;t.capture&&(g=`(${g})`);let _=k=>k.noglobstar===!0?g:`(${y}(?:(?!${p}${k.dot?c:i}).)*?)`,I=k=>{switch(k){case"*":return`${m}${a}${g}`;case".*":return`${i}${a}${g}`;case"*.*":return`${m}${g}${i}${a}${g}`;case"*/*":return`${m}${g}${o}${a}${h}${g}`;case"**":return m+_(t);case"**/*":return`(?:${m}${_(t)}${o})?${h}${a}${g}`;case"**/*.*":return`(?:${m}${_(t)}${o})?${h}${g}${i}${a}${g}`;case"**/.*":return`(?:${m}${_(t)}${o})?${i}${a}${g}`;default:{let $=/^(.*?)\.(\w+)$/.exec(k);if(!$)return;let P=I($[1]);return P?P+i+$[2]:void 0}}},v=ot.removePrefix(r,b),S=I(v);return S&&t.strictSlashes!==!0&&(S+=`${o}?`),S};rb.exports=lu});var ob=E((wN,ib)=>{"use strict";var jI=Zg(),du=nb(),sb=di(),FI=li(),VI=r=>r&&typeof r=="object"&&!Array.isArray(r),Ae=(r,e,t=!1)=>{if(Array.isArray(r)){let u=r.map(f=>Ae(f,e,t));return f=>{for(let p of u){let m=p(f);if(m)return m}return!1}}let n=VI(r)&&r.tokens&&r.input;if(r===""||typeof r!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let s=e||{},i=s.windows,o=n?Ae.compileRe(r,e):Ae.makeRe(r,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(s.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};c=Ae(s.ignore,u,t)}let l=(u,d=!1)=>{let{isMatch:f,match:p,output:m}=Ae.test(u,o,e,{glob:r,posix:i}),h={glob:r,state:a,regex:o,posix:i,input:u,output:m,match:p,isMatch:f};return typeof s.onResult=="function"&&s.onResult(h),f===!1?(h.isMatch=!1,d?h:!1):c(u)?(typeof s.onIgnore=="function"&&s.onIgnore(h),h.isMatch=!1,d?h:!1):(typeof s.onMatch=="function"&&s.onMatch(h),d?h:!0)};return t&&(l.state=a),l};Ae.test=(r,e,t,{glob:n,posix:s}={})=>{if(typeof r!="string")throw new TypeError("Expected input to be a string");if(r==="")return{isMatch:!1,output:""};let i=t||{},o=i.format||(s?sb.toPosixSlashes:null),a=r===n,c=a&&o?o(r):r;return a===!1&&(c=o?o(r):r,a=c===n),(a===!1||i.capture===!0)&&(i.matchBase===!0||i.basename===!0?a=Ae.matchBase(r,e,t,s):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};Ae.matchBase=(r,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:Ae.makeRe(e,t)).test(sb.basename(r,{windows:n}));Ae.isMatch=(r,e,t)=>Ae(e,t)(r);Ae.parse=(r,e)=>Array.isArray(r)?r.map(t=>Ae.parse(t,e)):du(r,{...e,fastpaths:!1});Ae.scan=(r,e)=>jI(r,e);Ae.compileRe=(r,e,t=!1,n=!1)=>{if(t===!0)return r.output;let s=e||{},i=s.contains?"":"^",o=s.contains?"":"$",a=`${i}(?:${r.output})${o}`;r&&r.negated===!0&&(a=`^(?!${a}).*$`);let c=Ae.toRegex(a,e);return n===!0&&(c.state=r),c};Ae.makeRe=(r,e={},t=!1,n=!1)=>{if(!r||typeof r!="string")throw new TypeError("Expected a non-empty string");let s={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(r[0]==="."||r[0]==="*")&&(s.output=du.fastpaths(r,e)),s.output||(s=du(r,e)),Ae.compileRe(s,e,t,n)};Ae.toRegex=(r,e)=>{try{let t=e||{};return new RegExp(r,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===!0)throw t;return/$^/}};Ae.constants=FI;ib.exports=Ae});var uu=E((_N,lb)=>{"use strict";var ab=ob(),UI=di();function cb(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:UI.isWindows()}),ab(r,e,t)}Object.assign(cb,ab);lb.exports=cb});var hR={};Pw(hR,{default:()=>cc});module.exports=Iw(hR);var L=require("obsidian");var C=class extends Error{constructor(t,n,s){super(n);O(this,"code");O(this,"details");this.code=t,this.details=s,this.name="InteropError"}toPortableError(t){return{code:this.code,message:this.message,...this.details===void 0?{}:{details:this.details},...t===void 0?{}:{retryable:t}}}},As=class extends Error{constructor(t,n){super(n.message);O(this,"status");O(this,"error");this.status=t,this.error=n,this.name="ActionHandlerError"}};var jm=Zr(yd(),1),Fm=Zr(kd(),1);var xd={contract:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/v0.3/data-contract.schema.json",title:"mdbase v0.3 contract frontmatter",type:"object",required:["kind","contract_type","id","version"],properties:{kind:{const:"mdbase.contract"},contract_type:{enum:["record","event","action"]},id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersion"},name:{type:"string",minLength:1},description:{type:"string"},record_schema:{$ref:"#/$defs/schemaWrapper"},binding_schema:{$ref:"#/$defs/schemaWrapper"},data_schema:{$ref:"#/$defs/schemaWrapper"},source_schema:{$ref:"#/$defs/schemaWrapper"},input_schema:{$ref:"#/$defs/schemaWrapper"},output_schema:{$ref:"#/$defs/schemaWrapper"},error_schema:{$ref:"#/$defs/schemaWrapper"},provider_schema:{$ref:"#/$defs/schemaWrapper"},behavior:{$ref:"#/$defs/actionBehavior"}},patternProperties:{"^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$":!0},oneOf:[{properties:{contract_type:{const:"record"},record_schema:!0,binding_schema:!0,data_schema:!1,source_schema:!1,input_schema:!1,output_schema:!1,error_schema:!1,provider_schema:!1,behavior:!1},required:["record_schema"]},{properties:{contract_type:{const:"event"},record_schema:!1,binding_schema:!1,data_schema:!0,source_schema:!0,input_schema:!1,output_schema:!1,error_schema:!1,provider_schema:!1,behavior:!1},required:["data_schema"]},{properties:{contract_type:{const:"action"},record_schema:!1,binding_schema:!1,data_schema:!1,source_schema:!1,input_schema:!0,output_schema:!0,error_schema:!0,provider_schema:!0,behavior:!0},required:["input_schema"]}],additionalProperties:!1,$defs:{contractId:{type:"string",minLength:3,maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$"},semanticVersion:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},schemaWrapper:{type:"object",required:["dialect"],properties:{dialect:{const:"json-schema-2020-12"},value:{type:"object"},ref:{type:"string",minLength:1}},oneOf:[{required:["value"],properties:{value:!0,ref:!1}},{required:["ref"],properties:{ref:!0,value:!1}}],additionalProperties:!1},actionBehavior:{type:"object",properties:{idempotency:{enum:["none","optional","required"]},cancellation:{enum:["none","cooperative"]}},additionalProperties:!1}}},profile:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/profile.schema.json",title:"mdbase event and action interoperability profile 0.1",oneOf:[{$ref:"#/$defs/event"},{$ref:"#/$defs/actionRequest"},{$ref:"#/$defs/actionInvocation"},{$ref:"#/$defs/actionOutcome"},{$ref:"#/$defs/actionCancellation"},{$ref:"#/$defs/eventSourceDeclaration"},{$ref:"#/$defs/actionProviderDeclaration"},{$ref:"#/$defs/conformanceClaim"}],$defs:{contractId:{type:"string",minLength:3,maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$"},semanticVersion:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},semanticVersionRequirement:{type:"string",minLength:1,maxLength:128},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"},portableId:{type:"string",minLength:1,maxLength:256,pattern:"^[A-Za-z0-9][A-Za-z0-9._:@/-]*$"},exactContract:{type:"object",required:["id","version","digest"],properties:{id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersion"},digest:{$ref:"#/$defs/digest"}},additionalProperties:!1},contractRequirement:{type:"object",required:["id","version"],properties:{id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersionRequirement"},digest:{$ref:"#/$defs/digest"}},additionalProperties:!1},implementationIdentity:{type:"object",required:["application","implementation","version"],properties:{application:{$ref:"#/$defs/portableId"},implementation:{$ref:"#/$defs/portableId"},version:{$ref:"#/$defs/semanticVersion"},instance_id:{$ref:"#/$defs/portableId"}},additionalProperties:!1},transportCapabilities:{type:"object",required:["delivery","ordering","cancellation","deadlines"],properties:{delivery:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["ephemeral","at_least_once","durable_cursor","offline_queue"]}},ordering:{type:"array",uniqueItems:!0,items:{enum:["none","source","subject"]}},cancellation:{type:"boolean"},deadlines:{type:"boolean"},provider_discovery:{type:"boolean"},max_payload_bytes:{type:"integer",minimum:1},outcome_retention_seconds:{type:"integer",minimum:0},request_deduplication:{type:"boolean"},cross_process_identity:{type:"boolean"}},additionalProperties:!1},extensionValue:{oneOf:[{type:"null"},{type:"boolean"},{type:"integer"},{type:"number"},{type:"string"}]},event:{title:"mdbase CloudEvents event envelope",type:"object",required:["specversion","id","source","type","time","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion"],properties:{specversion:{const:"1.0"},id:{$ref:"#/$defs/portableId"},source:{type:"string",format:"uri-reference",minLength:1},type:{$ref:"#/$defs/contractId"},time:{type:"string",format:"date-time"},subject:{type:"string",format:"uri-reference",minLength:1},datacontenttype:{const:"application/json"},dataschema:{type:"string",format:"uri",minLength:1},data:!0,mdbaseprofile:{const:"0.1"},mdbasecontractversion:{$ref:"#/$defs/semanticVersion"},mdbasecontractdigest:{$ref:"#/$defs/digest"},mdbaseapplication:{$ref:"#/$defs/portableId"},mdbaseimplementation:{$ref:"#/$defs/portableId"},mdbaseimplementationversion:{$ref:"#/$defs/semanticVersion"},mdbaseinstanceid:{$ref:"#/$defs/portableId"},correlationid:{$ref:"#/$defs/portableId"},causationid:{$ref:"#/$defs/portableId"}},propertyNames:{pattern:"^[a-z0-9]+$"},additionalProperties:{$ref:"#/$defs/extensionValue"}},actionRequest:{title:"mdbase action request",type:"object",required:["kind","profile_version","request_id","contract","caller","created_at","input"],properties:{kind:{const:"mdbase.action.request"},profile_version:{const:"0.1"},request_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/contractRequirement"},caller:{$ref:"#/$defs/implementationIdentity"},created_at:{type:"string",format:"date-time"},correlation_id:{$ref:"#/$defs/portableId"},causation_id:{$ref:"#/$defs/portableId"},subject:{type:"string",format:"uri-reference",minLength:1},idempotency_key:{type:"string",minLength:1,maxLength:512},deadline:{type:"string",format:"date-time"},requested_provider:{type:"object",properties:{application:{$ref:"#/$defs/portableId"},implementation:{$ref:"#/$defs/portableId"},instance_id:{$ref:"#/$defs/portableId"}},minProperties:1,additionalProperties:!1},authorization_context:{type:"string",format:"uri-reference",minLength:1},input:!0},additionalProperties:!1},actionInvocation:{title:"mdbase admitted action invocation",type:"object",required:["kind","profile_version","invocation_id","attempt_id","request_id","contract","caller","provider","provider_declaration_digest","handler_id","admitted_at","input"],properties:{kind:{const:"mdbase.action.invocation"},profile_version:{const:"0.1"},invocation_id:{$ref:"#/$defs/portableId"},attempt_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/exactContract"},caller:{$ref:"#/$defs/implementationIdentity"},provider:{$ref:"#/$defs/implementationIdentity"},provider_declaration_digest:{$ref:"#/$defs/digest"},handler_id:{$ref:"#/$defs/portableId"},admitted_at:{type:"string",format:"date-time"},correlation_id:{$ref:"#/$defs/portableId"},causation_id:{$ref:"#/$defs/portableId"},subject:{type:"string",format:"uri-reference",minLength:1},idempotency_key:{type:"string",minLength:1,maxLength:512},deadline:{type:"string",format:"date-time"},authorization_context:{type:"string",format:"uri-reference",minLength:1},input:!0},additionalProperties:!1},portableError:{type:"object",required:["code","message"],properties:{code:{enum:["unknown_contract","unsupported_contract_version","contract_digest_conflict","invalid_event_data","invalid_action_input","invalid_action_output","no_provider","ambiguous_provider","requested_provider_unavailable","unauthorized","capability_denied","request_rejected","deadline_exceeded","cancellation_unsupported","cancelled","handler_failure","outcome_indeterminate","transport_unavailable","unsupported_transport_capability"]},message:{type:"string",minLength:1},details:!0,retryable:{type:"boolean"}},additionalProperties:!1},actionOutcome:{title:"mdbase action outcome",type:"object",required:["kind","profile_version","outcome_id","request_id","invocation_id","attempt_id","contract","provider","provider_declaration_digest","status","completed_at"],properties:{kind:{const:"mdbase.action.outcome"},profile_version:{const:"0.1"},outcome_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},invocation_id:{$ref:"#/$defs/portableId"},attempt_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/exactContract"},provider:{$ref:"#/$defs/implementationIdentity"},provider_declaration_digest:{$ref:"#/$defs/digest"},status:{enum:["succeeded","rejected","failed","cancelled","outcome_indeterminate"]},completed_at:{type:"string",format:"date-time"},output:!0,error:{$ref:"#/$defs/portableError"}},allOf:[{if:{properties:{status:{const:"succeeded"}},required:["status"]},then:{required:["output"],not:{required:["error"]}},else:{required:["error"],not:{required:["output"]}}}],additionalProperties:!1},actionCancellation:{title:"mdbase action cancellation request",type:"object",required:["kind","profile_version","cancellation_id","request_id","caller","requested_at"],properties:{kind:{const:"mdbase.action.cancel"},profile_version:{const:"0.1"},cancellation_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},caller:{$ref:"#/$defs/implementationIdentity"},requested_at:{type:"string",format:"date-time"},reason:{type:"string",maxLength:1024}},additionalProperties:!1},eventSourceDeclaration:{title:"mdbase event-source declaration",type:"object",required:["kind","profile_version","declaration_id","declaration_digest","source","contracts"],properties:{kind:{const:"mdbase.event-source"},profile_version:{const:"0.1"},declaration_id:{$ref:"#/$defs/portableId"},declaration_digest:{$ref:"#/$defs/digest"},source:{$ref:"#/$defs/implementationIdentity"},contracts:{type:"array",minItems:1,items:{type:"object",required:["requirement","resolved"],properties:{requirement:{$ref:"#/$defs/contractRequirement"},resolved:{$ref:"#/$defs/exactContract"},binding:!0,ordering:{type:"array",uniqueItems:!0,items:{enum:["none","source","subject"]}}},additionalProperties:!1}}},additionalProperties:!1},actionProviderDeclaration:{title:"mdbase action-provider declaration",type:"object",required:["kind","profile_version","declaration_id","declaration_digest","provider","handlers"],properties:{kind:{const:"mdbase.action-provider"},profile_version:{const:"0.1"},declaration_id:{$ref:"#/$defs/portableId"},declaration_digest:{$ref:"#/$defs/digest"},provider:{$ref:"#/$defs/implementationIdentity"},handlers:{type:"array",minItems:1,items:{type:"object",required:["handler_id","requirement","resolved"],properties:{handler_id:{$ref:"#/$defs/portableId"},requirement:{$ref:"#/$defs/contractRequirement"},resolved:{$ref:"#/$defs/exactContract"},binding:!0,idempotency:{type:"object",required:["mode"],properties:{mode:{enum:["none","request"]},retention_seconds:{type:"integer",minimum:1}},additionalProperties:!1},cancellation:{enum:["none","cooperative"]},max_concurrency:{type:"integer",minimum:1}},additionalProperties:!1}}},additionalProperties:!1},conformanceClaim:{title:"mdbase interoperability conformance claim",type:"object",required:["kind","profile_version","implementation","roles","transport"],properties:{kind:{const:"mdbase.interop.conformance"},profile_version:{const:"0.1"},implementation:{$ref:"#/$defs/implementationIdentity"},roles:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["event_source","event_consumer","action_caller","action_provider","bridge"]}},transport:{$ref:"#/$defs/transportCapabilities"},evidence:{type:"array",items:{type:"object",required:["scenario","result"],properties:{scenario:{type:"string",minLength:1},result:{const:"pass"},uri:{type:"string",format:"uri-reference"}},additionalProperties:!1}}},additionalProperties:!1}}},event:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/event.schema.json",title:"mdbase CloudEvents event envelope",$ref:"profile.schema.json#/$defs/event"},actionRequest:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-request.schema.json",title:"mdbase action request",$ref:"profile.schema.json#/$defs/actionRequest"},actionInvocation:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-invocation.schema.json",title:"mdbase admitted action invocation",$ref:"profile.schema.json#/$defs/actionInvocation"},actionOutcome:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-outcome.schema.json",title:"mdbase action outcome",$ref:"profile.schema.json#/$defs/actionOutcome"},actionCancellation:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-cancellation.schema.json",title:"mdbase action cancellation request",$ref:"profile.schema.json#/$defs/actionCancellation"},eventSourceDeclaration:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/event-source-declaration.schema.json",title:"mdbase event-source declaration",$ref:"profile.schema.json#/$defs/eventSourceDeclaration"},actionProviderDeclaration:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-provider-declaration.schema.json",title:"mdbase action-provider declaration",$ref:"profile.schema.json#/$defs/actionProviderDeclaration"},conformanceClaim:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/conformance-claim.schema.json",title:"mdbase interoperability conformance claim",$ref:"profile.schema.json#/$defs/conformanceClaim"}};var zA=Fm.default;function Vm(){return Object.fromEntries(Object.entries(xd).map(([r,e])=>[r,structuredClone(e)]))}function Pd(){let r=new jm.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});zA(r);let e=Vm();r.addSchema(e.profile);for(let[t,n]of Object.entries(e))t!=="profile"&&r.addSchema(n);return r}function ur(r,e){let t=String(xd[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function jr(r){return(r!=null?r:[]).map(e=>{var t;return`${e.instancePath||"/"} ${(t=e.message)!=null?t:e.keyword}`}).join("; ")}function Xt(r,e){if(!("value"in r))throw new C("contract_digest_conflict",`${e} must be resolved to an inline JSON Schema before runtime registration.`);return structuredClone(r.value)}function Um(r){let e={kind:r.kind,contract_type:r.contract_type,id:r.id,version:r.version};switch(r.contract_type){case"record":e.record_schema=Xt(r.record_schema,"record_schema"),r.binding_schema&&(e.binding_schema=Xt(r.binding_schema,"binding_schema"));break;case"event":e.data_schema=Xt(r.data_schema,"data_schema"),r.source_schema&&(e.source_schema=Xt(r.source_schema,"source_schema"));break;case"action":e.input_schema=Xt(r.input_schema,"input_schema"),r.output_schema&&(e.output_schema=Xt(r.output_schema,"output_schema")),r.error_schema&&(e.error_schema=Xt(r.error_schema,"error_schema")),r.provider_schema&&(e.provider_schema=Xt(r.provider_schema,"provider_schema")),r.behavior&&(e.behavior=structuredClone(r.behavior));break}return e}async function No(r){return Gn(Um(r))}async function Gn(r){return`sha256:${await KA(Id(r))}`}function Hm(r,e){return{data:Wn(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:Wn(r,e.source_schema,`${e.id} source_schema`)}:{}}}function Bm(r,e){return{input:Wn(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:Wn(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:Wn(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:Wn(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function Lo(r,e,t,n){if(!(!r||r(e)))throw new C(t,`${n} failed JSON Schema validation: ${jr(r.errors)}`)}function Wn(r,e,t){try{return r.compile(Xt(e,t))}catch(n){throw new C("contract_digest_conflict",`${t} could not be compiled: ${n instanceof Error?n.message:String(n)}`)}}function Id(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(Id).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${Id(n)}`).join(",")}}`}async function KA(r){let e=new TextEncoder().encode(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(n=>n.toString(16).padStart(2,"0")).join("")}var pr=Zr(Ng(),1);var Yd={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},eI=new Set(["specversion","id","source","type","time","subject","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion","mdbaseinstanceid","correlationid","causationid"]),ci=class{constructor(e={}){O(this,"options");O(this,"profileVersion","0.1");O(this,"transport");O(this,"ajv",Pd());O(this,"contractValidator",ur(this.ajv,"contract"));O(this,"eventValidator",ur(this.ajv,"event"));O(this,"actionRequestValidator",ur(this.ajv,"actionRequest"));O(this,"actionInvocationValidator",ur(this.ajv,"actionInvocation"));O(this,"actionOutcomeValidator",ur(this.ajv,"actionOutcome"));O(this,"eventSourceDeclarationValidator",ur(this.ajv,"eventSourceDeclaration"));O(this,"actionProviderDeclarationValidator",ur(this.ajv,"actionProviderDeclaration"));O(this,"contracts",new Map);O(this,"clients",new Map);O(this,"eventSources",new Map);O(this,"actionProviders",new Map);O(this,"subscriptions",new Map);O(this,"activeActions",new Map);O(this,"completedActions",new Map);O(this,"admissionLocks",new Map);O(this,"recentEvents",new Map);O(this,"authorize");O(this,"now");O(this,"idFactory");O(this,"recentEventLimit");O(this,"completedRequestLimit");O(this,"nextSequence",0);O(this,"disposed",!1);var t,n,s,i,o,a,c,l,u,d;this.options=e,this.authorize=(t=e.authorize)!=null?t:(()=>!1),this.now=(n=e.now)!=null?n:(()=>new Date),this.idFactory=(s=e.idFactory)!=null?s:(f=>{var m;this.nextSequence+=1;let p=typeof((m=globalThis.crypto)==null?void 0:m.randomUUID)=="function"?globalThis.crypto.randomUUID():`${this.now().getTime().toString(36)}-${this.nextSequence.toString(36)}`;return`${f}_${p}`}),this.recentEventLimit=Math.max(1,(i=e.recentEventLimit)!=null?i:1e3),this.completedRequestLimit=Math.max(1,(o=e.completedRequestLimit)!=null?o:1e3),this.transport={...Yd,...structuredClone((a=e.transport)!=null?a:{}),delivery:[...(l=(c=e.transport)==null?void 0:c.delivery)!=null?l:Yd.delivery],ordering:[...(d=(u=e.transport)==null?void 0:u.ordering)!=null?d:Yd.ordering]}}connect(e){this.assertActive(),tI(e);let t=this.idFactory("client"),n={identity:structuredClone(e),disposed:!1,sources:new Set,providers:new Set,subscriptions:new Set};return this.clients.set(t,n),{identity:structuredClone(e),registerEventSource:s=>this.registerEventSource(t,s),publishEvent:s=>this.publishEvent(t,s),subscribeEvents:(s,i)=>this.subscribeEvents(t,s,i),registerActionProvider:s=>this.registerActionProvider(t,s),invokeAction:s=>this.invokeAction(t,s),cancelAction:(s,i)=>this.cancelAction(t,s,i),dispose:()=>this.disposeClient(t)}}describe(){return this.assertActive(),{profile_version:"0.1",transport:structuredClone(this.transport),contracts:[...this.contracts.values()].map(({artifact:e,reference:t})=>({artifact:structuredClone(e),reference:structuredClone(t)})).sort((e,t)=>e.reference.id.localeCompare(t.reference.id)||e.reference.version.localeCompare(t.reference.version)),event_sources:[...this.eventSources.values()].map(({declaration:e})=>structuredClone(e)).sort((e,t)=>e.declaration_id.localeCompare(t.declaration_id)),action_providers:[...this.actionProviders.values()].map(({declaration:e})=>structuredClone(e)).sort((e,t)=>e.declaration_id.localeCompare(t.declaration_id))}}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.clients.keys()])await this.disposeClient(e,!0);this.contracts.clear(),this.recentEvents.clear(),this.completedActions.clear()}}async registerEventSource(e,t){var l;let n=this.requireClient(e);if(t.contracts.length===0)throw new C("request_rejected","An event-source declaration must include a contract.");let s=`${e}:${t.declaration_id}`;if(this.eventSources.has(s))throw new C("request_rejected",`Event-source declaration ${t.declaration_id} is already registered.`);let i=new Map;for(let u of t.contracts){let d=await this.prepareEventContract(u.contract),f=Lg(u.requirement,d.reference);if(Dg(f,d.reference),await this.assertAuthorized({operation:"register_event_source",principal:n.identity,contract:d.reference}),d.sourceValidator&&!d.sourceValidator((l=u.binding)!=null?l:{}))throw new C("request_rejected",`${d.reference.id} source binding is invalid: ${jr(d.sourceValidator.errors)}`);let p=Jo(d.reference);if(i.has(p))throw new C("contract_digest_conflict",`Event contract ${p} is repeated by one declaration.`);i.set(p,{contract:d,requirement:f,...u.binding===void 0?{}:{binding:structuredClone(u.binding)},...u.ordering===void 0?{}:{ordering:[...u.ordering]}})}let o={kind:"mdbase.event-source",profile_version:"0.1",declaration_id:t.declaration_id,source:structuredClone(n.identity),contracts:[...i.values()].map(({contract:u,requirement:d,binding:f,ordering:p})=>({requirement:structuredClone(d),resolved:structuredClone(u.reference),...f===void 0?{}:{binding:f},...p===void 0?{}:{ordering:p}}))},a={...o,declaration_digest:await Gn(o)};Vr(this.eventSourceDeclarationValidator,a,"request_rejected","Event-source declaration"),this.commitContracts([...i.values()].map(({contract:u})=>u)),this.eventSources.set(s,{id:s,clientId:e,declaration:structuredClone(a),contracts:new Map([...i.entries()].map(([u,d])=>[u,{contract:d.contract,...d.binding===void 0?{}:{binding:d.binding}}]))}),n.sources.add(s);let c=!0;return{declaration:structuredClone(a),dispose:()=>{c&&(c=!1,this.removeEventSource(s))}}}async publishEvent(e,t){var m,h,y,b;let n=this.requireClient(e),s=Jo(t.contract),i=[...n.sources].map(g=>this.eventSources.get(g)).find(g=>g==null?void 0:g.contracts.has(s));if(!i)throw new C("unknown_contract",`This client has not registered event contract ${t.contract.id} ${t.contract.version}.`);let o=(m=i.contracts.get(s))==null?void 0:m.contract;if(!o)throw new C("unknown_contract",`Event contract ${s} is unavailable.`);if(t.contract.digest&&t.contract.digest!==o.reference.digest)throw new C("contract_digest_conflict",`Event contract ${s} has a different digest.`);await this.assertAuthorized({operation:"publish_event",principal:n.identity,contract:o.reference,...t.subject===void 0?{}:{subject:t.subject}}),Xd(t.data,"invalid_event_data",`Event ${o.reference.id} data`),Lo(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=(h=t.extensions)!=null?h:{};for(let g of Object.keys(a))if(eI.has(g))throw new C("request_rejected",`Event extension ${g} is reserved.`);let c={...structuredClone(a),specversion:"1.0",id:(y=t.id)!=null?y:this.idFactory("evt"),source:rI(n.identity),type:o.reference.id,time:(b=t.time)!=null?b:this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:Fg(o.reference),data:structuredClone(t.data),mdbaseprofile:"0.1",mdbasecontractversion:o.reference.version,mdbasecontractdigest:o.reference.digest,mdbaseapplication:n.identity.application,mdbaseimplementation:n.identity.implementation,mdbaseimplementationversion:n.identity.version,...n.identity.instance_id===void 0?{}:{mdbaseinstanceid:n.identity.instance_id},...t.correlation_id===void 0?{}:{correlationid:t.correlation_id},...t.causation_id===void 0?{}:{causationid:t.causation_id}};Vr(this.eventValidator,c,"invalid_event_data","Event envelope"),Qd(this.transport,c),nI(c,o.reference);let l=`${c.source}\0${c.id}`,u=this.recentEvents.get(l);if(u){if(JSON.stringify(u)!==JSON.stringify(c))throw new C("contract_digest_conflict",`Event ${c.source} ${c.id} was reused with different content.`);return{event:structuredClone(u),deliveries:0,duplicate:!0}}this.recentEvents.set(l,structuredClone(c)),jg(this.recentEvents,this.recentEventLimit);let d=[...this.subscriptions.values()].filter(({subscription:g})=>Yo(g.contract,o.reference)),f=await Promise.allSettled(d.map(async g=>await this.isAuthorized({operation:"subscribe_event",principal:g.principal,contract:o.reference,...c.subject===void 0?{}:{subject:c.subject}})?(await g.handler(structuredClone(c)),!0):!1)),p=0;for(let g of f)g.status==="fulfilled"&&g.value?p+=1:g.status==="rejected"&&this.report({severity:"error",code:"event_consumer_failed",message:`An event consumer failed while handling ${c.type}.`,contract:o.reference,cause:g.reason});return{event:structuredClone(c),deliveries:p,duplicate:!1}}async subscribeEvents(e,t,n){let s=this.requireClient(e);Zd(t.contract),oI(this.transport,t.require_transport),await this.assertAuthorized({operation:"subscribe_event",principal:s.identity,contract:t.contract});let i=this.idFactory("subscription");this.subscriptions.set(i,{id:i,clientId:e,principal:structuredClone(s.identity),subscription:structuredClone(t),handler:n}),s.subscriptions.add(i);let o=!0;return{dispose:()=>{o&&(o=!1,this.removeSubscription(i))}}}async registerActionProvider(e,t){var d,f,p,m,h,y,b;let n=this.requireClient(e);if(t.handlers.length===0)throw new C("request_rejected","An action-provider declaration must include a handler.");let s=`${e}:${t.declaration_id}`;if(this.actionProviders.has(s))throw new C("request_rejected",`Action-provider declaration ${t.declaration_id} is already registered.`);let i=[],o=new Set;for(let g of t.handlers){if(o.has(g.handler_id))throw new C("request_rejected",`Handler ${g.handler_id} is repeated.`);o.add(g.handler_id);let _=await this.prepareActionContract(g.contract),I=Lg(g.requirement,_.reference);if(Dg(I,_.reference),await this.assertAuthorized({operation:"register_action_provider",principal:n.identity,contract:_.reference,provider:n.identity}),_.providerValidator&&!_.providerValidator((d=g.binding)!=null?d:{}))throw new C("request_rejected",`${_.reference.id} provider binding is invalid: ${jr(_.providerValidator.errors)}`);let v=(p=(f=g.contract.behavior)==null?void 0:f.idempotency)!=null?p:"none";if(((m=g.idempotency)==null?void 0:m.mode)==="request"&&v==="none")throw new C("request_rejected",`${_.reference.id} does not permit request deduplication.`);if(v==="required"&&((h=g.idempotency)==null?void 0:h.mode)!=="request")throw new C("request_rejected",`${_.reference.id} requires a provider with request deduplication.`);let S=(b=(y=g.contract.behavior)==null?void 0:y.cancellation)!=null?b:"none";if(g.cancellation==="cooperative"&&S!=="cooperative")throw new C("request_rejected",`${_.reference.id} does not declare cooperative cancellation.`);i.push({contract:_,declaration:{handler_id:g.handler_id,requirement:I,resolved:structuredClone(_.reference),...g.binding===void 0?{}:{binding:structuredClone(g.binding)},...g.idempotency===void 0?{}:{idempotency:structuredClone(g.idempotency)},...g.cancellation===void 0?{}:{cancellation:g.cancellation},...g.max_concurrency===void 0?{}:{max_concurrency:g.max_concurrency}},handler:g.handler})}let a={kind:"mdbase.action-provider",profile_version:"0.1",declaration_id:t.declaration_id,provider:structuredClone(n.identity),handlers:i.map(({declaration:g})=>structuredClone(g))},c={...a,declaration_digest:await Gn(a)};Vr(this.actionProviderDeclarationValidator,c,"request_rejected","Action-provider declaration"),this.commitContracts(i.map(({contract:g})=>g));let l=i.map(({contract:g,declaration:_,handler:I})=>({registrationId:s,clientId:e,declaration:structuredClone(c),handlerDeclaration:structuredClone(_),contract:g,handler:I,active:0}));this.actionProviders.set(s,{id:s,clientId:e,declaration:structuredClone(c),handlers:l}),n.providers.add(s);let u=!0;return{declaration:structuredClone(c),dispose:()=>{u&&(u=!1,this.removeActionProvider(s))}}}async invokeAction(e,t){var a,c,l,u,d,f,p,m,h,y,b,g;let n=this.requireClient(e);Zd(t.contract);let s=(a=t.request_id)!=null?a:this.idFactory("req");this.cleanCompletedActions(),Xd(t.input,"invalid_action_input",`Action ${t.contract.id} input`);let i={kind:"mdbase.action.request",profile_version:"0.1",request_id:s,contract:structuredClone(t.contract),caller:structuredClone(n.identity),created_at:(c=t.created_at)!=null?c:this.now().toISOString(),...t.correlation_id===void 0?{}:{correlation_id:t.correlation_id},...t.causation_id===void 0?{}:{causation_id:t.causation_id},...t.subject===void 0?{}:{subject:t.subject},...t.idempotency_key===void 0?{}:{idempotency_key:t.idempotency_key},...t.deadline===void 0?{}:{deadline:t.deadline},...t.requested_provider===void 0?{}:{requested_provider:structuredClone(t.requested_provider)},input:structuredClone(t.input)};Vr(this.actionRequestValidator,i,"request_rejected","Action request"),Qd(this.transport,i);let o=await this.acquireAdmission(s);try{let _=await Gn(sI(i)),I=this.activeActions.get(s);if(I){if(qg(e,s,_,I),((l=I.handler.handlerDeclaration.idempotency)==null?void 0:l.mode)!=="request")throw new C("request_rejected",`Action request ${s} is already active without deduplication.`);return structuredClone(await I.promise)}let v=this.completedActions.get(s);if(v){if(qg(e,s,_,v),!v.reusable)throw new C("request_rejected",`Action request ${s} was already completed without deduplication.`);return structuredClone(v.outcome)}if(i.deadline&&new Date(i.deadline).getTime()<=this.now().getTime())throw new C("deadline_exceeded",`Action request ${s} passed its deadline before admission.`);if(i.deadline&&!this.transport.deadlines)throw new C("unsupported_transport_capability","The active transport cannot enforce action deadlines.");let S=this.resolveActionCandidates(i.contract,i.requested_provider);S.length===0&&this.throwResolutionFailure(i.contract,i.requested_provider);let k=[];for(let ae of S)await this.isAuthorized({operation:"invoke_action",principal:n.identity,contract:ae.contract.reference,provider:ae.declaration.provider,...i.subject===void 0?{}:{subject:i.subject}})&&k.push(ae);if(k.length===0)throw new C("unauthorized",`No authorized provider can execute ${i.contract.id}.`);if(k.length>1)throw new C("ambiguous_provider",`Action ${i.contract.id} has ${k.length} eligible providers; select one explicitly.`);let $=k[0];if($.handlerDeclaration.max_concurrency!==void 0&&$.active>=$.handlerDeclaration.max_concurrency)throw new C("request_rejected",`Provider ${$.declaration.provider.implementation} is at capacity.`);if(((d=(u=$.contract.artifact.behavior)==null?void 0:u.idempotency)!=null?d:"none")==="required"&&!i.idempotency_key)throw new C("request_rejected",`${$.contract.reference.id} requires an idempotency key.`);Lo($.contract.inputValidator,i.input,"invalid_action_input",`Action ${$.contract.reference.id} input`);let w={operation:"invoke_action",principal:n.identity,contract:$.contract.reference,provider:$.declaration.provider,...i.subject===void 0?{}:{subject:i.subject}},N=await((p=(f=this.options).authorizationContext)==null?void 0:p.call(f,w)),j={kind:"mdbase.action.invocation",profile_version:"0.1",invocation_id:this.idFactory("inv"),attempt_id:this.idFactory("attempt"),request_id:s,contract:structuredClone($.contract.reference),caller:structuredClone(n.identity),provider:structuredClone($.declaration.provider),provider_declaration_digest:$.declaration.declaration_digest,handler_id:$.handlerDeclaration.handler_id,admitted_at:this.now().toISOString(),...i.correlation_id===void 0?{}:{correlation_id:i.correlation_id},...i.causation_id===void 0?{}:{causation_id:i.causation_id},...i.subject===void 0?{}:{subject:i.subject},...i.idempotency_key===void 0?{}:{idempotency_key:i.idempotency_key},...i.deadline===void 0?{}:{deadline:i.deadline},...N===void 0?{}:{authorization_context:N},input:structuredClone(i.input)};Vr(this.actionInvocationValidator,j,"request_rejected","Action invocation"),await((h=(m=this.options).onInvocation)==null?void 0:h.call(m,structuredClone(j)));let H=new AbortController,A;if(j.deadline){let ae=Math.max(0,new Date(j.deadline).getTime()-this.now().getTime());A=setTimeout(()=>H.abort(new C("deadline_exceeded",`Action request ${s} exceeded its deadline.`)),ae)}$.active+=1;let x=this.executeAction($,j,H).finally(()=>{A!==void 0&&clearTimeout(A),$.active=Math.max(0,$.active-1),this.activeActions.delete(s)});this.activeActions.set(s,{clientId:e,requestId:s,requestDigest:_,handler:$,invocation:j,controller:H,promise:x}),o();let _e=await x,oe=(b=(y=$.handlerDeclaration.idempotency)==null?void 0:y.retention_seconds)!=null?b:300;return this.completedActions.set(s,{clientId:e,requestDigest:_,outcome:structuredClone(_e),reusable:((g=$.handlerDeclaration.idempotency)==null?void 0:g.mode)==="request",expiresAt:this.now().getTime()+oe*1e3}),jg(this.completedActions,this.completedRequestLimit),structuredClone(_e)}finally{o()}}async executeAction(e,t,n){var s;try{let i=await e.handler(structuredClone(t.input),{invocation:structuredClone(t),signal:n.signal});if(n.signal.aborted){let a=n.signal.reason;return a instanceof C&&a.code==="deadline_exceeded"?this.failureOutcome(t,"failed",a.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}Xd(i,"invalid_action_output",`Action ${e.contract.reference.id} output`),Lo(e.contract.outputValidator,i,"invalid_action_output",`Action ${e.contract.reference.id} output`);let o={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:t.request_id,invocation_id:t.invocation_id,attempt_id:t.attempt_id,contract:structuredClone(t.contract),provider:structuredClone(t.provider),provider_declaration_digest:t.provider_declaration_digest,status:"succeeded",completed_at:this.now().toISOString(),output:structuredClone(i)};return Vr(this.actionOutcomeValidator,o,"invalid_action_output","Action outcome"),Qd(this.transport,o),o}catch(i){if(i instanceof As)return e.contract.errorValidator&&!e.contract.errorValidator((s=i.error.details)!=null?s:{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${jr(e.contract.errorValidator.errors)}`}):this.failureOutcome(t,i.status,i.error);if(i instanceof C)return this.failureOutcome(t,i.code==="cancelled"?"cancelled":i.code==="outcome_indeterminate"?"outcome_indeterminate":"failed",i.toPortableError());if(n.signal.aborted||aI(i)){let o=n.signal.reason;return o instanceof C&&o.code==="deadline_exceeded"?this.failureOutcome(t,"failed",o.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}return this.report({severity:"error",code:"action_handler_failed",message:`Provider ${t.provider.implementation} failed ${t.contract.id}.`,principal:t.provider,contract:t.contract,cause:i}),this.failureOutcome(t,"failed",{code:"handler_failure",message:"The selected provider failed while executing the action."})}}failureOutcome(e,t,n){let s={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:e.request_id,invocation_id:e.invocation_id,attempt_id:e.attempt_id,contract:structuredClone(e.contract),provider:structuredClone(e.provider),provider_declaration_digest:e.provider_declaration_digest,status:t,completed_at:this.now().toISOString(),error:structuredClone(n)};return Vr(this.actionOutcomeValidator,s,"invalid_action_output","Action outcome"),s}async cancelAction(e,t,n){let s=this.requireClient(e),i=this.admissionLocks.get(t);i&&await i;let o=this.activeActions.get(t);if(!o){let a=this.completedActions.get(t);if(a&&a.clientId!==e)throw new C("unauthorized",`Action request ${t} belongs to another caller.`);return a?structuredClone(a.outcome):null}if(o.clientId!==e)throw new C("unauthorized",`Action request ${t} belongs to another caller.`);if(await this.assertAuthorized({operation:"cancel_action",principal:s.identity,contract:o.invocation.contract,provider:o.invocation.provider,...o.invocation.subject===void 0?{}:{subject:o.invocation.subject}}),!this.transport.cancellation)throw new C("unsupported_transport_capability","The active transport cannot deliver cancellation.");if(o.handler.handlerDeclaration.cancellation!=="cooperative")throw new C("cancellation_unsupported",`Provider ${o.invocation.provider.implementation} does not support cancellation.`);return o.controller.abort(new C("cancelled",(n==null?void 0:n.trim())||`Action request ${t} was cancelled.`)),structuredClone(await o.promise)}resolveActionCandidates(e,t){let n=[...this.actionProviders.values()].flatMap(({handlers:i})=>i).filter(({contract:i,declaration:o})=>Yo(e,i.reference)&&iI(t,o.provider)),s=(0,pr.maxSatisfying)([...new Set(n.map(({contract:i})=>i.reference.version))],e.version,{includePrerelease:!0});return s?n.filter(({contract:i})=>i.reference.version===s).sort((i,o)=>{var a,c;return i.declaration.provider.application.localeCompare(o.declaration.provider.application)||i.declaration.provider.implementation.localeCompare(o.declaration.provider.implementation)||((a=i.declaration.provider.instance_id)!=null?a:"").localeCompare((c=o.declaration.provider.instance_id)!=null?c:"")||i.handlerDeclaration.handler_id.localeCompare(o.handlerDeclaration.handler_id)}):[]}throwResolutionFailure(e,t){let n=[...this.contracts.values()].filter(s=>s.artifact.contract_type==="action"&&s.reference.id===e.id);throw n.length===0?new C("unknown_contract",`Action contract ${e.id} is unknown.`):n.some(({reference:s})=>Yo(e,s))?t?new C("requested_provider_unavailable",`The requested provider is unavailable for ${e.id}.`):new C("no_provider",`No provider is registered for ${e.id}.`):new C("unsupported_contract_version",`No ${e.id} artifact satisfies ${e.version}.`)}async prepareEventContract(e){if(this.assertContractArtifact(e),e.contract_type!=="event")throw new C("unknown_contract",`${e.id} is not an event contract.`);let t={id:e.id,version:e.version,digest:await No(e)};this.assertNoContractConflict(t);let n=Hm(this.ajv,e);return{artifact:structuredClone(e),reference:t,dataValidator:n.data,...n.source===void 0?{}:{sourceValidator:n.source}}}async prepareActionContract(e){if(this.assertContractArtifact(e),e.contract_type!=="action")throw new C("unknown_contract",`${e.id} is not an action contract.`);let t={id:e.id,version:e.version,digest:await No(e)};this.assertNoContractConflict(t);let n=Bm(this.ajv,e);return{artifact:structuredClone(e),reference:t,inputValidator:n.input,...n.output===void 0?{}:{outputValidator:n.output},...n.error===void 0?{}:{errorValidator:n.error},...n.provider===void 0?{}:{providerValidator:n.provider}}}assertContractArtifact(e){if(Vr(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,pr.valid)(e.version))throw new C("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(Jo(e));if(t&&t.reference.digest!==e.digest)throw new C("contract_digest_conflict",`Contract ${e.id} ${e.version} conflicts with the registered artifact.`)}commitContracts(e){var n;let t=new Map;for(let s of e){let i=Jo(s.reference),o=(n=t.get(i))!=null?n:this.contracts.get(i);if(o&&o.reference.digest!==s.reference.digest)throw new C("contract_digest_conflict",`Contract ${s.reference.id} ${s.reference.version} conflicts within the registration.`);t.set(i,s)}for(let[s,i]of t)this.contracts.has(s)||this.contracts.set(s,i)}async disposeClient(e,t=!1){let n=this.clients.get(e);if(!(!n||n.disposed)){n.disposed=!0;for(let s of[...n.subscriptions])this.removeSubscription(s);for(let s of[...n.sources])this.removeEventSource(s);for(let s of[...n.providers])this.removeActionProvider(s);for(let s of[...this.activeActions.values()])s.clientId===e&&s.handler.handlerDeclaration.cancellation==="cooperative"&&s.controller.abort(new C("cancelled","The caller unloaded.")),s.handler.clientId===e&&s.handler.handlerDeclaration.cancellation==="cooperative"&&s.controller.abort(new C("cancelled","The provider unloaded."));this.clients.delete(e),t||this.assertActive()}}removeEventSource(e){var n;let t=this.eventSources.get(e);t&&(this.eventSources.delete(e),(n=this.clients.get(t.clientId))==null||n.sources.delete(e))}removeActionProvider(e){var n;let t=this.actionProviders.get(e);if(t){this.actionProviders.delete(e),(n=this.clients.get(t.clientId))==null||n.providers.delete(e);for(let s of this.activeActions.values())s.handler.registrationId===e&&s.handler.handlerDeclaration.cancellation==="cooperative"&&s.controller.abort(new C("cancelled","The provider unloaded."))}}removeSubscription(e){var n;let t=this.subscriptions.get(e);t&&(this.subscriptions.delete(e),(n=this.clients.get(t.clientId))==null||n.subscriptions.delete(e))}requireClient(e){this.assertActive();let t=this.clients.get(e);if(!t||t.disposed)throw new C("transport_unavailable","Interop client is disposed.");return t}assertActive(){if(this.disposed)throw new C("transport_unavailable","Interop bridge is disposed.")}async assertAuthorized(e){if(!await this.isAuthorized(e))throw new C("unauthorized",`${e.operation} is not authorized.`)}async isAuthorized(e){try{return await this.authorize(structuredClone(e))}catch(t){return this.report({severity:"error",code:"authorization_failed",message:`Authorization failed for ${e.operation}.`,principal:e.principal,cause:t}),!1}}cleanCompletedActions(){let e=this.now().getTime();for(let[t,n]of this.completedActions)n.expiresAt<=e&&this.completedActions.delete(t)}async acquireAdmission(e){var a;let t=(a=this.admissionLocks.get(e))!=null?a:Promise.resolve(),n,s=new Promise(c=>{n=c}),i=t.then(()=>s);this.admissionLocks.set(e,i),await t;let o=!1;return()=>{o||(o=!0,n(),this.admissionLocks.get(e)===i&&this.admissionLocks.delete(e))}}report(e){var t,n;(n=(t=this.options).onDiagnostic)==null||n.call(t,structuredClone(e))}};function Vr(r,e,t,n){if(!r(e))throw new C(t,`${n} is invalid: ${jr(r.errors)}`)}function tI(r){for(let[e,t]of Object.entries(r))if(t!==void 0&&(typeof t!="string"||t.length===0||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/u.test(t)))throw new C("request_rejected",`Implementation identity ${e} is invalid.`);if(!(0,pr.valid)(r.version))throw new C("request_rejected","Implementation identity version must be exact SemVer.")}function Zd(r){if(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(r.id))throw new C("unknown_contract",`Contract ID ${r.id} is invalid.`);if(!(0,pr.validRange)(r.version,{includePrerelease:!0}))throw new C("unsupported_contract_version",`Contract requirement ${r.version} is not a SemVer range.`);if(r.digest&&!/^sha256:[0-9a-f]{64}$/u.test(r.digest))throw new C("contract_digest_conflict","Contract digest is invalid.")}function Lg(r,e){let t=r!=null?r:{id:e.id,version:e.version,digest:e.digest};return Zd(t),structuredClone(t)}function Dg(r,e){if(!Yo(r,e))throw new C("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function Yo(r,e){return r.id===e.id&&(0,pr.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function Jo(r){return`${r.id}@${r.version}`}function Fg(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function rI(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function nI(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==Fg(e))throw new C("contract_digest_conflict","Event contract evidence is inconsistent.")}function sI(r){let{created_at:e,...t}=r;return t}function qg(r,e,t,n){if(n.clientId!==r)throw new C("unauthorized",`Action request ${e} belongs to another caller.`);if(n.requestDigest!==t)throw new C("request_rejected",`Action request ${e} was reused with different content.`)}function Xd(r,e,t){let n=new Set,s=(i,o)=>{if(!(i===null||typeof i=="boolean"||typeof i=="string")){if(typeof i=="number"){if(Number.isFinite(i))return;throw new C(e,`${t}${o} must be a finite JSON number.`)}if(typeof i!="object")throw new C(e,`${t}${o} is not a JSON value.`);if(n.has(i))throw new C(e,`${t}${o} contains a cycle.`);if(n.add(i),Array.isArray(i))i.forEach((a,c)=>s(a,`${o}/${c}`));else{let a=Object.getPrototypeOf(i);if(a!==Object.prototype&&a!==null)throw new C(e,`${t}${o} must be a plain JSON object.`);for(let[c,l]of Object.entries(i))s(l,`${o}/${c}`)}n.delete(i)}};s(r,"")}function Qd(r,e){if(r.max_payload_bytes===void 0)return;let t=JSON.stringify(e),n=new TextEncoder().encode(t).byteLength;if(n>r.max_payload_bytes)throw new C("unsupported_transport_capability",`The portable envelope is ${n} bytes; the active transport allows ${r.max_payload_bytes}.`)}function iI(r,e){return r?(r.application===void 0||r.application===e.application)&&(r.implementation===void 0||r.implementation===e.implementation)&&(r.instance_id===void 0||r.instance_id===e.instance_id):!0}function oI(r,e){var t,n;if(e){if((t=e.delivery)!=null&&t.some(s=>!r.delivery.includes(s)))throw new C("unsupported_transport_capability","The active transport lacks a required delivery capability.");if((n=e.ordering)!=null&&n.some(s=>!r.ordering.includes(s)))throw new C("unsupported_transport_capability","The active transport lacks a required ordering capability.");for(let s of["cancellation","deadlines","provider_discovery","request_deduplication","cross_process_identity"])if(e[s]===!0&&r[s]!==!0)throw new C("unsupported_transport_capability",`The active transport lacks ${s}.`);if(e.max_payload_bytes!==void 0&&(r.max_payload_bytes===void 0||r.max_payload_bytese;){let t=r.keys().next().value;if(t===void 0)return;r.delete(t)}}function aI(r){return r instanceof Error&&r.name==="AbortError"}var Xo=class{constructor(e,t){this.app=e;this.profileVersion="0.1";this.bridge=new ci({authorize:()=>t(),transport:{delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},onDiagnostic:n=>{var i;(n.severity==="error"?console.error:console.warn)(`[mdbase/interop] ${n.code}: ${n.message}`,(i=n.cause)!=null?i:"")}}),this.transport=this.bridge.describe().transport}connect(e){var i,o;let t=(i=e.manifest)==null?void 0:i.id,n=(o=e.manifest)==null?void 0:o.version;if(!t||!n)throw new Error("Only a loaded Obsidian plugin with manifest identity can connect to mdbase interop.");let s=this.app.plugins;if(!s||s.getPlugin(t)!==e)throw new Error(`Obsidian plugin ${t} is not the active loaded instance.`);return this.bridge.connect({application:t,implementation:`${t}.obsidian`,version:n})}describe(){return this.bridge.describe()}dispose(){return this.bridge.dispose()}};var pe=require("obsidian"),ub=Zr(yd(),1),fb=Zr(kd(),1),mu=Zr(uu(),1),ta=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},Tt={spec_version:"0.3.0",name:"My mdbase collection",description:"Typed markdown collection",settings:{types_folder:"_types",explicit_type_keys:["type","types"],default_strict:!1,include_subfolders:!0,exclude:["_types",".obsidian",".git","node_modules",".trash",".mdbase"]}},pi=null;function HI(){return pi||(pi=new ub.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,fb.default)(pi),pi)}function Z(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function We(r){return JSON.parse(JSON.stringify(r))}function BI(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function fu(r){return Array.isArray(r)?`[${r.map(e=>fu(e)).join(",")}]`:Z(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${fu(r[t])}`).join(",")}}`:JSON.stringify(r)}function zI(r){let e=r.indexOf("."),t=r.indexOf("[");return e===-1&&t===-1?r:e===-1?r.slice(0,t):t===-1?r.slice(0,e):r.slice(0,Math.min(e,t))}function KI(r){let e=new Map,t=new Set,n=s=>{var l,u,d,f;let i=e.get(s);if(i)return i;let o=r.get(s);if(!o)return null;if(t.has(s)){let p={...o,fields:We(o.fields)};return e.set(s,p),p}t.add(s);let a=o.extends?n(o.extends):null;t.delete(s);let c={...o,fields:a?{...We(a.fields),...We(o.fields)}:We(o.fields),display_name_key:(l=o.display_name_key)!=null?l:a==null?void 0:a.display_name_key,path_pattern:(u=o.path_pattern)!=null?u:a==null?void 0:a.path_pattern,filename_pattern:(d=o.filename_pattern)!=null?d:a==null?void 0:a.filename_pattern,strict:o.strict!==void 0?o.strict:a==null?void 0:a.strict,match:(f=o.match)!=null?f:a==null?void 0:a.match};return e.set(s,c),c};for(let s of r.keys())n(s);return e}function pb(r){let e=(0,pe.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function hb(r){let e=r.trim();e.startsWith("[[")&&e.endsWith("]]")&&(e=e.slice(2,-2));let t=e.indexOf("|");t>=0&&(e=e.slice(0,t));let n=e.indexOf("#");return n>=0&&(e=e.slice(0,n)),e.trim()}function mb(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function yb(r,e,t){var c;let n=hb(t);if(!n||mb(n))return null;let s=new Set,i=(0,pe.normalizePath)(n);s.add(i),i.endsWith(".md")||s.add(`${i}.md`);let o=pb(e);if(o){let l=(0,pe.normalizePath)(`${o}/${n}`);s.add(l),l.endsWith(".md")||s.add(`${l}.md`)}for(let l of s){let u=r.getAbstractFileByPath(l);if(u instanceof pe.TFile)return u}let a=n.replace(/\.md$/i,"");return(c=r.getMarkdownFiles().find(l=>l.basename===a))!=null?c:null}function WI(r,e,t){return mb(hb(t))||yb(r,e,t)!==null}function _t(r){let e=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m);if(!e)return{hasFrontmatter:!1,frontmatter:{},body:r};try{let t=e[1],n=(0,pe.parseYaml)(t);return n==null&&t.trim()!==""?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:n!=null&&!Z(n)?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:{hasFrontmatter:!0,frontmatter:n!=null?n:{},body:r.slice(e[0].length)}}catch(t){return{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:t instanceof Error?t.message:String(t)}}}function at(r,e=""){if(Object.keys(r).length===0)return e;let t=(0,pe.stringifyYaml)(r).trimEnd(),n=e.replace(/^\n+/,"");return`--- + deps: ${t}}`};var qE={keyword:"dependencies",type:"object",schemaType:"object",error:ar.error,code(r){let[e,t]=jE(r);Yh(r,e),Xh(r,t)}};function jE({schema:r}){let e={},t={};for(let n in r){if(n==="__proto__")continue;let i=Array.isArray(r[n])?e:t;i[n]=r[n]}return[e,t]}function Yh(r,e=r.schema){let{gen:t,data:n,it:i}=r;if(Object.keys(e).length===0)return;let s=t.let("missing");for(let o in e){let a=e[o];if(a.length===0)continue;let c=(0,ds.propertyInData)(t,n,o,i.opts.ownProperties);r.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),i.allErrors?t.if(c,()=>{for(let l of a)(0,ds.checkReportMissingProp)(r,l)}):(t.if((0,ed._)`${c} && (${(0,ds.checkMissingProp)(r,a,s)})`),(0,ds.reportMissingProp)(r,s),t.else())}}ar.validatePropertyDeps=Yh;function Xh(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,DE.alwaysValidSchema)(s,e[a])||(t.if((0,ds.propertyInData)(t,n,a,s.opts.ownProperties),()=>{let c=r.subschema({keyword:i,schemaProp:a},o);r.mergeValidEvaluated(c,o)},()=>t.var(o,!0)),r.ok(o))}ar.validateSchemaDeps=Xh;ar.default=qE});var Zh=A(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var Qh=K(),FE=ee(),VE={message:"property name must be valid",params:({params:r})=>(0,Qh._)`{propertyName: ${r.propertyName}}`},UE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:VE,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,FE.alwaysValidSchema)(i,t))return;let s=e.name("valid");e.forIn("key",n,o=>{r.setParams({propertyName:o}),r.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),e.if((0,Qh.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};td.default=UE});var nd=A(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var Vo=xt(),Ft=K(),BE=kt(),Uo=ee(),zE={message:"must NOT have additional properties",params:({params:r})=>(0,Ft._)`{additionalProperty: ${r.additionalProperty}}`},HE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:zE,code(r){let{gen:e,schema:t,parentSchema:n,data:i,errsCount:s,it:o}=r;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,Uo.alwaysValidSchema)(o,t))return;let l=(0,Vo.allSchemaProperties)(n.properties),u=(0,Vo.allSchemaProperties)(n.patternProperties);d(),r.ok((0,Ft._)`${s} === ${BE.default.errors}`);function d(){e.forIn("key",i,y=>{!l.length&&!u.length?m(y):e.if(f(y),()=>m(y))})}function f(y){let b;if(l.length>8){let g=(0,Uo.schemaRefOrVal)(o,n.properties,"properties");b=(0,Vo.isOwnProperty)(e,g,y)}else l.length?b=(0,Ft.or)(...l.map(g=>(0,Ft._)`${y} === ${g}`)):b=Ft.nil;return u.length&&(b=(0,Ft.or)(b,...u.map(g=>(0,Ft._)`${(0,Vo.usePattern)(r,g)}.test(${y})`))),(0,Ft.not)(b)}function p(y){e.code((0,Ft._)`delete ${i}[${y}]`)}function m(y){if(c.removeAdditional==="all"||c.removeAdditional&&t===!1){p(y);return}if(t===!1){r.setParams({additionalProperty:y}),r.error(),a||e.break();return}if(typeof t=="object"&&!(0,Uo.alwaysValidSchema)(o,t)){let b=e.name("valid");c.removeAdditional==="failing"?(h(y,b,!1),e.if((0,Ft.not)(b),()=>{r.reset(),p(y)})):(h(y,b),a||e.if((0,Ft.not)(b),()=>e.break()))}}function h(y,b,g){let _={keyword:"additionalProperties",dataProp:y,dataPropType:Uo.Type.Str};g===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(_,b)}}};rd.default=HE});var rm=A(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var KE=Un(),em=xt(),id=ee(),tm=nd(),WE={keyword:"properties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,parentSchema:n,data:i,it:s}=r;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&tm.default.code(new KE.KeywordCxt(s,tm.default,"additionalProperties"));let o=(0,em.allSchemaProperties)(t);for(let d of o)s.definedProperties.add(d);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=id.mergeEvaluated.props(e,(0,id.toHash)(o),s.props));let a=o.filter(d=>!(0,id.alwaysValidSchema)(s,t[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)l(d)?u(d):(e.if((0,em.propertyInData)(e,i,d,s.opts.ownProperties)),u(d),s.allErrors||e.else().var(c,!0),e.endIf()),r.it.definedProperties.add(d),r.ok(c);function l(d){return s.opts.useDefaults&&!s.compositeRule&&t[d].default!==void 0}function u(d){r.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};sd.default=WE});var om=A(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var nm=xt(),Bo=K(),im=ee(),sm=ee(),GE={keyword:"patternProperties",type:"object",schemaType:"object",code(r){let{gen:e,schema:t,data:n,parentSchema:i,it:s}=r,{opts:o}=s,a=(0,nm.allSchemaProperties)(t),c=a.filter(h=>(0,im.alwaysValidSchema)(s,t[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof Bo.Name)&&(s.props=(0,sm.evaluatedPropsToName)(e,s.props));let{props:d}=s;f();function f(){for(let h of a)l&&p(h),s.allErrors?m(h):(e.var(u,!0),m(h),e.if(u))}function p(h){for(let y in l)new RegExp(h).test(y)&&(0,im.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,Bo._)`${(0,nm.usePattern)(r,h)}.test(${y})`,()=>{let b=c.includes(h);b||r.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:sm.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,Bo._)`${d}[${y}]`,!0):!b&&!s.allErrors&&e.if((0,Bo.not)(u),()=>e.break())})})}}};od.default=GE});var am=A(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var JE=ee(),YE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,JE.alwaysValidSchema)(n,t)){r.fail();return}let i=e.name("valid");r.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),r.failResult(i,()=>r.reset(),()=>r.error())},error:{message:"must NOT be valid"}};ad.default=YE});var cm=A(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});var XE=xt(),QE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:XE.validateUnion,error:{message:"must match a schema in anyOf"}};cd.default=QE});var lm=A(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});var zo=K(),ZE=ee(),eA={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,zo._)`{passingSchemas: ${r.passing}}`},tA={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:eA,code(r){let{gen:e,schema:t,parentSchema:n,it:i}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let s=t,o=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");r.setParams({passing:a}),e.block(l),r.result(o,()=>r.reset(),()=>r.error(!0));function l(){s.forEach((u,d)=>{let f;(0,ZE.alwaysValidSchema)(i,u)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,zo._)`${c} && ${o}`).assign(o,!1).assign(a,(0,zo._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,d),f&&r.mergeEvaluated(f,zo.Name)})})}}};ld.default=tA});var dm=A(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var rA=ee(),nA={keyword:"allOf",schemaType:"array",code(r){let{gen:e,schema:t,it:n}=r;if(!Array.isArray(t))throw new Error("ajv implementation error");let i=e.name("valid");t.forEach((s,o)=>{if((0,rA.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};dd.default=nA});var pm=A(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var Ho=K(),fm=ee(),iA={message:({params:r})=>(0,Ho.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,Ho._)`{failingKeyword: ${r.ifClause}}`},sA={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:iA,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,fm.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=um(n,"then"),s=um(n,"else");if(!i&&!s)return;let o=e.let("valid",!0),a=e.name("_valid");if(c(),r.reset(),i&&s){let u=e.let("ifClause");r.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else i?e.if(a,l("then")):e.if((0,Ho.not)(a),l("else"));r.pass(o,()=>r.error(!0));function c(){let u=r.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);r.mergeEvaluated(u)}function l(u,d){return()=>{let f=r.subschema({keyword:u},a);e.assign(o,a),r.mergeValidEvaluated(f,o),d?e.assign(d,(0,Ho._)`${u}`):r.setParams({ifClause:u})}}}};function um(r,e){let t=r.schema[e];return t!==void 0&&!(0,fm.alwaysValidSchema)(r,t)}ud.default=sA});var hm=A(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var oA=ee(),aA={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,oA.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};fd.default=aA});var hd=A(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});var cA=Jl(),lA=Kh(),dA=Yl(),uA=Gh(),fA=Jh(),pA=Fo(),hA=Zh(),mA=nd(),yA=rm(),gA=om(),bA=am(),_A=cm(),wA=lm(),vA=dm(),$A=pm(),SA=hm();function EA(r=!1){let e=[bA.default,_A.default,wA.default,vA.default,$A.default,SA.default,hA.default,mA.default,pA.default,yA.default,gA.default];return r?e.push(lA.default,uA.default):e.push(cA.default,dA.default),e.push(fA.default),e}pd.default=EA});var yd=A(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});us.dynamicAnchor=void 0;var md=K(),AA=kt(),mm=Xi(),kA=Mo(),xA={keyword:"$dynamicAnchor",schemaType:"string",code:r=>ym(r,r.schema)};function ym(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,md._)`${AA.default.dynamicAnchors}${(0,md.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:PA(r);t.if((0,md._)`!${i}`,()=>t.assign(i,s))}us.dynamicAnchor=ym;function PA(r){let{schemaEnv:e,schema:t,self:n}=r.it,{root:i,baseId:s,localRefs:o,meta:a}=e.root,{schemaId:c}=n.opts,l=new mm.SchemaEnv({schema:t,schemaId:c,root:i,baseId:s,localRefs:o,meta:a});return mm.compileSchema.call(n,l),(0,kA.getValidate)(r,l)}us.default=xA});var gd=A(fs=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});fs.dynamicRef=void 0;var gm=K(),IA=kt(),bm=Mo(),OA={keyword:"$dynamicRef",schemaType:"string",code:r=>_m(r,r.schema)};function _m(r,e){let{gen:t,keyword:n,it:i}=r;if(e[0]!=="#")throw new Error(`"${n}" only supports hash fragment reference`);let s=e.slice(1);if(i.allErrors)o();else{let c=t.let("valid",!1);o(c),r.ok(c)}function o(c){if(i.schemaEnv.root.dynamicAnchors[s]){let l=t.let("_v",(0,gm._)`${IA.default.dynamicAnchors}${(0,gm.getProperty)(s)}`);t.if(l,a(l,c),a(i.validateName,c))}else a(i.validateName,c)()}function a(c,l){return l?()=>t.block(()=>{(0,bm.callRef)(r,c),t.let(l,!0)}):()=>(0,bm.callRef)(r,c)}}fs.dynamicRef=_m;fs.default=OA});var wm=A(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var TA=yd(),RA=ee(),CA={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,TA.dynamicAnchor)(r,""):(0,RA.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};bd.default=CA});var vm=A(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var MA=gd(),NA={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,MA.dynamicRef)(r,r.schema)};_d.default=NA});var $m=A(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var LA=yd(),DA=gd(),qA=wm(),jA=vm(),FA=[LA.default,DA.default,qA.default,jA.default];wd.default=FA});var Em=A(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var Sm=Fo(),VA={keyword:"dependentRequired",type:"object",schemaType:"object",error:Sm.error,code:r=>(0,Sm.validatePropertyDeps)(r)};vd.default=VA});var Am=A($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var UA=Fo(),BA={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,UA.validateSchemaDeps)(r)};$d.default=BA});var km=A(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var zA=ee(),HA={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,zA.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};Sd.default=HA});var xm=A(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var KA=Em(),WA=Am(),GA=km(),JA=[KA.default,WA.default,GA.default];Ed.default=JA});var Im=A(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var Hr=K(),Pm=ee(),YA=kt(),XA={message:"must NOT have unevaluated properties",params:({params:r})=>(0,Hr._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},QA={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:XA,code(r){let{gen:e,schema:t,data:n,errsCount:i,it:s}=r;if(!i)throw new Error("ajv implementation error");let{allErrors:o,props:a}=s;a instanceof Hr.Name?e.if((0,Hr._)`${a} !== true`,()=>e.forIn("key",n,d=>e.if(l(a,d),()=>c(d)))):a!==!0&&e.forIn("key",n,d=>a===void 0?c(d):e.if(u(a,d),()=>c(d))),s.props=!0,r.ok((0,Hr._)`${i} === ${YA.default.errors}`);function c(d){if(t===!1){r.setParams({unevaluatedProperty:d}),r.error(),o||e.break();return}if(!(0,Pm.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:Pm.Type.Str},f),o||e.if((0,Hr.not)(f),()=>e.break())}}function l(d,f){return(0,Hr._)`!${d} || !${d}[${f}]`}function u(d,f){let p=[];for(let m in d)d[m]===!0&&p.push((0,Hr._)`${f} !== ${m}`);return(0,Hr.and)(...p)}}};Ad.default=QA});var Tm=A(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var vn=K(),Om=ee(),ZA={message:({params:{len:r}})=>(0,vn.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,vn._)`{limit: ${r}}`},e1={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:ZA,code(r){let{gen:e,schema:t,data:n,it:i}=r,s=i.items||0;if(s===!0)return;let o=e.const("len",(0,vn._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,vn._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,Om.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,vn._)`${o} <= ${s}`);e.if((0,vn.not)(c),()=>a(c,s)),r.ok(c)}i.items=!0;function a(c,l){e.forRange("i",l,o,u=>{r.subschema({keyword:"unevaluatedItems",dataProp:u,dataPropType:Om.Type.Num},c),i.allErrors||e.if((0,vn.not)(c),()=>e.break())})}}};kd.default=e1});var Rm=A(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var t1=Im(),r1=Tm(),n1=[t1.default,r1.default];xd.default=n1});var Cm=A(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var xe=K(),i1={message:({schemaCode:r})=>(0,xe.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,xe._)`{format: ${r}}`},s1={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:i1,code(r,e){let{gen:t,data:n,$data:i,schema:s,schemaCode:o,it:a}=r,{opts:c,errSchemaPath:l,schemaEnv:u,self:d}=a;if(!c.validateFormats)return;i?f():p();function f(){let m=t.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=t.const("fDef",(0,xe._)`${m}[${o}]`),y=t.let("fType"),b=t.let("format");t.if((0,xe._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>t.assign(y,(0,xe._)`${h}.type || "string"`).assign(b,(0,xe._)`${h}.validate`),()=>t.assign(y,(0,xe._)`"string"`).assign(b,h)),r.fail$data((0,xe.or)(g(),_()));function g(){return c.strictSchema===!1?xe.nil:(0,xe._)`${o} && !${b}`}function _(){let k=u.$async?(0,xe._)`(${h}.async ? await ${b}(${n}) : ${b}(${n}))`:(0,xe._)`${b}(${n})`,v=(0,xe._)`(typeof ${b} == "function" ? ${k} : ${b}.test(${n}))`;return(0,xe._)`${b} && ${b} !== true && ${y} === ${e} && !${v}`}}function p(){let m=d.formats[s];if(!m){g();return}if(m===!0)return;let[h,y,b]=_(m);h===e&&r.pass(k());function g(){if(c.strictSchema===!1){d.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function _(v){let E=v instanceof RegExp?(0,xe.regexpCode)(v):c.code.formats?(0,xe._)`${c.code.formats}${(0,xe.getProperty)(s)}`:void 0,O=t.scopeValue("formats",{key:s,ref:v,code:E});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,xe._)`${O}.validate`]:["string",v,O]}function k(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,xe._)`await ${b}(${n})`}return typeof y=="function"?(0,xe._)`${b}(${n})`:(0,xe._)`${b}.test(${n})`}}}};Pd.default=s1});var Od=A(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var o1=Cm(),a1=[o1.default];Id.default=a1});var Td=A(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.contentVocabulary=Gn.metadataVocabulary=void 0;Gn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Gn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Nm=A(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var c1=Tl(),l1=Wl(),d1=hd(),u1=$m(),f1=xm(),p1=Rm(),h1=Od(),Mm=Td(),m1=[u1.default,c1.default,l1.default,(0,d1.default)(!0),h1.default,Mm.metadataVocabulary,Mm.contentVocabulary,f1.default,p1.default];Rd.default=m1});var Dm=A(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.DiscrError=void 0;var Lm;(function(r){r.Tag="tag",r.Mapping="mapping"})(Lm||(Ko.DiscrError=Lm={}))});var Nd=A(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var Jn=K(),Cd=Dm(),qm=Xi(),y1=Bn(),g1=ee(),b1={message:({params:{discrError:r,tagName:e}})=>r===Cd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Jn._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},_1={keyword:"discriminator",type:"object",schemaType:"object",error:b1,code(r){let{gen:e,data:t,schema:n,parentSchema:i,it:s}=r,{oneOf:o}=i;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!o)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Jn._)`${t}${(0,Jn.getProperty)(a)}`);e.if((0,Jn._)`typeof ${l} == "string"`,()=>u(),()=>r.error(!1,{discrError:Cd.DiscrError.Tag,tag:l,tagName:a})),r.ok(c);function u(){let p=f();e.if(!1);for(let m in p)e.elseIf((0,Jn._)`${l} === ${m}`),e.assign(c,d(p[m]));e.else(),r.error(!1,{discrError:Cd.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function d(p){let m=e.name("valid"),h=r.subschema({keyword:"oneOf",schemaProp:p},m);return r.mergeEvaluated(h,Jn.Name),m}function f(){var p;let m={},h=b(i),y=!0;for(let k=0;k{w1.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 Fm=A((VM,v1)=>{v1.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 Vm=A((UM,$1)=>{$1.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 Um=A((BM,S1)=>{S1.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 Bm=A((zM,E1)=>{E1.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 zm=A((HM,A1)=>{A1.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 Hm=A((KM,k1)=>{k1.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 Km=A((WM,x1)=>{x1.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 Wm=A(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var P1=jm(),I1=Fm(),O1=Vm(),T1=Um(),R1=Bm(),C1=zm(),M1=Hm(),N1=Km(),L1=["/properties"];function D1(r){return[P1,I1,O1,T1,R1,e(this,C1),M1,e(this,N1)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,L1):n}}Ld.default=D1});var jd=A((we,qd)=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.MissingRefError=we.ValidationError=we.CodeGen=we.Name=we.nil=we.stringify=we.str=we._=we.KeywordCxt=we.Ajv2020=void 0;var q1=Pl(),j1=Nm(),F1=Nd(),V1=Wm(),Dd="https://json-schema.org/draft/2020-12/schema",Yn=class extends q1.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),j1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(F1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(V1.default.call(this,e),this.refs["http://json-schema.org/schema"]=Dd)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Dd)?Dd:void 0)}};we.Ajv2020=Yn;qd.exports=we=Yn;qd.exports.Ajv2020=Yn;Object.defineProperty(we,"__esModule",{value:!0});we.default=Yn;var U1=Un();Object.defineProperty(we,"KeywordCxt",{enumerable:!0,get:function(){return U1.KeywordCxt}});var Xn=K();Object.defineProperty(we,"_",{enumerable:!0,get:function(){return Xn._}});Object.defineProperty(we,"str",{enumerable:!0,get:function(){return Xn.str}});Object.defineProperty(we,"stringify",{enumerable:!0,get:function(){return Xn.stringify}});Object.defineProperty(we,"nil",{enumerable:!0,get:function(){return Xn.nil}});Object.defineProperty(we,"Name",{enumerable:!0,get:function(){return Xn.Name}});Object.defineProperty(we,"CodeGen",{enumerable:!0,get:function(){return Xn.CodeGen}});var B1=Yi();Object.defineProperty(we,"ValidationError",{enumerable:!0,get:function(){return B1.default}});var z1=Bn();Object.defineProperty(we,"MissingRefError",{enumerable:!0,get:function(){return z1.default}})});var ty=A(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.formatNames=lr.fastFormats=lr.fullFormats=void 0;function cr(r,e){return{validate:r,compare:e}}lr.fullFormats={date:cr(Xm,Bd),time:cr(Vd(!0),zd),"date-time":cr(Gm(!0),Zm),"iso-time":cr(Vd(),Qm),"iso-date-time":cr(Gm(),ey),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Y1,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:nk,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:X1,int32:{type:"number",validate:ek},int64:{type:"number",validate:tk},float:{type:"number",validate:Ym},double:{type:"number",validate:Ym},password:!0,binary:!0};lr.fastFormats={...lr.fullFormats,date:cr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Bd),time:cr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,zd),"date-time":cr(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Zm),"iso-time":cr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Qm),"iso-date-time":cr(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,ey),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};lr.formatNames=Object.keys(lr.fullFormats);function H1(r){return r%4===0&&(r%100!==0||r%400===0)}var K1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,W1=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Xm(r){let e=K1.exec(r);if(!e)return!1;let t=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n===2&&H1(t)?29:W1[n])}function Bd(r,e){if(r&&e)return r>e?1:r23||u>59||r&&!a)return!1;if(i<=23&&s<=59&&o<60)return!0;let d=s-u*c,f=i-l*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&o<61}}function zd(r,e){if(!(r&&e))return;let t=new Date("2020-01-01T"+r).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(t&&n)return t-n}function Qm(r,e){if(!(r&&e))return;let t=Fd.exec(r),n=Fd.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=Q1}function tk(r){return Number.isInteger(r)}function Ym(){return!0}var rk=/[^\\]\\Z/;function nk(r){if(rk.test(r))return!1;try{return new RegExp(r),!0}catch(e){return!1}}});var ny=A(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var ik=Tl(),sk=Wl(),ok=hd(),ak=Od(),ry=Td(),ck=[ik.default,sk.default,(0,ok.default)(),ak.default,ry.metadataVocabulary,ry.contentVocabulary];Hd.default=ck});var iy=A((XM,lk)=>{lk.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var oy=A((ve,Kd)=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.MissingRefError=ve.ValidationError=ve.CodeGen=ve.Name=ve.nil=ve.stringify=ve.str=ve._=ve.KeywordCxt=ve.Ajv=void 0;var dk=Pl(),uk=ny(),fk=Nd(),sy=iy(),pk=["/properties"],Wo="http://json-schema.org/draft-07/schema",Qn=class extends dk.default{_addVocabularies(){super._addVocabularies(),uk.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(fk.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(sy,pk):sy;this.addMetaSchema(e,Wo,!1),this.refs["http://json-schema.org/schema"]=Wo}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Wo)?Wo:void 0)}};ve.Ajv=Qn;Kd.exports=ve=Qn;Kd.exports.Ajv=Qn;Object.defineProperty(ve,"__esModule",{value:!0});ve.default=Qn;var hk=Un();Object.defineProperty(ve,"KeywordCxt",{enumerable:!0,get:function(){return hk.KeywordCxt}});var Zn=K();Object.defineProperty(ve,"_",{enumerable:!0,get:function(){return Zn._}});Object.defineProperty(ve,"str",{enumerable:!0,get:function(){return Zn.str}});Object.defineProperty(ve,"stringify",{enumerable:!0,get:function(){return Zn.stringify}});Object.defineProperty(ve,"nil",{enumerable:!0,get:function(){return Zn.nil}});Object.defineProperty(ve,"Name",{enumerable:!0,get:function(){return Zn.Name}});Object.defineProperty(ve,"CodeGen",{enumerable:!0,get:function(){return Zn.CodeGen}});var mk=Yi();Object.defineProperty(ve,"ValidationError",{enumerable:!0,get:function(){return mk.default}});var yk=Bn();Object.defineProperty(ve,"MissingRefError",{enumerable:!0,get:function(){return yk.default}})});var ay=A(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.formatLimitDefinition=void 0;var gk=oy(),Vt=K(),Kr=Vt.operators,Go={formatMaximum:{okStr:"<=",ok:Kr.LTE,fail:Kr.GT},formatMinimum:{okStr:">=",ok:Kr.GTE,fail:Kr.LT},formatExclusiveMaximum:{okStr:"<",ok:Kr.LT,fail:Kr.GTE},formatExclusiveMinimum:{okStr:">",ok:Kr.GT,fail:Kr.LTE}},bk={message:({keyword:r,schemaCode:e})=>(0,Vt.str)`should be ${Go[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Vt._)`{comparison: ${Go[r].okStr}, limit: ${e}}`};ei.formatLimitDefinition={keyword:Object.keys(Go),type:"string",schemaType:"string",$data:!0,error:bk,code(r){let{gen:e,data:t,schemaCode:n,keyword:i,it:s}=r,{opts:o,self:a}=s;if(!o.validateFormats)return;let c=new gk.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let f=e.scopeValue("formats",{ref:a.formats,code:o.code.formats}),p=e.const("fmt",(0,Vt._)`${f}[${c.schemaCode}]`);r.fail$data((0,Vt.or)((0,Vt._)`typeof ${p} != "object"`,(0,Vt._)`${p} instanceof RegExp`,(0,Vt._)`typeof ${p}.compare != "function"`,d(p)))}function u(){let f=c.schema,p=a.formats[f];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw new Error(`"${i}": format "${f}" does not define "compare" function`);let m=e.scopeValue("formats",{key:f,ref:p,code:o.code.formats?(0,Vt._)`${o.code.formats}${(0,Vt.getProperty)(f)}`:void 0});r.fail$data(d(m))}function d(f){return(0,Vt._)`${f}.compare(${t}, ${n}) ${Go[i].fail} 0`}},dependencies:["format"]};var _k=r=>(r.addKeyword(ei.formatLimitDefinition),r);ei.default=_k});var Jd=A((ps,dy)=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});var ti=ty(),wk=ay(),Wd=K(),cy=new Wd.Name("fullFormats"),vk=new Wd.Name("fastFormats"),Gd=(r,e={keywords:!0})=>{if(Array.isArray(e))return ly(r,e,ti.fullFormats,cy),r;let[t,n]=e.mode==="fast"?[ti.fastFormats,vk]:[ti.fullFormats,cy],i=e.formats||ti.formatNames;return ly(r,i,t,n),e.keywords&&(0,wk.default)(r),r};Gd.get=(r,e="full")=>{let n=(e==="fast"?ti.fastFormats:ti.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function ly(r,e,t,n){var i,s;(i=(s=r.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,Wd._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}dy.exports=ps=Gd;Object.defineProperty(ps,"__esModule",{value:!0});ps.default=Gd});var ii=A((sN,gy)=>{"use strict";var Ek="2.0.0",Ak=Number.MAX_SAFE_INTEGER||9007199254740991,kk=16,xk=250,Pk=["major","premajor","minor","preminor","patch","prepatch","prerelease"];gy.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:kk,MAX_SAFE_BUILD_LENGTH:xk,MAX_SAFE_INTEGER:Ak,RELEASE_TYPES:Pk,SEMVER_SPEC_VERSION:Ek,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var hs=A((oN,by)=>{"use strict";var Ik=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};by.exports=Ik});var si=A((ur,_y)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Zd,MAX_SAFE_BUILD_LENGTH:Ok,MAX_LENGTH:Tk}=ii(),Rk=hs();ur=_y.exports={};var Ck=ur.re=[],Mk=ur.safeRe=[],q=ur.src=[],Nk=ur.safeSrc=[],j=ur.t={},Lk=0,eu="[a-zA-Z0-9-]",Dk=[["\\s",1],["\\d",Tk],[eu,Ok]],qk=r=>{for(let[e,t]of Dk)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},W=(r,e,t)=>{let n=qk(e),i=Lk++;Rk(r,i,e),j[r]=i,q[i]=e,Nk[i]=n,Ck[i]=new RegExp(e,t?"g":void 0),Mk[i]=new RegExp(n,t?"g":void 0)};W("NUMERICIDENTIFIER","0|[1-9]\\d*");W("NUMERICIDENTIFIERLOOSE","\\d+");W("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${eu}*`);W("MAINVERSION",`(${q[j.NUMERICIDENTIFIER]})\\.(${q[j.NUMERICIDENTIFIER]})\\.(${q[j.NUMERICIDENTIFIER]})`);W("MAINVERSIONLOOSE",`(${q[j.NUMERICIDENTIFIERLOOSE]})\\.(${q[j.NUMERICIDENTIFIERLOOSE]})\\.(${q[j.NUMERICIDENTIFIERLOOSE]})`);W("PRERELEASEIDENTIFIER",`(?:${q[j.NONNUMERICIDENTIFIER]}|${q[j.NUMERICIDENTIFIER]})`);W("PRERELEASEIDENTIFIERLOOSE",`(?:${q[j.NONNUMERICIDENTIFIER]}|${q[j.NUMERICIDENTIFIERLOOSE]})`);W("PRERELEASE",`(?:-(${q[j.PRERELEASEIDENTIFIER]}(?:\\.${q[j.PRERELEASEIDENTIFIER]})*))`);W("PRERELEASELOOSE",`(?:-?(${q[j.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${q[j.PRERELEASEIDENTIFIERLOOSE]})*))`);W("BUILDIDENTIFIER",`${eu}+`);W("BUILD",`(?:\\+(${q[j.BUILDIDENTIFIER]}(?:\\.${q[j.BUILDIDENTIFIER]})*))`);W("FULLPLAIN",`v?${q[j.MAINVERSION]}${q[j.PRERELEASE]}?${q[j.BUILD]}?`);W("FULL",`^${q[j.FULLPLAIN]}$`);W("LOOSEPLAIN",`[v=\\s]*${q[j.MAINVERSIONLOOSE]}${q[j.PRERELEASELOOSE]}?${q[j.BUILD]}?`);W("LOOSE",`^${q[j.LOOSEPLAIN]}$`);W("GTLT","((?:<|>)?=?)");W("XRANGEIDENTIFIERLOOSE",`${q[j.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);W("XRANGEIDENTIFIER",`${q[j.NUMERICIDENTIFIER]}|x|X|\\*`);W("XRANGEPLAIN",`[v=\\s]*(${q[j.XRANGEIDENTIFIER]})(?:\\.(${q[j.XRANGEIDENTIFIER]})(?:\\.(${q[j.XRANGEIDENTIFIER]})(?:${q[j.PRERELEASE]})?${q[j.BUILD]}?)?)?`);W("XRANGEPLAINLOOSE",`[v=\\s]*(${q[j.XRANGEIDENTIFIERLOOSE]})(?:\\.(${q[j.XRANGEIDENTIFIERLOOSE]})(?:\\.(${q[j.XRANGEIDENTIFIERLOOSE]})(?:${q[j.PRERELEASELOOSE]})?${q[j.BUILD]}?)?)?`);W("XRANGE",`^${q[j.GTLT]}\\s*${q[j.XRANGEPLAIN]}$`);W("XRANGELOOSE",`^${q[j.GTLT]}\\s*${q[j.XRANGEPLAINLOOSE]}$`);W("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Zd}})(?:\\.(\\d{1,${Zd}}))?(?:\\.(\\d{1,${Zd}}))?`);W("COERCE",`${q[j.COERCEPLAIN]}(?:$|[^\\d])`);W("COERCEFULL",q[j.COERCEPLAIN]+`(?:${q[j.PRERELEASE]})?(?:${q[j.BUILD]})?(?:$|[^\\d])`);W("COERCERTL",q[j.COERCE],!0);W("COERCERTLFULL",q[j.COERCEFULL],!0);W("LONETILDE","(?:~>?)");W("TILDETRIM",`(\\s*)${q[j.LONETILDE]}\\s+`,!0);ur.tildeTrimReplace="$1~";W("TILDE",`^${q[j.LONETILDE]}${q[j.XRANGEPLAIN]}$`);W("TILDELOOSE",`^${q[j.LONETILDE]}${q[j.XRANGEPLAINLOOSE]}$`);W("LONECARET","(?:\\^)");W("CARETTRIM",`(\\s*)${q[j.LONECARET]}\\s+`,!0);ur.caretTrimReplace="$1^";W("CARET",`^${q[j.LONECARET]}${q[j.XRANGEPLAIN]}$`);W("CARETLOOSE",`^${q[j.LONECARET]}${q[j.XRANGEPLAINLOOSE]}$`);W("COMPARATORLOOSE",`^${q[j.GTLT]}\\s*(${q[j.LOOSEPLAIN]})$|^$`);W("COMPARATOR",`^${q[j.GTLT]}\\s*(${q[j.FULLPLAIN]})$|^$`);W("COMPARATORTRIM",`(\\s*)${q[j.GTLT]}\\s*(${q[j.LOOSEPLAIN]}|${q[j.XRANGEPLAIN]})`,!0);ur.comparatorTrimReplace="$1$2$3";W("HYPHENRANGE",`^\\s*(${q[j.XRANGEPLAIN]})\\s+-\\s+(${q[j.XRANGEPLAIN]})\\s*$`);W("HYPHENRANGELOOSE",`^\\s*(${q[j.XRANGEPLAINLOOSE]})\\s+-\\s+(${q[j.XRANGEPLAINLOOSE]})\\s*$`);W("STAR","(<|>)?=?\\s*\\*");W("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");W("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Xo=A((aN,wy)=>{"use strict";var jk=Object.freeze({loose:!0}),Fk=Object.freeze({}),Vk=r=>r?typeof r!="object"?jk:r:Fk;wy.exports=Vk});var tu=A((cN,Sy)=>{"use strict";var vy=/^[0-9]+$/,$y=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:r$y(e,r);Sy.exports={compareIdentifiers:$y,rcompareIdentifiers:Uk}});var Ue=A((lN,Ay)=>{"use strict";var Qo=hs(),{MAX_LENGTH:Ey,MAX_SAFE_INTEGER:Zo}=ii(),{safeRe:ea,t:ta}=si(),Bk=Xo(),{compareIdentifiers:ru}=tu(),zk=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nEy)throw new TypeError(`version is longer than ${Ey} characters`);Qo("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?ea[ta.LOOSE]:ea[ta.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Zo||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Zo||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Zo||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(i=>{if(/^[0-9]+$/.test(i)){let s=+i;if(s>=0&&se.major?1:this.minore.minor?1:this.patche.patch?1:0}comparePre(e){if(e instanceof r||(e=new r(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let n=this.prerelease[t],i=e.prerelease[t];if(Qo("prerelease compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return ru(n,i)}while(++t)}compareBuild(e){e instanceof r||(e=new r(e,this.options));let t=0;do{let n=this.build[t],i=e.build[t];if(Qo("build compare",t,n,i),n===void 0&&i===void 0)return 0;if(i===void 0)return 1;if(n===void 0)return-1;if(n===i)continue;return ru(n,i)}while(++t)}inc(e,t,n){if(e.startsWith("pre")){if(!t&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(t){let i=`-${t}`.match(this.options.loose?ea[ta.PRERELEASELOOSE]:ea[ta.PRERELEASE]);if(!i||i[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,n),this.inc("pre",t,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",t,n),this.inc("pre",t,n);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{let i=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[i];else{let s=this.prerelease.length;for(;--s>=0;)typeof this.prerelease[s]=="number"&&(this.prerelease[s]++,s=-2);if(s===-1){if(t===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(i)}}if(t){let s=[t,i];if(n===!1&&(s=[t]),zk(this.prerelease,t)){let o=this.prerelease[t.split(".").length];isNaN(o)&&(this.prerelease=s)}else this.prerelease=s}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Ay.exports=nu});var Gr=A((dN,xy)=>{"use strict";var ky=Ue(),Hk=(r,e,t=!1)=>{if(r instanceof ky)return r;try{return new ky(r,e)}catch(n){if(!t)return null;throw n}};xy.exports=Hk});var Iy=A((uN,Py)=>{"use strict";var Kk=Gr(),Wk=(r,e)=>{let t=Kk(r,e);return t?t.version:null};Py.exports=Wk});var Ty=A((fN,Oy)=>{"use strict";var Gk=Gr(),Jk=(r,e)=>{let t=Gk(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Oy.exports=Jk});var My=A((pN,Cy)=>{"use strict";var Ry=Ue(),Yk=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Ry(r instanceof Ry?r.version:r,t).inc(e,n,i).version}catch(s){return null}};Cy.exports=Yk});var Dy=A((hN,Ly)=>{"use strict";var Ny=Gr(),Xk=(r,e)=>{let t=Ny(r,null,!0),n=Ny(e,null,!0),i=t.compare(n);if(i===0)return null;let s=i>0,o=s?t:n,a=s?n:t,c=!!o.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0)return a.minor&&!a.patch?"minor":"patch"}let u=c?"pre":"";return t.major!==n.major?u+"major":t.minor!==n.minor?u+"minor":t.patch!==n.patch?u+"patch":"prerelease"};Ly.exports=Xk});var jy=A((mN,qy)=>{"use strict";var Qk=Ue(),Zk=(r,e)=>new Qk(r,e).major;qy.exports=Zk});var Vy=A((yN,Fy)=>{"use strict";var ex=Ue(),tx=(r,e)=>new ex(r,e).minor;Fy.exports=tx});var By=A((gN,Uy)=>{"use strict";var rx=Ue(),nx=(r,e)=>new rx(r,e).patch;Uy.exports=nx});var Hy=A((bN,zy)=>{"use strict";var ix=Gr(),sx=(r,e)=>{let t=ix(r,e);return t&&t.prerelease.length?t.prerelease:null};zy.exports=sx});var Ot=A((_N,Wy)=>{"use strict";var Ky=Ue(),ox=(r,e,t)=>new Ky(r,t).compare(new Ky(e,t));Wy.exports=ox});var Jy=A((wN,Gy)=>{"use strict";var ax=Ot(),cx=(r,e,t)=>ax(e,r,t);Gy.exports=cx});var Xy=A((vN,Yy)=>{"use strict";var lx=Ot(),dx=(r,e)=>lx(r,e,!0);Yy.exports=dx});var ra=A(($N,Zy)=>{"use strict";var Qy=Ue(),ux=(r,e,t)=>{let n=new Qy(r,t),i=new Qy(e,t);return n.compare(i)||n.compareBuild(i)};Zy.exports=ux});var tg=A((SN,eg)=>{"use strict";var fx=ra(),px=(r,e)=>r.sort((t,n)=>fx(t,n,e));eg.exports=px});var ng=A((EN,rg)=>{"use strict";var hx=ra(),mx=(r,e)=>r.sort((t,n)=>hx(n,t,e));rg.exports=mx});var ms=A((AN,ig)=>{"use strict";var yx=Ot(),gx=(r,e,t)=>yx(r,e,t)>0;ig.exports=gx});var na=A((kN,sg)=>{"use strict";var bx=Ot(),_x=(r,e,t)=>bx(r,e,t)<0;sg.exports=_x});var iu=A((xN,og)=>{"use strict";var wx=Ot(),vx=(r,e,t)=>wx(r,e,t)===0;og.exports=vx});var su=A((PN,ag)=>{"use strict";var $x=Ot(),Sx=(r,e,t)=>$x(r,e,t)!==0;ag.exports=Sx});var ia=A((IN,cg)=>{"use strict";var Ex=Ot(),Ax=(r,e,t)=>Ex(r,e,t)>=0;cg.exports=Ax});var sa=A((ON,lg)=>{"use strict";var kx=Ot(),xx=(r,e,t)=>kx(r,e,t)<=0;lg.exports=xx});var ou=A((TN,dg)=>{"use strict";var Px=iu(),Ix=su(),Ox=ms(),Tx=ia(),Rx=na(),Cx=sa(),Mx=(r,e,t,n)=>{switch(e){case"===":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r===t;case"!==":return typeof r=="object"&&(r=r.version),typeof t=="object"&&(t=t.version),r!==t;case"":case"=":case"==":return Px(r,t,n);case"!=":return Ix(r,t,n);case">":return Ox(r,t,n);case">=":return Tx(r,t,n);case"<":return Rx(r,t,n);case"<=":return Cx(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};dg.exports=Mx});var fg=A((RN,ug)=>{"use strict";var Nx=Ue(),Lx=Gr(),{safeRe:oa,t:aa}=si(),Dx=(r,e)=>{if(r instanceof Nx)return r;if(typeof r=="number"&&(r=String(r)),typeof r!="string")return null;e=e||{};let t=null;if(!e.rtl)t=r.match(e.includePrerelease?oa[aa.COERCEFULL]:oa[aa.COERCE]);else{let c=e.includePrerelease?oa[aa.COERCERTLFULL]:oa[aa.COERCERTL],l;for(;(l=c.exec(r))&&(!t||t.index+t[0].length!==r.length);)(!t||l.index+l[0].length!==t.index+t[0].length)&&(t=l),c.lastIndex=l.index+l[1].length+l[2].length;c.lastIndex=-1}if(t===null)return null;let n=t[2],i=t[3]||"0",s=t[4]||"0",o=e.includePrerelease&&t[5]?`-${t[5]}`:"",a=e.includePrerelease&&t[6]?`+${t[6]}`:"";return Lx(`${n}.${i}.${s}${o}${a}`,e)};ug.exports=Dx});var hg=A((CN,pg)=>{"use strict";var qx=Gr(),jx=ii(),Fx=Ue(),Vx=(r,e,t)=>{if(!jx.RELEASE_TYPES.includes(e))return null;let n=Ux(r,t);return n&&Bx(n,e)},Ux=(r,e)=>{let t=r instanceof Fx?r.version:r;return qx(t,e)},Bx=(r,e)=>{if(zx(e))return r.version;switch(r.prerelease=[],e){case"major":r.minor=0,r.patch=0;break;case"minor":r.patch=0;break}return r.format()},zx=r=>r.startsWith("pre");pg.exports=Vx});var yg=A((MN,mg)=>{"use strict";var au=class{constructor(){this.max=1e3,this.map=new Map}get(e){let t=this.map.get(e);if(t!==void 0)return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let i=this.map.keys().next().value;this.delete(i)}this.map.set(e,t)}return this}};mg.exports=au});var Tt=A((NN,wg)=>{"use strict";var Hx=/\s+/g,cu=class r{constructor(e,t){if(t=Wx(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof lu)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(Hx," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(i=>!bg(i[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let i of this.set)if(i.length===1&&rP(i[0])){this.set=[i];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e0&&(this.formatted+="||");let t=this.set[e];for(let n=0;n0&&(this.formatted+=" "),this.formatted+=t[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){e=e.replace(tP,"");let n=((this.options.includePrerelease&&Zx)|(this.options.loose&&eP))+":"+e,i=gg.get(n);if(i)return i;let s=this.options.loose,o=s?nt[Be.HYPHENRANGELOOSE]:nt[Be.HYPHENRANGE];e=e.replace(o,pP(this.options.includePrerelease)),$e("hyphen replace",e),e=e.replace(nt[Be.COMPARATORTRIM],Yx),$e("comparator trim",e),e=e.replace(nt[Be.TILDETRIM],Xx),$e("tilde trim",e),e=e.replace(nt[Be.CARETTRIM],Qx),$e("caret trim",e);let a=e.split(" ").map(d=>nP(d,this.options)).join(" ").split(/\s+/).map(d=>fP(d,this.options));s&&(a=a.filter(d=>($e("loose invalid filter",d,this.options),!!d.match(nt[Be.COMPARATORLOOSE])))),$e("range list",a);let c=new Map,l=a.map(d=>new lu(d,this.options));for(let d of l){if(bg(d))return[d];c.set(d.value,d)}c.size>1&&c.has("")&&c.delete("");let u=[...c.values()];return gg.set(n,u),u}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>_g(n,t)&&e.set.some(i=>_g(i,t)&&n.every(s=>i.every(o=>s.intersects(o,t)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new Gx(e,this.options)}catch(t){return!1}for(let t=0;tr.value==="<0.0.0-0",rP=r=>r.value==="",_g=(r,e)=>{let t=!0,n=r.slice(),i=n.pop();for(;t&&n.length;)t=n.every(s=>i.intersects(s,e)),i=n.pop();return t},nP=(r,e)=>(r=r.replace(nt[Be.BUILD],""),$e("comp",r,e),r=aP(r,e),$e("caret",r),r=sP(r,e),$e("tildes",r),r=lP(r,e),$e("xrange",r),r=uP(r,e),$e("stars",r),r),Ce=r=>!r||r.toLowerCase()==="x"||r==="*",iP=(r,e,t)=>Ce(r)&&!Ce(e)||Ce(e)&&t&&!Ce(t),sP=(r,e)=>r.trim().split(/\s+/).map(t=>oP(t,e)).join(" "),oP=(r,e)=>{let t=e.loose?nt[Be.TILDELOOSE]:nt[Be.TILDE],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{$e("tilde",r,i,s,o,a,c);let l;return Ce(s)?l="":Ce(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Ce(a)?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:c?($e("replaceTilde pr",c),l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`):l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`,$e("tilde return",l),l})},aP=(r,e)=>r.trim().split(/\s+/).map(t=>cP(t,e)).join(" "),cP=(r,e)=>{$e("caret",r,e);let t=e.loose?nt[Be.CARETLOOSE]:nt[Be.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{$e("caret",r,i,s,o,a,c);let l;return Ce(s)?l="":Ce(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Ce(a)?s==="0"?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:c?($e("replaceCaret pr",c),s==="0"?o==="0"?l=`>=${s}.${o}.${a}-${c} <${s}.${o}.${+a+1}-0`:l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.${a}-${c} <${+s+1}.0.0-0`):($e("no pr"),s==="0"?o==="0"?l=`>=${s}.${o}.${a} <${s}.${o}.${+a+1}-0`:l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.${a} <${+s+1}.0.0-0`),$e("caret return",l),l})},lP=(r,e)=>($e("replaceXRanges",r,e),r.split(/\s+/).map(t=>dP(t,e)).join(" ")),dP=(r,e)=>{r=r.trim();let t=e.loose?nt[Be.XRANGELOOSE]:nt[Be.XRANGE];return r.replace(t,(n,i,s,o,a,c)=>{if($e("xRange",r,n,i,s,o,a,c),iP(s,o,a))return r;let l=Ce(s),u=l||Ce(o),d=u||Ce(a),f=d;return i==="="&&f&&(i=""),c=e.includePrerelease?"-0":"",l?i===">"||i==="<"?n="<0.0.0-0":n="*":i&&f?(u&&(o=0),a=0,i===">"?(i=">=",u?(s=+s+1,o=0,a=0):(o=+o+1,a=0)):i==="<="&&(i="<",u?s=+s+1:o=+o+1),i==="<"&&(c="-0"),n=`${i+s}.${o}.${a}${c}`):u?n=`>=${s}.0.0${c} <${+s+1}.0.0-0`:d&&(n=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`),$e("xRange return",n),n})},uP=(r,e)=>($e("replaceStars",r,e),r.trim().replace(nt[Be.STAR],"")),fP=(r,e)=>($e("replaceGTE0",r,e),r.trim().replace(nt[e.includePrerelease?Be.GTE0PRE:Be.GTE0],"")),pP=r=>(e,t,n,i,s,o,a,c,l,u,d,f)=>(Ce(n)?t="":Ce(i)?t=`>=${n}.0.0${r?"-0":""}`:Ce(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Ce(l)?c="":Ce(u)?c=`<${+l+1}.0.0-0`:Ce(d)?c=`<${l}.${+u+1}.0-0`:f?c=`<=${l}.${u}.${d}-${f}`:r?c=`<${l}.${u}.${+d+1}-0`:c=`<=${c}`,`${t} ${c}`.trim()),hP=(r,e,t)=>{for(let n=0;n0){let i=r[n].semver;if(i.major===e.major&&i.minor===e.minor&&i.patch===e.patch)return!0}return!1}return!0}});var ys=A((LN,kg)=>{"use strict";var gs=Symbol("SemVer ANY"),fu=class r{static get ANY(){return gs}constructor(e,t){if(t=vg(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),uu("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===gs?this.value="":this.value=this.operator+this.semver.version,uu("comp",this)}parse(e){let t=this.options.loose?$g[Sg.COMPARATORLOOSE]:$g[Sg.COMPARATOR],n=e.match(t);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Eg(n[2],this.options.loose):this.semver=gs}toString(){return this.value}test(e){if(uu("Comparator.test",e,this.options.loose),this.semver===gs||e===gs)return!0;if(typeof e=="string")try{e=new Eg(e,this.options)}catch(t){return!1}return du(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new Ag(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Ag(this.value,t).test(e.semver):(t=vg(t),t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||du(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||du(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};kg.exports=fu;var vg=Xo(),{safeRe:$g,t:Sg}=si(),du=ou(),uu=hs(),Eg=Ue(),Ag=Tt()});var bs=A((DN,xg)=>{"use strict";var mP=Tt(),yP=(r,e,t)=>{try{e=new mP(e,t)}catch(n){return!1}return e.test(r)};xg.exports=yP});var Ig=A((qN,Pg)=>{"use strict";var gP=Tt(),bP=(r,e)=>new gP(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));Pg.exports=bP});var Tg=A((jN,Og)=>{"use strict";var _P=Ue(),wP=Tt(),vP=(r,e,t)=>{let n=null,i=null,s=null;try{s=new wP(e,t)}catch(o){return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new _P(n,t))}),n};Og.exports=vP});var Cg=A((FN,Rg)=>{"use strict";var $P=Ue(),SP=Tt(),EP=(r,e,t)=>{let n=null,i=null,s=null;try{s=new SP(e,t)}catch(o){return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new $P(n,t))}),n};Rg.exports=EP});var Lg=A((VN,Ng)=>{"use strict";var pu=Ue(),AP=Tt(),Mg=ms(),kP=(r,e)=>{r=new AP(r,e);let t=new pu("0.0.0");if(r.test(t)||(t=new pu("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new pu(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||Mg(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||Mg(t,s))&&(t=s)}return t&&r.test(t)?t:null};Ng.exports=kP});var qg=A((UN,Dg)=>{"use strict";var xP=Tt(),PP=(r,e)=>{try{return new xP(r,e).range||"*"}catch(t){return null}};Dg.exports=PP});var ca=A((BN,Ug)=>{"use strict";var IP=Ue(),Vg=ys(),{ANY:OP}=Vg,TP=Tt(),RP=bs(),jg=ms(),Fg=na(),CP=sa(),MP=ia(),NP=(r,e,t,n)=>{r=new IP(r,n),e=new TP(e,n);let i,s,o,a,c;switch(t){case">":i=jg,s=CP,o=Fg,a=">",c=">=";break;case"<":i=Fg,s=MP,o=jg,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(RP(r,e,n))return!1;for(let l=0;l{p.semver===OP&&(p=new Vg(">=0.0.0")),d=d||p,f=f||p,i(p.semver,d.semver,n)?d=p:o(p.semver,f.semver,n)&&(f=p)}),d.operator===a||d.operator===c||(!f.operator||f.operator===a)&&s(r,f.semver))return!1;if(f.operator===c&&o(r,f.semver))return!1}return!0};Ug.exports=NP});var zg=A((zN,Bg)=>{"use strict";var LP=ca(),DP=(r,e,t)=>LP(r,e,">",t);Bg.exports=DP});var Kg=A((HN,Hg)=>{"use strict";var qP=ca(),jP=(r,e,t)=>qP(r,e,"<",t);Hg.exports=jP});var Jg=A((KN,Gg)=>{"use strict";var Wg=Tt(),FP=(r,e,t)=>(r=new Wg(r,t),e=new Wg(e,t),r.intersects(e,t));Gg.exports=FP});var Xg=A((WN,Yg)=>{"use strict";var VP=bs(),UP=Ot();Yg.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((u,d)=>UP(u,d,t));for(let u of o)VP(u,e,t)?(s=u,i||(i=u)):(s&&n.push([i,s]),s=null,i=null);i&&n.push([i,null]);let a=[];for(let[u,d]of n)u===d?a.push(u):!d&&u===o[0]?a.push("*"):d?u===o[0]?a.push(`<=${d}`):a.push(`${u} - ${d}`):a.push(`>=${u}`);let c=a.join(" || "),l=typeof e.raw=="string"?e.raw:String(e);return c.length{"use strict";var Qg=Tt(),yu=ys(),{ANY:hu}=yu,mu=bs(),gu=Ot(),BP=(r,e,t={})=>{if(r===e)return!0;r=new Qg(r,t),e=new Qg(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=HP(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},zP=[new yu(">=0.0.0-0")],Zg=[new yu(">=0.0.0")],HP=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===hu){if(e.length===1&&e[0].semver===hu)return!0;t.includePrerelease?r=zP:r=Zg}if(e.length===1&&e[0].semver===hu){if(t.includePrerelease)return!0;e=Zg}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=eb(i,p,t):p.operator==="<"||p.operator==="<="?s=tb(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=gu(i.semver,s.semver,t),o>0)return null;if(o===0&&(i.operator!==">="||s.operator!=="<="))return null}for(let p of n){if(i&&!mu(p,String(i),t)||s&&!mu(p,String(s),t))return null;for(let m of e)if(!mu(p,String(m),t))return!1;return!0}let a,c,l,u,d=s&&!t.includePrerelease&&s.semver.prerelease.length?s.semver:!1,f=i&&!t.includePrerelease&&i.semver.prerelease.length?i.semver:!1;d&&d.prerelease.length===1&&s.operator==="<"&&d.prerelease[0]===0&&(d=!1);for(let p of e){if(u=u||p.operator===">"||p.operator===">=",l=l||p.operator==="<"||p.operator==="<=",i){if(f&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch&&(f=!1),p.operator===">"||p.operator===">="){if(a=eb(i,p,t),a===p&&a!==i)return!1}else if(i.operator===">="&&!p.test(i.semver))return!1}if(s){if(d&&p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===d.major&&p.semver.minor===d.minor&&p.semver.patch===d.patch&&(d=!1),p.operator==="<"||p.operator==="<="){if(c=tb(s,p,t),c===p&&c!==s)return!1}else if(s.operator==="<="&&!p.test(s.semver))return!1}if(!p.operator&&(s||i)&&o!==0)return!1}return!(i&&l&&!s&&o!==0||s&&u&&!i&&o!==0||f||d)},eb=(r,e,t)=>{if(!r)return e;let n=gu(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},tb=(r,e,t)=>{if(!r)return e;let n=gu(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};rb.exports=BP});var ab=A((JN,ob)=>{"use strict";var bu=si(),ib=ii(),KP=Ue(),sb=tu(),WP=Gr(),GP=Iy(),JP=Ty(),YP=My(),XP=Dy(),QP=jy(),ZP=Vy(),eI=By(),tI=Hy(),rI=Ot(),nI=Jy(),iI=Xy(),sI=ra(),oI=tg(),aI=ng(),cI=ms(),lI=na(),dI=iu(),uI=su(),fI=ia(),pI=sa(),hI=ou(),mI=fg(),yI=hg(),gI=ys(),bI=Tt(),_I=bs(),wI=Ig(),vI=Tg(),$I=Cg(),SI=Lg(),EI=qg(),AI=ca(),kI=zg(),xI=Kg(),PI=Jg(),II=Xg(),OI=nb();ob.exports={parse:WP,valid:GP,clean:JP,inc:YP,diff:XP,major:QP,minor:ZP,patch:eI,prerelease:tI,compare:rI,rcompare:nI,compareLoose:iI,compareBuild:sI,sort:oI,rsort:aI,gt:cI,lt:lI,eq:dI,neq:uI,gte:fI,lte:pI,cmp:hI,coerce:mI,truncate:yI,Comparator:gI,Range:bI,satisfies:_I,toComparators:wI,maxSatisfying:vI,minSatisfying:$I,minVersion:SI,validRange:EI,outside:AI,gtr:kI,ltr:xI,intersects:PI,simplifyRange:II,subset:OI,SemVer:KP,re:bu.re,src:bu.src,tokens:bu.t,SEMVER_SPEC_VERSION:ib.SEMVER_SPEC_VERSION,RELEASE_TYPES:ib.RELEASE_TYPES,compareIdentifiers:sb.compareIdentifiers,rcompareIdentifiers:sb.rcompareIdentifiers}});var ws=A((p2,gb)=>{"use strict";var pb="[^\\\\/]",jI="(?=.)",hb="[^/]",Su="(?:\\/|$)",mb="(?:^|\\/)",Eu=`\\.{1,2}${Su}`,FI="(?!\\.)",VI=`(?!${mb}${Eu})`,UI=`(?!\\.{0,1}${Su})`,BI=`(?!${Eu})`,zI="[^.\\/]",HI=`${hb}*?`,KI="/",yb={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:jI,QMARK:hb,END_ANCHOR:Su,DOTS_SLASH:Eu,NO_DOT:FI,NO_DOTS:VI,NO_DOT_SLASH:UI,NO_DOTS_SLASH:BI,QMARK_NO_DOT:zI,STAR:HI,START_ANCHOR:mb,SEP:KI},WI={...yb,SLASH_LITERAL:"[\\\\/]",QMARK:pb,STAR:`${pb}*?`,DOTS_SLASH:"\\.{1,2}(?:[\\\\/]|$)",NO_DOT:"(?!\\.)",NO_DOTS:"(?!(?:^|[\\\\/])\\.{1,2}(?:[\\\\/]|$))",NO_DOT_SLASH:"(?!\\.{0,1}(?:[\\\\/]|$))",NO_DOTS_SLASH:"(?!\\.{1,2}(?:[\\\\/]|$))",QMARK_NO_DOT:"[^.\\\\/]",START_ANCHOR:"(?:^|[\\\\/])",END_ANCHOR:"(?:[\\\\/]|$)",SEP:"\\"},GI={__proto__:null,alnum:"a-zA-Z0-9",alpha:"a-zA-Z",ascii:"\\x00-\\x7F",blank:" \\t",cntrl:"\\x00-\\x1F\\x7F",digit:"0-9",graph:"\\x21-\\x7E",lower:"a-z",print:"\\x20-\\x7E ",punct:"\\-!\"#$%&'()\\*+,./:;<=>?@[\\]^_`{|}~",space:" \\t\\r\\n\\v\\f",upper:"A-Z",word:"A-Za-z0-9_",xdigit:"A-Fa-f0-9"};gb.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:GI,REGEX_BACKSLASH:/\\(?![*+?^${}(|)[\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\].,$*+?^{}()|\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\?)((\W)(\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\[.*?[^\\]\]|\\(?=.))/g,REPLACEMENTS:{__proto__:null,"***":"*","**/**":"**","**/**/**":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,extglobChars(r){return{"!":{type:"negate",open:"(?:(?!(?:",close:`))${r.STAR})`},"?":{type:"qmark",open:"(?:",close:")?"},"+":{type:"plus",open:"(?:",close:")+"},"*":{type:"star",open:"(?:",close:")*"},"@":{type:"at",open:"(?:",close:")"}}},globChars(r){return r===!0?WI:yb}}});var vs=A(pt=>{"use strict";var{REGEX_BACKSLASH:JI,REGEX_REMOVE_BACKSLASH:YI,REGEX_SPECIAL_CHARS:XI,REGEX_SPECIAL_CHARS_GLOBAL:QI}=ws();pt.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);pt.hasRegexChars=r=>XI.test(r);pt.isRegexChar=r=>r.length===1&&pt.hasRegexChars(r);pt.escapeRegex=r=>r.replace(QI,"\\$1");pt.toPosixSlashes=r=>r.replace(JI,"/");pt.isWindows=()=>{if(typeof navigator!="undefined"&&navigator.platform){let r=navigator.platform.toLowerCase();return r==="win32"||r==="windows"}return typeof process!="undefined"&&process.platform?process.platform==="win32":!1};pt.removeBackslashes=r=>r.replace(YI,e=>e==="\\"?"":e);pt.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?pt.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};pt.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};pt.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",i=t.contains?"":"$",s=`${n}(?:${r})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s};pt.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n}});var Ab=A((m2,Eb)=>{"use strict";var bb=vs(),{CHAR_ASTERISK:Au,CHAR_AT:ZI,CHAR_BACKWARD_SLASH:$s,CHAR_COMMA:eO,CHAR_DOT:ku,CHAR_EXCLAMATION_MARK:xu,CHAR_FORWARD_SLASH:Sb,CHAR_LEFT_CURLY_BRACE:Pu,CHAR_LEFT_PARENTHESES:Iu,CHAR_LEFT_SQUARE_BRACKET:tO,CHAR_PLUS:rO,CHAR_QUESTION_MARK:_b,CHAR_RIGHT_CURLY_BRACE:nO,CHAR_RIGHT_PARENTHESES:wb,CHAR_RIGHT_SQUARE_BRACKET:iO}=ws(),vb=r=>r===Sb||r===$s,$b=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},sO=(r,e)=>{let t=e||{},n=r.length-1,i=t.parts===!0||t.scanToEnd===!0,s=[],o=[],a=[],c=r,l=-1,u=0,d=0,f=!1,p=!1,m=!1,h=!1,y=!1,b=!1,g=!1,_=!1,k=!1,v=!1,E=0,O,w,x={value:"",depth:0,isGlob:!1},$=()=>l>=n,L=()=>c.charCodeAt(l+1),F=()=>(O=w,c.charCodeAt(++l));for(;l0&&(P=c.slice(0,u),c=c.slice(u),d-=u),z&&m===!0&&d>0?(z=c.slice(0,d),I=c.slice(d)):m===!0?(z="",I=c):z=c,z&&z!==""&&z!=="/"&&z!==c&&vb(z.charCodeAt(z.length-1))&&(z=z.slice(0,-1)),t.unescape===!0&&(I&&(I=bb.removeBackslashes(I)),z&&g===!0&&(z=bb.removeBackslashes(z)));let ke={prefix:P,input:r,start:u,base:z,glob:I,isBrace:f,isBracket:p,isGlob:m,isExtglob:h,isGlobstar:y,negated:_,negatedExtglob:k};if(t.tokens===!0&&(ke.maxDepth=0,vb(w)||o.push(x),ke.tokens=o),t.parts===!0||t.tokens===!0){let ce;for(let de=0;de{"use strict";var Ss=ws(),_t=vs(),{MAX_LENGTH:fa,POSIX_REGEX_SOURCE:oO,REGEX_NON_SPECIAL_CHARS:aO,REGEX_SPECIAL_CHARS_BACKREF:cO,REPLACEMENTS:kb}=Ss,lO=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch(n){return r.map(i=>_t.escapeRegex(i)).join("..")}return t},oi=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,xb=r=>{let e=[],t=0,n=0,i=0,s="",o=!1;for(let a of r){if(o===!0){s+=a,o=!1;continue}if(a==="\\"){s+=a,o=!0;continue}if(a==='"'){i=i===1?0:1,s+=a;continue}if(i===0){if(a==="[")t++;else if(a==="]"&&t>0)t--;else if(t===0){if(a==="(")n++;else if(a===")"&&n>0)n--;else if(a==="|"&&n===0){e.push(s),s="";continue}}}s+=a}return e.push(s),e},dO=r=>{let e=!1;for(let t of r){if(e===!0){e=!1;continue}if(t==="\\"){e=!0;continue}if(/[?*+@!()[\]{}]/.test(t))return!1}return!0},Tu=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(dO(e))return e.replace(/\\(.)/g,"$1")},uO=r=>{let e=r.map(Tu).filter(Boolean);for(let t=0;t{if(r[0]!=="+"&&r[0]!=="*"||r[1]!=="(")return;let t=0,n=0,i=0,s=!1;for(let o=1;o0){t--;continue}if(!(t>0)){if(a==="("){n++;continue}if(a===")"&&(n--,n===0))return e===!0&&o!==r.length-1?void 0:{type:r[0],body:r.slice(2,o),end:o}}}}},fO=r=>`${r.length===1?_t.escapeRegex(r[0]):`[${r.map(t=>_t.escapeRegex(t)).join("")}]`}*`,pO=r=>{let e=0,t=[];for(;eo.trim());if(i.length!==1)return;let s=Tu(i[0]);if(!s||s.length!==1)return;t.push(s),e+=n.end+1}if(!(t.length<1))return t},hO=r=>{let e=0,t=r.trim(),n=Ou(t);for(;n;)e++,t=n.body.trim(),n=Ou(t);return e},mO=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Ss.DEFAULT_MAX_EXTGLOB_RECURSION,n=xb(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||uO(n)))return{risky:!0};let i=[],s=!1,o=!0;for(let a of n){let c=pO(a);if(c){s=!0,i.push(...c);continue}let l=Tu(a);if(l&&l.length===1){i.push(l);continue}if(o=!1,hO(a)>t)return{risky:!0}}return s?o?{risky:!0,safeOutput:fO([...new Set(i)])}:{risky:!0}:{risky:!1}},Ru=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=kb[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(fa,t.maxLength):fa,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);let s={type:"bos",value:"",output:t.prepend||""},o=[s],a=t.capture?"":"?:",c=Ss.globChars(t.windows),l=Ss.extglobChars(c),{DOT_LITERAL:u,PLUS_LITERAL:d,SLASH_LITERAL:f,ONE_CHAR:p,DOTS_SLASH:m,NO_DOT:h,NO_DOT_SLASH:y,NO_DOTS_SLASH:b,QMARK:g,QMARK_NO_DOT:_,STAR:k,START_ANCHOR:v}=c,E=R=>`(${a}(?:(?!${v}${R.dot?m:u}).)*?)`,O=t.dot?"":h,w=t.dot?g:_,x=t.bash===!0?E(t):k;t.capture&&(x=`(${x})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let $={input:r,index:-1,start:0,dot:t.dot===!0,consumed:"",output:"",prefix:"",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:o};r=_t.removePrefix(r,$),i=r.length;let L=[],F=[],z=[],P=s,I,ke=()=>$.index===i-1,ce=$.peek=(R=1)=>r[$.index+R],de=$.advance=()=>r[++$.index]||"",Et=()=>r.slice($.index+1),Ze=(R="",fe=0)=>{$.consumed+=R,$.index+=fe},Lt=R=>{$.output+=R.output!=null?R.output:R.value,Ze(R.value)},fo=()=>{let R=1;for(;ce()==="!"&&(ce(2)!=="("||ce(3)==="?");)de(),$.start++,R++;return R%2===0?!1:($.negated=!0,$.start++,!0)},cn=R=>{$[R]++,z.push(R)},U=R=>{$[R]--,z.pop()},M=R=>{if(P.type==="globstar"){let fe=$.braces>0&&(R.type==="comma"||R.type==="brace"),C=R.extglob===!0||L.length&&(R.type==="pipe"||R.type==="paren");R.type!=="slash"&&R.type!=="paren"&&!fe&&!C&&($.output=$.output.slice(0,-P.output.length),P.type="star",P.value="*",P.output=x,$.output+=P.output)}if(L.length&&R.type!=="paren"&&(L[L.length-1].inner+=R.value),(R.value||R.output)&&Lt(R),P&&P.type==="text"&&R.type==="text"){P.output=(P.output||P.value)+R.value,P.value+=R.value;return}R.prev=P,o.push(R),P=R},te=(R,fe)=>{let C={...l[fe],conditions:1,inner:""};C.prev=P,C.parens=$.parens,C.output=$.output,C.startIndex=$.index,C.tokensIndex=o.length;let X=(t.capture?"(":"")+C.open;cn("parens"),M({type:R,value:fe,output:$.output?"":p}),M({type:"paren",extglob:!0,value:de(),output:X}),L.push(C)},et=R=>{let fe=r.slice(R.startIndex,$.index+1),C=r.slice(R.startIndex+2,$.index),X=mO(C,t);if((R.type==="plus"||R.type==="star")&&X.risky){let ye=X.safeOutput?(R.output?"":p)+(t.capture?`(${X.safeOutput})`:X.safeOutput):void 0,nr=o[R.tokensIndex];nr.type="text",nr.value=fe,nr.output=ye||_t.escapeRegex(fe);for(let ir=R.tokensIndex+1;ir1&&R.inner.includes("/")&&(ye=E(t)),(ye!==x||ke()||/^\)+$/.test(Et()))&&(be=R.close=`)$))${ye}`),R.inner.includes("*")&&(Re=Et())&&/^\.[^\\/.]+$/.test(Re)){let nr=Ru(Re,{...e,fastpaths:!1}).output;be=R.close=`)${nr})${ye})`}R.prev.type==="bos"&&($.negatedExtglob=!0)}M({type:"paren",extglob:!0,value:I,output:be}),U("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let R=!1,fe=r.replace(cO,(C,X,be,Re,ye,nr)=>Re==="\\"?(R=!0,C):Re==="?"?X?X+Re+(ye?g.repeat(ye.length):""):nr===0?w+(ye?g.repeat(ye.length):""):g.repeat(be.length):Re==="."?u.repeat(be.length):Re==="*"?X?X+Re+(ye?x:""):x:X?C:`\\${C}`);return R===!0&&(t.unescape===!0?fe=fe.replace(/\\/g,""):fe=fe.replace(/\\+/g,C=>C.length%2===0?"\\\\":C?"\\":"")),fe===r&&t.contains===!0?($.output=r,$):($.output=_t.wrapOutput(fe,$,e),$)}for(;!ke();){if(I=de(),I==="\0")continue;if(I==="\\"){let C=ce();if(C==="/"&&t.bash!==!0||C==="."||C===";")continue;if(!C){I+="\\",M({type:"text",value:I});continue}let X=/^\\+/.exec(Et()),be=0;if(X&&X[0].length>2&&(be=X[0].length,$.index+=be,be%2!==0&&(I+="\\")),t.unescape===!0?I=de():I+=de(),$.brackets===0){M({type:"text",value:I});continue}}if($.brackets>0&&(I!=="]"||P.value==="["||P.value==="[^")){if(t.posix!==!1&&I===":"){let C=P.value.slice(1);if(C.includes("[")&&(P.posix=!0,C.includes(":"))){let X=P.value.lastIndexOf("["),be=P.value.slice(0,X),Re=P.value.slice(X+2),ye=oO[Re];if(ye){P.value=be+ye,$.backtrack=!0,de(),!s.output&&o.indexOf(P)===1&&(s.output=p);continue}}}(I==="["&&ce()!==":"||I==="-"&&ce()==="]")&&(I=`\\${I}`),I==="]"&&(P.value==="["||P.value==="[^")&&(I=`\\${I}`),t.posix===!0&&I==="!"&&P.value==="["&&(I="^"),P.value+=I,Lt({value:I});continue}if($.quotes===1&&I!=='"'){I=_t.escapeRegex(I),P.value+=I,Lt({value:I});continue}if(I==='"'){$.quotes=$.quotes===1?0:1,t.keepQuotes===!0&&M({type:"text",value:I});continue}if(I==="("){cn("parens"),M({type:"paren",value:I});continue}if(I===")"){if($.parens===0&&t.strictBrackets===!0)throw new SyntaxError(oi("opening","("));let C=L[L.length-1];if(C&&$.parens===C.parens+1){et(L.pop());continue}M({type:"paren",value:I,output:$.parens?")":"\\)"}),U("parens");continue}if(I==="["){if(t.nobracket===!0||!Et().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(oi("closing","]"));I=`\\${I}`}else cn("brackets");M({type:"bracket",value:I});continue}if(I==="]"){if(t.nobracket===!0||P&&P.type==="bracket"&&P.value.length===1){M({type:"text",value:I,output:`\\${I}`});continue}if($.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(oi("opening","["));M({type:"text",value:I,output:`\\${I}`});continue}U("brackets");let C=P.value.slice(1);if(P.posix!==!0&&C[0]==="^"&&!C.includes("/")&&(I=`/${I}`),P.value+=I,Lt({value:I}),t.literalBrackets===!1||_t.hasRegexChars(C))continue;let X=_t.escapeRegex(P.value);if($.output=$.output.slice(0,-P.value.length),t.literalBrackets===!0){$.output+=X,P.value=X;continue}P.value=`(${a}${X}|${P.value})`,$.output+=P.value;continue}if(I==="{"&&t.nobrace!==!0){cn("braces");let C={type:"brace",value:I,output:"(",outputIndex:$.output.length,tokensIndex:$.tokens.length};F.push(C),M(C);continue}if(I==="}"){let C=F[F.length-1];if(t.nobrace===!0||!C){M({type:"text",value:I,output:I});continue}let X=")";if(C.dots===!0){let be=o.slice(),Re=[];for(let ye=be.length-1;ye>=0&&(o.pop(),be[ye].type!=="brace");ye--)be[ye].type!=="dots"&&Re.unshift(be[ye].value);X=lO(Re,t),$.backtrack=!0}if(C.comma!==!0&&C.dots!==!0){let be=$.output.slice(0,C.outputIndex),Re=$.tokens.slice(C.tokensIndex);C.value=C.output="\\{",I=X="\\}",$.output=be;for(let ye of Re)$.output+=ye.output||ye.value}M({type:"brace",value:I,output:X}),U("braces"),F.pop();continue}if(I==="|"){L.length>0&&L[L.length-1].conditions++,M({type:"text",value:I});continue}if(I===","){let C=I,X=F[F.length-1];X&&z[z.length-1]==="braces"&&(X.comma=!0,C="|"),M({type:"comma",value:I,output:C});continue}if(I==="/"){if(P.type==="dot"&&$.index===$.start+1){$.start=$.index+1,$.consumed="",$.output="",o.pop(),P=s;continue}M({type:"slash",value:I,output:f});continue}if(I==="."){if($.braces>0&&P.type==="dot"){P.value==="."&&(P.output=u);let C=F[F.length-1];P.type="dots",P.output+=I,P.value+=I,C.dots=!0;continue}if($.braces+$.parens===0&&P.type!=="bos"&&P.type!=="slash"){M({type:"text",value:I,output:u});continue}M({type:"dot",value:I,output:u});continue}if(I==="?"){if(!(P&&P.value==="(")&&t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){te("qmark",I);continue}if(P&&P.type==="paren"){let X=ce(),be=I;(P.value==="("&&!/[!=<:]/.test(X)||X==="<"&&!/<([!=]|\w+>)/.test(Et()))&&(be=`\\${I}`),M({type:"text",value:I,output:be});continue}if(t.dot!==!0&&(P.type==="slash"||P.type==="bos")){M({type:"qmark",value:I,output:_});continue}M({type:"qmark",value:I,output:g});continue}if(I==="!"){if(t.noextglob!==!0&&ce()==="("&&(ce(2)!=="?"||!/[!=<:]/.test(ce(3)))){te("negate",I);continue}if(t.nonegate!==!0&&$.index===0){fo();continue}}if(I==="+"){if(t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){te("plus",I);continue}if(P&&P.value==="("||t.regex===!1){M({type:"plus",value:I,output:d});continue}if(P&&(P.type==="bracket"||P.type==="paren"||P.type==="brace")||$.parens>0){M({type:"plus",value:I});continue}M({type:"plus",value:d});continue}if(I==="@"){if(t.noextglob!==!0&&ce()==="("&&ce(2)!=="?"){M({type:"at",extglob:!0,value:I,output:""});continue}M({type:"text",value:I});continue}if(I!=="*"){(I==="$"||I==="^")&&(I=`\\${I}`);let C=aO.exec(Et());C&&(I+=C[0],$.index+=C[0].length),M({type:"text",value:I});continue}if(P&&(P.type==="globstar"||P.star===!0)){P.type="star",P.star=!0,P.value+=I,P.output=x,$.backtrack=!0,$.globstar=!0,Ze(I);continue}let R=Et();if(t.noextglob!==!0&&/^\([^?]/.test(R)){te("star",I);continue}if(P.type==="star"){if(t.noglobstar===!0){Ze(I);continue}let C=P.prev,X=C.prev,be=C.type==="slash"||C.type==="bos",Re=X&&(X.type==="star"||X.type==="globstar");if(t.bash===!0&&(!be||R[0]&&R[0]!=="/")){M({type:"star",value:I,output:""});continue}let ye=$.braces>0&&(C.type==="comma"||C.type==="brace"),nr=L.length&&(C.type==="pipe"||C.type==="paren");if(!be&&C.type!=="paren"&&!ye&&!nr){M({type:"star",value:I,output:""});continue}for(;R.slice(0,3)==="/**";){let ir=r[$.index+4];if(ir&&ir!=="/")break;R=R.slice(3),Ze("/**",3)}if(C.type==="bos"&&ke()){P.type="globstar",P.value+=I,P.output=E(t),$.output=P.output,$.globstar=!0,Ze(I);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&!Re&&ke()){$.output=$.output.slice(0,-(C.output+P.output).length),C.output=`(?:${C.output}`,P.type="globstar",P.output=E(t)+(t.strictSlashes?")":"|$)"),P.value+=I,$.globstar=!0,$.output+=C.output+P.output,Ze(I);continue}if(C.type==="slash"&&C.prev.type!=="bos"&&R[0]==="/"){let ir=R[1]!==void 0?"|$":"";$.output=$.output.slice(0,-(C.output+P.output).length),C.output=`(?:${C.output}`,P.type="globstar",P.output=`${E(t)}${f}|${f}${ir})`,P.value+=I,$.output+=C.output+P.output,$.globstar=!0,Ze(I+de()),M({type:"slash",value:"/",output:""});continue}if(C.type==="bos"&&R[0]==="/"){P.type="globstar",P.value+=I,P.output=`(?:^|${f}|${E(t)}${f})`,$.output=P.output,$.globstar=!0,Ze(I+de()),M({type:"slash",value:"/",output:""});continue}$.output=$.output.slice(0,-P.output.length),P.type="globstar",P.output=E(t),P.value+=I,$.output+=P.output,$.globstar=!0,Ze(I);continue}let fe={type:"star",value:I,output:x};if(t.bash===!0){fe.output=".*?",(P.type==="bos"||P.type==="slash")&&(fe.output=O+fe.output),M(fe);continue}if(P&&(P.type==="bracket"||P.type==="paren")&&t.regex===!0){fe.output=I,M(fe);continue}($.index===$.start||P.type==="slash"||P.type==="dot")&&(P.type==="dot"?($.output+=y,P.output+=y):t.dot===!0?($.output+=b,P.output+=b):($.output+=O,P.output+=O),ce()!=="*"&&($.output+=p,P.output+=p)),M(fe)}for(;$.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(oi("closing","]"));$.output=_t.escapeLast($.output,"["),U("brackets")}for(;$.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(oi("closing",")"));$.output=_t.escapeLast($.output,"("),U("parens")}for(;$.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(oi("closing","}"));$.output=_t.escapeLast($.output,"{"),U("braces")}if(t.strictSlashes!==!0&&(P.type==="star"||P.type==="bracket")&&M({type:"maybe_slash",value:"",output:`${f}?`}),$.backtrack===!0){$.output="";for(let R of $.tokens)$.output+=R.output!=null?R.output:R.value,R.suffix&&($.output+=R.suffix)}return $};Ru.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(fa,t.maxLength):fa,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=kb[r]||r;let{DOT_LITERAL:s,SLASH_LITERAL:o,ONE_CHAR:a,DOTS_SLASH:c,NO_DOT:l,NO_DOTS:u,NO_DOTS_SLASH:d,STAR:f,START_ANCHOR:p}=Ss.globChars(t.windows),m=t.dot?u:l,h=t.dot?d:l,y=t.capture?"":"?:",b={negated:!1,prefix:""},g=t.bash===!0?".*?":f;t.capture&&(g=`(${g})`);let _=O=>O.noglobstar===!0?g:`(${y}(?:(?!${p}${O.dot?c:s}).)*?)`,k=O=>{switch(O){case"*":return`${m}${a}${g}`;case".*":return`${s}${a}${g}`;case"*.*":return`${m}${g}${s}${a}${g}`;case"*/*":return`${m}${g}${o}${a}${h}${g}`;case"**":return m+_(t);case"**/*":return`(?:${m}${_(t)}${o})?${h}${a}${g}`;case"**/*.*":return`(?:${m}${_(t)}${o})?${h}${g}${s}${a}${g}`;case"**/.*":return`(?:${m}${_(t)}${o})?${s}${a}${g}`;default:{let w=/^(.*?)\.(\w+)$/.exec(O);if(!w)return;let x=k(w[1]);return x?x+s+w[2]:void 0}}},v=_t.removePrefix(r,b),E=k(v);return E&&t.strictSlashes!==!0&&(E+=`${o}?`),E};Pb.exports=Ru});var Rb=A((g2,Tb)=>{"use strict";var yO=Ab(),Cu=Ib(),Ob=vs(),gO=ws(),bO=r=>r&&typeof r=="object"&&!Array.isArray(r),Pe=(r,e,t=!1)=>{if(Array.isArray(r)){let u=r.map(f=>Pe(f,e,t));return f=>{for(let p of u){let m=p(f);if(m)return m}return!1}}let n=bO(r)&&r.tokens&&r.input;if(r===""||typeof r!="string"&&!n)throw new TypeError("Expected pattern to be a non-empty string");let i=e||{},s=i.windows,o=n?Pe.compileRe(r,e):Pe.makeRe(r,e,!1,!0),a=o.state;delete o.state;let c=()=>!1;if(i.ignore){let u={...e,ignore:null,onMatch:null,onResult:null};c=Pe(i.ignore,u,t)}let l=(u,d=!1)=>{let{isMatch:f,match:p,output:m}=Pe.test(u,o,e,{glob:r,posix:s}),h={glob:r,state:a,regex:o,posix:s,input:u,output:m,match:p,isMatch:f};return typeof i.onResult=="function"&&i.onResult(h),f===!1?(h.isMatch=!1,d?h:!1):c(u)?(typeof i.onIgnore=="function"&&i.onIgnore(h),h.isMatch=!1,d?h:!1):(typeof i.onMatch=="function"&&i.onMatch(h),d?h:!0)};return t&&(l.state=a),l};Pe.test=(r,e,t,{glob:n,posix:i}={})=>{if(typeof r!="string")throw new TypeError("Expected input to be a string");if(r==="")return{isMatch:!1,output:""};let s=t||{},o=s.format||(i?Ob.toPosixSlashes:null),a=r===n,c=a&&o?o(r):r;return a===!1&&(c=o?o(r):r,a=c===n),(a===!1||s.capture===!0)&&(s.matchBase===!0||s.basename===!0?a=Pe.matchBase(r,e,t,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};Pe.matchBase=(r,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:Pe.makeRe(e,t)).test(Ob.basename(r,{windows:n}));Pe.isMatch=(r,e,t)=>Pe(e,t)(r);Pe.parse=(r,e)=>Array.isArray(r)?r.map(t=>Pe.parse(t,e)):Cu(r,{...e,fastpaths:!1});Pe.scan=(r,e)=>yO(r,e);Pe.compileRe=(r,e,t=!1,n=!1)=>{if(t===!0)return r.output;let i=e||{},s=i.contains?"":"^",o=i.contains?"":"$",a=`${s}(?:${r.output})${o}`;r&&r.negated===!0&&(a=`^(?!${a}).*$`);let c=Pe.toRegex(a,e);return n===!0&&(c.state=r),c};Pe.makeRe=(r,e={},t=!1,n=!1)=>{if(!r||typeof r!="string")throw new TypeError("Expected a non-empty string");let i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(r[0]==="."||r[0]==="*")&&(i.output=Cu.fastpaths(r,e)),i.output||(i=Cu(r,e)),Pe.compileRe(i,e,t,n)};Pe.toRegex=(r,e)=>{try{let t=e||{};return new RegExp(r,t.flags||(t.nocase?"i":""))}catch(t){if(e&&e.debug===!0)throw t;return/$^/}};Pe.constants=gO;Tb.exports=Pe});var Mu=A((b2,Nb)=>{"use strict";var Cb=Rb(),_O=vs();function Mb(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:_O.isWindows()}),Cb(r,e,t)}Object.assign(Mb,Cb);Nb.exports=Mb});var fC={};i0(fC,{default:()=>Tc});module.exports=s0(fC);var D=require("obsidian");var N=class extends Error{constructor(t,n,i){super(n);T(this,"code");T(this,"details");this.code=t,this.details=i,this.name="InteropError"}toPortableError(t){return{code:this.code,message:this.message,...this.details===void 0?{}:{details:this.details},...t===void 0?{}:{retryable:t}}}},Li=class extends Error{constructor(t,n){super(n.message);T(this,"status");T(this,"error");this.status=t,this.error=n,this.name="ActionHandlerError"}};var uy=ln(jd(),1),fy=ln(Jd(),1);var Yd={contract:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/v0.3/data-contract.schema.json",title:"mdbase v0.3 contract frontmatter",type:"object",required:["kind","contract_type","id","version"],properties:{kind:{const:"mdbase.contract"},contract_type:{enum:["record","event","action"]},id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersion"},name:{type:"string",minLength:1},description:{type:"string"},record_schema:{$ref:"#/$defs/schemaWrapper"},binding_schema:{$ref:"#/$defs/schemaWrapper"},data_schema:{$ref:"#/$defs/schemaWrapper"},source_schema:{$ref:"#/$defs/schemaWrapper"},input_schema:{$ref:"#/$defs/schemaWrapper"},output_schema:{$ref:"#/$defs/schemaWrapper"},error_schema:{$ref:"#/$defs/schemaWrapper"},provider_schema:{$ref:"#/$defs/schemaWrapper"},behavior:{$ref:"#/$defs/actionBehavior"}},patternProperties:{"^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$":!0},oneOf:[{properties:{contract_type:{const:"record"},record_schema:!0,binding_schema:!0,data_schema:!1,source_schema:!1,input_schema:!1,output_schema:!1,error_schema:!1,provider_schema:!1,behavior:!1},required:["record_schema"]},{properties:{contract_type:{const:"event"},record_schema:!1,binding_schema:!1,data_schema:!0,source_schema:!0,input_schema:!1,output_schema:!1,error_schema:!1,provider_schema:!1,behavior:!1},required:["data_schema"]},{properties:{contract_type:{const:"action"},record_schema:!1,binding_schema:!1,data_schema:!1,source_schema:!1,input_schema:!0,output_schema:!0,error_schema:!0,provider_schema:!0,behavior:!0},required:["input_schema"]}],additionalProperties:!1,$defs:{contractId:{type:"string",minLength:3,maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$"},semanticVersion:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},schemaWrapper:{type:"object",required:["dialect"],properties:{dialect:{const:"json-schema-2020-12"},value:{type:"object"},ref:{type:"string",minLength:1}},oneOf:[{required:["value"],properties:{value:!0,ref:!1}},{required:["ref"],properties:{ref:!0,value:!1}}],additionalProperties:!1},actionBehavior:{type:"object",properties:{idempotency:{enum:["none","optional","required"]},cancellation:{enum:["none","cooperative"]}},additionalProperties:!1}}},profile:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/profile.schema.json",title:"mdbase event and action interoperability profile 0.1",oneOf:[{$ref:"#/$defs/event"},{$ref:"#/$defs/actionRequest"},{$ref:"#/$defs/actionInvocation"},{$ref:"#/$defs/actionOutcome"},{$ref:"#/$defs/actionCancellation"},{$ref:"#/$defs/eventSourceDeclaration"},{$ref:"#/$defs/actionProviderDeclaration"},{$ref:"#/$defs/conformanceClaim"}],$defs:{contractId:{type:"string",minLength:3,maxLength:128,pattern:"^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$"},semanticVersion:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},semanticVersionRequirement:{type:"string",minLength:1,maxLength:128},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"},portableId:{type:"string",minLength:1,maxLength:256,pattern:"^[A-Za-z0-9][A-Za-z0-9._:@/-]*$"},exactContract:{type:"object",required:["id","version","digest"],properties:{id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersion"},digest:{$ref:"#/$defs/digest"}},additionalProperties:!1},contractRequirement:{type:"object",required:["id","version"],properties:{id:{$ref:"#/$defs/contractId"},version:{$ref:"#/$defs/semanticVersionRequirement"},digest:{$ref:"#/$defs/digest"}},additionalProperties:!1},implementationIdentity:{type:"object",required:["application","implementation","version"],properties:{application:{$ref:"#/$defs/portableId"},implementation:{$ref:"#/$defs/portableId"},version:{$ref:"#/$defs/semanticVersion"},instance_id:{$ref:"#/$defs/portableId"}},additionalProperties:!1},transportCapabilities:{type:"object",required:["delivery","ordering","cancellation","deadlines"],properties:{delivery:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["ephemeral","at_least_once","durable_cursor","offline_queue"]}},ordering:{type:"array",uniqueItems:!0,items:{enum:["none","source","subject"]}},cancellation:{type:"boolean"},deadlines:{type:"boolean"},provider_discovery:{type:"boolean"},max_payload_bytes:{type:"integer",minimum:1},outcome_retention_seconds:{type:"integer",minimum:0},request_deduplication:{type:"boolean"},cross_process_identity:{type:"boolean"}},additionalProperties:!1},extensionValue:{oneOf:[{type:"null"},{type:"boolean"},{type:"integer"},{type:"number"},{type:"string"}]},event:{title:"mdbase CloudEvents event envelope",type:"object",required:["specversion","id","source","type","time","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion"],properties:{specversion:{const:"1.0"},id:{$ref:"#/$defs/portableId"},source:{type:"string",format:"uri-reference",minLength:1},type:{$ref:"#/$defs/contractId"},time:{type:"string",format:"date-time"},subject:{type:"string",format:"uri-reference",minLength:1},datacontenttype:{const:"application/json"},dataschema:{type:"string",format:"uri",minLength:1},data:!0,mdbaseprofile:{const:"0.1"},mdbasecontractversion:{$ref:"#/$defs/semanticVersion"},mdbasecontractdigest:{$ref:"#/$defs/digest"},mdbaseapplication:{$ref:"#/$defs/portableId"},mdbaseimplementation:{$ref:"#/$defs/portableId"},mdbaseimplementationversion:{$ref:"#/$defs/semanticVersion"},mdbaseinstanceid:{$ref:"#/$defs/portableId"},correlationid:{$ref:"#/$defs/portableId"},causationid:{$ref:"#/$defs/portableId"}},propertyNames:{pattern:"^[a-z0-9]+$"},additionalProperties:{$ref:"#/$defs/extensionValue"}},actionRequest:{title:"mdbase action request",type:"object",required:["kind","profile_version","request_id","contract","caller","created_at","input"],properties:{kind:{const:"mdbase.action.request"},profile_version:{const:"0.1"},request_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/contractRequirement"},caller:{$ref:"#/$defs/implementationIdentity"},created_at:{type:"string",format:"date-time"},correlation_id:{$ref:"#/$defs/portableId"},causation_id:{$ref:"#/$defs/portableId"},subject:{type:"string",format:"uri-reference",minLength:1},idempotency_key:{type:"string",minLength:1,maxLength:512},deadline:{type:"string",format:"date-time"},requested_provider:{type:"object",properties:{application:{$ref:"#/$defs/portableId"},implementation:{$ref:"#/$defs/portableId"},instance_id:{$ref:"#/$defs/portableId"}},minProperties:1,additionalProperties:!1},authorization_context:{type:"string",format:"uri-reference",minLength:1},input:!0},additionalProperties:!1},actionInvocation:{title:"mdbase admitted action invocation",type:"object",required:["kind","profile_version","invocation_id","attempt_id","request_id","contract","caller","provider","provider_declaration_digest","handler_id","admitted_at","input"],properties:{kind:{const:"mdbase.action.invocation"},profile_version:{const:"0.1"},invocation_id:{$ref:"#/$defs/portableId"},attempt_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/exactContract"},caller:{$ref:"#/$defs/implementationIdentity"},provider:{$ref:"#/$defs/implementationIdentity"},provider_declaration_digest:{$ref:"#/$defs/digest"},handler_id:{$ref:"#/$defs/portableId"},admitted_at:{type:"string",format:"date-time"},correlation_id:{$ref:"#/$defs/portableId"},causation_id:{$ref:"#/$defs/portableId"},subject:{type:"string",format:"uri-reference",minLength:1},idempotency_key:{type:"string",minLength:1,maxLength:512},deadline:{type:"string",format:"date-time"},authorization_context:{type:"string",format:"uri-reference",minLength:1},input:!0},additionalProperties:!1},portableError:{type:"object",required:["code","message"],properties:{code:{enum:["unknown_contract","unsupported_contract_version","contract_digest_conflict","invalid_event_data","invalid_action_input","invalid_action_output","no_provider","ambiguous_provider","requested_provider_unavailable","unauthorized","capability_denied","request_rejected","deadline_exceeded","cancellation_unsupported","cancelled","handler_failure","outcome_indeterminate","transport_unavailable","unsupported_transport_capability"]},message:{type:"string",minLength:1},details:!0,retryable:{type:"boolean"}},additionalProperties:!1},actionOutcome:{title:"mdbase action outcome",type:"object",required:["kind","profile_version","outcome_id","request_id","invocation_id","attempt_id","contract","provider","provider_declaration_digest","status","completed_at"],properties:{kind:{const:"mdbase.action.outcome"},profile_version:{const:"0.1"},outcome_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},invocation_id:{$ref:"#/$defs/portableId"},attempt_id:{$ref:"#/$defs/portableId"},contract:{$ref:"#/$defs/exactContract"},provider:{$ref:"#/$defs/implementationIdentity"},provider_declaration_digest:{$ref:"#/$defs/digest"},status:{enum:["succeeded","rejected","failed","cancelled","outcome_indeterminate"]},completed_at:{type:"string",format:"date-time"},output:!0,error:{$ref:"#/$defs/portableError"}},allOf:[{if:{properties:{status:{const:"succeeded"}},required:["status"]},then:{required:["output"],not:{required:["error"]}},else:{required:["error"],not:{required:["output"]}}}],additionalProperties:!1},actionCancellation:{title:"mdbase action cancellation request",type:"object",required:["kind","profile_version","cancellation_id","request_id","caller","requested_at"],properties:{kind:{const:"mdbase.action.cancel"},profile_version:{const:"0.1"},cancellation_id:{$ref:"#/$defs/portableId"},request_id:{$ref:"#/$defs/portableId"},caller:{$ref:"#/$defs/implementationIdentity"},requested_at:{type:"string",format:"date-time"},reason:{type:"string",maxLength:1024}},additionalProperties:!1},eventSourceDeclaration:{title:"mdbase event-source declaration",type:"object",required:["kind","profile_version","declaration_id","declaration_digest","source","contracts"],properties:{kind:{const:"mdbase.event-source"},profile_version:{const:"0.1"},declaration_id:{$ref:"#/$defs/portableId"},declaration_digest:{$ref:"#/$defs/digest"},source:{$ref:"#/$defs/implementationIdentity"},contracts:{type:"array",minItems:1,items:{type:"object",required:["requirement","resolved"],properties:{requirement:{$ref:"#/$defs/contractRequirement"},resolved:{$ref:"#/$defs/exactContract"},binding:!0,ordering:{type:"array",uniqueItems:!0,items:{enum:["none","source","subject"]}}},additionalProperties:!1}}},additionalProperties:!1},actionProviderDeclaration:{title:"mdbase action-provider declaration",type:"object",required:["kind","profile_version","declaration_id","declaration_digest","provider","handlers"],properties:{kind:{const:"mdbase.action-provider"},profile_version:{const:"0.1"},declaration_id:{$ref:"#/$defs/portableId"},declaration_digest:{$ref:"#/$defs/digest"},provider:{$ref:"#/$defs/implementationIdentity"},handlers:{type:"array",minItems:1,items:{type:"object",required:["handler_id","requirement","resolved"],properties:{handler_id:{$ref:"#/$defs/portableId"},requirement:{$ref:"#/$defs/contractRequirement"},resolved:{$ref:"#/$defs/exactContract"},binding:!0,idempotency:{type:"object",required:["mode"],properties:{mode:{enum:["none","request"]},retention_seconds:{type:"integer",minimum:1}},additionalProperties:!1},cancellation:{enum:["none","cooperative"]},max_concurrency:{type:"integer",minimum:1}},additionalProperties:!1}}},additionalProperties:!1},conformanceClaim:{title:"mdbase interoperability conformance claim",type:"object",required:["kind","profile_version","implementation","roles","transport"],properties:{kind:{const:"mdbase.interop.conformance"},profile_version:{const:"0.1"},implementation:{$ref:"#/$defs/implementationIdentity"},roles:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["event_source","event_consumer","action_caller","action_provider","bridge"]}},transport:{$ref:"#/$defs/transportCapabilities"},evidence:{type:"array",items:{type:"object",required:["scenario","result"],properties:{scenario:{type:"string",minLength:1},result:{const:"pass"},uri:{type:"string",format:"uri-reference"}},additionalProperties:!1}}},additionalProperties:!1}}},event:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/event.schema.json",title:"mdbase CloudEvents event envelope",$ref:"profile.schema.json#/$defs/event"},actionRequest:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-request.schema.json",title:"mdbase action request",$ref:"profile.schema.json#/$defs/actionRequest"},actionInvocation:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-invocation.schema.json",title:"mdbase admitted action invocation",$ref:"profile.schema.json#/$defs/actionInvocation"},actionOutcome:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-outcome.schema.json",title:"mdbase action outcome",$ref:"profile.schema.json#/$defs/actionOutcome"},actionCancellation:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-cancellation.schema.json",title:"mdbase action cancellation request",$ref:"profile.schema.json#/$defs/actionCancellation"},eventSourceDeclaration:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/event-source-declaration.schema.json",title:"mdbase event-source declaration",$ref:"profile.schema.json#/$defs/eventSourceDeclaration"},actionProviderDeclaration:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/action-provider-declaration.schema.json",title:"mdbase action-provider declaration",$ref:"profile.schema.json#/$defs/actionProviderDeclaration"},conformanceClaim:{$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/schemas/interop/v0.1/conformance-claim.schema.json",title:"mdbase interoperability conformance claim",$ref:"profile.schema.json#/$defs/conformanceClaim"}};var $k=fy.default;function py(){return Object.fromEntries(Object.entries(Yd).map(([r,e])=>[r,structuredClone(e)]))}function Xd(){let r=new uy.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});$k(r);let e=py();r.addSchema(e.profile);for(let[t,n]of Object.entries(e))t!=="profile"&&r.addSchema(n);return r}function $r(r,e){let t=String(Yd[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function Wr(r){return(r!=null?r:[]).map(e=>{var t;return`${e.instancePath||"/"} ${(t=e.message)!=null?t:e.keyword}`}).join("; ")}function dr(r,e){if(!("value"in r))throw new N("contract_digest_conflict",`${e} must be resolved to an inline JSON Schema before runtime registration.`);return structuredClone(r.value)}function hy(r){let e={kind:r.kind,contract_type:r.contract_type,id:r.id,version:r.version};switch(r.contract_type){case"record":e.record_schema=dr(r.record_schema,"record_schema"),r.binding_schema&&(e.binding_schema=dr(r.binding_schema,"binding_schema"));break;case"event":e.data_schema=dr(r.data_schema,"data_schema"),r.source_schema&&(e.source_schema=dr(r.source_schema,"source_schema"));break;case"action":e.input_schema=dr(r.input_schema,"input_schema"),r.output_schema&&(e.output_schema=dr(r.output_schema,"output_schema")),r.error_schema&&(e.error_schema=dr(r.error_schema,"error_schema")),r.provider_schema&&(e.provider_schema=dr(r.provider_schema,"provider_schema")),r.behavior&&(e.behavior=structuredClone(r.behavior));break}return e}async function Jo(r){return ni(hy(r))}async function ni(r){return`sha256:${await Sk(Qd(r))}`}function my(r,e){return{data:ri(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:ri(r,e.source_schema,`${e.id} source_schema`)}:{}}}function yy(r,e){return{input:ri(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:ri(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:ri(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:ri(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function Yo(r,e,t,n){if(!(!r||r(e)))throw new N(t,`${n} failed JSON Schema validation: ${Wr(r.errors)}`)}function ri(r,e,t){try{return r.compile(dr(e,t))}catch(n){throw new N("contract_digest_conflict",`${t} could not be compiled: ${n instanceof Error?n.message:String(n)}`)}}function Qd(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(Qd).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${Qd(n)}`).join(",")}}`}async function Sk(r){let e=new TextEncoder().encode(r),t=await globalThis.crypto.subtle.digest("SHA-256",e);return[...new Uint8Array(t)].map(n=>n.toString(16).padStart(2,"0")).join("")}var Er=ln(ab(),1);var _u={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},TI=new Set(["specversion","id","source","type","time","subject","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion","mdbaseinstanceid","correlationid","causationid"]),_s=class{constructor(e={}){T(this,"options");T(this,"profileVersion","0.1");T(this,"transport");T(this,"ajv",Xd());T(this,"contractValidator",$r(this.ajv,"contract"));T(this,"eventValidator",$r(this.ajv,"event"));T(this,"actionRequestValidator",$r(this.ajv,"actionRequest"));T(this,"actionInvocationValidator",$r(this.ajv,"actionInvocation"));T(this,"actionOutcomeValidator",$r(this.ajv,"actionOutcome"));T(this,"eventSourceDeclarationValidator",$r(this.ajv,"eventSourceDeclaration"));T(this,"actionProviderDeclarationValidator",$r(this.ajv,"actionProviderDeclaration"));T(this,"contracts",new Map);T(this,"clients",new Map);T(this,"eventSources",new Map);T(this,"actionProviders",new Map);T(this,"subscriptions",new Map);T(this,"activeActions",new Map);T(this,"completedActions",new Map);T(this,"admissionLocks",new Map);T(this,"recentEvents",new Map);T(this,"authorize");T(this,"now");T(this,"idFactory");T(this,"recentEventLimit");T(this,"completedRequestLimit");T(this,"nextSequence",0);T(this,"disposed",!1);var t,n,i,s,o,a,c,l,u,d;this.options=e,this.authorize=(t=e.authorize)!=null?t:(()=>!1),this.now=(n=e.now)!=null?n:(()=>new Date),this.idFactory=(i=e.idFactory)!=null?i:(f=>{var m;this.nextSequence+=1;let p=typeof((m=globalThis.crypto)==null?void 0:m.randomUUID)=="function"?globalThis.crypto.randomUUID():`${this.now().getTime().toString(36)}-${this.nextSequence.toString(36)}`;return`${f}_${p}`}),this.recentEventLimit=Math.max(1,(s=e.recentEventLimit)!=null?s:1e3),this.completedRequestLimit=Math.max(1,(o=e.completedRequestLimit)!=null?o:1e3),this.transport={..._u,...structuredClone((a=e.transport)!=null?a:{}),delivery:[...(l=(c=e.transport)==null?void 0:c.delivery)!=null?l:_u.delivery],ordering:[...(d=(u=e.transport)==null?void 0:u.ordering)!=null?d:_u.ordering]}}connect(e){this.assertActive(),RI(e);let t=this.idFactory("client"),n={identity:structuredClone(e),disposed:!1,sources:new Set,providers:new Set,subscriptions:new Set};return this.clients.set(t,n),{identity:structuredClone(e),registerEventSource:i=>this.registerEventSource(t,i),publishEvent:i=>this.publishEvent(t,i),subscribeEvents:(i,s)=>this.subscribeEvents(t,i,s),registerActionProvider:i=>this.registerActionProvider(t,i),invokeAction:i=>this.invokeAction(t,i),cancelAction:(i,s)=>this.cancelAction(t,i,s),dispose:()=>this.disposeClient(t)}}describe(){return this.assertActive(),{profile_version:"0.1",transport:structuredClone(this.transport),contracts:[...this.contracts.values()].map(({artifact:e,reference:t})=>({artifact:structuredClone(e),reference:structuredClone(t)})).sort((e,t)=>e.reference.id.localeCompare(t.reference.id)||e.reference.version.localeCompare(t.reference.version)),event_sources:[...this.eventSources.values()].map(({declaration:e})=>structuredClone(e)).sort((e,t)=>e.declaration_id.localeCompare(t.declaration_id)),action_providers:[...this.actionProviders.values()].map(({declaration:e})=>structuredClone(e)).sort((e,t)=>e.declaration_id.localeCompare(t.declaration_id))}}async dispose(){if(!this.disposed){this.disposed=!0;for(let e of[...this.clients.keys()])await this.disposeClient(e,!0);this.contracts.clear(),this.recentEvents.clear(),this.completedActions.clear()}}async registerEventSource(e,t){var l;let n=this.requireClient(e);if(t.contracts.length===0)throw new N("request_rejected","An event-source declaration must include a contract.");let i=`${e}:${t.declaration_id}`;if(this.eventSources.has(i))throw new N("request_rejected",`Event-source declaration ${t.declaration_id} is already registered.`);let s=new Map;for(let u of t.contracts){let d=await this.prepareEventContract(u.contract),f=cb(u.requirement,d.reference);if(lb(f,d.reference),await this.assertAuthorized({operation:"register_event_source",principal:n.identity,contract:d.reference}),d.sourceValidator&&!d.sourceValidator((l=u.binding)!=null?l:{}))throw new N("request_rejected",`${d.reference.id} source binding is invalid: ${Wr(d.sourceValidator.errors)}`);let p=la(d.reference);if(s.has(p))throw new N("contract_digest_conflict",`Event contract ${p} is repeated by one declaration.`);s.set(p,{contract:d,requirement:f,...u.binding===void 0?{}:{binding:structuredClone(u.binding)},...u.ordering===void 0?{}:{ordering:[...u.ordering]}})}let o={kind:"mdbase.event-source",profile_version:"0.1",declaration_id:t.declaration_id,source:structuredClone(n.identity),contracts:[...s.values()].map(({contract:u,requirement:d,binding:f,ordering:p})=>({requirement:structuredClone(d),resolved:structuredClone(u.reference),...f===void 0?{}:{binding:f},...p===void 0?{}:{ordering:p}}))},a={...o,declaration_digest:await ni(o)};Jr(this.eventSourceDeclarationValidator,a,"request_rejected","Event-source declaration"),this.commitContracts([...s.values()].map(({contract:u})=>u)),this.eventSources.set(i,{id:i,clientId:e,declaration:structuredClone(a),contracts:new Map([...s.entries()].map(([u,d])=>[u,{contract:d.contract,...d.binding===void 0?{}:{binding:d.binding}}]))}),n.sources.add(i);let c=!0;return{declaration:structuredClone(a),dispose:()=>{c&&(c=!1,this.removeEventSource(i))}}}async publishEvent(e,t){var m,h,y,b;let n=this.requireClient(e),i=la(t.contract),s=[...n.sources].map(g=>this.eventSources.get(g)).find(g=>g==null?void 0:g.contracts.has(i));if(!s)throw new N("unknown_contract",`This client has not registered event contract ${t.contract.id} ${t.contract.version}.`);let o=(m=s.contracts.get(i))==null?void 0:m.contract;if(!o)throw new N("unknown_contract",`Event contract ${i} is unavailable.`);if(t.contract.digest&&t.contract.digest!==o.reference.digest)throw new N("contract_digest_conflict",`Event contract ${i} has a different digest.`);await this.assertAuthorized({operation:"publish_event",principal:n.identity,contract:o.reference,...t.subject===void 0?{}:{subject:t.subject}}),wu(t.data,"invalid_event_data",`Event ${o.reference.id} data`),Yo(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=(h=t.extensions)!=null?h:{};for(let g of Object.keys(a))if(TI.has(g))throw new N("request_rejected",`Event extension ${g} is reserved.`);let c={...structuredClone(a),specversion:"1.0",id:(y=t.id)!=null?y:this.idFactory("evt"),source:CI(n.identity),type:o.reference.id,time:(b=t.time)!=null?b:this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:fb(o.reference),data:structuredClone(t.data),mdbaseprofile:"0.1",mdbasecontractversion:o.reference.version,mdbasecontractdigest:o.reference.digest,mdbaseapplication:n.identity.application,mdbaseimplementation:n.identity.implementation,mdbaseimplementationversion:n.identity.version,...n.identity.instance_id===void 0?{}:{mdbaseinstanceid:n.identity.instance_id},...t.correlation_id===void 0?{}:{correlationid:t.correlation_id},...t.causation_id===void 0?{}:{causationid:t.causation_id}};Jr(this.eventValidator,c,"invalid_event_data","Event envelope"),vu(this.transport,c),MI(c,o.reference);let l=`${c.source}\0${c.id}`,u=this.recentEvents.get(l);if(u){if(JSON.stringify(u)!==JSON.stringify(c))throw new N("contract_digest_conflict",`Event ${c.source} ${c.id} was reused with different content.`);return{event:structuredClone(u),deliveries:0,duplicate:!0}}this.recentEvents.set(l,structuredClone(c)),ub(this.recentEvents,this.recentEventLimit);let d=[...this.subscriptions.values()].filter(({subscription:g})=>da(g.contract,o.reference)),f=await Promise.allSettled(d.map(async g=>await this.isAuthorized({operation:"subscribe_event",principal:g.principal,contract:o.reference,...c.subject===void 0?{}:{subject:c.subject}})?(await g.handler(structuredClone(c)),!0):!1)),p=0;for(let g of f)g.status==="fulfilled"&&g.value?p+=1:g.status==="rejected"&&this.report({severity:"error",code:"event_consumer_failed",message:`An event consumer failed while handling ${c.type}.`,contract:o.reference,cause:g.reason});return{event:structuredClone(c),deliveries:p,duplicate:!1}}async subscribeEvents(e,t,n){let i=this.requireClient(e);$u(t.contract),DI(this.transport,t.require_transport),await this.assertAuthorized({operation:"subscribe_event",principal:i.identity,contract:t.contract});let s=this.idFactory("subscription");this.subscriptions.set(s,{id:s,clientId:e,principal:structuredClone(i.identity),subscription:structuredClone(t),handler:n}),i.subscriptions.add(s);let o=!0;return{dispose:()=>{o&&(o=!1,this.removeSubscription(s))}}}async registerActionProvider(e,t){var d,f,p,m,h,y,b;let n=this.requireClient(e);if(t.handlers.length===0)throw new N("request_rejected","An action-provider declaration must include a handler.");let i=`${e}:${t.declaration_id}`;if(this.actionProviders.has(i))throw new N("request_rejected",`Action-provider declaration ${t.declaration_id} is already registered.`);let s=[],o=new Set;for(let g of t.handlers){if(o.has(g.handler_id))throw new N("request_rejected",`Handler ${g.handler_id} is repeated.`);o.add(g.handler_id);let _=await this.prepareActionContract(g.contract),k=cb(g.requirement,_.reference);if(lb(k,_.reference),await this.assertAuthorized({operation:"register_action_provider",principal:n.identity,contract:_.reference,provider:n.identity}),_.providerValidator&&!_.providerValidator((d=g.binding)!=null?d:{}))throw new N("request_rejected",`${_.reference.id} provider binding is invalid: ${Wr(_.providerValidator.errors)}`);let v=(p=(f=g.contract.behavior)==null?void 0:f.idempotency)!=null?p:"none";if(((m=g.idempotency)==null?void 0:m.mode)==="request"&&v==="none")throw new N("request_rejected",`${_.reference.id} does not permit request deduplication.`);if(v==="required"&&((h=g.idempotency)==null?void 0:h.mode)!=="request")throw new N("request_rejected",`${_.reference.id} requires a provider with request deduplication.`);let E=(b=(y=g.contract.behavior)==null?void 0:y.cancellation)!=null?b:"none";if(g.cancellation==="cooperative"&&E!=="cooperative")throw new N("request_rejected",`${_.reference.id} does not declare cooperative cancellation.`);s.push({contract:_,declaration:{handler_id:g.handler_id,requirement:k,resolved:structuredClone(_.reference),...g.binding===void 0?{}:{binding:structuredClone(g.binding)},...g.idempotency===void 0?{}:{idempotency:structuredClone(g.idempotency)},...g.cancellation===void 0?{}:{cancellation:g.cancellation},...g.max_concurrency===void 0?{}:{max_concurrency:g.max_concurrency}},handler:g.handler})}let a={kind:"mdbase.action-provider",profile_version:"0.1",declaration_id:t.declaration_id,provider:structuredClone(n.identity),handlers:s.map(({declaration:g})=>structuredClone(g))},c={...a,declaration_digest:await ni(a)};Jr(this.actionProviderDeclarationValidator,c,"request_rejected","Action-provider declaration"),this.commitContracts(s.map(({contract:g})=>g));let l=s.map(({contract:g,declaration:_,handler:k})=>({registrationId:i,clientId:e,declaration:structuredClone(c),handlerDeclaration:structuredClone(_),contract:g,handler:k,active:0}));this.actionProviders.set(i,{id:i,clientId:e,declaration:structuredClone(c),handlers:l}),n.providers.add(i);let u=!0;return{declaration:structuredClone(c),dispose:()=>{u&&(u=!1,this.removeActionProvider(i))}}}async invokeAction(e,t){var a,c,l,u,d,f,p,m,h,y,b,g;let n=this.requireClient(e);$u(t.contract);let i=(a=t.request_id)!=null?a:this.idFactory("req");this.cleanCompletedActions(),wu(t.input,"invalid_action_input",`Action ${t.contract.id} input`);let s={kind:"mdbase.action.request",profile_version:"0.1",request_id:i,contract:structuredClone(t.contract),caller:structuredClone(n.identity),created_at:(c=t.created_at)!=null?c:this.now().toISOString(),...t.correlation_id===void 0?{}:{correlation_id:t.correlation_id},...t.causation_id===void 0?{}:{causation_id:t.causation_id},...t.subject===void 0?{}:{subject:t.subject},...t.idempotency_key===void 0?{}:{idempotency_key:t.idempotency_key},...t.deadline===void 0?{}:{deadline:t.deadline},...t.requested_provider===void 0?{}:{requested_provider:structuredClone(t.requested_provider)},input:structuredClone(t.input)};Jr(this.actionRequestValidator,s,"request_rejected","Action request"),vu(this.transport,s);let o=await this.acquireAdmission(i);try{let _=await ni(NI(s)),k=this.activeActions.get(i);if(k){if(db(e,i,_,k),((l=k.handler.handlerDeclaration.idempotency)==null?void 0:l.mode)!=="request")throw new N("request_rejected",`Action request ${i} is already active without deduplication.`);return structuredClone(await k.promise)}let v=this.completedActions.get(i);if(v){if(db(e,i,_,v),!v.reusable)throw new N("request_rejected",`Action request ${i} was already completed without deduplication.`);return structuredClone(v.outcome)}if(s.deadline&&new Date(s.deadline).getTime()<=this.now().getTime())throw new N("deadline_exceeded",`Action request ${i} passed its deadline before admission.`);if(s.deadline&&!this.transport.deadlines)throw new N("unsupported_transport_capability","The active transport cannot enforce action deadlines.");let E=this.resolveActionCandidates(s.contract,s.requested_provider);E.length===0&&this.throwResolutionFailure(s.contract,s.requested_provider);let O=[];for(let de of E)await this.isAuthorized({operation:"invoke_action",principal:n.identity,contract:de.contract.reference,provider:de.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}})&&O.push(de);if(O.length===0)throw new N("unauthorized",`No authorized provider can execute ${s.contract.id}.`);if(O.length>1)throw new N("ambiguous_provider",`Action ${s.contract.id} has ${O.length} eligible providers; select one explicitly.`);let w=O[0];if(w.handlerDeclaration.max_concurrency!==void 0&&w.active>=w.handlerDeclaration.max_concurrency)throw new N("request_rejected",`Provider ${w.declaration.provider.implementation} is at capacity.`);if(((d=(u=w.contract.artifact.behavior)==null?void 0:u.idempotency)!=null?d:"none")==="required"&&!s.idempotency_key)throw new N("request_rejected",`${w.contract.reference.id} requires an idempotency key.`);Yo(w.contract.inputValidator,s.input,"invalid_action_input",`Action ${w.contract.reference.id} input`);let $={operation:"invoke_action",principal:n.identity,contract:w.contract.reference,provider:w.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}},L=await((p=(f=this.options).authorizationContext)==null?void 0:p.call(f,$)),F={kind:"mdbase.action.invocation",profile_version:"0.1",invocation_id:this.idFactory("inv"),attempt_id:this.idFactory("attempt"),request_id:i,contract:structuredClone(w.contract.reference),caller:structuredClone(n.identity),provider:structuredClone(w.declaration.provider),provider_declaration_digest:w.declaration.declaration_digest,handler_id:w.handlerDeclaration.handler_id,admitted_at:this.now().toISOString(),...s.correlation_id===void 0?{}:{correlation_id:s.correlation_id},...s.causation_id===void 0?{}:{causation_id:s.causation_id},...s.subject===void 0?{}:{subject:s.subject},...s.idempotency_key===void 0?{}:{idempotency_key:s.idempotency_key},...s.deadline===void 0?{}:{deadline:s.deadline},...L===void 0?{}:{authorization_context:L},input:structuredClone(s.input)};Jr(this.actionInvocationValidator,F,"request_rejected","Action invocation"),await((h=(m=this.options).onInvocation)==null?void 0:h.call(m,structuredClone(F)));let z=new AbortController,P;if(F.deadline){let de=Math.max(0,new Date(F.deadline).getTime()-this.now().getTime());P=setTimeout(()=>z.abort(new N("deadline_exceeded",`Action request ${i} exceeded its deadline.`)),de)}w.active+=1;let I=this.executeAction(w,F,z).finally(()=>{P!==void 0&&clearTimeout(P),w.active=Math.max(0,w.active-1),this.activeActions.delete(i)});this.activeActions.set(i,{clientId:e,requestId:i,requestDigest:_,handler:w,invocation:F,controller:z,promise:I}),o();let ke=await I,ce=(b=(y=w.handlerDeclaration.idempotency)==null?void 0:y.retention_seconds)!=null?b:300;return this.completedActions.set(i,{clientId:e,requestDigest:_,outcome:structuredClone(ke),reusable:((g=w.handlerDeclaration.idempotency)==null?void 0:g.mode)==="request",expiresAt:this.now().getTime()+ce*1e3}),ub(this.completedActions,this.completedRequestLimit),structuredClone(ke)}finally{o()}}async executeAction(e,t,n){var i;try{let s=await e.handler(structuredClone(t.input),{invocation:structuredClone(t),signal:n.signal});if(n.signal.aborted){let a=n.signal.reason;return a instanceof N&&a.code==="deadline_exceeded"?this.failureOutcome(t,"failed",a.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}wu(s,"invalid_action_output",`Action ${e.contract.reference.id} output`),Yo(e.contract.outputValidator,s,"invalid_action_output",`Action ${e.contract.reference.id} output`);let o={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:t.request_id,invocation_id:t.invocation_id,attempt_id:t.attempt_id,contract:structuredClone(t.contract),provider:structuredClone(t.provider),provider_declaration_digest:t.provider_declaration_digest,status:"succeeded",completed_at:this.now().toISOString(),output:structuredClone(s)};return Jr(this.actionOutcomeValidator,o,"invalid_action_output","Action outcome"),vu(this.transport,o),o}catch(s){if(s instanceof Li)return e.contract.errorValidator&&!e.contract.errorValidator((i=s.error.details)!=null?i:{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${Wr(e.contract.errorValidator.errors)}`}):this.failureOutcome(t,s.status,s.error);if(s instanceof N)return this.failureOutcome(t,s.code==="cancelled"?"cancelled":s.code==="outcome_indeterminate"?"outcome_indeterminate":"failed",s.toPortableError());if(n.signal.aborted||qI(s)){let o=n.signal.reason;return o instanceof N&&o.code==="deadline_exceeded"?this.failureOutcome(t,"failed",o.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}return this.report({severity:"error",code:"action_handler_failed",message:`Provider ${t.provider.implementation} failed ${t.contract.id}.`,principal:t.provider,contract:t.contract,cause:s}),this.failureOutcome(t,"failed",{code:"handler_failure",message:"The selected provider failed while executing the action."})}}failureOutcome(e,t,n){let i={kind:"mdbase.action.outcome",profile_version:"0.1",outcome_id:this.idFactory("outcome"),request_id:e.request_id,invocation_id:e.invocation_id,attempt_id:e.attempt_id,contract:structuredClone(e.contract),provider:structuredClone(e.provider),provider_declaration_digest:e.provider_declaration_digest,status:t,completed_at:this.now().toISOString(),error:structuredClone(n)};return Jr(this.actionOutcomeValidator,i,"invalid_action_output","Action outcome"),i}async cancelAction(e,t,n){let i=this.requireClient(e),s=this.admissionLocks.get(t);s&&await s;let o=this.activeActions.get(t);if(!o){let a=this.completedActions.get(t);if(a&&a.clientId!==e)throw new N("unauthorized",`Action request ${t} belongs to another caller.`);return a?structuredClone(a.outcome):null}if(o.clientId!==e)throw new N("unauthorized",`Action request ${t} belongs to another caller.`);if(await this.assertAuthorized({operation:"cancel_action",principal:i.identity,contract:o.invocation.contract,provider:o.invocation.provider,...o.invocation.subject===void 0?{}:{subject:o.invocation.subject}}),!this.transport.cancellation)throw new N("unsupported_transport_capability","The active transport cannot deliver cancellation.");if(o.handler.handlerDeclaration.cancellation!=="cooperative")throw new N("cancellation_unsupported",`Provider ${o.invocation.provider.implementation} does not support cancellation.`);return o.controller.abort(new N("cancelled",(n==null?void 0:n.trim())||`Action request ${t} was cancelled.`)),structuredClone(await o.promise)}resolveActionCandidates(e,t){let n=[...this.actionProviders.values()].flatMap(({handlers:s})=>s).filter(({contract:s,declaration:o})=>da(e,s.reference)&&LI(t,o.provider)),i=(0,Er.maxSatisfying)([...new Set(n.map(({contract:s})=>s.reference.version))],e.version,{includePrerelease:!0});return i?n.filter(({contract:s})=>s.reference.version===i).sort((s,o)=>{var a,c;return s.declaration.provider.application.localeCompare(o.declaration.provider.application)||s.declaration.provider.implementation.localeCompare(o.declaration.provider.implementation)||((a=s.declaration.provider.instance_id)!=null?a:"").localeCompare((c=o.declaration.provider.instance_id)!=null?c:"")||s.handlerDeclaration.handler_id.localeCompare(o.handlerDeclaration.handler_id)}):[]}throwResolutionFailure(e,t){let n=[...this.contracts.values()].filter(i=>i.artifact.contract_type==="action"&&i.reference.id===e.id);throw n.length===0?new N("unknown_contract",`Action contract ${e.id} is unknown.`):n.some(({reference:i})=>da(e,i))?t?new N("requested_provider_unavailable",`The requested provider is unavailable for ${e.id}.`):new N("no_provider",`No provider is registered for ${e.id}.`):new N("unsupported_contract_version",`No ${e.id} artifact satisfies ${e.version}.`)}async prepareEventContract(e){if(this.assertContractArtifact(e),e.contract_type!=="event")throw new N("unknown_contract",`${e.id} is not an event contract.`);let t={id:e.id,version:e.version,digest:await Jo(e)};this.assertNoContractConflict(t);let n=my(this.ajv,e);return{artifact:structuredClone(e),reference:t,dataValidator:n.data,...n.source===void 0?{}:{sourceValidator:n.source}}}async prepareActionContract(e){if(this.assertContractArtifact(e),e.contract_type!=="action")throw new N("unknown_contract",`${e.id} is not an action contract.`);let t={id:e.id,version:e.version,digest:await Jo(e)};this.assertNoContractConflict(t);let n=yy(this.ajv,e);return{artifact:structuredClone(e),reference:t,inputValidator:n.input,...n.output===void 0?{}:{outputValidator:n.output},...n.error===void 0?{}:{errorValidator:n.error},...n.provider===void 0?{}:{providerValidator:n.provider}}}assertContractArtifact(e){if(Jr(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,Er.valid)(e.version))throw new N("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(la(e));if(t&&t.reference.digest!==e.digest)throw new N("contract_digest_conflict",`Contract ${e.id} ${e.version} conflicts with the registered artifact.`)}commitContracts(e){var n;let t=new Map;for(let i of e){let s=la(i.reference),o=(n=t.get(s))!=null?n:this.contracts.get(s);if(o&&o.reference.digest!==i.reference.digest)throw new N("contract_digest_conflict",`Contract ${i.reference.id} ${i.reference.version} conflicts within the registration.`);t.set(s,i)}for(let[i,s]of t)this.contracts.has(i)||this.contracts.set(i,s)}async disposeClient(e,t=!1){let n=this.clients.get(e);if(!(!n||n.disposed)){n.disposed=!0;for(let i of[...n.subscriptions])this.removeSubscription(i);for(let i of[...n.sources])this.removeEventSource(i);for(let i of[...n.providers])this.removeActionProvider(i);for(let i of[...this.activeActions.values()])i.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new N("cancelled","The caller unloaded.")),i.handler.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new N("cancelled","The provider unloaded."));this.clients.delete(e),t||this.assertActive()}}removeEventSource(e){var n;let t=this.eventSources.get(e);t&&(this.eventSources.delete(e),(n=this.clients.get(t.clientId))==null||n.sources.delete(e))}removeActionProvider(e){var n;let t=this.actionProviders.get(e);if(t){this.actionProviders.delete(e),(n=this.clients.get(t.clientId))==null||n.providers.delete(e);for(let i of this.activeActions.values())i.handler.registrationId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new N("cancelled","The provider unloaded."))}}removeSubscription(e){var n;let t=this.subscriptions.get(e);t&&(this.subscriptions.delete(e),(n=this.clients.get(t.clientId))==null||n.subscriptions.delete(e))}requireClient(e){this.assertActive();let t=this.clients.get(e);if(!t||t.disposed)throw new N("transport_unavailable","Interop client is disposed.");return t}assertActive(){if(this.disposed)throw new N("transport_unavailable","Interop bridge is disposed.")}async assertAuthorized(e){if(!await this.isAuthorized(e))throw new N("unauthorized",`${e.operation} is not authorized.`)}async isAuthorized(e){try{return await this.authorize(structuredClone(e))}catch(t){return this.report({severity:"error",code:"authorization_failed",message:`Authorization failed for ${e.operation}.`,principal:e.principal,cause:t}),!1}}cleanCompletedActions(){let e=this.now().getTime();for(let[t,n]of this.completedActions)n.expiresAt<=e&&this.completedActions.delete(t)}async acquireAdmission(e){var a;let t=(a=this.admissionLocks.get(e))!=null?a:Promise.resolve(),n,i=new Promise(c=>{n=c}),s=t.then(()=>i);this.admissionLocks.set(e,s),await t;let o=!1;return()=>{o||(o=!0,n(),this.admissionLocks.get(e)===s&&this.admissionLocks.delete(e))}}report(e){var t,n;(n=(t=this.options).onDiagnostic)==null||n.call(t,structuredClone(e))}};function Jr(r,e,t,n){if(!r(e))throw new N(t,`${n} is invalid: ${Wr(r.errors)}`)}function RI(r){for(let[e,t]of Object.entries(r))if(t!==void 0&&(typeof t!="string"||t.length===0||!/^[A-Za-z0-9][A-Za-z0-9._:@/-]*$/u.test(t)))throw new N("request_rejected",`Implementation identity ${e} is invalid.`);if(!(0,Er.valid)(r.version))throw new N("request_rejected","Implementation identity version must be exact SemVer.")}function $u(r){if(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(r.id))throw new N("unknown_contract",`Contract ID ${r.id} is invalid.`);if(!(0,Er.validRange)(r.version,{includePrerelease:!0}))throw new N("unsupported_contract_version",`Contract requirement ${r.version} is not a SemVer range.`);if(r.digest&&!/^sha256:[0-9a-f]{64}$/u.test(r.digest))throw new N("contract_digest_conflict","Contract digest is invalid.")}function cb(r,e){let t=r!=null?r:{id:e.id,version:e.version,digest:e.digest};return $u(t),structuredClone(t)}function lb(r,e){if(!da(r,e))throw new N("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function da(r,e){return r.id===e.id&&(0,Er.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function la(r){return`${r.id}@${r.version}`}function fb(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function CI(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function MI(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==fb(e))throw new N("contract_digest_conflict","Event contract evidence is inconsistent.")}function NI(r){let{created_at:e,...t}=r;return t}function db(r,e,t,n){if(n.clientId!==r)throw new N("unauthorized",`Action request ${e} belongs to another caller.`);if(n.requestDigest!==t)throw new N("request_rejected",`Action request ${e} was reused with different content.`)}function wu(r,e,t){let n=new Set,i=(s,o)=>{if(!(s===null||typeof s=="boolean"||typeof s=="string")){if(typeof s=="number"){if(Number.isFinite(s))return;throw new N(e,`${t}${o} must be a finite JSON number.`)}if(typeof s!="object")throw new N(e,`${t}${o} is not a JSON value.`);if(n.has(s))throw new N(e,`${t}${o} contains a cycle.`);if(n.add(s),Array.isArray(s))s.forEach((a,c)=>i(a,`${o}/${c}`));else{let a=Object.getPrototypeOf(s);if(a!==Object.prototype&&a!==null)throw new N(e,`${t}${o} must be a plain JSON object.`);for(let[c,l]of Object.entries(s))i(l,`${o}/${c}`)}n.delete(s)}};i(r,"")}function vu(r,e){if(r.max_payload_bytes===void 0)return;let t=JSON.stringify(e),n=new TextEncoder().encode(t).byteLength;if(n>r.max_payload_bytes)throw new N("unsupported_transport_capability",`The portable envelope is ${n} bytes; the active transport allows ${r.max_payload_bytes}.`)}function LI(r,e){return r?(r.application===void 0||r.application===e.application)&&(r.implementation===void 0||r.implementation===e.implementation)&&(r.instance_id===void 0||r.instance_id===e.instance_id):!0}function DI(r,e){var t,n;if(e){if((t=e.delivery)!=null&&t.some(i=>!r.delivery.includes(i)))throw new N("unsupported_transport_capability","The active transport lacks a required delivery capability.");if((n=e.ordering)!=null&&n.some(i=>!r.ordering.includes(i)))throw new N("unsupported_transport_capability","The active transport lacks a required ordering capability.");for(let i of["cancellation","deadlines","provider_discovery","request_deduplication","cross_process_identity"])if(e[i]===!0&&r[i]!==!0)throw new N("unsupported_transport_capability",`The active transport lacks ${i}.`);if(e.max_payload_bytes!==void 0&&(r.max_payload_bytes===void 0||r.max_payload_bytese;){let t=r.keys().next().value;if(t===void 0)return;r.delete(t)}}function qI(r){return r instanceof Error&&r.name==="AbortError"}var ua=class{constructor(e,t){this.app=e;this.profileVersion="0.1";this.bridge=new _s({authorize:()=>t(),transport:{delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},onDiagnostic:n=>{var s;(n.severity==="error"?console.error:console.warn)(`[mdbase/interop] ${n.code}: ${n.message}`,(s=n.cause)!=null?s:"")}}),this.transport=this.bridge.describe().transport}connect(e){var s,o;let t=(s=e.manifest)==null?void 0:s.id,n=(o=e.manifest)==null?void 0:o.version;if(!t||!n)throw new Error("Only a loaded Obsidian plugin with manifest identity can connect to mdbase interop.");let i=this.app.plugins;if(!i||i.getPlugin(t)!==e)throw new Error(`Obsidian plugin ${t} is not the active loaded instance.`);return this.bridge.connect({application:t,implementation:`${t}.obsidian`,version:n})}describe(){return this.bridge.describe()}dispose(){return this.bridge.dispose()}};var ge=require("obsidian"),Db=ln(jd(),1),qb=ln(Jd(),1),qu=ln(Mu(),1),ma=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},Ut={spec_version:"0.3.0",name:"My mdbase collection",description:"Typed markdown collection",settings:{types_folder:"_types",explicit_type_keys:["type","types"],default_strict:!1,include_subfolders:!0,exclude:["_types",".obsidian",".git","node_modules",".trash",".mdbase"]}},Es=null;function wO(){return Es||(Es=new Db.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,qb.default)(Es),Es)}function re(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function it(r){return JSON.parse(JSON.stringify(r))}function vO(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function Nu(r){return Array.isArray(r)?`[${r.map(e=>Nu(e)).join(",")}]`:re(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${Nu(r[t])}`).join(",")}}`:JSON.stringify(r)}function $O(r){let e=r.indexOf("."),t=r.indexOf("[");return e===-1&&t===-1?r:e===-1?r.slice(0,t):t===-1?r.slice(0,e):r.slice(0,Math.min(e,t))}function SO(r){let e=new Map,t=new Set,n=i=>{var l,u,d,f;let s=e.get(i);if(s)return s;let o=r.get(i);if(!o)return null;if(t.has(i)){let p={...o,fields:it(o.fields)};return e.set(i,p),p}t.add(i);let a=o.extends?n(o.extends):null;t.delete(i);let c={...o,fields:a?{...it(a.fields),...it(o.fields)}:it(o.fields),display_name_key:(l=o.display_name_key)!=null?l:a==null?void 0:a.display_name_key,path_pattern:(u=o.path_pattern)!=null?u:a==null?void 0:a.path_pattern,filename_pattern:(d=o.filename_pattern)!=null?d:a==null?void 0:a.filename_pattern,strict:o.strict!==void 0?o.strict:a==null?void 0:a.strict,match:(f=o.match)!=null?f:a==null?void 0:a.match};return e.set(i,c),c};for(let i of r.keys())n(i);return e}function jb(r){let e=(0,ge.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function Fb(r){let e=r.trim();e.startsWith("[[")&&e.endsWith("]]")&&(e=e.slice(2,-2));let t=e.indexOf("|");t>=0&&(e=e.slice(0,t));let n=e.indexOf("#");return n>=0&&(e=e.slice(0,n)),e.trim()}function Vb(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function Ub(r,e,t){var c;let n=Fb(t);if(!n||Vb(n))return null;let i=new Set,s=(0,ge.normalizePath)(n);i.add(s),s.endsWith(".md")||i.add(`${s}.md`);let o=jb(e);if(o){let l=(0,ge.normalizePath)(`${o}/${n}`);i.add(l),l.endsWith(".md")||i.add(`${l}.md`)}for(let l of i){let u=r.getAbstractFileByPath(l);if(u instanceof ge.TFile)return u}let a=n.replace(/\.md$/i,"");return(c=r.getMarkdownFiles().find(l=>l.basename===a))!=null?c:null}function EO(r,e,t){return Vb(Fb(t))||Ub(r,e,t)!==null}function Ct(r){let e=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)/m);if(!e)return{hasFrontmatter:!1,frontmatter:{},body:r};try{let t=e[1],n=(0,ge.parseYaml)(t);return n==null&&t.trim()!==""?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:n!=null&&!re(n)?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:"Frontmatter must be a YAML object"}:{hasFrontmatter:!0,frontmatter:n!=null?n:{},body:r.slice(e[0].length)}}catch(t){return{hasFrontmatter:!0,frontmatter:{},body:r.slice(e[0].length),error:t instanceof Error?t.message:String(t)}}}function wt(r,e=""){if(Object.keys(r).length===0)return e;let t=(0,ge.stringifyYaml)(r).trimEnd(),n=e.replace(/^\n+/,"");return`--- ${t} --- -${n}`}async function Zn(r){let e=r.getAbstractFileByPath("mdbase.yaml");if(!(e instanceof pe.TFile))return null;try{let t=await r.cachedRead(e),n=(0,pe.parseYaml)(t);if(!Z(n))return null;let s=Z(n.settings)?n.settings:{},i=Z(n.runtime)?n.runtime:void 0;return{spec_version:typeof n.spec_version=="string"?n.spec_version:Tt.spec_version,name:typeof n.name=="string"?n.name:Tt.name,description:typeof n.description=="string"?n.description:Tt.description,runtime:i?{profile_version:typeof i.profile_version=="string"?i.profile_version:void 0,enabled:typeof i.enabled=="boolean"?i.enabled:void 0,policy:typeof i.policy=="string"?i.policy:void 0}:void 0,settings:{types_folder:typeof s.types_folder=="string"?s.types_folder:Tt.settings.types_folder,explicit_type_keys:Array.isArray(s.explicit_type_keys)?s.explicit_type_keys.filter(o=>typeof o=="string"):[...Tt.settings.explicit_type_keys],default_strict:typeof s.default_strict=="boolean"?s.default_strict:Tt.settings.default_strict,include_subfolders:typeof s.include_subfolders=="boolean"?s.include_subfolders:Tt.settings.include_subfolders,exclude:Array.isArray(s.exclude)?s.exclude.filter(o=>typeof o=="string"):[...Tt.settings.exclude]}}}catch(t){return null}}async function gb(r){var c;let e=[];if(!(r.getAbstractFileByPath("mdbase.yaml")instanceof pe.TFile)){let l=(0,pe.stringifyYaml)(Tt).trimEnd()+` -`;await r.create("mdbase.yaml",l),e.push("mdbase.yaml")}let n=(c=await Zn(r))!=null?c:Tt,s=n.settings.types_folder;await r.adapter.exists(s)||(await r.createFolder(s),e.push(s));let o=(0,pe.normalizePath)(`${s}/note.md`);if(!await r.adapter.exists(o)){let l=hT("note",void 0,n.spec_version);await r.create(o,l),e.push(o)}return{created:e}}function bb(r,e){let t=Z(r)?r:{},n=Array.isArray(t.type)?t.type.find(i=>i!=="null"):t.type,s={required:e};return Array.isArray(t.enum)?(s.type="enum",s.values=We(t.enum)):n==="array"?(s.type="list",s.items=bb(t.items,!1)):n==="object"?(s.type="object",s.fields=pn(t)):n==="string"&&t.format==="date"?s.type="date":n==="string"&&t.format==="date-time"?s.type="datetime":n==="string"&&t.format==="time"?s.type="time":typeof n=="string"?s.type=n:s.type="any",t.default!==void 0&&(s.default=We(t.default)),typeof t.description=="string"&&(s.description=t.description),typeof t.minimum=="number"&&(s.min=t.minimum),typeof t.maximum=="number"&&(s.max=t.maximum),typeof t.minLength=="number"&&(s.min_length=t.minLength),typeof t.maxLength=="number"&&(s.max_length=t.maxLength),typeof t.pattern=="string"&&(s.pattern=t.pattern),typeof t.minItems=="number"&&(s.min_length=t.minItems),typeof t.maxItems=="number"&&(s.max_length=t.maxItems),s}function pn(r){let e=Z(r.properties)?r.properties:{},t=new Set(Array.isArray(r.required)?r.required.filter(n=>typeof n=="string"):[]);return Object.fromEntries(Object.entries(e).map(([n,s])=>[n,bb(s,t.has(n))]))}function wb(r,e){var c,l,u,d;let t={...We(e)},n=(c=r.type)!=null?c:"string",s=()=>{delete t.properties,delete t.required,delete t.additionalProperties},i=()=>{delete t.items};if(n==="enum")delete t.type,t.enum=We((l=r.values)!=null?l:[]),delete t.format,s(),i();else if(n==="list")t.type="array",delete t.enum,delete t.format,s(),t.items=wb((u=r.items)!=null?u:{type:"any"},Z(t.items)?t.items:{});else if(n==="object"){t.type="object",delete t.enum,delete t.format,i();let f=yu((d=r.fields)!=null?d:{},Z(t)?t:{},!1);t.properties=f.properties,f.required?t.required=f.required:delete t.required}else n==="link"?(t.type="string",delete t.enum,delete t.format,s(),i()):["date","datetime","time"].includes(n)?(t.type="string",t.format=n==="datetime"?"date-time":n,delete t.enum,s(),i()):["string","integer","number","boolean"].includes(n)?(t.type=n,delete t.format,delete t.enum,s(),i()):(delete t.type,delete t.enum,delete t.format,s(),i());r.default!==void 0?t.default=We(r.default):delete t.default,typeof r.description=="string"&&r.description.trim()?t.description=r.description:delete t.description;let o=n==="integer"||n==="number";o&&typeof r.min=="number"?t.minimum=r.min:delete t.minimum,o&&typeof r.max=="number"?t.maximum=r.max:delete t.maximum;let a=["string","link","date","datetime","time"].includes(n);return n==="list"&&typeof r.min_length=="number"?t.minItems=r.min_length:delete t.minItems,n==="list"&&typeof r.max_length=="number"?t.maxItems=r.max_length:delete t.maxItems,a&&typeof r.min_length=="number"?t.minLength=r.min_length:delete t.minLength,a&&typeof r.max_length=="number"?t.maxLength=r.max_length:delete t.maxLength,a&&typeof r.pattern=="string"?t.pattern=r.pattern:delete t.pattern,t}function yu(r,e={},t=!1){let n=Z(e.properties)?e.properties:{},s=Object.create(null),i=[];for(let[a,c]of Object.entries(r))s[a]=wb(c,Z(n[a])?n[a]:{}),c.required===!0&&i.push(a);let o={...We(e),type:"object",properties:s,additionalProperties:!t};return i.length>0?o.required=i:delete o.required,o}function GI(r,e){if(!e)return r;if(!e.startsWith("/"))return;let t=r;for(let n of e.slice(1).split("/")){let s=n.replace(/~1/g,"/").replace(/~0/g,"~");if(Array.isArray(t)){let i=Number(s);if(!Number.isInteger(i)||i<0||i>=t.length)return;t=t[i]}else if(Z(t)&&s in t)t=t[s];else return}return t}async function JI(r,e,t){let[n,s=""]=t.split("#",2);if(!n||/^[a-z][a-z0-9+.-]*:/i.test(n)||n.startsWith("/"))return null;let i=pb(e),o=[];for(let l of`${i}/${n}`.replace(/\\/g,"/").split("/"))if(!(!l||l==="."))if(l===".."){if(o.length===0)return null;o.pop()}else o.push(l);let a=(0,pe.normalizePath)(o.join("/")),c=r.getAbstractFileByPath(a);if(!(c instanceof pe.TFile))return null;try{let l=JSON.parse(await r.cachedRead(c)),u=GI(l,s);return Z(u)?u:null}catch(l){return null}}async function _b(r,e){var s,i,o,a;let t=new Map,n=`${(0,pe.normalizePath)(e.settings.types_folder)}/`;for(let c of r.getMarkdownFiles()){if(!c.path.startsWith(n))continue;let l=await r.cachedRead(c),u=_t(l);if(!u.hasFrontmatter||u.error)continue;let d=u.frontmatter;if(e.spec_version.startsWith("0.3.")){if(d.kind!=="mdbase.type"||typeof d.name!="string"||!Z(d.schema))continue;let m=d.schema,h=Z(m.value)?m.value:null;if(!h&&typeof m.ref=="string"&&(h=await JI(r,c.path,m.ref)),!h)continue;let y=Z(d.collection)?We(d.collection):void 0,b=pn(h);for(let g of(s=y==null?void 0:y.unique)!=null?s:[])typeof g.field=="string"&&b[g.field]&&(b[g.field].unique=!0);for(let[g,_]of Object.entries((i=y==null?void 0:y.links)!=null?i:{}))b[g]&&(b[g].target=_.target_type,b[g].validate_exists=_.validate_exists);t.set(d.name,{name:d.name,version:typeof d.version=="number"?d.version:void 0,description:typeof d.description=="string"?d.description:void 0,display_name_key:(o=y==null?void 0:y.display)==null?void 0:o.name_field,path_pattern:(a=y==null?void 0:y.path)==null?void 0:a.pattern,strict:h.additionalProperties===!1,match:Z(d.match)?d.match:void 0,fields:b,filePath:c.path,specProfile:"v0.3",schema:We(h),collection:y,originalFrontmatter:We(d)});continue}if(!Z(d.fields))continue;let f=typeof d.name=="string"&&d.name.trim().length>0?d.name.trim():c.basename,p={};for(let[m,h]of Object.entries(d.fields))Z(h)&&(p[m]=h);t.set(f,{name:f,extends:typeof d.extends=="string"?d.extends:void 0,display_name_key:typeof d.display_name_key=="string"?d.display_name_key:void 0,path_pattern:typeof d.path_pattern=="string"?d.path_pattern:void 0,filename_pattern:typeof d.filename_pattern=="string"?d.filename_pattern:void 0,strict:BI(d.strict),match:Z(d.match)?d.match:void 0,fields:p,filePath:c.path,specProfile:"v0.2",originalFrontmatter:We(d)})}return KI(t)}function YI(r,e){for(let t of e){let n=r[t];if(Array.isArray(n))return n.filter(i=>typeof i=="string")}for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim().length>0)return[n.trim()]}return null}function gu(r,e){return r.replace(/\{([^}]+)\}/g,(t,n)=>{let s=e[n];return s==null?"":Array.isArray(s)?s.join("-"):String(s)})}function hi(r){let e=r.replace(/\\/g,"/");if(!e||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||e.includes("\0"))throw new ta("invalid_path",`Invalid collection-relative path: ${r}`);let t=e.split("/");if(t.includes(".."))throw new ta("path_traversal",`Path escapes the collection root: ${r}`);return(0,pe.normalizePath)(t.filter(n=>n&&n!==".").join("/"))}function XI(r){let e=r.search(/[\*\?\[]/),n=(e===-1?r:r.slice(0,e)).replace(/\/+$/,"");if(n.endsWith(".md")){let s=n.lastIndexOf("/");return s>=0?n.slice(0,s):""}return n}function QI(r,e){var t;if(r.path_pattern){let n=(0,pe.normalizePath)(gu(r.path_pattern,e));if(n.endsWith(".md")){let s=n.lastIndexOf("/");return s>=0?n.slice(0,s):""}return n.replace(/\/+$/,"")}return(t=r.match)!=null&&t.path_glob?XI(r.match.path_glob):""}function ZI(r,e){var o,a;let t=(o=r.display_name_key)!=null?o:"title",n=e[t],s=`${r.name}-${new Date().toISOString().slice(0,10)}`,i=typeof n=="string"&&n.trim().length>0?n:s;if(r.filename_pattern&&r.filename_pattern.trim().length>0){let c=(0,pe.normalizePath)(gu(r.filename_pattern,e)),u=((a=c.split("/").pop())!=null?a:c).replace(/\.md$/i,"").trim();if(u.length>0)return`${db(u)}.md`}return`${db(i)}.md`}function Qn(r){return Array.isArray(r)?`[${r.map(Qn).join(",")}]`:Z(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Qn(r[e])}`).join(",")}}`:JSON.stringify(r)}function eT(r,e){let t=[r];for(let n of e.split(".").filter(Boolean)){let s=n.endsWith("[]"),i=s?n.slice(0,-2):n,o=[];for(let a of t){if(!Z(a)||!Object.prototype.hasOwnProperty.call(a,i))continue;let c=a[i];s&&Array.isArray(c)?o.push(...c):s||o.push(c)}if(!o.length)return{present:!1,value:void 0};t=o}return{present:!0,value:t[0]}}function Zo(r,e,t){return(typeof r=="number"&&typeof e=="number"&&Number.isFinite(r)&&Number.isFinite(e)||typeof r=="string"&&typeof e=="string")&&t(r,e)}function tT(r,e,t,n){let s=(i,o)=>Qn(i)===Qn(o);switch(e){case"eq":case"const":return r.present&&r.value!=null&&s(r.value,t);case"neq":return r.present&&r.value!=null&&!s(r.value,t);case"gt":return Zo(r.value,t,(i,o)=>i>o);case"gte":return Zo(r.value,t,(i,o)=>i>=o);case"lt":return Zo(r.value,t,(i,o)=>ii<=o);case"exists":return n.startsWith("0.3.")?t===!0?r.present:!r.present:t===!0?r.present&&r.value!=null:!r.present||r.value==null;case"contains":return Array.isArray(r.value)?r.value.some(i=>s(i,t)):typeof r.value=="string"&&r.value.includes(String(t));case"containsAll":return!Array.isArray(r.value)||!Array.isArray(t)?!1:t.every(i=>r.value.some(o=>s(o,i)));case"containsAny":return!Array.isArray(r.value)||!Array.isArray(t)?!1:t.some(i=>r.value.some(o=>s(o,i)));case"in":return r.value!=null&&Array.isArray(t)&&t.some(i=>s(i,r.value));case"startsWith":case"starts_with":return typeof r.value=="string"&&r.value.startsWith(String(t));case"endsWith":case"ends_with":return typeof r.value=="string"&&r.value.endsWith(String(t));case"matches":try{return r.value!=null&&new RegExp(String(t).replace(/\\\\/g,"\\")).test(String(r.value))}catch(i){return!1}default:return!1}}function ea(r,e,t){if("and"in r)return Array.isArray(r.and)&&r.and.every(n=>Z(n)&&ea(n,e,t));if("or"in r)return Array.isArray(r.or)&&r.or.some(n=>Z(n)&&ea(n,e,t));if("not"in r)return Z(r.not)&&!ea(r.not,e,t);for(let[n,s]of Object.entries(r)){let i=eT(e,n);if(!Z(s)){if(!i.present||Qn(i.value)!==Qn(s))return!1;continue}for(let[o,a]of Object.entries(s))if(!tT(i,o,a,t))return!1}return!0}function es(r,e,t,n){let s=YI(e,t.settings.explicit_type_keys);if(s)return s;let i=[];for(let[o,a]of n.entries()){let c=a.match;if(!c)continue;let l=!0;if(typeof c.path_glob=="string"&&((0,mu.default)(c.path_glob,{dot:!0})(r)||(l=!1)),l&&Array.isArray(c.fields_present)){for(let u of c.fields_present)if(!(u in e)){l=!1;break}}l&&Z(c.where)&&(l=ea(c.where,e,t.spec_version)),l&&typeof c.where=="string"&&(l=!1),l&&i.push(o)}return i}function vb(r){return r==null||typeof r=="string"&&r.trim().length===0}function rT(r){return/^\d{4}-\d{2}-\d{2}$/.test(r)}function nT(r){return/^\d{2}:\d{2}(:\d{2})?$/.test(r)}function sT(r){return typeof r=="string"||Array.isArray(r)?r.length:null}function Te(r,e,t,n,s,i){r.push({path:e,code:n,message:s,severity:t,field:i})}function wt(r,e,t,n,s){typeof r=="number"&&(typeof e.min=="number"&&r= ${e.min}`,t),typeof e.max=="number"&&r>e.max&&Te(s,n,"error","above_max",`Field '${t}' must be <= ${e.max}`,t));let i=sT(r);if(i!=null&&(typeof e.min_length=="number"&&i= ${e.min_length}`,t),typeof e.max_length=="number"&&i>e.max_length&&Te(s,n,"error","above_max_length",`Field '${t}' length must be <= ${e.max_length}`,t)),typeof e.pattern=="string"&&typeof r=="string")try{new RegExp(e.pattern).test(r)||Te(s,n,"error","pattern_mismatch",`Field '${t}' must match pattern /${e.pattern}/`,t)}catch(o){Te(s,n,"warn","invalid_pattern",`Field '${t}' has invalid regex pattern: ${o instanceof Error?o.message:String(o)}`,t)}}function pu(r,e,t,n,s,i){var c;let o=(c=e.type)!=null?c:"any";if(r==null)return;e.deprecated===!0&&Te(s,n,"warn","deprecated_field",`Field '${t}' is marked deprecated`,t);let a=l=>{Te(s,n,"error","invalid_type",`Field '${t}' expected ${l}`,t)};switch(o){case"any":wt(r,e,t,n,s);return;case"string":if(typeof r!="string"){a("a string");return}wt(r,e,t,n,s);return;case"integer":if(typeof r!="number"||!Number.isInteger(r)){a("an integer");return}wt(r,e,t,n,s);return;case"number":if(typeof r!="number"||Number.isNaN(r)){a("a number");return}wt(r,e,t,n,s);return;case"boolean":typeof r!="boolean"&&a("a boolean");return;case"date":if(typeof r!="string"||!rT(r)){a("a date (YYYY-MM-DD)");return}wt(r,e,t,n,s);return;case"datetime":if(typeof r!="string"||Number.isNaN(Date.parse(r))){a("a datetime string");return}wt(r,e,t,n,s);return;case"time":if(typeof r!="string"||!nT(r)){a("a time string (HH:MM)");return}wt(r,e,t,n,s);return;case"enum":{let l=Array.isArray(e.values)?e.values:[];if(!l.includes(r)){Te(s,n,"error","invalid_enum",`Field '${t}' must be one of: ${l.map(u=>String(u)).join(", ")}`,t);return}wt(r,e,t,n,s);return}case"list":{if(!Array.isArray(r)){a("a list");return}wt(r,e,t,n,s),e.items&&r.forEach((l,u)=>{pu(l,e.items,`${t}[${u}]`,n,s,i)});return}case"object":{if(!Z(r)){a("an object");return}if(e.fields&&Z(e.fields))for(let[l,u]of Object.entries(e.fields)){if(!Z(u))continue;let d=u,f=`${t}.${l}`,p=r[l];if(d.required&&vb(p)){Te(s,n,"error","missing_required",`Missing required field '${f}'`,f);continue}pu(p,d,f,n,s,i)}return}case"link":{if(typeof r!="string"&&!Z(r)){a("a link string");return}if(e.validate_exists===!0&&i){let l=typeof r=="string"?r:typeof r.path=="string"?r.path:typeof r.file=="string"?r.file:"";(!l||!WI(i,n,l))&&Te(s,n,"error","missing_link_target",`Field '${t}' references a missing note`,t)}return}case"tags":if(typeof r=="string"){wt(r,e,t,n,s);return}if(Array.isArray(r)&&r.every(l=>typeof l=="string")){wt(r,e,t,n,s);return}a("a tag string or list of strings");return;default:wt(r,e,t,n,s);return}}function iT(r){return r.replace(/^\//,"").split("/").filter(Boolean).map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")||void 0}function oT(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function aT(r,e,t){var c;let n=r.params,s=iT(r.instancePath),i=typeof n.missingProperty=="string"?n.missingProperty:typeof n.additionalProperty=="string"?n.additionalProperty:void 0,o=s&&i?`${s}.${i}`:i!=null?i:s,a=r.keyword==="format"?"format_invalid":`schema_${oT(r.keyword)}`;return{path:e,code:a,message:`JSON Schema ${r.keyword} failed for type '${t}': ${(c=r.message)!=null?c:"invalid value"}`,severity:"error",field:o,type:t,schema_location:`embedded://type/schema#${r.schemaPath}`,details:{instance_path:r.instancePath,schema_path:r.schemaPath}}}function hu(r){if(Array.isArray(r)){for(let e of r){let t=hu(e);if(t)return t}return null}if(!Z(r))return null;if(typeof r.$ref=="string"&&!r.$ref.startsWith("#"))return r.$ref;for(let e of Object.values(r)){let t=hu(e);if(t)return t}return null}function cT(r,e,t,n){var i;if(!t.schema)return;let s=hu(t.schema);if(s){n.push({path:r,code:/^[a-z][a-z0-9+.-]*:/i.test(s)?"schema_ref_forbidden":"unsupported_profile",message:`Unsupported JSON Schema reference '${s}' for type '${t.name}'`,severity:"error",type:t.name});return}try{let o=HI().compile(t.schema);if(o(e))return;for(let a of(i=o.errors)!=null?i:[])n.push(aT(a,r,t.name))}catch(o){n.push({path:r,code:"invalid_embedded_schema",message:o instanceof Error?o.message:String(o),severity:"error",type:t.name})}}async function lT(r,e,t,n,s,i,o){var a,c;for(let[l,u]of Object.entries((c=(a=n.collection)==null?void 0:a.links)!=null?c:{})){let d=t[l],f=Array.isArray(d)?d:[d];for(let p of f){if(p==null||typeof p!="string")continue;let m=yb(r,e,p);if(!m&&u.validate_exists===!0){Te(o,e,"error","link_not_found",`Field '${l}' references a missing note`,l);continue}if(m&&u.target_type&&u.target_type!=="any"){let h=_t(await r.cachedRead(m));es(m.path,h.frontmatter,s,i).includes(u.target_type)||Te(o,e,"error","link_wrong_type",`Field '${l}' must reference type '${u.target_type}'`,l)}}}}function dT(r,e,t,n,s){if(t.specProfile==="v0.3"){cT(r,e,t,n);return}for(let[i,o]of Object.entries(t.fields)){if(!Z(o))continue;let a=o,c=e[i];if(a.required&&vb(c)){Te(n,r,"error","missing_required",`Missing required field '${i}' for type '${t.name}'`,i);continue}pu(c,a,i,r,n,s)}}function uT(r){let e=new Set;for(let t of r)for(let n of Object.keys(t.fields))e.add(n);return e}function fT(r,e){let t=!1,n=!1;for(let s of r){if(s.strict===!0)return!0;s.strict==="warn"&&(t=!0),s.strict===void 0&&(n=!0)}return t||n&&e.settings.default_strict?"warn":!1}function mi(r,e){let t=(0,pe.normalizePath)(r),n=(0,pe.normalizePath)(e.settings.types_folder);if(t.startsWith(`${n}/`)||t===n||!e.settings.include_subfolders&&t.includes("/"))return!0;for(let s of e.settings.exclude)if((0,mu.default)(s,{dot:!0,matchBase:!s.includes("/")})(t)||!s.includes("*")&&!s.includes("?")&&!s.includes("/")&&t.startsWith(`${s}/`))return!0;return!1}async function bu(r,e,t,n){if(mi(e.path,t))return[];let s=[],i=await r.cachedRead(e),o=_t(i);if(o.error)return Te(s,e.path,"error","invalid_frontmatter",o.error),s;let a=o.frontmatter,c=es(e.path,a,t,n);if(c.length===0)return Te(s,e.path,"warn","no_matching_type","No type could be resolved for this file"),s;let l=c.map(d=>n.get(d)).filter(d=>!!d);if(l.length===0)return Te(s,e.path,"error","unknown_type",`Resolved types are not defined: ${c.join(", ")}`),s;for(let d of l)dT(e.path,a,d,s,r),d.specProfile==="v0.3"&&await lT(r,e.path,a,d,t,n,s);let u=t.spec_version.startsWith("0.3.")?!1:fT(l,t);if(u!==!1){let d=uT(l),f=new Set(t.settings.explicit_type_keys),p=u===!0?"error":"warn";for(let m of Object.keys(a))d.has(m)||f.has(m)||Te(s,e.path,p,"unknown_field",`Unknown field '${m}' in strict mode`,m)}return s}async function pT(r,e,t){var i,o;let n=new Map;for(let a of r.getMarkdownFiles()){if(mi(a.path,e))continue;let c=await r.cachedRead(a),l=_t(c);if(l.error)continue;let d=es(a.path,l.frontmatter,e,t).map(f=>t.get(f)).filter(f=>!!f);for(let f of d)for(let[p,m]of Object.entries(f.fields)){if(!Z(m)||m.unique!==!0)continue;let y=l.frontmatter[p];if(y==null)continue;let b=fu(y),g=`${f.name}::${p}::${b}`,_=(i=n.get(g))!=null?i:[];_.push({path:a.path,typeName:f.name,fieldName:p,value:y,fingerprint:b}),n.set(g,_)}}let s=[];for(let a of n.values())if(!(a.length<=1))for(let c of a){let l=a.filter(u=>u.path!==c.path).map(u=>u.path).join(", ");Te(s,c.path,"error",((o=t.get(c.typeName))==null?void 0:o.specProfile)==="v0.3"?"duplicate_value":"duplicate_unique",`Field '${c.fieldName}' must be unique for type '${c.typeName}'. Duplicate found in: ${l}`,c.fieldName)}return s}async function $b(r,e,t){let n=[];for(let i of r.getMarkdownFiles()){if(mi(i.path,e))continue;let o=await bu(r,i,e,t);n.push(...o)}let s=await pT(r,e,t);return n.push(...s),n}function hT(r,e,t=Tt.spec_version){if(t.startsWith("0.3.")){let s={kind:"mdbase.type",name:r,version:1,description:`${r} type`,schema:{dialect:"json-schema-2020-12",value:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",required:["title"],additionalProperties:!0,properties:{title:{type:"string",minLength:1},tags:{type:"array",items:{type:"string"}}}}}};return e&&e.trim()&&(s.match={path_glob:e.trim()}),`${at(s,`# ${r} +${n}`}async function ci(r){let e=r.getAbstractFileByPath("mdbase.yaml");if(!(e instanceof ge.TFile))return null;try{let t=await r.cachedRead(e),n=(0,ge.parseYaml)(t);if(!re(n))return null;let i=re(n.settings)?n.settings:{},s=re(n.runtime)?n.runtime:void 0;return{spec_version:typeof n.spec_version=="string"?n.spec_version:Ut.spec_version,name:typeof n.name=="string"?n.name:Ut.name,description:typeof n.description=="string"?n.description:Ut.description,runtime:s?{profile_version:typeof s.profile_version=="string"?s.profile_version:void 0,enabled:typeof s.enabled=="boolean"?s.enabled:void 0,policy:typeof s.policy=="string"?s.policy:void 0}:void 0,settings:{types_folder:typeof i.types_folder=="string"?i.types_folder:Ut.settings.types_folder,explicit_type_keys:Array.isArray(i.explicit_type_keys)?i.explicit_type_keys.filter(o=>typeof o=="string"):[...Ut.settings.explicit_type_keys],default_strict:typeof i.default_strict=="boolean"?i.default_strict:Ut.settings.default_strict,include_subfolders:typeof i.include_subfolders=="boolean"?i.include_subfolders:Ut.settings.include_subfolders,exclude:Array.isArray(i.exclude)?i.exclude.filter(o=>typeof o=="string"):[...Ut.settings.exclude]}}}catch(t){return null}}async function Bb(r){var c;let e=[];if(!(r.getAbstractFileByPath("mdbase.yaml")instanceof ge.TFile)){let l=(0,ge.stringifyYaml)(Ut).trimEnd()+` +`;await r.create("mdbase.yaml",l),e.push("mdbase.yaml")}let n=(c=await ci(r))!=null?c:Ut,i=n.settings.types_folder;await r.adapter.exists(i)||(await r.createFolder(i),e.push(i));let o=(0,ge.normalizePath)(`${i}/note.md`);if(!await r.adapter.exists(o)){let l=HO("note",void 0,n.spec_version);await r.create(o,l),e.push(o)}return{created:e}}function zb(r,e){let t=re(r)?r:{},n=Array.isArray(t.type)?t.type.find(s=>s!=="null"):t.type,i={required:e};return Array.isArray(t.enum)?(i.type="enum",i.values=it(t.enum)):n==="array"?(i.type="list",i.items=zb(t.items,!1)):n==="object"?(i.type="object",i.fields=$n(t)):n==="string"&&t.format==="date"?i.type="date":n==="string"&&t.format==="date-time"?i.type="datetime":n==="string"&&t.format==="time"?i.type="time":typeof n=="string"?i.type=n:i.type="any",t.default!==void 0&&(i.default=it(t.default)),typeof t.description=="string"&&(i.description=t.description),typeof t.minimum=="number"&&(i.min=t.minimum),typeof t.maximum=="number"&&(i.max=t.maximum),typeof t.minLength=="number"&&(i.min_length=t.minLength),typeof t.maxLength=="number"&&(i.max_length=t.maxLength),typeof t.pattern=="string"&&(i.pattern=t.pattern),typeof t.minItems=="number"&&(i.min_length=t.minItems),typeof t.maxItems=="number"&&(i.max_length=t.maxItems),i}function $n(r){let e=re(r.properties)?r.properties:{},t=new Set(Array.isArray(r.required)?r.required.filter(n=>typeof n=="string"):[]);return Object.fromEntries(Object.entries(e).map(([n,i])=>[n,zb(i,t.has(n))]))}function Hb(r,e){var c,l,u,d;let t={...it(e)},n=(c=r.type)!=null?c:"string",i=()=>{delete t.properties,delete t.required,delete t.additionalProperties},s=()=>{delete t.items};if(n==="enum")delete t.type,t.enum=it((l=r.values)!=null?l:[]),delete t.format,i(),s();else if(n==="list")t.type="array",delete t.enum,delete t.format,i(),t.items=Hb((u=r.items)!=null?u:{type:"any"},re(t.items)?t.items:{});else if(n==="object"){t.type="object",delete t.enum,delete t.format,s();let f=ju((d=r.fields)!=null?d:{},re(t)?t:{},!1);t.properties=f.properties,f.required?t.required=f.required:delete t.required}else n==="link"?(t.type="string",delete t.enum,delete t.format,i(),s()):["date","datetime","time"].includes(n)?(t.type="string",t.format=n==="datetime"?"date-time":n,delete t.enum,i(),s()):["string","integer","number","boolean"].includes(n)?(t.type=n,delete t.format,delete t.enum,i(),s()):(delete t.type,delete t.enum,delete t.format,i(),s());r.default!==void 0?t.default=it(r.default):delete t.default,typeof r.description=="string"&&r.description.trim()?t.description=r.description:delete t.description;let o=n==="integer"||n==="number";o&&typeof r.min=="number"?t.minimum=r.min:delete t.minimum,o&&typeof r.max=="number"?t.maximum=r.max:delete t.maximum;let a=["string","link","date","datetime","time"].includes(n);return n==="list"&&typeof r.min_length=="number"?t.minItems=r.min_length:delete t.minItems,n==="list"&&typeof r.max_length=="number"?t.maxItems=r.max_length:delete t.maxItems,a&&typeof r.min_length=="number"?t.minLength=r.min_length:delete t.minLength,a&&typeof r.max_length=="number"?t.maxLength=r.max_length:delete t.maxLength,a&&typeof r.pattern=="string"?t.pattern=r.pattern:delete t.pattern,t}function ju(r,e={},t=!1){let n=re(e.properties)?e.properties:{},i=Object.create(null),s=[];for(let[a,c]of Object.entries(r))i[a]=Hb(c,re(n[a])?n[a]:{}),c.required===!0&&s.push(a);let o={...it(e),type:"object",properties:i,additionalProperties:!t};return s.length>0?o.required=s:delete o.required,o}function AO(r,e){if(!e)return r;if(!e.startsWith("/"))return;let t=r;for(let n of e.slice(1).split("/")){let i=n.replace(/~1/g,"/").replace(/~0/g,"~");if(Array.isArray(t)){let s=Number(i);if(!Number.isInteger(s)||s<0||s>=t.length)return;t=t[s]}else if(re(t)&&i in t)t=t[i];else return}return t}async function kO(r,e,t){let[n,i=""]=t.split("#",2);if(!n||/^[a-z][a-z0-9+.-]*:/i.test(n)||n.startsWith("/"))return null;let s=jb(e),o=[];for(let l of`${s}/${n}`.replace(/\\/g,"/").split("/"))if(!(!l||l==="."))if(l===".."){if(o.length===0)return null;o.pop()}else o.push(l);let a=(0,ge.normalizePath)(o.join("/")),c=r.getAbstractFileByPath(a);if(!(c instanceof ge.TFile))return null;try{let l=JSON.parse(await r.cachedRead(c)),u=AO(l,i);return re(u)?u:null}catch(l){return null}}async function Kb(r,e){var i,s,o,a;let t=new Map,n=`${(0,ge.normalizePath)(e.settings.types_folder)}/`;for(let c of r.getMarkdownFiles()){if(!c.path.startsWith(n))continue;let l=await r.cachedRead(c),u=Ct(l);if(!u.hasFrontmatter||u.error)continue;let d=u.frontmatter;if(e.spec_version.startsWith("0.3.")){if(d.kind!=="mdbase.type"||typeof d.name!="string"||!re(d.schema))continue;let m=d.schema,h=re(m.value)?m.value:null;if(!h&&typeof m.ref=="string"&&(h=await kO(r,c.path,m.ref)),!h)continue;let y=re(d.collection)?it(d.collection):void 0,b=$n(h);for(let g of(i=y==null?void 0:y.unique)!=null?i:[])typeof g.field=="string"&&b[g.field]&&(b[g.field].unique=!0);for(let[g,_]of Object.entries((s=y==null?void 0:y.links)!=null?s:{}))b[g]&&(b[g].target=_.target_type,b[g].validate_exists=_.validate_exists);t.set(d.name,{name:d.name,version:typeof d.version=="number"?d.version:void 0,description:typeof d.description=="string"?d.description:void 0,display_name_key:(o=y==null?void 0:y.display)==null?void 0:o.name_field,path_pattern:(a=y==null?void 0:y.path)==null?void 0:a.pattern,strict:h.additionalProperties===!1,match:re(d.match)?d.match:void 0,fields:b,filePath:c.path,specProfile:"v0.3",schema:it(h),collection:y,originalFrontmatter:it(d)});continue}if(!re(d.fields))continue;let f=typeof d.name=="string"&&d.name.trim().length>0?d.name.trim():c.basename,p={};for(let[m,h]of Object.entries(d.fields))re(h)&&(p[m]=h);t.set(f,{name:f,extends:typeof d.extends=="string"?d.extends:void 0,display_name_key:typeof d.display_name_key=="string"?d.display_name_key:void 0,path_pattern:typeof d.path_pattern=="string"?d.path_pattern:void 0,filename_pattern:typeof d.filename_pattern=="string"?d.filename_pattern:void 0,strict:vO(d.strict),match:re(d.match)?d.match:void 0,fields:p,filePath:c.path,specProfile:"v0.2",originalFrontmatter:it(d)})}return SO(t)}function xO(r,e){for(let t of e){let n=r[t];if(Array.isArray(n))return n.filter(s=>typeof s=="string")}for(let t of e){let n=r[t];if(typeof n=="string"&&n.trim().length>0)return[n.trim()]}return null}function Fu(r,e){return r.replace(/\{([^}]+)\}/g,(t,n)=>{let i=e[n];return i==null?"":Array.isArray(i)?i.join("-"):String(i)})}function As(r){let e=r.replace(/\\/g,"/");if(!e||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||e.includes("\0"))throw new ma("invalid_path",`Invalid collection-relative path: ${r}`);let t=e.split("/");if(t.includes(".."))throw new ma("path_traversal",`Path escapes the collection root: ${r}`);return(0,ge.normalizePath)(t.filter(n=>n&&n!==".").join("/"))}function PO(r){let e=r.search(/[\*\?\[]/),n=(e===-1?r:r.slice(0,e)).replace(/\/+$/,"");if(n.endsWith(".md")){let i=n.lastIndexOf("/");return i>=0?n.slice(0,i):""}return n}function IO(r,e){var t;if(r.path_pattern){let n=(0,ge.normalizePath)(Fu(r.path_pattern,e));if(n.endsWith(".md")){let i=n.lastIndexOf("/");return i>=0?n.slice(0,i):""}return n.replace(/\/+$/,"")}return(t=r.match)!=null&&t.path_glob?PO(r.match.path_glob):""}function OO(r,e){var o,a;let t=(o=r.display_name_key)!=null?o:"title",n=e[t],i=`${r.name}-${new Date().toISOString().slice(0,10)}`,s=typeof n=="string"&&n.trim().length>0?n:i;if(r.filename_pattern&&r.filename_pattern.trim().length>0){let c=(0,ge.normalizePath)(Fu(r.filename_pattern,e)),u=((a=c.split("/").pop())!=null?a:c).replace(/\.md$/i,"").trim();if(u.length>0)return`${Lb(u)}.md`}return`${Lb(s)}.md`}function ai(r){return Array.isArray(r)?`[${r.map(ai).join(",")}]`:re(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${ai(r[e])}`).join(",")}}`:JSON.stringify(r)}function TO(r,e){let t=[r];for(let n of e.split(".").filter(Boolean)){let i=n.endsWith("[]"),s=i?n.slice(0,-2):n,o=[];for(let a of t){if(!re(a)||!Object.prototype.hasOwnProperty.call(a,s))continue;let c=a[s];i&&Array.isArray(c)?o.push(...c):i||o.push(c)}if(!o.length)return{present:!1,value:void 0};t=o}return{present:!0,value:t[0]}}function pa(r,e,t){return(typeof r=="number"&&typeof e=="number"&&Number.isFinite(r)&&Number.isFinite(e)||typeof r=="string"&&typeof e=="string")&&t(r,e)}function RO(r,e,t,n){let i=(s,o)=>ai(s)===ai(o);switch(e){case"eq":case"const":return r.present&&r.value!=null&&i(r.value,t);case"neq":return r.present&&r.value!=null&&!i(r.value,t);case"gt":return pa(r.value,t,(s,o)=>s>o);case"gte":return pa(r.value,t,(s,o)=>s>=o);case"lt":return pa(r.value,t,(s,o)=>ss<=o);case"exists":return n.startsWith("0.3.")?t===!0?r.present:!r.present:t===!0?r.present&&r.value!=null:!r.present||r.value==null;case"contains":return Array.isArray(r.value)?r.value.some(s=>i(s,t)):typeof r.value=="string"&&r.value.includes(String(t));case"containsAll":return!Array.isArray(r.value)||!Array.isArray(t)?!1:t.every(s=>r.value.some(o=>i(o,s)));case"containsAny":return!Array.isArray(r.value)||!Array.isArray(t)?!1:t.some(s=>r.value.some(o=>i(o,s)));case"in":return r.value!=null&&Array.isArray(t)&&t.some(s=>i(s,r.value));case"startsWith":case"starts_with":return typeof r.value=="string"&&r.value.startsWith(String(t));case"endsWith":case"ends_with":return typeof r.value=="string"&&r.value.endsWith(String(t));case"matches":try{return r.value!=null&&new RegExp(String(t).replace(/\\\\/g,"\\")).test(String(r.value))}catch(s){return!1}default:return!1}}function ha(r,e,t){if("and"in r)return Array.isArray(r.and)&&r.and.every(n=>re(n)&&ha(n,e,t));if("or"in r)return Array.isArray(r.or)&&r.or.some(n=>re(n)&&ha(n,e,t));if("not"in r)return re(r.not)&&!ha(r.not,e,t);for(let[n,i]of Object.entries(r)){let s=TO(e,n);if(!re(i)){if(!s.present||ai(s.value)!==ai(i))return!1;continue}for(let[o,a]of Object.entries(i))if(!RO(s,o,a,t))return!1}return!0}function li(r,e,t,n){let i=xO(e,t.settings.explicit_type_keys);if(i)return i;let s=[];for(let[o,a]of n.entries()){let c=a.match;if(!c)continue;let l=!0;if(typeof c.path_glob=="string"&&((0,qu.default)(c.path_glob,{dot:!0})(r)||(l=!1)),l&&Array.isArray(c.fields_present)){for(let u of c.fields_present)if(!(u in e)){l=!1;break}}l&&re(c.where)&&(l=ha(c.where,e,t.spec_version)),l&&typeof c.where=="string"&&(l=!1),l&&s.push(o)}return s}function Wb(r){return r==null||typeof r=="string"&&r.trim().length===0}function CO(r){return/^\d{4}-\d{2}-\d{2}$/.test(r)}function MO(r){return/^\d{2}:\d{2}(:\d{2})?$/.test(r)}function NO(r){return typeof r=="string"||Array.isArray(r)?r.length:null}function Me(r,e,t,n,i,s){r.push({path:e,code:n,message:i,severity:t,field:s})}function Rt(r,e,t,n,i){typeof r=="number"&&(typeof e.min=="number"&&r= ${e.min}`,t),typeof e.max=="number"&&r>e.max&&Me(i,n,"error","above_max",`Field '${t}' must be <= ${e.max}`,t));let s=NO(r);if(s!=null&&(typeof e.min_length=="number"&&s= ${e.min_length}`,t),typeof e.max_length=="number"&&s>e.max_length&&Me(i,n,"error","above_max_length",`Field '${t}' length must be <= ${e.max_length}`,t)),typeof e.pattern=="string"&&typeof r=="string")try{new RegExp(e.pattern).test(r)||Me(i,n,"error","pattern_mismatch",`Field '${t}' must match pattern /${e.pattern}/`,t)}catch(o){Me(i,n,"warn","invalid_pattern",`Field '${t}' has invalid regex pattern: ${o instanceof Error?o.message:String(o)}`,t)}}function Lu(r,e,t,n,i,s){var c;let o=(c=e.type)!=null?c:"any";if(r==null)return;e.deprecated===!0&&Me(i,n,"warn","deprecated_field",`Field '${t}' is marked deprecated`,t);let a=l=>{Me(i,n,"error","invalid_type",`Field '${t}' expected ${l}`,t)};switch(o){case"any":Rt(r,e,t,n,i);return;case"string":if(typeof r!="string"){a("a string");return}Rt(r,e,t,n,i);return;case"integer":if(typeof r!="number"||!Number.isInteger(r)){a("an integer");return}Rt(r,e,t,n,i);return;case"number":if(typeof r!="number"||Number.isNaN(r)){a("a number");return}Rt(r,e,t,n,i);return;case"boolean":typeof r!="boolean"&&a("a boolean");return;case"date":if(typeof r!="string"||!CO(r)){a("a date (YYYY-MM-DD)");return}Rt(r,e,t,n,i);return;case"datetime":if(typeof r!="string"||Number.isNaN(Date.parse(r))){a("a datetime string");return}Rt(r,e,t,n,i);return;case"time":if(typeof r!="string"||!MO(r)){a("a time string (HH:MM)");return}Rt(r,e,t,n,i);return;case"enum":{let l=Array.isArray(e.values)?e.values:[];if(!l.includes(r)){Me(i,n,"error","invalid_enum",`Field '${t}' must be one of: ${l.map(u=>String(u)).join(", ")}`,t);return}Rt(r,e,t,n,i);return}case"list":{if(!Array.isArray(r)){a("a list");return}Rt(r,e,t,n,i),e.items&&r.forEach((l,u)=>{Lu(l,e.items,`${t}[${u}]`,n,i,s)});return}case"object":{if(!re(r)){a("an object");return}if(e.fields&&re(e.fields))for(let[l,u]of Object.entries(e.fields)){if(!re(u))continue;let d=u,f=`${t}.${l}`,p=r[l];if(d.required&&Wb(p)){Me(i,n,"error","missing_required",`Missing required field '${f}'`,f);continue}Lu(p,d,f,n,i,s)}return}case"link":{if(typeof r!="string"&&!re(r)){a("a link string");return}if(e.validate_exists===!0&&s){let l=typeof r=="string"?r:typeof r.path=="string"?r.path:typeof r.file=="string"?r.file:"";(!l||!EO(s,n,l))&&Me(i,n,"error","missing_link_target",`Field '${t}' references a missing note`,t)}return}case"tags":if(typeof r=="string"){Rt(r,e,t,n,i);return}if(Array.isArray(r)&&r.every(l=>typeof l=="string")){Rt(r,e,t,n,i);return}a("a tag string or list of strings");return;default:Rt(r,e,t,n,i);return}}function LO(r){return r.replace(/^\//,"").split("/").filter(Boolean).map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")||void 0}function DO(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function qO(r,e,t){var c;let n=r.params,i=LO(r.instancePath),s=typeof n.missingProperty=="string"?n.missingProperty:typeof n.additionalProperty=="string"?n.additionalProperty:void 0,o=i&&s?`${i}.${s}`:s!=null?s:i,a=r.keyword==="format"?"format_invalid":`schema_${DO(r.keyword)}`;return{path:e,code:a,message:`JSON Schema ${r.keyword} failed for type '${t}': ${(c=r.message)!=null?c:"invalid value"}`,severity:"error",field:o,type:t,schema_location:`embedded://type/schema#${r.schemaPath}`,details:{instance_path:r.instancePath,schema_path:r.schemaPath}}}function Du(r){if(Array.isArray(r)){for(let e of r){let t=Du(e);if(t)return t}return null}if(!re(r))return null;if(typeof r.$ref=="string"&&!r.$ref.startsWith("#"))return r.$ref;for(let e of Object.values(r)){let t=Du(e);if(t)return t}return null}function jO(r,e,t,n){var s;if(!t.schema)return;let i=Du(t.schema);if(i){n.push({path:r,code:/^[a-z][a-z0-9+.-]*:/i.test(i)?"schema_ref_forbidden":"unsupported_profile",message:`Unsupported JSON Schema reference '${i}' for type '${t.name}'`,severity:"error",type:t.name});return}try{let o=wO().compile(t.schema);if(o(e))return;for(let a of(s=o.errors)!=null?s:[])n.push(qO(a,r,t.name))}catch(o){n.push({path:r,code:"invalid_embedded_schema",message:o instanceof Error?o.message:String(o),severity:"error",type:t.name})}}async function FO(r,e,t,n,i,s,o){var a,c;for(let[l,u]of Object.entries((c=(a=n.collection)==null?void 0:a.links)!=null?c:{})){let d=t[l],f=Array.isArray(d)?d:[d];for(let p of f){if(p==null||typeof p!="string")continue;let m=Ub(r,e,p);if(!m&&u.validate_exists===!0){Me(o,e,"error","link_not_found",`Field '${l}' references a missing note`,l);continue}if(m&&u.target_type&&u.target_type!=="any"){let h=Ct(await r.cachedRead(m));li(m.path,h.frontmatter,i,s).includes(u.target_type)||Me(o,e,"error","link_wrong_type",`Field '${l}' must reference type '${u.target_type}'`,l)}}}}function VO(r,e,t,n,i){if(t.specProfile==="v0.3"){jO(r,e,t,n);return}for(let[s,o]of Object.entries(t.fields)){if(!re(o))continue;let a=o,c=e[s];if(a.required&&Wb(c)){Me(n,r,"error","missing_required",`Missing required field '${s}' for type '${t.name}'`,s);continue}Lu(c,a,s,r,n,i)}}function UO(r){let e=new Set;for(let t of r)for(let n of Object.keys(t.fields))e.add(n);return e}function BO(r,e){let t=!1,n=!1;for(let i of r){if(i.strict===!0)return!0;i.strict==="warn"&&(t=!0),i.strict===void 0&&(n=!0)}return t||n&&e.settings.default_strict?"warn":!1}function ks(r,e){let t=(0,ge.normalizePath)(r),n=(0,ge.normalizePath)(e.settings.types_folder);if(t.startsWith(`${n}/`)||t===n||!e.settings.include_subfolders&&t.includes("/"))return!0;for(let i of e.settings.exclude)if((0,qu.default)(i,{dot:!0,matchBase:!i.includes("/")})(t)||!i.includes("*")&&!i.includes("?")&&!i.includes("/")&&t.startsWith(`${i}/`))return!0;return!1}async function Vu(r,e,t,n){if(ks(e.path,t))return[];let i=[],s=await r.cachedRead(e),o=Ct(s);if(o.error)return Me(i,e.path,"error","invalid_frontmatter",o.error),i;let a=o.frontmatter,c=li(e.path,a,t,n);if(c.length===0)return Me(i,e.path,"warn","no_matching_type","No type could be resolved for this file"),i;let l=c.map(d=>n.get(d)).filter(d=>!!d);if(l.length===0)return Me(i,e.path,"error","unknown_type",`Resolved types are not defined: ${c.join(", ")}`),i;for(let d of l)VO(e.path,a,d,i,r),d.specProfile==="v0.3"&&await FO(r,e.path,a,d,t,n,i);let u=t.spec_version.startsWith("0.3.")?!1:BO(l,t);if(u!==!1){let d=UO(l),f=new Set(t.settings.explicit_type_keys),p=u===!0?"error":"warn";for(let m of Object.keys(a))d.has(m)||f.has(m)||Me(i,e.path,p,"unknown_field",`Unknown field '${m}' in strict mode`,m)}return i}async function zO(r,e,t){var s,o;let n=new Map;for(let a of r.getMarkdownFiles()){if(ks(a.path,e))continue;let c=await r.cachedRead(a),l=Ct(c);if(l.error)continue;let d=li(a.path,l.frontmatter,e,t).map(f=>t.get(f)).filter(f=>!!f);for(let f of d)for(let[p,m]of Object.entries(f.fields)){if(!re(m)||m.unique!==!0)continue;let y=l.frontmatter[p];if(y==null)continue;let b=Nu(y),g=`${f.name}::${p}::${b}`,_=(s=n.get(g))!=null?s:[];_.push({path:a.path,typeName:f.name,fieldName:p,value:y,fingerprint:b}),n.set(g,_)}}let i=[];for(let a of n.values())if(!(a.length<=1))for(let c of a){let l=a.filter(u=>u.path!==c.path).map(u=>u.path).join(", ");Me(i,c.path,"error",((o=t.get(c.typeName))==null?void 0:o.specProfile)==="v0.3"?"duplicate_value":"duplicate_unique",`Field '${c.fieldName}' must be unique for type '${c.typeName}'. Duplicate found in: ${l}`,c.fieldName)}return i}async function Gb(r,e,t){let n=[];for(let s of r.getMarkdownFiles()){if(ks(s.path,e))continue;let o=await Vu(r,s,e,t);n.push(...o)}let i=await zO(r,e,t);return n.push(...i),n}function HO(r,e,t=Ut.spec_version){if(t.startsWith("0.3.")){let i={kind:"mdbase.type",name:r,version:1,description:`${r} type`,schema:{dialect:"json-schema-2020-12",value:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",required:["title"],additionalProperties:!0,properties:{title:{type:"string",minLength:1},tags:{type:"array",items:{type:"string"}}}}}};return e&&e.trim()&&(i.match={path_glob:e.trim()}),`${wt(i,`# ${r} Type definition for ${r}.`)} -`}let n={name:r,description:`${r} type`,strict:!1,fields:{title:{type:"string",required:!0}}};return e&&e.trim().length>0&&(n.match={path_glob:e.trim()}),`${at(n,`# ${r} +`}let n={name:r,description:`${r} type`,strict:!1,fields:{title:{type:"string",required:!0}}};return e&&e.trim().length>0&&(n.match={path_glob:e.trim()}),`${wt(n,`# ${r} Type definition for ${r}.`)} -`}function Sb(r,e){var s;let t={},n=(s=e.settings.explicit_type_keys[0])!=null?s:"type";t[n]=n==="types"?[r.name]:r.name;for(let[i,o]of Object.entries(r.fields)){if(!Z(o))continue;let a=o;a.default!==void 0&&(t[i]=We(a.default))}return t}function Eb(r,e){let t=[];for(let[n,s]of Object.entries(r.fields)){if(!Z(s))continue;let i=s;i.computed||i.required&&e[n]===void 0&&t.push([n,i])}return t}function wu(r,e){var s;let t=r.trim();switch((s=e.type)!=null?s:"string"){case"string":case"date":case"datetime":case"time":case"link":case"enum":case"any":return t;case"integer":{let i=Number.parseInt(t,10);if(!Number.isInteger(i))throw new Error("Expected integer input");return i}case"number":{let i=Number.parseFloat(t);if(Number.isNaN(i))throw new Error("Expected numeric input");return i}case"boolean":{let i=t.toLowerCase();if(["true","1","yes","y"].includes(i))return!0;if(["false","0","no","n"].includes(i))return!1;throw new Error("Expected boolean input: true/false")}case"list":{let i=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);return e.items?i.map(o=>wu(o,e.items)):i}case"object":{let i=(0,pe.parseYaml)(t);if(!Z(i))throw new Error("Expected YAML object value");return i}case"tags":return t.split(",").map(i=>i.trim()).filter(i=>i.length>0);default:return t}}function db(r){let e=r.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-+/,"").replace(/-+$/,"");return e.length>0?e:"note"}async function Ab(r,e){let t=(0,pe.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n=t.split("/"),s="";for(let i of n)s=s?`${s}/${i}`:i,await r.adapter.exists(s)||await r.createFolder(s)}function mT(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,pe.normalizePath)(gu(r.path_pattern,e));return t.endsWith(".md")?t:null}async function kb(r,e,t){var u;let n=mT(e,t),s=QI(e,t),i=n?(u=n.split("/").pop())!=null?u:n:ZI(e,t),o=hi(n||`${s?`${s}/`:""}${i.endsWith(".md")?i:`${i}.md`}`),a=o,c=2;for(;r.getAbstractFileByPath(a);)a=o.replace(/\.md$/,`-${c}.md`),c+=1;let l=a.lastIndexOf("/");return l>0&&await Ab(r,a.slice(0,l)),a}async function xb(r,e,t,n=""){let s=hi(e),i=s.lastIndexOf("/");if(i>0&&await Ab(r,s.slice(0,i)),await r.adapter.exists(s))throw new Error(`File already exists: ${s}`);let o=`${at(t,n)} -`;return r.create(s,o)}function ra(r){return zI(r)}var le=require("obsidian"),lw=Zr(uu(),1);var na=Symbol.for("yaml.alias"),sa=Symbol.for("yaml.document"),Ot=Symbol.for("yaml.map"),_u=Symbol.for("yaml.pair"),ct=Symbol.for("yaml.scalar"),hr=Symbol.for("yaml.seq"),Ge=Symbol.for("yaml.node.type"),Rt=r=>!!r&&typeof r=="object"&&r[Ge]===na,Mt=r=>!!r&&typeof r=="object"&&r[Ge]===sa,Ct=r=>!!r&&typeof r=="object"&&r[Ge]===Ot,ee=r=>!!r&&typeof r=="object"&&r[Ge]===_u,W=r=>!!r&&typeof r=="object"&&r[Ge]===ct,Nt=r=>!!r&&typeof r=="object"&&r[Ge]===hr;function ie(r){if(r&&typeof r=="object")switch(r[Ge]){case Ot:case hr:return!0}return!1}function re(r){if(r&&typeof r=="object")switch(r[Ge]){case na:case Ot:case ct:case hr:return!0}return!1}var ia=r=>(W(r)||ie(r))&&!!r.anchor;var tt=Symbol("break visit"),Pb=Symbol("skip children"),Zt=Symbol("remove node");function er(r,e){let t=Ib(e);Mt(r)?ts(null,r.contents,t,Object.freeze([r]))===Zt&&(r.contents=null):ts(null,r,t,Object.freeze([]))}er.BREAK=tt;er.SKIP=Pb;er.REMOVE=Zt;function ts(r,e,t,n){let s=Tb(r,e,t,n);if(re(s)||ee(s))return Ob(r,n,s),ts(r,s,t,n);if(typeof s!="symbol"){if(ie(e)){n=Object.freeze(n.concat(e));for(let i=0;ir.replace(/[!,[\]{}]/g,e=>yT[e]),tr=class r{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},r.defaultYaml,e),this.tags=Object.assign({},r.defaultTags,t)}clone(){let e=new r(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new r(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:r.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},r.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:r.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},r.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),s=n.shift();switch(s){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[i,o]=n;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[i]=n;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let o=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,o),!1}}default:return t(0,`Unknown directive ${s}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}let[,n,s]=e.match(/^(.*!)([^!]*)$/s);s||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(s)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+gT(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),s;if(e&&n.length>0&&re(e.contents)){let i={};er(e.contents,(o,a)=>{re(a)&&a.tag&&(i[a.tag]=!0)}),s=Object.keys(i)}else s=[];for(let[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||s.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(` -`)}};tr.defaultYaml={explicit:!1,version:"1.2"};tr.defaultTags={"!!":"tag:yaml.org,2002:"};function aa(r){if(/[\x00-\x19\s,[\]{}]/.test(r)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(r)}`;throw new Error(t)}return!0}function vu(r){let e=new Set;return er(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function $u(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function Rb(r,e){let t=[],n=new Map,s=null;return{onAnchor:i=>{t.push(i),s!=null||(s=vu(r));let o=$u(e,s);return s.add(o),o},setAnchors:()=>{for(let i of t){let o=n.get(i);if(typeof o=="object"&&o.anchor&&(W(o.node)||ie(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},sourceObjects:n}}function Ur(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let s=0,i=n.length;sOe(n,String(s),t));if(r&&typeof r.toJSON=="function"){if(!t||!ia(r))return r.toJSON(e,t);let n={aliasCount:0,count:1,res:void 0};t.anchors.set(r,n),t.onCreate=i=>{n.res=i,delete t.onCreate};let s=r.toJSON(e,t);return t.onCreate&&t.onCreate(s),s}return typeof r=="bigint"&&!(t!=null&&t.keep)?Number(r):r}var Hr=class{constructor(e){Object.defineProperty(this,Ge,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:s,reviver:i}={}){if(!Mt(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=Oe(this,"",o);if(typeof s=="function")for(let{count:c,res:l}of o.anchors.values())s(l,c);return typeof i=="function"?Ur(i,{"":a},"",a):a}};var mr=class extends Hr{constructor(e){super(na),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if((t==null?void 0:t.maxAliasCount)===0)throw new ReferenceError("Alias resolution is disabled");let n;t!=null&&t.aliasResolveCache?n=t.aliasResolveCache:(n=[],er(e,{Node:(i,o)=>{(Rt(o)||ia(o))&&n.push(o)}}),t&&(t.aliasResolveCache=n));let s;for(let i of n){if(i===this)break;i.anchor===this.source&&(s=i)}return s}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:s,maxAliasCount:i}=t,o=this.resolve(s,t);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(o);if(a||(Oe(o,null,t),a=n.get(o)),(a==null?void 0:a.res)===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=ca(s,o,n)),a.count*a.aliasCount>i)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,n){let s=`*${this.source}`;if(e){if(aa(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${s} `}return s}};function ca(r,e,t){if(Rt(e)){let n=e.resolve(r),s=t&&n&&t.get(n);return s?s.count*s.aliasCount:0}else if(ie(e)){let n=0;for(let s of e.items){let i=ca(r,s,t);i>n&&(n=i)}return n}else if(ee(e)){let n=ca(r,e.key,t),s=ca(r,e.value,t);return Math.max(n,s)}return 1}var la=r=>!r||typeof r!="function"&&typeof r!="object",F=class extends Hr{constructor(e){super(ct),this.value=e}toJSON(e,t){return t!=null&&t.keep?this.value:Oe(this.value,e,t)}toString(){return String(this.value)}};F.BLOCK_FOLDED="BLOCK_FOLDED";F.BLOCK_LITERAL="BLOCK_LITERAL";F.PLAIN="PLAIN";F.QUOTE_DOUBLE="QUOTE_DOUBLE";F.QUOTE_SINGLE="QUOTE_SINGLE";var bT="tag:yaml.org,2002:";function wT(r,e,t){var n;if(e){let s=t.filter(o=>o.tag===e),i=(n=s.find(o=>!o.format))!=null?n:s[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(s=>{var i;return((i=s.identify)==null?void 0:i.call(s,r))&&!s.format})}function yr(r,e,t){var d,f,p,m;if(Mt(r)&&(r=r.contents),re(r))return r;if(ee(r)){let h=(f=(d=t.schema[Ot]).createNode)==null?void 0:f.call(d,t.schema,null,t);return h.items.push(r),h}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt!="undefined"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:s,onTagObj:i,schema:o,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return(p=c.anchor)!=null||(c.anchor=s(r)),new mr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e!=null&&e.startsWith("!!")&&(e=bT+e.slice(2));let l=wT(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let h=new F(r);return c&&(c.node=h),h}l=r instanceof Map?o[Ot]:Symbol.iterator in Object(r)?o[hr]:o[Ot]}i&&(i(l),delete t.onTagObj);let u=l!=null&&l.createNode?l.createNode(t.schema,r,t):typeof((m=l==null?void 0:l.nodeClass)==null?void 0:m.from)=="function"?l.nodeClass.from(t.schema,r,t):new F(r);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}function yi(r,e,t){let n=t;for(let s=e.length-1;s>=0;--s){let i=e[s];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let o=[];o[i]=n,n=o}else n=new Map([[i,n]])}return yr(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:r,sourceObjects:new Map})}var ss=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,ns=class extends Hr{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>re(n)||ee(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(ss(e))this.add(t);else{let[n,...s]=e,i=this.get(n,!0);if(ie(i))i.addIn(s,t);else if(i===void 0&&this.schema)this.set(n,yi(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let s=this.get(t,!0);if(ie(s))return s.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...s]=e,i=this.get(n,!0);return s.length===0?!t&&W(i)?i.value:i:ie(i)?i.getIn(s,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ee(t))return!1;let n=t.value;return n==null||e&&W(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let s=this.get(t,!0);return ie(s)?s.hasIn(n):!1}setIn(e,t){let[n,...s]=e;if(s.length===0)this.set(n,t);else{let i=this.get(n,!0);if(ie(i))i.setIn(s,t);else if(i===void 0&&this.schema)this.set(n,yi(this.schema,s,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${s}`)}}};var Mb=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function vt(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var rr=(r,e,t)=>r.endsWith(` -`)?vt(t,e):t.includes(` +`}function Jb(r,e){var i;let t={},n=(i=e.settings.explicit_type_keys[0])!=null?i:"type";t[n]=n==="types"?[r.name]:r.name;for(let[s,o]of Object.entries(r.fields)){if(!re(o))continue;let a=o;a.default!==void 0&&(t[s]=it(a.default))}return t}function Yb(r,e){let t=[];for(let[n,i]of Object.entries(r.fields)){if(!re(i))continue;let s=i;s.computed||s.required&&e[n]===void 0&&t.push([n,s])}return t}function Uu(r,e){var i;let t=r.trim();switch((i=e.type)!=null?i:"string"){case"string":case"date":case"datetime":case"time":case"link":case"enum":case"any":return t;case"integer":{let s=Number.parseInt(t,10);if(!Number.isInteger(s))throw new Error("Expected integer input");return s}case"number":{let s=Number.parseFloat(t);if(Number.isNaN(s))throw new Error("Expected numeric input");return s}case"boolean":{let s=t.toLowerCase();if(["true","1","yes","y"].includes(s))return!0;if(["false","0","no","n"].includes(s))return!1;throw new Error("Expected boolean input: true/false")}case"list":{let s=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);return e.items?s.map(o=>Uu(o,e.items)):s}case"object":{let s=(0,ge.parseYaml)(t);if(!re(s))throw new Error("Expected YAML object value");return s}case"tags":return t.split(",").map(s=>s.trim()).filter(s=>s.length>0);default:return t}}function Lb(r){let e=r.toLowerCase().replace(/[^a-z0-9\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-+/,"").replace(/-+$/,"");return e.length>0?e:"note"}async function Xb(r,e){let t=(0,ge.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n=t.split("/"),i="";for(let s of n)i=i?`${i}/${s}`:s,await r.adapter.exists(i)||await r.createFolder(i)}function KO(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,ge.normalizePath)(Fu(r.path_pattern,e));return t.endsWith(".md")?t:null}async function Qb(r,e,t){var u;let n=KO(e,t),i=IO(e,t),s=n?(u=n.split("/").pop())!=null?u:n:OO(e,t),o=As(n||`${i?`${i}/`:""}${s.endsWith(".md")?s:`${s}.md`}`),a=o,c=2;for(;r.getAbstractFileByPath(a);)a=o.replace(/\.md$/,`-${c}.md`),c+=1;let l=a.lastIndexOf("/");return l>0&&await Xb(r,a.slice(0,l)),a}async function Zb(r,e,t,n=""){let i=As(e),s=i.lastIndexOf("/");if(s>0&&await Xb(r,i.slice(0,s)),await r.adapter.exists(i))throw new Error(`File already exists: ${i}`);let o=`${wt(t,n)} +`;return r.create(i,o)}function ya(r){return $O(r)}var ae=require("obsidian"),Uw=ln(Mu(),1);var ga=Symbol.for("yaml.alias"),ba=Symbol.for("yaml.document"),Bt=Symbol.for("yaml.map"),Bu=Symbol.for("yaml.pair"),vt=Symbol.for("yaml.scalar"),Ar=Symbol.for("yaml.seq"),st=Symbol.for("yaml.node.type"),zt=r=>!!r&&typeof r=="object"&&r[st]===ga,Ht=r=>!!r&&typeof r=="object"&&r[st]===ba,Kt=r=>!!r&&typeof r=="object"&&r[st]===Bt,ne=r=>!!r&&typeof r=="object"&&r[st]===Bu,J=r=>!!r&&typeof r=="object"&&r[st]===vt,Wt=r=>!!r&&typeof r=="object"&&r[st]===Ar;function pe(r){if(r&&typeof r=="object")switch(r[st]){case Bt:case Ar:return!0}return!1}function se(r){if(r&&typeof r=="object")switch(r[st]){case ga:case Bt:case vt:case Ar:return!0}return!1}var _a=r=>(J(r)||pe(r))&&!!r.anchor;var ht=Symbol("break visit"),e_=Symbol("skip children"),fr=Symbol("remove node");function pr(r,e){let t=t_(e);Ht(r)?di(null,r.contents,t,Object.freeze([r]))===fr&&(r.contents=null):di(null,r,t,Object.freeze([]))}pr.BREAK=ht;pr.SKIP=e_;pr.REMOVE=fr;function di(r,e,t,n){let i=r_(r,e,t,n);if(se(i)||ne(i))return n_(r,n,i),di(r,i,t,n);if(typeof i!="symbol"){if(pe(e)){n=Object.freeze(n.concat(e));for(let s=0;sr.replace(/[!,[\]{}]/g,e=>WO[e]),hr=class r{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},r.defaultYaml,e),this.tags=Object.assign({},r.defaultTags,t)}clone(){let e=new r(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new r(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:r.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},r.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:r.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},r.defaultTags),this.atNextDocument=!1);let n=e.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;let[s,o]=n;return this.tags[s]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[s]=n;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let o=/^\d+\.\d+$/.test(s);return t(6,`Unsupported YAML version ${s}`,o),!1}}default:return t(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}let[,n,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);let s=this.tags[n];if(s)try{return s+decodeURIComponent(i)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+GO(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags),i;if(e&&n.length>0&&se(e.contents)){let s={};pr(e.contents,(o,a)=>{se(a)&&a.tag&&(s[a.tag]=!0)}),i=Object.keys(s)}else i=[];for(let[s,o]of n)s==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${s} ${o}`);return t.join(` +`)}};hr.defaultYaml={explicit:!1,version:"1.2"};hr.defaultTags={"!!":"tag:yaml.org,2002:"};function va(r){if(/[\x00-\x19\s,[\]{}]/.test(r)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(r)}`;throw new Error(t)}return!0}function zu(r){let e=new Set;return pr(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function Hu(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function i_(r,e){let t=[],n=new Map,i=null;return{onAnchor:s=>{t.push(s),i!=null||(i=zu(r));let o=Hu(e,i);return i.add(o),o},setAnchors:()=>{for(let s of t){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(J(o.node)||pe(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:n}}function Yr(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;iNe(n,String(i),t));if(r&&typeof r.toJSON=="function"){if(!t||!_a(r))return r.toJSON(e,t);let n={aliasCount:0,count:1,res:void 0};t.anchors.set(r,n),t.onCreate=s=>{n.res=s,delete t.onCreate};let i=r.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof r=="bigint"&&!(t!=null&&t.keep)?Number(r):r}var Xr=class{constructor(e){Object.defineProperty(this,st,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:i,reviver:s}={}){if(!Ht(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=Ne(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof s=="function"?Yr(s,{"":a},"",a):a}};var kr=class extends Xr{constructor(e){super(ga),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if((t==null?void 0:t.maxAliasCount)===0)throw new ReferenceError("Alias resolution is disabled");let n;t!=null&&t.aliasResolveCache?n=t.aliasResolveCache:(n=[],pr(e,{Node:(s,o)=>{(zt(o)||_a(o))&&n.push(o)}}),t&&(t.aliasResolveCache=n));let i;for(let s of n){if(s===this)break;s.anchor===this.source&&(i=s)}return i}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:i,maxAliasCount:s}=t,o=this.resolve(i,t);if(!o){let c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(o);if(a||(Ne(o,null,t),a=n.get(o)),(a==null?void 0:a.res)===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(s>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=$a(i,o,n)),a.count*a.aliasCount>s)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,n){let i=`*${this.source}`;if(e){if(va(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let s=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(s)}if(e.implicitKey)return`${i} `}return i}};function $a(r,e,t){if(zt(e)){let n=e.resolve(r),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(pe(e)){let n=0;for(let i of e.items){let s=$a(r,i,t);s>n&&(n=s)}return n}else if(ne(e)){let n=$a(r,e.key,t),i=$a(r,e.value,t);return Math.max(n,i)}return 1}var Sa=r=>!r||typeof r!="function"&&typeof r!="object",V=class extends Xr{constructor(e){super(vt),this.value=e}toJSON(e,t){return t!=null&&t.keep?this.value:Ne(this.value,e,t)}toString(){return String(this.value)}};V.BLOCK_FOLDED="BLOCK_FOLDED";V.BLOCK_LITERAL="BLOCK_LITERAL";V.PLAIN="PLAIN";V.QUOTE_DOUBLE="QUOTE_DOUBLE";V.QUOTE_SINGLE="QUOTE_SINGLE";var JO="tag:yaml.org,2002:";function YO(r,e,t){var n;if(e){let i=t.filter(o=>o.tag===e),s=(n=i.find(o=>!o.format))!=null?n:i[0];if(!s)throw new Error(`Tag ${e} not found`);return s}return t.find(i=>{var s;return((s=i.identify)==null?void 0:s.call(i,r))&&!i.format})}function xr(r,e,t){var d,f,p,m;if(Ht(r)&&(r=r.contents),se(r))return r;if(ne(r)){let h=(f=(d=t.schema[Bt]).createNode)==null?void 0:f.call(d,t.schema,null,t);return h.items.push(r),h}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt!="undefined"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:n,onAnchor:i,onTagObj:s,schema:o,sourceObjects:a}=t,c;if(n&&r&&typeof r=="object"){if(c=a.get(r),c)return(p=c.anchor)!=null||(c.anchor=i(r)),new kr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e!=null&&e.startsWith("!!")&&(e=JO+e.slice(2));let l=YO(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let h=new V(r);return c&&(c.node=h),h}l=r instanceof Map?o[Bt]:Symbol.iterator in Object(r)?o[Ar]:o[Bt]}s&&(s(l),delete t.onTagObj);let u=l!=null&&l.createNode?l.createNode(t.schema,r,t):typeof((m=l==null?void 0:l.nodeClass)==null?void 0:m.from)=="function"?l.nodeClass.from(t.schema,r,t):new V(r);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}function xs(r,e,t){let n=t;for(let i=e.length-1;i>=0;--i){let s=e[i];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let o=[];o[s]=n,n=o}else n=new Map([[s,n]])}return xr(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:r,sourceObjects:new Map})}var pi=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,fi=class extends Xr{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>se(n)||ne(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(pi(e))this.add(t);else{let[n,...i]=e,s=this.get(n,!0);if(pe(s))s.addIn(i,t);else if(s===void 0&&this.schema)this.set(n,xs(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let i=this.get(t,!0);if(pe(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...i]=e,s=this.get(n,!0);return i.length===0?!t&&J(s)?s.value:s:pe(s)?s.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!ne(t))return!1;let n=t.value;return n==null||e&&J(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let i=this.get(t,!0);return pe(i)?i.hasIn(n):!1}setIn(e,t){let[n,...i]=e;if(i.length===0)this.set(n,t);else{let s=this.get(n,!0);if(pe(s))s.setIn(i,t);else if(s===void 0&&this.schema)this.set(n,xs(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};var s_=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Mt(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var mr=(r,e,t)=>r.endsWith(` +`)?Mt(t,e):t.includes(` `)?` -`+vt(t,e):(r.endsWith(" ")?"":" ")+t;var Su="flow",da="block",gi="quoted";function bi(r,e,t="flow",{indentAtStart:n,lineWidth:s=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!s||s<0)return r;ss-Math.max(2,i)?l.push(0):d=s-n);let f,p,m=!1,h=-1,y=-1,b=-1;t===da&&(h=Cb(r,h,e.length),h!==-1&&(d=h+c));for(let _;_=r[h+=1];){if(t===gi&&_==="\\"){switch(y=h,r[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}b=h}if(_===` -`)t===da&&(h=Cb(r,h,e.length)),d=h+e.length+c,f=void 0;else{if(_===" "&&p&&p!==" "&&p!==` -`&&p!==" "){let I=r[h+1];I&&I!==" "&&I!==` -`&&I!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(t===gi){for(;p===" "||p===" ";)p=_,_=r[h+=1],m=!0;let I=h>b+1?h-2:y-1;if(u[I])return r;l.push(I),u[I]=!0,d=I+c,f=void 0}else m=!0}p=_}if(m&&a&&a(),l.length===0)return r;o&&o();let g=r.slice(0,l[0]);for(let _=0;_({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),pa=r=>/^(%|---|\.\.\.)/m.test(r);function _T(r,e,t){if(!e||e<0)return!1;let n=e-t,s=r.length;if(s<=n)return!1;for(let i=0,o=0;in)return!0;if(o=i+1,s-o<=n)return!1}return!0}function wi(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,s=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(pa(r)?" ":""),o="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);let u=t.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.lengthi-Math.max(2,s)?l.push(0):d=i-n);let f,p,m=!1,h=-1,y=-1,b=-1;t===Ea&&(h=o_(r,h,e.length),h!==-1&&(d=h+c));for(let _;_=r[h+=1];){if(t===Ps&&_==="\\"){switch(y=h,r[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}b=h}if(_===` +`)t===Ea&&(h=o_(r,h,e.length)),d=h+e.length+c,f=void 0;else{if(_===" "&&p&&p!==" "&&p!==` +`&&p!==" "){let k=r[h+1];k&&k!==" "&&k!==` +`&&k!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(t===Ps){for(;p===" "||p===" ";)p=_,_=r[h+=1],m=!0;let k=h>b+1?h-2:y-1;if(u[k])return r;l.push(k),u[k]=!0,d=k+c,f=void 0}else m=!0}p=_}if(m&&a&&a(),l.length===0)return r;o&&o();let g=r.slice(0,l[0]);for(let _=0;_({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),xa=r=>/^(%|---|\.\.\.)/m.test(r);function XO(r,e,t){if(!e||e<0)return!1;let n=e-t,i=r.length;if(i<=n)return!1;for(let s=0,o=0;sn)return!0;if(o=s+1,i-o<=n)return!1}return!0}function Os(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(xa(r)?" ":""),o="",a=0;for(let c=0,l=t[c];l;l=t[++c])if(l===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,l="\\"),l==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);let u=t.substr(c+2,4);switch(u){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:u.substr(0,2)==="00"?o+="\\x"+u.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.length `;let d,f;for(f=t.length;f>0;--f){let v=t[f-1];if(v!==` `&&v!==" "&&v!==" ")break}let p=t.substring(f),m=p.indexOf(` -`);m===-1?d="-":t===p||m!==p.length-1?(d="+",i&&i()):d="",p&&(t=t.slice(0,-p.length),p[p.length-1]===` -`&&(p=p.slice(0,-1)),p=p.replace(Au,`$&${l}`));let h=!1,y,b=-1;for(y=0;y{S=!0});let $=bi(`${g}${v}${p}`,l,da,k);if(!S)return`>${I} -${l}${$}`}return t=t.replace(/\n+/g,`$&${l}`),`|${I} -${l}${g}${t}${p}`}function vT(r,e,t,n){let{type:s,value:i}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=e;if(a&&i.includes(` -`)||u&&/[[\]{},]/.test(i))return is(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||u||!i.includes(` -`)?is(i,e):ua(r,e,t,n);if(!a&&!u&&s!==F.PLAIN&&i.includes(` -`))return ua(r,e,t,n);if(pa(i)){if(c==="")return e.forceBlockIndent=!0,ua(r,e,t,n);if(a&&c===l)return is(i,e)}let d=i.replace(/\n+/g,`$& -${c}`);if(o){let f=h=>{var y;return h.default&&h.tag!=="tag:yaml.org,2002:str"&&((y=h.test)==null?void 0:y.test(d))},{compat:p,tags:m}=e.doc.schema;if(m.some(f)||p!=null&&p.some(f))return is(i,e)}return a?d:bi(d,c,Su,fa(e,!1))}function hn(r,e,t,n){let{implicitKey:s,inFlow:i}=e,o=typeof r.value=="string"?r:Object.assign({},r,{value:String(r.value)}),{type:a}=r;a!==F.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=F.QUOTE_DOUBLE);let c=u=>{switch(u){case F.BLOCK_FOLDED:case F.BLOCK_LITERAL:return s||i?is(o.value,e):ua(o,e,t,n);case F.QUOTE_DOUBLE:return wi(o.value,e);case F.QUOTE_SINGLE:return Eu(o.value,e);case F.PLAIN:return vT(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:u,defaultStringType:d}=e.options,f=s&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}function ha(r,e){let t=Object.assign({blockQuote:!0,commentString:Mb,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},r.schema.toStringOptions,e),n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:r,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}function $T(r,e){var s,i,o,a;if(e.tag){let c=r.filter(l=>l.tag===e.tag);if(c.length>0)return(s=c.find(l=>l.format===e.format))!=null?s:c[0]}let t,n;if(W(e)){n=e.value;let c=r.filter(l=>{var u;return(u=l.identify)==null?void 0:u.call(l,n)});if(c.length>1){let l=c.filter(u=>u.test);l.length>0&&(c=l)}t=(i=c.find(l=>l.format===e.format))!=null?i:c.find(l=>!l.format)}else n=e,t=r.find(c=>c.nodeClass&&n instanceof c.nodeClass);if(!t){let c=(a=(o=n==null?void 0:n.constructor)==null?void 0:o.name)!=null?a:n===null?"null":typeof n;throw new Error(`Tag not resolved for ${c} value`)}return t}function ST(r,e,{anchors:t,doc:n}){var a;if(!n.directives)return"";let s=[],i=(W(r)||ie(r))&&r.anchor;i&&aa(i)&&(t.add(i),s.push(`&${i}`));let o=(a=r.tag)!=null?a:e.default?null:e.tag;return o&&s.push(n.directives.tagString(o)),s.join(" ")}function gr(r,e,t,n){var c,l;if(ee(r))return r.toString(e,t,n);if(Rt(r)){if(e.doc.directives)return r.toString(e);if((c=e.resolvedAliases)!=null&&c.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let s,i=re(r)?r:e.doc.createNode(r,{onTagObj:u=>s=u});s!=null||(s=$T(e.doc.schema.tags,i));let o=ST(i,s,e);o.length>0&&(e.indentAtStart=((l=e.indentAtStart)!=null?l:0)+o.length+1);let a=typeof s.stringify=="function"?s.stringify(i,e,t,n):W(i)?hn(i,e,t,n):i.toString(e,t,n);return o?W(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} -${e.indent}${a}`:a}function Nb({key:r,value:e},t,n,s){var k,$;let{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=t,f=re(r)&&r.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(ie(r)||!re(r)&&typeof r=="object"){let P="With simple keys, collection cannot be used as a key value";throw new Error(P)}}let p=!d&&(!r||f&&e==null&&!t.inFlow||ie(r)||(W(r)?r.type===F.BLOCK_FOLDED||r.type===F.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(d||!i),indent:a+c});let m=!1,h=!1,y=gr(r,t,()=>m=!0,()=>h=!0);if(!p&&!t.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(t.inFlow){if(i||e==null)return m&&n&&n(),y===""?"?":p?`? ${y}`:y}else if(i&&!d||e==null&&p)return y=`? ${y}`,f&&!m?y+=rr(y,t.indent,l(f)):h&&s&&s(),y;m&&(f=null),p?(f&&(y+=rr(y,t.indent,l(f))),y=`? ${y} -${a}:`):(y=`${y}:`,f&&(y+=rr(y,t.indent,l(f))));let b,g,_;re(e)?(b=!!e.spaceBefore,g=e.commentBefore,_=e.comment):(b=!1,g=null,_=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&W(e)&&(t.indentAtStart=y.length+1),h=!1,!u&&c.length>=2&&!t.inFlow&&!p&&Nt(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let I=!1,v=gr(e,t,()=>I=!0,()=>h=!0),S=" ";if(f||b||g){if(S=b?` -`:"",g){let P=l(g);S+=` -${vt(P,t.indent)}`}v===""&&!t.inFlow?S===` -`&&_&&(S=` +`);m===-1?d="-":t===p||m!==p.length-1?(d="+",s&&s()):d="",p&&(t=t.slice(0,-p.length),p[p.length-1]===` +`&&(p=p.slice(0,-1)),p=p.replace(Gu,`$&${l}`));let h=!1,y,b=-1;for(y=0;y{E=!0});let w=Is(`${g}${v}${p}`,l,Ea,O);if(!E)return`>${k} +${l}${w}`}return t=t.replace(/\n+/g,`$&${l}`),`|${k} +${l}${g}${t}${p}`}function QO(r,e,t,n){let{type:i,value:s}=r,{actualString:o,implicitKey:a,indent:c,indentStep:l,inFlow:u}=e;if(a&&s.includes(` +`)||u&&/[[\]{},]/.test(s))return hi(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes(` +`)?hi(s,e):Aa(r,e,t,n);if(!a&&!u&&i!==V.PLAIN&&s.includes(` +`))return Aa(r,e,t,n);if(xa(s)){if(c==="")return e.forceBlockIndent=!0,Aa(r,e,t,n);if(a&&c===l)return hi(s,e)}let d=s.replace(/\n+/g,`$& +${c}`);if(o){let f=h=>{var y;return h.default&&h.tag!=="tag:yaml.org,2002:str"&&((y=h.test)==null?void 0:y.test(d))},{compat:p,tags:m}=e.doc.schema;if(m.some(f)||p!=null&&p.some(f))return hi(s,e)}return a?d:Is(d,c,Ku,ka(e,!1))}function Sn(r,e,t,n){let{implicitKey:i,inFlow:s}=e,o=typeof r.value=="string"?r:Object.assign({},r,{value:String(r.value)}),{type:a}=r;a!==V.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=V.QUOTE_DOUBLE);let c=u=>{switch(u){case V.BLOCK_FOLDED:case V.BLOCK_LITERAL:return i||s?hi(o.value,e):Aa(o,e,t,n);case V.QUOTE_DOUBLE:return Os(o.value,e);case V.QUOTE_SINGLE:return Wu(o.value,e);case V.PLAIN:return QO(o,e,t,n);default:return null}},l=c(a);if(l===null){let{defaultKeyType:u,defaultStringType:d}=e.options,f=i&&u||d;if(l=c(f),l===null)throw new Error(`Unsupported default string type ${f}`)}return l}function Pa(r,e){let t=Object.assign({blockQuote:!0,commentString:s_,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},r.schema.toStringOptions,e),n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:r,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}function ZO(r,e){var i,s,o,a;if(e.tag){let c=r.filter(l=>l.tag===e.tag);if(c.length>0)return(i=c.find(l=>l.format===e.format))!=null?i:c[0]}let t,n;if(J(e)){n=e.value;let c=r.filter(l=>{var u;return(u=l.identify)==null?void 0:u.call(l,n)});if(c.length>1){let l=c.filter(u=>u.test);l.length>0&&(c=l)}t=(s=c.find(l=>l.format===e.format))!=null?s:c.find(l=>!l.format)}else n=e,t=r.find(c=>c.nodeClass&&n instanceof c.nodeClass);if(!t){let c=(a=(o=n==null?void 0:n.constructor)==null?void 0:o.name)!=null?a:n===null?"null":typeof n;throw new Error(`Tag not resolved for ${c} value`)}return t}function eT(r,e,{anchors:t,doc:n}){var a;if(!n.directives)return"";let i=[],s=(J(r)||pe(r))&&r.anchor;s&&va(s)&&(t.add(s),i.push(`&${s}`));let o=(a=r.tag)!=null?a:e.default?null:e.tag;return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Pr(r,e,t,n){var c,l;if(ne(r))return r.toString(e,t,n);if(zt(r)){if(e.doc.directives)return r.toString(e);if((c=e.resolvedAliases)!=null&&c.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let i,s=se(r)?r:e.doc.createNode(r,{onTagObj:u=>i=u});i!=null||(i=ZO(e.doc.schema.tags,s));let o=eT(s,i,e);o.length>0&&(e.indentAtStart=((l=e.indentAtStart)!=null?l:0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,e,t,n):J(s)?Sn(s,e,t,n):s.toString(e,t,n);return o?J(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${e.indent}${a}`:a}function a_({key:r,value:e},t,n,i){var O,w;let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=t,f=se(r)&&r.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(pe(r)||!se(r)&&typeof r=="object"){let x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let p=!d&&(!r||f&&e==null&&!t.inFlow||pe(r)||(J(r)?r.type===V.BLOCK_FOLDED||r.type===V.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(d||!s),indent:a+c});let m=!1,h=!1,y=Pr(r,t,()=>m=!0,()=>h=!0);if(!p&&!t.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(t.inFlow){if(s||e==null)return m&&n&&n(),y===""?"?":p?`? ${y}`:y}else if(s&&!d||e==null&&p)return y=`? ${y}`,f&&!m?y+=mr(y,t.indent,l(f)):h&&i&&i(),y;m&&(f=null),p?(f&&(y+=mr(y,t.indent,l(f))),y=`? ${y} +${a}:`):(y=`${y}:`,f&&(y+=mr(y,t.indent,l(f))));let b,g,_;se(e)?(b=!!e.spaceBefore,g=e.commentBefore,_=e.comment):(b=!1,g=null,_=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&J(e)&&(t.indentAtStart=y.length+1),h=!1,!u&&c.length>=2&&!t.inFlow&&!p&&Wt(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let k=!1,v=Pr(e,t,()=>k=!0,()=>h=!0),E=" ";if(f||b||g){if(E=b?` +`:"",g){let x=l(g);E+=` +${Mt(x,t.indent)}`}v===""&&!t.inFlow?E===` +`&&_&&(E=` -`):S+=` -${t.indent}`}else if(!p&&ie(e)){let P=v[0],w=v.indexOf(` -`),N=w!==-1,j=($=(k=t.inFlow)!=null?k:e.flow)!=null?$:e.items.length===0;if(N||!j){let H=!1;if(N&&(P==="&"||P==="!")){let A=v.indexOf(" ");P==="&"&&A!==-1&&Ar===ya||typeof r=="symbol"&&r.description===ya,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new F(Symbol(ya)),{addToJSMap:xu}),stringify:()=>ya},Lb=(r,e)=>(Lt.identify(e)||W(e)&&(!e.type||e.type===F.PLAIN)&&Lt.identify(e.value))&&(r==null?void 0:r.doc.schema.tags.some(t=>t.tag===Lt.tag&&t.default));function xu(r,e,t){let n=Db(r,t);if(Nt(n))for(let s of n.items)ku(r,e,s);else if(Array.isArray(n))for(let s of n)ku(r,e,s);else ku(r,e,n)}function ku(r,e,t){let n=Db(r,t);if(!Ct(n))throw new Error("Merge sources must be maps or map aliases");let s=n.toJSON(null,r,Map);for(let[i,o]of s)e instanceof Map?e.has(i)||e.set(i,o):e instanceof Set?e.add(i):Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function Db(r,e){return r&&Rt(e)?e.resolve(r.doc,r):e}function ga(r,e,{key:t,value:n}){if(re(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(Lb(r,t))xu(r,e,n);else{let s=Oe(t,"",r);if(e instanceof Map)e.set(s,Oe(n,s,r));else if(e instanceof Set)e.add(s);else{let i=ET(t,s,r),o=Oe(n,i,r);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}function ET(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(re(r)&&(t!=null&&t.doc)){let n=ha(t.doc,{});n.anchors=new Set;for(let i of t.anchors.keys())n.anchors.add(i.anchor);n.inFlow=!0,n.inStringifyKey=!0;let s=r.toString(n);if(!t.mapKeyWarned){let i=JSON.stringify(s);i.length>40&&(i=i.substring(0,36)+'..."'),ma(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return s}return JSON.stringify(e)}function os(r,e,t){let n=yr(r,void 0,t),s=yr(e,void 0,t);return new $e(n,s)}var $e=class r{constructor(e,t=null){Object.defineProperty(this,Ge,{value:_u}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return re(t)&&(t=t.clone(e)),re(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t!=null&&t.mapAsMap?new Map:{};return ga(t,n,this)}toString(e,t,n){return e!=null&&e.doc?Nb(this,e,t,n):JSON.stringify(this)}};function wa(r,e,t){var i;return(((i=e.inFlow)!=null?i:r.flow)?kT:AT)(r,e,t)}function AT({comment:r,items:e},t,{blockItemPrefix:n,flowChars:s,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,u=Object.assign({},t,{indent:i,type:null}),d=!1,f=[];for(let m=0;my=null,()=>d=!0);y&&(b+=rr(b,i,l(y))),d&&y&&(d=!1),f.push(n+b)}let p;if(f.length===0)p=s.start+s.end;else{p=f[0];for(let m=1;mr===Oa||typeof r=="symbol"&&r.description===Oa,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new V(Symbol(Oa)),{addToJSMap:Yu}),stringify:()=>Oa},c_=(r,e)=>(Gt.identify(e)||J(e)&&(!e.type||e.type===V.PLAIN)&&Gt.identify(e.value))&&(r==null?void 0:r.doc.schema.tags.some(t=>t.tag===Gt.tag&&t.default));function Yu(r,e,t){let n=l_(r,t);if(Wt(n))for(let i of n.items)Ju(r,e,i);else if(Array.isArray(n))for(let i of n)Ju(r,e,i);else Ju(r,e,n)}function Ju(r,e,t){let n=l_(r,t);if(!Kt(n))throw new Error("Merge sources must be maps or map aliases");let i=n.toJSON(null,r,Map);for(let[s,o]of i)e instanceof Map?e.has(s)||e.set(s,o):e instanceof Set?e.add(s):Object.prototype.hasOwnProperty.call(e,s)||Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}function l_(r,e){return r&&zt(e)?e.resolve(r.doc,r):e}function Ta(r,e,{key:t,value:n}){if(se(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(c_(r,t))Yu(r,e,n);else{let i=Ne(t,"",r);if(e instanceof Map)e.set(i,Ne(n,i,r));else if(e instanceof Set)e.add(i);else{let s=tT(t,i,r),o=Ne(n,s,r);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function tT(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(se(r)&&(t!=null&&t.doc)){let n=Pa(t.doc,{});n.anchors=new Set;for(let s of t.anchors.keys())n.anchors.add(s.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=r.toString(n);if(!t.mapKeyWarned){let s=JSON.stringify(i);s.length>40&&(s=s.substring(0,36)+'..."'),Ia(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${s}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return i}return JSON.stringify(e)}function mi(r,e,t){let n=xr(r,void 0,t),i=xr(e,void 0,t);return new Ee(n,i)}var Ee=class r{constructor(e,t=null){Object.defineProperty(this,st,{value:Bu}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return se(t)&&(t=t.clone(e)),se(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t!=null&&t.mapAsMap?new Map:{};return Ta(t,n,this)}toString(e,t,n){return e!=null&&e.doc?a_(this,e,t,n):JSON.stringify(this)}};function Ca(r,e,t){var s;return(((s=e.inFlow)!=null?s:r.flow)?nT:rT)(r,e,t)}function rT({comment:r,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:s,onChompKeep:o,onComment:a}){let{indent:c,options:{commentString:l}}=t,u=Object.assign({},t,{indent:s,type:null}),d=!1,f=[];for(let m=0;my=null,()=>d=!0);y&&(b+=mr(b,s,l(y))),d&&y&&(d=!1),f.push(n+b)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let m=1;my=null);l||(l=d.length>u||b.includes(` -`)),m0&&(l||(l=d.reduce((g,_)=>g+_.length+2,2)+(b.length+2)>e.options.lineWidth)),l&&(b+=",")),y&&(b+=rr(b,n,a(y))),d.push(b),u=d.length}let{start:f,end:p}=t;if(d.length===0)return f+p;if(!l){let m=d.reduce((h,y)=>h+y.length+2,2);l=e.options.lineWidth>0&&m>e.options.lineWidth}if(l){let m=f;for(let h of d)m+=h?` -${i}${s}${h}`:` +`+Mt(l(r),c),a&&a()):d&&o&&o(),p}function nT({items:r},e,{flowChars:t,itemIndent:n}){let{indent:i,indentStep:s,flowCollectionPadding:o,options:{commentString:a}}=e;n+=s;let c=Object.assign({},e,{indent:n,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let m=0;my=null);l||(l=d.length>u||b.includes(` +`)),m0&&(l||(l=d.reduce((g,_)=>g+_.length+2,2)+(b.length+2)>e.options.lineWidth)),l&&(b+=",")),y&&(b+=mr(b,n,a(y))),d.push(b),u=d.length}let{start:f,end:p}=t;if(d.length===0)return f+p;if(!l){let m=d.reduce((h,y)=>h+y.length+2,2);l=e.options.lineWidth>0&&m>e.options.lineWidth}if(l){let m=f;for(let h of d)m+=h?` +${s}${i}${h}`:` `;return`${m} -${s}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function ba({indent:r,options:{commentString:e}},t,n,s){if(n&&s&&(n=n.replace(/^\n+/,"")),n){let i=vt(e(n),r);t.push(i.trimStart())}}function Br(r,e){let t=W(e)?e.value:e;for(let n of r)if(ee(n)&&(n.key===e||n.key===t||W(n.key)&&n.key.value===t))return n}var ke=class extends ns{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ot,e),this.items=[]}static from(e,t,n){let{keepUndefined:s,replacer:i}=n,o=new this(e),a=(c,l)=>{if(typeof i=="function")l=i.call(t,c,l);else if(Array.isArray(i)&&!i.includes(c))return;(l!==void 0||s)&&o.items.push(os(c,l,n))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){var o;let n;ee(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new $e(e,e==null?void 0:e.value):n=new $e(e.key,e.value);let s=Br(this.items,n.key),i=(o=this.schema)==null?void 0:o.sortMapEntries;if(s){if(!t)throw new Error(`Key ${n.key} already set`);W(s.value)&&la(n.value)?s.value.value=n.value:s.value=n.value}else if(i){let a=this.items.findIndex(c=>i(n,c)<0);a===-1?this.items.push(n):this.items.splice(a,0,n)}else this.items.push(n)}delete(e){let t=Br(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){var i;let n=Br(this.items,e),s=n==null?void 0:n.value;return(i=!t&&W(s)?s.value:s)!=null?i:void 0}has(e){return!!Br(this.items,e)}set(e,t){this.add(new $e(e,t),!0)}toJSON(e,t,n){let s=n?new n:t!=null&&t.mapAsMap?new Map:{};t!=null&&t.onCreate&&t.onCreate(s);for(let i of this.items)ga(t,s,i);return s}toString(e,t,n){if(!e)return JSON.stringify(this);for(let s of this.items)if(!ee(s))throw new Error(`Map items must all be pairs; found ${JSON.stringify(s)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),wa(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var Dt={collection:"map",default:!0,nodeClass:ke,tag:"tag:yaml.org,2002:map",resolve(r,e){return Ct(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>ke.from(r,e,t)};var Ve=class extends ns{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(hr,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=_a(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=_a(e);if(typeof n!="number")return;let s=this.items[n];return!t&&W(s)?s.value:s}has(e){let t=_a(e);return typeof t=="number"&&t=0?e:null}var qt={collection:"seq",default:!0,nodeClass:Ve,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Nt(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Ve.from(r,e,t)};var zr={identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify(r,e,t,n){return e=Object.assign({actualString:!0},e),hn(r,e,t,n)}};var mn={identify:r=>r==null,createNode:()=>new F(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new F(null),stringify:({source:r},e)=>typeof r=="string"&&mn.test.test(r)?r:e.options.nullStr};var _i={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new F(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&_i.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};function Ue({format:r,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);let s=typeof n=="number"?n:Number(n);if(!isFinite(s))return isNaN(s)?".nan":s<0?"-.inf":".inf";let i=Object.is(n,-0)?"-0":JSON.stringify(n);if(!r&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^-?\d/.test(i)&&!i.includes("e")){let o=i.indexOf(".");o<0&&(o=i.length,i+=".");let a=e-(i.length-o-1);for(;a-- >0;)i+="0"}return i}var va={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ue},$a={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Ue(r)}},Sa={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(r){let e=new F(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:Ue};var Ea=r=>typeof r=="bigint"||Number.isInteger(r),Pu=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function qb(r,e,t){let{value:n}=r;return Ea(n)&&n>=0?t+n.toString(e):Ue(r)}var Aa={identify:r=>Ea(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>Pu(r,2,8,t),stringify:r=>qb(r,8,"0o")},ka={identify:Ea,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>Pu(r,0,10,t),stringify:Ue},xa={identify:r=>Ea(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>Pu(r,2,16,t),stringify:r=>qb(r,16,"0x")};var jb=[Dt,qt,zr,mn,_i,Aa,ka,xa,va,$a,Sa];function Fb(r){return typeof r=="bigint"||Number.isInteger(r)}var Pa=({value:r})=>JSON.stringify(r),xT=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Pa},{identify:r=>r==null,createNode:()=>new F(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Pa},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Pa},{identify:Fb,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(r,e,{intAsBigInt:t})=>t?BigInt(r):parseInt(r,10),stringify:({value:r})=>Fb(r)?r.toString():JSON.stringify(r)},{identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:r=>parseFloat(r),stringify:Pa}],PT={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},Vb=[Dt,qt].concat(xT,PT);var vi={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof atob=="function"){let t=atob(r.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let s=0;s1&&e("Each pair must have its own sequence indicator");let i=s.items[0]||new $e(new F(null));if(s.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${s.commentBefore} -${i.key.commentBefore}`:s.commentBefore),s.comment){let o=(t=i.value)!=null?t:i.key;o.comment=o.comment?`${s.comment} -${o.comment}`:s.comment}s=i}r.items[n]=ee(s)?s:new $e(s)}}else e("Expected a sequence for this tag");return r}function Tu(r,e,t){let{replacer:n}=t,s=new Ve(r);s.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(i++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;s.items.push(os(a,c,t))}return s}var $i={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Iu,createNode:Tu};var as=class r extends Ve{constructor(){super(),this.add=ke.prototype.add.bind(this),this.delete=ke.prototype.delete.bind(this),this.get=ke.prototype.get.bind(this),this.has=ke.prototype.has.bind(this),this.set=ke.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t!=null&&t.onCreate&&t.onCreate(n);for(let s of this.items){let i,o;if(ee(s)?(i=Oe(s.key,"",t),o=Oe(s.value,i,t)):i=Oe(s,"",t),n.has(i))throw new Error("Ordered maps must not include duplicate keys");n.set(i,o)}return n}static from(e,t,n){let s=Tu(e,t,n),i=new this;return i.items=s.items,i}};as.tag="tag:yaml.org,2002:omap";var Si={collection:"seq",identify:r=>r instanceof Map,nodeClass:as,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Iu(r,e),n=[];for(let{key:s}of t.items)W(s)&&(n.includes(s.value)?e(`Ordered maps must not include duplicate keys: ${s.value}`):n.push(s.value));return Object.assign(new as,t)},createNode:(r,e,t)=>as.from(r,e,t)};function Ub({value:r,source:e},t){return e&&(r?Ou:Ru).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Ou={identify:r=>r===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new F(!0),stringify:Ub},Ru={identify:r=>r===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new F(!1),stringify:Ub};var Hb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ue},Bb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Ue(r)}},zb={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(r){let e=new F(parseFloat(r.replace(/_/g,""))),t=r.indexOf(".");if(t!==-1){let n=r.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:Ue};var Ei=r=>typeof r=="bigint"||Number.isInteger(r);function Ia(r,e,t,{intAsBigInt:n}){let s=r[0];if((s==="-"||s==="+")&&(e+=1),r=r.substring(e).replace(/_/g,""),n){switch(t){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}let o=BigInt(r);return s==="-"?BigInt(-1)*o:o}let i=parseInt(r,t);return s==="-"?-1*i:i}function Mu(r,e,t){let{value:n}=r;if(Ei(n)){let s=n.toString(e);return n<0?"-"+t+s.substr(1):t+s}return Ue(r)}var Kb={identify:Ei,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Ia(r,2,2,t),stringify:r=>Mu(r,2,"0b")},Wb={identify:Ei,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Ia(r,1,8,t),stringify:r=>Mu(r,8,"0")},Gb={identify:Ei,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Ia(r,0,10,t),stringify:Ue},Jb={identify:Ei,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Ia(r,2,16,t),stringify:r=>Mu(r,16,"0x")};var cs=class r extends ke{constructor(e){super(e),this.tag=r.tag}add(e){let t;ee(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new $e(e.key,null):t=new $e(e,null),Br(this.items,t.key)||this.items.push(t)}get(e,t){let n=Br(this.items,e);return!t&&ee(n)?W(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=Br(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new $e(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){let{replacer:s}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof s=="function"&&(o=s.call(t,o,o)),i.items.push(os(o,null,n));return i}};cs.tag="tag:yaml.org,2002:set";var Ai={collection:"map",identify:r=>r instanceof Set,nodeClass:cs,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>cs.from(r,e,t),resolve(r,e){if(Ct(r)){if(r.hasAllNullValues(!0))return Object.assign(new cs,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function Cu(r,e){let t=r[0],n=t==="-"||t==="+"?r.substring(1):r,s=o=>e?BigInt(o):Number(o),i=n.replace(/_/g,"").split(":").reduce((o,a)=>o*s(60)+s(a),s(0));return t==="-"?s(-1)*i:i}function Yb(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Ue(r);let n="";e<0&&(n="-",e*=t(-1));let s=t(60),i=[e%s];return e<60?i.unshift(0):(e=(e-i[0])/s,i.unshift(e%s),e>=60&&(e=(e-i[0])/s,i.unshift(e))),n+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Ta={identify:r=>typeof r=="bigint"||Number.isInteger(r),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(r,e,{intAsBigInt:t})=>Cu(r,t),stringify:Yb},Oa={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:r=>Cu(r,!1),stringify:Yb},ls={identify:r=>r instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(r){let e=r.match(ls.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,s,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,s,i||0,o||0,a||0,c),u=e[8];if(u&&u!=="Z"){let d=Cu(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:r})=>{var e;return(e=r==null?void 0:r.toISOString().replace(/(T00:00:00)?\.000Z$/,""))!=null?e:""}};var Nu=[Dt,qt,zr,mn,Ou,Ru,Kb,Wb,Gb,Jb,Hb,Bb,zb,vi,Lt,Si,$i,Ai,Ta,Oa,ls];var Xb=new Map([["core",jb],["failsafe",[Dt,qt,zr]],["json",Vb],["yaml11",Nu],["yaml-1.1",Nu]]),Qb={binary:vi,bool:_i,float:Sa,floatExp:$a,floatNaN:va,floatTime:Oa,int:ka,intHex:xa,intOct:Aa,intTime:Ta,map:Dt,merge:Lt,null:mn,omap:Si,pairs:$i,seq:qt,set:Ai,timestamp:ls},Zb={"tag:yaml.org,2002:binary":vi,"tag:yaml.org,2002:merge":Lt,"tag:yaml.org,2002:omap":Si,"tag:yaml.org,2002:pairs":$i,"tag:yaml.org,2002:set":Ai,"tag:yaml.org,2002:timestamp":ls};function Ra(r,e,t){let n=Xb.get(e);if(n&&!r)return t&&!n.includes(Lt)?n.concat(Lt):n.slice();let s=n;if(!s)if(Array.isArray(r))s=[];else{let i=Array.from(Xb.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(r))for(let i of r)s=s.concat(i);else typeof r=="function"&&(s=r(s.slice()));return t&&(s=s.concat(Lt)),s.reduce((i,o)=>{let a=typeof o=="string"?Qb[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Qb).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return i.includes(a)||i.push(a),i},[])}var IT=(r,e)=>r.keye.key?1:0,ki=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:s,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Ra(e,"compat"):e?Ra(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=s?Zb:{},this.tags=Ra(t,this.name,n),this.toStringOptions=a!=null?a:null,Object.defineProperty(this,Ot,{value:Dt}),Object.defineProperty(this,ct,{value:zr}),Object.defineProperty(this,hr,{value:qt}),this.sortMapEntries=typeof o=="function"?o:o===!0?IT:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function e0(r,e){var c;let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let l=r.directives.toString(r);l?(t.push(l),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let s=ha(r,e),{commentString:i}=s.options;if(r.commentBefore){t.length!==1&&t.unshift("");let l=i(r.commentBefore);t.unshift(vt(l,""))}let o=!1,a=null;if(r.contents){if(re(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let d=i(r.contents.commentBefore);t.push(vt(d,""))}s.forceBlockIndent=!!r.comment,a=r.contents.comment}let l=a?void 0:()=>o=!0,u=gr(r.contents,s,()=>a=null,l);a&&(u+=rr(u,"",i(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(gr(r.contents,s));if((c=r.directives)!=null&&c.docEnd)if(r.comment){let l=i(r.comment);l.includes(` -`)?(t.push("..."),t.push(vt(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=r.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(vt(i(l),"")))}return t.join(` +${i}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function Ra({indent:r,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=Mt(e(n),r);t.push(s.trimStart())}}function Qr(r,e){let t=J(e)?e.value:e;for(let n of r)if(ne(n)&&(n.key===e||n.key===t||J(n.key)&&n.key.value===t))return n}var Ie=class extends fi{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Bt,e),this.items=[]}static from(e,t,n){let{keepUndefined:i,replacer:s}=n,o=new this(e),a=(c,l)=>{if(typeof s=="function")l=s.call(t,c,l);else if(Array.isArray(s)&&!s.includes(c))return;(l!==void 0||i)&&o.items.push(mi(c,l,n))};if(t instanceof Map)for(let[c,l]of t)a(c,l);else if(t&&typeof t=="object")for(let c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){var o;let n;ne(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Ee(e,e==null?void 0:e.value):n=new Ee(e.key,e.value);let i=Qr(this.items,n.key),s=(o=this.schema)==null?void 0:o.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);J(i.value)&&Sa(n.value)?i.value.value=n.value:i.value=n.value}else if(s){let a=this.items.findIndex(c=>s(n,c)<0);a===-1?this.items.push(n):this.items.splice(a,0,n)}else this.items.push(n)}delete(e){let t=Qr(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){var s;let n=Qr(this.items,e),i=n==null?void 0:n.value;return(s=!t&&J(i)?i.value:i)!=null?s:void 0}has(e){return!!Qr(this.items,e)}set(e,t){this.add(new Ee(e,t),!0)}toJSON(e,t,n){let i=n?new n:t!=null&&t.mapAsMap?new Map:{};t!=null&&t.onCreate&&t.onCreate(i);for(let s of this.items)Ta(t,i,s);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!ne(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Ca(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var Jt={collection:"map",default:!0,nodeClass:Ie,tag:"tag:yaml.org,2002:map",resolve(r,e){return Kt(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Ie.from(r,e,t)};var Ge=class extends fi{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ar,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Ma(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=Ma(e);if(typeof n!="number")return;let i=this.items[n];return!t&&J(i)?i.value:i}has(e){let t=Ma(e);return typeof t=="number"&&t=0?e:null}var Yt={collection:"seq",default:!0,nodeClass:Ge,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Wt(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Ge.from(r,e,t)};var Zr={identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify(r,e,t,n){return e=Object.assign({actualString:!0},e),Sn(r,e,t,n)}};var En={identify:r=>r==null,createNode:()=>new V(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new V(null),stringify:({source:r},e)=>typeof r=="string"&&En.test.test(r)?r:e.options.nullStr};var Ts={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new V(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Ts.test.test(r)){let n=r[0]==="t"||r[0]==="T";if(e===n)return r}return e?t.options.trueStr:t.options.falseStr}};function Je({format:r,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);let i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let s=Object.is(n,-0)?"-0":JSON.stringify(n);if(!r&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^-?\d/.test(s)&&!s.includes("e")){let o=s.indexOf(".");o<0&&(o=s.length,s+=".");let a=e-(s.length-o-1);for(;a-- >0;)s+="0"}return s}var Na={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Je},La={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Je(r)}},Da={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(r){let e=new V(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:Je};var qa=r=>typeof r=="bigint"||Number.isInteger(r),Xu=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function d_(r,e,t){let{value:n}=r;return qa(n)&&n>=0?t+n.toString(e):Je(r)}var ja={identify:r=>qa(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>Xu(r,2,8,t),stringify:r=>d_(r,8,"0o")},Fa={identify:qa,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>Xu(r,0,10,t),stringify:Je},Va={identify:r=>qa(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>Xu(r,2,16,t),stringify:r=>d_(r,16,"0x")};var u_=[Jt,Yt,Zr,En,Ts,ja,Fa,Va,Na,La,Da];function f_(r){return typeof r=="bigint"||Number.isInteger(r)}var Ua=({value:r})=>JSON.stringify(r),iT=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Ua},{identify:r=>r==null,createNode:()=>new V(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ua},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Ua},{identify:f_,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(r,e,{intAsBigInt:t})=>t?BigInt(r):parseInt(r,10),stringify:({value:r})=>f_(r)?r.toString():JSON.stringify(r)},{identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:r=>parseFloat(r),stringify:Ua}],sT={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},p_=[Jt,Yt].concat(iT,sT);var Rs={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof atob=="function"){let t=atob(r.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let i=0;i1&&e("Each pair must have its own sequence indicator");let s=i.items[0]||new Ee(new V(null));if(i.commentBefore&&(s.key.commentBefore=s.key.commentBefore?`${i.commentBefore} +${s.key.commentBefore}`:i.commentBefore),i.comment){let o=(t=s.value)!=null?t:s.key;o.comment=o.comment?`${i.comment} +${o.comment}`:i.comment}i=s}r.items[n]=ne(i)?i:new Ee(i)}}else e("Expected a sequence for this tag");return r}function Zu(r,e,t){let{replacer:n}=t,i=new Ge(r);i.tag="tag:yaml.org,2002:pairs";let s=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(s++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let l=Object.keys(o);if(l.length===1)a=l[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${l.length} keys`)}else a=o;i.items.push(mi(a,c,t))}return i}var Cs={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Qu,createNode:Zu};var yi=class r extends Ge{constructor(){super(),this.add=Ie.prototype.add.bind(this),this.delete=Ie.prototype.delete.bind(this),this.get=Ie.prototype.get.bind(this),this.has=Ie.prototype.has.bind(this),this.set=Ie.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t!=null&&t.onCreate&&t.onCreate(n);for(let i of this.items){let s,o;if(ne(i)?(s=Ne(i.key,"",t),o=Ne(i.value,s,t)):s=Ne(i,"",t),n.has(s))throw new Error("Ordered maps must not include duplicate keys");n.set(s,o)}return n}static from(e,t,n){let i=Zu(e,t,n),s=new this;return s.items=i.items,s}};yi.tag="tag:yaml.org,2002:omap";var Ms={collection:"seq",identify:r=>r instanceof Map,nodeClass:yi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Qu(r,e),n=[];for(let{key:i}of t.items)J(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new yi,t)},createNode:(r,e,t)=>yi.from(r,e,t)};function h_({value:r,source:e},t){return e&&(r?ef:tf).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var ef={identify:r=>r===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new V(!0),stringify:h_},tf={identify:r=>r===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new V(!1),stringify:h_};var m_={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Je},y_={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():Je(r)}},g_={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(r){let e=new V(parseFloat(r.replace(/_/g,""))),t=r.indexOf(".");if(t!==-1){let n=r.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:Je};var Ns=r=>typeof r=="bigint"||Number.isInteger(r);function Ba(r,e,t,{intAsBigInt:n}){let i=r[0];if((i==="-"||i==="+")&&(e+=1),r=r.substring(e).replace(/_/g,""),n){switch(t){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}let o=BigInt(r);return i==="-"?BigInt(-1)*o:o}let s=parseInt(r,t);return i==="-"?-1*s:s}function rf(r,e,t){let{value:n}=r;if(Ns(n)){let i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return Je(r)}var b_={identify:Ns,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Ba(r,2,2,t),stringify:r=>rf(r,2,"0b")},__={identify:Ns,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Ba(r,1,8,t),stringify:r=>rf(r,8,"0")},w_={identify:Ns,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Ba(r,0,10,t),stringify:Je},v_={identify:Ns,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Ba(r,2,16,t),stringify:r=>rf(r,16,"0x")};var gi=class r extends Ie{constructor(e){super(e),this.tag=r.tag}add(e){let t;ne(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Ee(e.key,null):t=new Ee(e,null),Qr(this.items,t.key)||this.items.push(t)}get(e,t){let n=Qr(this.items,e);return!t&&ne(n)?J(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=Qr(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Ee(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){let{replacer:i}=n,s=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof i=="function"&&(o=i.call(t,o,o)),s.items.push(mi(o,null,n));return s}};gi.tag="tag:yaml.org,2002:set";var Ls={collection:"map",identify:r=>r instanceof Set,nodeClass:gi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>gi.from(r,e,t),resolve(r,e){if(Kt(r)){if(r.hasAllNullValues(!0))return Object.assign(new gi,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function nf(r,e){let t=r[0],n=t==="-"||t==="+"?r.substring(1):r,i=o=>e?BigInt(o):Number(o),s=n.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return t==="-"?i(-1)*s:s}function $_(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Je(r);let n="";e<0&&(n="-",e*=t(-1));let i=t(60),s=[e%i];return e<60?s.unshift(0):(e=(e-s[0])/i,s.unshift(e%i),e>=60&&(e=(e-s[0])/i,s.unshift(e))),n+s.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var za={identify:r=>typeof r=="bigint"||Number.isInteger(r),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(r,e,{intAsBigInt:t})=>nf(r,t),stringify:$_},Ha={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:r=>nf(r,!1),stringify:$_},bi={identify:r=>r instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(r){let e=r.match(bi.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,n,i,s,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0,l=Date.UTC(t,n-1,i,s||0,o||0,a||0,c),u=e[8];if(u&&u!=="Z"){let d=nf(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:r})=>{var e;return(e=r==null?void 0:r.toISOString().replace(/(T00:00:00)?\.000Z$/,""))!=null?e:""}};var sf=[Jt,Yt,Zr,En,ef,tf,b_,__,w_,v_,m_,y_,g_,Rs,Gt,Ms,Cs,Ls,za,Ha,bi];var S_=new Map([["core",u_],["failsafe",[Jt,Yt,Zr]],["json",p_],["yaml11",sf],["yaml-1.1",sf]]),E_={binary:Rs,bool:Ts,float:Da,floatExp:La,floatNaN:Na,floatTime:Ha,int:Fa,intHex:Va,intOct:ja,intTime:za,map:Jt,merge:Gt,null:En,omap:Ms,pairs:Cs,seq:Yt,set:Ls,timestamp:bi},A_={"tag:yaml.org,2002:binary":Rs,"tag:yaml.org,2002:merge":Gt,"tag:yaml.org,2002:omap":Ms,"tag:yaml.org,2002:pairs":Cs,"tag:yaml.org,2002:set":Ls,"tag:yaml.org,2002:timestamp":bi};function Ka(r,e,t){let n=S_.get(e);if(n&&!r)return t&&!n.includes(Gt)?n.concat(Gt):n.slice();let i=n;if(!i)if(Array.isArray(r))i=[];else{let s=Array.from(S_.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${s} or define customTags array`)}if(Array.isArray(r))for(let s of r)i=i.concat(s);else typeof r=="function"&&(i=r(i.slice()));return t&&(i=i.concat(Gt)),i.reduce((s,o)=>{let a=typeof o=="string"?E_[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(E_).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${l}`)}return s.includes(a)||s.push(a),s},[])}var oT=(r,e)=>r.keye.key?1:0,Ds=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Ka(e,"compat"):e?Ka(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?A_:{},this.tags=Ka(t,this.name,n),this.toStringOptions=a!=null?a:null,Object.defineProperty(this,Bt,{value:Jt}),Object.defineProperty(this,vt,{value:Zr}),Object.defineProperty(this,Ar,{value:Yt}),this.sortMapEntries=typeof o=="function"?o:o===!0?oT:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function k_(r,e){var c;let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let l=r.directives.toString(r);l?(t.push(l),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let i=Pa(r,e),{commentString:s}=i.options;if(r.commentBefore){t.length!==1&&t.unshift("");let l=s(r.commentBefore);t.unshift(Mt(l,""))}let o=!1,a=null;if(r.contents){if(se(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let d=s(r.contents.commentBefore);t.push(Mt(d,""))}i.forceBlockIndent=!!r.comment,a=r.contents.comment}let l=a?void 0:()=>o=!0,u=Pr(r.contents,i,()=>a=null,l);a&&(u+=mr(u,"",s(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(Pr(r.contents,i));if((c=r.directives)!=null&&c.docEnd)if(r.comment){let l=s(r.comment);l.includes(` +`)?(t.push("..."),t.push(Mt(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=r.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(Mt(s(l),"")))}return t.join(` `)+` -`}var br=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ge,{value:sa});let s=null;typeof t=="function"||Array.isArray(t)?s=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=i;let{version:o}=i;n!=null&&n._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new tr({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,s,n)}clone(){let e=Object.create(r.prototype,{[Ge]:{value:sa}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=re(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){ds(this.contents)&&this.contents.add(e)}addIn(e,t){ds(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=vu(this);e.anchor=!t||n.has(t)?$u(t||"a",n):t}return new mr(e.anchor)}createNode(e,t,n){let s;if(typeof t=="function")e=t.call({"":e},"",e),s=t;else if(Array.isArray(t)){let y=g=>typeof g=="number"||g instanceof String||g instanceof Number,b=t.filter(y).map(String);b.length>0&&(t=t.concat(b)),s=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:u}=n!=null?n:{},{onAnchor:d,setAnchors:f,sourceObjects:p}=Rb(this,o||"a"),m={aliasDuplicateObjects:i!=null?i:!0,keepUndefined:c!=null?c:!1,onAnchor:d,onTagObj:l,replacer:s,schema:this.schema,sourceObjects:p},h=yr(e,u,m);return a&&ie(h)&&(h.flow=!0),f(),h}createPair(e,t,n={}){let s=this.createNode(e,null,n),i=this.createNode(t,null,n);return new $e(s,i)}delete(e){return ds(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ss(e)?this.contents==null?!1:(this.contents=null,!0):ds(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return ie(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return ss(e)?!t&&W(this.contents)?this.contents.value:this.contents:ie(this.contents)?this.contents.getIn(e,t):void 0}has(e){return ie(this.contents)?this.contents.has(e):!1}hasIn(e){return ss(e)?this.contents!==void 0:ie(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=yi(this.schema,[e],t):ds(this.contents)&&this.contents.set(e,t)}setIn(e,t){ss(e)?this.contents=t:this.contents==null?this.contents=yi(this.schema,Array.from(e),t):ds(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new tr({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new tr({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let s=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${s}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new ki(Object.assign(n,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:s,onAnchor:i,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},c=Oe(this.contents,t!=null?t:"",a);if(typeof i=="function")for(let{count:l,res:u}of a.anchors.values())i(u,l);return typeof o=="function"?Ur(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return e0(this,e)}};function ds(r){if(ie(r))return!0;throw new Error("Expected a YAML collection as document contents")}var xi=class extends Error{constructor(e,t,n,s){super(),this.name=e,this.code=n,this.message=s,this.pos=t}},jt=class extends xi{constructor(e,t,n){super("YAMLParseError",e,t,n)}},Pi=class extends xi{constructor(e,t,n){super("YAMLWarning",e,t,n)}},Lu=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:n,col:s}=t.linePos[0];t.message+=` at line ${n}, column ${s}`;let i=s-1,o=r.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){let a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,i))){let a=r.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026 -`),o=a+o}if(/[^ ]/.test(o)){let a=1,c=t.linePos[1];(c==null?void 0:c.line)===n&&c.col>s&&(a=Math.max(1,Math.min(c.col-s,80-i)));let l=" ".repeat(i)+"^".repeat(a);t.message+=`: +`}var Ir=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,st,{value:ba});let i=null;typeof t=="function"||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);let s=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=s;let{version:o}=s;n!=null&&n._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new hr({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(r.prototype,{[st]:{value:ba}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=se(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){_i(this.contents)&&this.contents.add(e)}addIn(e,t){_i(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=zu(this);e.anchor=!t||n.has(t)?Hu(t||"a",n):t}return new kr(e.anchor)}createNode(e,t,n){let i;if(typeof t=="function")e=t.call({"":e},"",e),i=t;else if(Array.isArray(t)){let y=g=>typeof g=="number"||g instanceof String||g instanceof Number,b=t.filter(y).map(String);b.length>0&&(t=t.concat(b)),i=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:s,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:l,tag:u}=n!=null?n:{},{onAnchor:d,setAnchors:f,sourceObjects:p}=i_(this,o||"a"),m={aliasDuplicateObjects:s!=null?s:!0,keepUndefined:c!=null?c:!1,onAnchor:d,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},h=xr(e,u,m);return a&&pe(h)&&(h.flow=!0),f(),h}createPair(e,t,n={}){let i=this.createNode(e,null,n),s=this.createNode(t,null,n);return new Ee(i,s)}delete(e){return _i(this.contents)?this.contents.delete(e):!1}deleteIn(e){return pi(e)?this.contents==null?!1:(this.contents=null,!0):_i(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return pe(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return pi(e)?!t&&J(this.contents)?this.contents.value:this.contents:pe(this.contents)?this.contents.getIn(e,t):void 0}has(e){return pe(this.contents)?this.contents.has(e):!1}hasIn(e){return pi(e)?this.contents!==void 0:pe(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=xs(this.schema,[e],t):_i(this.contents)&&this.contents.set(e,t)}setIn(e,t){pi(e)?this.contents=t:this.contents==null?this.contents=xs(this.schema,Array.from(e),t):_i(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new hr({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new hr({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{let i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new Ds(Object.assign(n,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:i,onAnchor:s,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=Ne(this.contents,t!=null?t:"",a);if(typeof s=="function")for(let{count:l,res:u}of a.anchors.values())s(u,l);return typeof o=="function"?Yr(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return k_(this,e)}};function _i(r){if(pe(r))return!0;throw new Error("Expected a YAML collection as document contents")}var qs=class extends Error{constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}},Xt=class extends qs{constructor(e,t,n){super("YAMLParseError",e,t,n)}},js=class extends qs{constructor(e,t,n){super("YAMLWarning",e,t,n)}},of=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:n,col:i}=t.linePos[0];t.message+=` at line ${n}, column ${i}`;let s=i-1,o=r.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(s>=60&&o.length>80){let a=Math.min(s-39,o.length-79);o="\u2026"+o.substring(a),s-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,s))){let a=r.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026 +`),o=a+o}if(/[^ ]/.test(o)){let a=1,c=t.linePos[1];(c==null?void 0:c.line)===n&&c.col>i&&(a=Math.max(1,Math.min(c.col-i,80-s)));let l=" ".repeat(s)+"^".repeat(a);t.message+=`: ${o} ${l} -`}};function nr(r,{flow:e,indicator:t,next:n,offset:s,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,d="",f="",p=!1,m=!1,h=null,y=null,b=null,g=null,_=null,I=null,v=null;for(let $ of r)switch(m&&($.type!=="space"&&$.type!=="newline"&&$.type!=="comma"&&i($.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&$.type!=="comment"&&$.type!=="newline"&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),$.type){case"space":!e&&(t!=="doc-start"||(n==null?void 0:n.type)!=="flow-collection")&&$.source.includes(" ")&&(h=$),u=!0;break;case"comment":{u||i($,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let P=$.source.substring(1)||" ";d?d+=f+P:d=P,f="",l=!1;break}case"newline":l?d?d+=$.source:(!I||t!=="seq-item-ind")&&(c=!0):f+=$.source,l=!0,p=!0,(y||b)&&(g=$),u=!0;break;case"anchor":y&&i($,"MULTIPLE_ANCHORS","A node can have at most one anchor"),$.source.endsWith(":")&&i($.offset+$.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=$,v!=null||(v=$.offset),l=!1,u=!1,m=!0;break;case"tag":{b&&i($,"MULTIPLE_TAGS","A node can have at most one tag"),b=$,v!=null||(v=$.offset),l=!1,u=!1,m=!0;break}case t:(y||b)&&i($,"BAD_PROP_ORDER",`Anchors and tags must be after the ${$.source} indicator`),I&&i($,"UNEXPECTED_TOKEN",`Unexpected ${$.source} in ${e!=null?e:"collection"}`),I=$,l=t==="seq-item-ind"||t==="explicit-key-ind",u=!1;break;case"comma":if(e){_&&i($,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),_=$,l=!1,u=!1;break}default:i($,"UNEXPECTED_TOKEN",`Unexpected ${$.type} token`),l=!1,u=!1}let S=r[r.length-1],k=S?S.offset+S.source.length:s;return m&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&i(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||(n==null?void 0:n.type)==="block-map"||(n==null?void 0:n.type)==="block-seq")&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:_,found:I,spaceBefore:c,comment:d,hasNewline:p,anchor:y,tag:b,newlineAfterProp:g,end:k,start:v!=null?v:k}}function Kr(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(` -`))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(Kr(e.key)||Kr(e.value))return!0}return!1;default:return!0}}function Ii(r,e,t){if((e==null?void 0:e.type)==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&Kr(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Ma(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let s=typeof n=="function"?n:(i,o)=>i===o||W(i)&&W(o)&&i.value===o.value;return e.some(i=>s(i.key,t))}var t0="All mapping items must start at the same column";function r0({composeNode:r,composeEmptyNode:e},t,n,s,i){var u,d;let o=(u=i==null?void 0:i.nodeClass)!=null?u:ke,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let f of n.items){let{start:p,key:m,sep:h,value:y}=f,b=nr(p,{indicator:"explicit-key-ind",next:m!=null?m:h==null?void 0:h[0],offset:c,onError:s,parentIndent:n.indent,startOnNewline:!0}),g=!b.found;if(g){if(m&&(m.type==="block-seq"?s(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in m&&m.indent!==n.indent&&s(c,"BAD_INDENT",t0)),!b.anchor&&!b.tag&&!h){l=b.end,b.comment&&(a.comment?a.comment+=` -`+b.comment:a.comment=b.comment);continue}(b.newlineAfterProp||Kr(m))&&s(m!=null?m:p[p.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else((d=b.found)==null?void 0:d.indent)!==n.indent&&s(c,"BAD_INDENT",t0);t.atKey=!0;let _=b.end,I=m?r(t,m,b,s):e(t,_,p,null,b,s);t.schema.compat&&Ii(n.indent,m,s),t.atKey=!1,Ma(t,a.items,I)&&s(_,"DUPLICATE_KEY","Map keys must be unique");let v=nr(h!=null?h:[],{indicator:"map-value-ind",next:y,offset:I.range[2],onError:s,parentIndent:n.indent,startOnNewline:!m||m.type==="block-scalar"});if(c=v.end,v.found){g&&((y==null?void 0:y.type)==="block-map"&&!v.hasNewline&&s(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&b.startr&&(r.type==="block-map"||r.type==="block-seq");function s0({composeNode:r,composeEmptyNode:e},t,n,s,i){var y,b,g;let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=(y=i==null?void 0:i.nodeClass)!=null?y:o?ke:Ve,l=new c(t.schema);l.flow=!0;let u=t.atRoot;u&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let d=n.offset+n.start.source.length;for(let _=0;_0){let _=sr(m,h,t.options.strict,s);_.comment&&(l.comment?l.comment+=` -`+_.comment:l.comment=_.comment),l.range=[n.offset,h,_.offset]}else l.range=[n.offset,h,h];return l}function ju(r,e,t,n,s,i){let o=t.type==="block-map"?r0(r,e,t,n,i):t.type==="block-seq"?n0(r,e,t,n,i):s0(r,e,t,n,i),a=o.constructor;return s==="!"||s===a.tagName?(o.tag=a.tagName,o):(s&&(o.tag=s),o)}function i0(r,e,t,n,s){var f,p,m;let i=n.tag,o=i?e.directives.tagName(i.source,h=>s(i,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){let{anchor:h,newlineAfterProp:y}=n,b=h&&i?h.offset>i.offset?h:i:h!=null?h:i;b&&(!y||y.offseth.tag===o&&h.collection===a);if(!c){let h=e.schema.knownTags[o];if((h==null?void 0:h.collection)===a)e.schema.tags.push(Object.assign({},h,{default:!1})),c=h;else return h?s(i,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${(f=h.collection)!=null?f:"scalar"}`,!0):s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),ju(r,e,t,s,o)}let l=ju(r,e,t,s,o,c),u=(m=(p=c.resolve)==null?void 0:p.call(c,l,h=>s(i,"TAG_RESOLVE_FAILED",h),e.options))!=null?m:l,d=re(u)?u:new F(u);return d.range=l.range,d.tag=o,c!=null&&c.format&&(d.format=c.format),d}function Fu(r,e,t){let n=e.offset,s=TT(e,r.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[n,n,n]};let i=s.mode===">"?F.BLOCK_FOLDED:F.BLOCK_LITERAL,o=e.source?OT(e.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let y=o[h][1];if(y===""||y==="\r")a=h;else break}if(a===0){let h=s.chomp==="+"&&o.length>0?` -`.repeat(Math.max(1,o.length-1)):"",y=n+s.length;return e.source&&(y+=e.source.length),{value:h,type:i,comment:s.comment,range:[n,y,y]}}let c=e.indent+s.indent,l=e.offset+s.length,u=0;for(let h=0;hc&&(c=y.length);else{y.length=a;--h)o[h][0].length>c&&(a=h+1);let d="",f="",p=!1;for(let h=0;hs===o||J(s)&&J(o)&&s.value===o.value;return e.some(s=>i(s.key,t))}var x_="All mapping items must start at the same column";function P_({composeNode:r,composeEmptyNode:e},t,n,i,s){var u,d;let o=(u=s==null?void 0:s.nodeClass)!=null?u:Ie,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let f of n.items){let{start:p,key:m,sep:h,value:y}=f,b=yr(p,{indicator:"explicit-key-ind",next:m!=null?m:h==null?void 0:h[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),g=!b.found;if(g){if(m&&(m.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in m&&m.indent!==n.indent&&i(c,"BAD_INDENT",x_)),!b.anchor&&!b.tag&&!h){l=b.end,b.comment&&(a.comment?a.comment+=` +`+b.comment:a.comment=b.comment);continue}(b.newlineAfterProp||en(m))&&i(m!=null?m:p[p.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else((d=b.found)==null?void 0:d.indent)!==n.indent&&i(c,"BAD_INDENT",x_);t.atKey=!0;let _=b.end,k=m?r(t,m,b,i):e(t,_,p,null,b,i);t.schema.compat&&Fs(n.indent,m,i),t.atKey=!1,Wa(t,a.items,k)&&i(_,"DUPLICATE_KEY","Map keys must be unique");let v=yr(h!=null?h:[],{indicator:"map-value-ind",next:y,offset:k.range[2],onError:i,parentIndent:n.indent,startOnNewline:!m||m.type==="block-scalar"});if(c=v.end,v.found){g&&((y==null?void 0:y.type)==="block-map"&&!v.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&b.startr&&(r.type==="block-map"||r.type==="block-seq");function O_({composeNode:r,composeEmptyNode:e},t,n,i,s){var y,b,g;let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=(y=s==null?void 0:s.nodeClass)!=null?y:o?Ie:Ge,l=new c(t.schema);l.flow=!0;let u=t.atRoot;u&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let d=n.offset+n.start.source.length;for(let _=0;_0){let _=gr(m,h,t.options.strict,i);_.comment&&(l.comment?l.comment+=` +`+_.comment:l.comment=_.comment),l.range=[n.offset,h,_.offset]}else l.range=[n.offset,h,h];return l}function lf(r,e,t,n,i,s){let o=t.type==="block-map"?P_(r,e,t,n,s):t.type==="block-seq"?I_(r,e,t,n,s):O_(r,e,t,n,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function T_(r,e,t,n,i){var f,p,m;let s=n.tag,o=s?e.directives.tagName(s.source,h=>i(s,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){let{anchor:h,newlineAfterProp:y}=n,b=h&&s?h.offset>s.offset?h:s:h!=null?h:s;b&&(!y||y.offseth.tag===o&&h.collection===a);if(!c){let h=e.schema.knownTags[o];if((h==null?void 0:h.collection)===a)e.schema.tags.push(Object.assign({},h,{default:!1})),c=h;else return h?i(s,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${(f=h.collection)!=null?f:"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),lf(r,e,t,i,o)}let l=lf(r,e,t,i,o,c),u=(m=(p=c.resolve)==null?void 0:p.call(c,l,h=>i(s,"TAG_RESOLVE_FAILED",h),e.options))!=null?m:l,d=se(u)?u:new V(u);return d.range=l.range,d.tag=o,c!=null&&c.format&&(d.format=c.format),d}function df(r,e,t){let n=e.offset,i=aT(e,r.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let s=i.mode===">"?V.BLOCK_FOLDED:V.BLOCK_LITERAL,o=e.source?cT(e.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let y=o[h][1];if(y===""||y==="\r")a=h;else break}if(a===0){let h=i.chomp==="+"&&o.length>0?` +`.repeat(Math.max(1,o.length-1)):"",y=n+i.length;return e.source&&(y+=e.source.length),{value:h,type:s,comment:i.comment,range:[n,y,y]}}let c=e.indent+i.indent,l=e.offset+i.length,u=0;for(let h=0;hc&&(c=y.length);else{y.length=a;--h)o[h][0].length>c&&(a=h+1);let d="",f="",p=!1;for(let h=0;hc||b[0]===" "?(f===" "?f=` `:!p&&f===` `&&(f=` @@ -101,82 +101,82 @@ ${l} `,p=!0):b===""?f===` `?d+=` `:f=` -`:(d+=f+b,f=" ",p=!1)}switch(s.chomp){case"-":break;case"+":for(let h=a;ht(n+f,p,m);switch(s){case"scalar":a=F.PLAIN,c=RT(i,l);break;case"single-quoted-scalar":a=F.QUOTE_SINGLE,c=MT(i,l);break;case"double-quoted-scalar":a=F.QUOTE_DOUBLE,c=CT(i,l);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${s}`),{value:"",type:null,comment:"",range:[n,n+i.length,n+i.length]}}let u=n+i.length,d=sr(o,u,e,t);return{value:c,type:a,comment:d.comment,range:[n,u,d.offset]}}function RT(r,e){let t="";switch(r[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${r[0]}`;break}case"@":case"`":{t=`reserved character ${r[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),o0(r)}function MT(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),o0(r.slice(1,-1)).replace(/''/g,"'")}function o0(r){var c;let e,t;try{e=new RegExp(`(.*?)(?t(n+f,p,m);switch(i){case"scalar":a=V.PLAIN,c=lT(s,l);break;case"single-quoted-scalar":a=V.QUOTE_SINGLE,c=dT(s,l);break;case"double-quoted-scalar":a=V.QUOTE_DOUBLE,c=uT(s,l);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+s.length,n+s.length]}}let u=n+s.length,d=gr(o,u,e,t);return{value:c,type:a,comment:d.comment,range:[n,u,d.offset]}}function lT(r,e){let t="";switch(r[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${r[0]}`;break}case"@":case"`":{t=`reserved character ${r[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),R_(r)}function dT(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),R_(r.slice(1,-1)).replace(/''/g,"'")}function R_(r){var c;let e,t;try{e=new RegExp(`(.*?)(?i?r.slice(i,n+1):s)}else t+=s}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function NT(r,e){let t="",n=r[e+1];for(;(n===" "||n===" "||n===` +`)&&(t+=n>s?r.slice(s,n+1):i)}else t+=i}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function fT(r,e){let t="",n=r[e+1];for(;(n===" "||n===" "||n===` `||n==="\r")&&!(n==="\r"&&r[e+2]!==` `);)n===` `&&(t+=` -`),e+=1,n=r[e+1];return t||(t=" "),{fold:t,offset:e}}var LT={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function DT(r,e,t,n){let s=r.substr(e,t),o=s.length===t&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;try{return String.fromCodePoint(o)}catch(a){let c=r.substr(e-2,t+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${c}`),c}}function Uu(r,e,t,n){let{value:s,type:i,comment:o,range:a}=e.type==="block-scalar"?Fu(r,e,n):Vu(e,r.options.strict,n),c=t?r.directives.tagName(t.source,d=>n(t,"TAG_RESOLVE_FAILED",d)):null,l;r.options.stringKeys&&r.atKey?l=r.schema[ct]:c?l=qT(r.schema,s,c,t,n):e.type==="scalar"?l=jT(r,s,e,n):l=r.schema[ct];let u;try{let d=l.resolve(s,f=>n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),r.options);u=W(d)?d:new F(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),u=new F(s)}return u.range=a,u.source=s,i&&(u.type=i),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function qT(r,e,t,n,s){var a;if(t==="!")return r[ct];let i=[];for(let c of r.tags)if(!c.collection&&c.tag===t)if(c.default&&c.test)i.push(c);else return c;for(let c of i)if((a=c.test)!=null&&a.test(e))return c;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(s(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[ct])}function jT({atKey:r,directives:e,schema:t},n,s,i){var a;let o=t.tags.find(c=>{var l;return(c.default===!0||r&&c.default==="key")&&((l=c.test)==null?void 0:l.test(n))})||t[ct];if(t.compat){let c=(a=t.compat.find(l=>{var u;return l.default&&((u=l.test)==null?void 0:u.test(n))}))!=null?a:t[ct];if(o.tag!==c.tag){let l=e.tagString(o.tag),u=e.tagString(c.tag),d=`Value may be parsed as either ${l} or ${u}`;i(s,"TAG_RESOLVE_FAILED",d,!0)}}return o}function a0(r,e,t){if(e){t!=null||(t=e.length);for(let n=t-1;n>=0;--n){let s=e[n];switch(s.type){case"space":case"comment":case"newline":r-=s.source.length;continue}for(s=e[++n];(s==null?void 0:s.type)==="space";)r+=s.source.length,s=e[++n];break}}return r}var FT={composeNode:Hu,composeEmptyNode:Ca};function Hu(r,e,t,n){let s=r.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=t,l,u=!0;switch(e.type){case"alias":l=VT(r,e,n),(a||c)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=Uu(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=i0(FT,r,e,t,n),a&&(l.anchor=a.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);n(e,"RESOURCE_EXHAUSTION",f)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",d),u=!1}}return l!=null||(l=Ca(r,e.offset,void 0,null,t,n)),a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),s&&r.options.stringKeys&&(!W(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c!=null?c:e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&u&&(l.srcToken=e),l}function Ca(r,e,t,n,{spaceBefore:s,comment:i,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:a0(e,t,n),indent:-1,source:""},d=Uu(r,u,a,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),s&&(d.spaceBefore=!0),i&&(d.comment=i,d.range[2]=c),d}function VT({options:r},{offset:e,source:t,end:n},s){let i=new mr(t.substring(1));i.source===""&&s(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&s(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=sr(n,o,r.strict,s);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}function c0(r,e,{offset:t,start:n,value:s,end:i},o){let a=Object.assign({_directives:e},r),c=new br(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=nr(n,{indicator:"doc-start",next:s!=null?s:i==null?void 0:i[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,s&&(s.type==="block-map"||s.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=s?Hu(l,s,u,o):Ca(l,u.end,n,null,u,o);let d=c.contents.range[2],f=sr(i,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,d,f.offset],c}function Ti(r){if(typeof r=="number")return[r,r+1];if(Array.isArray(r))return r.length===2?r:[r[0],r[1]];let{offset:e,source:t}=r;return[e,e+(typeof t=="string"?t.length:1)]}function l0(r){var s;let e="",t=!1,n=!1;for(let i=0;in(t,"TAG_RESOLVE_FAILED",d)):null,l;r.options.stringKeys&&r.atKey?l=r.schema[vt]:c?l=mT(r.schema,i,c,t,n):e.type==="scalar"?l=yT(r,i,e,n):l=r.schema[vt];let u;try{let d=l.resolve(i,f=>n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),r.options);u=J(d)?d:new V(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(t!=null?t:e,"TAG_RESOLVE_FAILED",f),u=new V(i)}return u.range=a,u.source=i,s&&(u.type=s),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function mT(r,e,t,n,i){var a;if(t==="!")return r[vt];let s=[];for(let c of r.tags)if(!c.collection&&c.tag===t)if(c.default&&c.test)s.push(c);else return c;for(let c of s)if((a=c.test)!=null&&a.test(e))return c;let o=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[vt])}function yT({atKey:r,directives:e,schema:t},n,i,s){var a;let o=t.tags.find(c=>{var l;return(c.default===!0||r&&c.default==="key")&&((l=c.test)==null?void 0:l.test(n))})||t[vt];if(t.compat){let c=(a=t.compat.find(l=>{var u;return l.default&&((u=l.test)==null?void 0:u.test(n))}))!=null?a:t[vt];if(o.tag!==c.tag){let l=e.tagString(o.tag),u=e.tagString(c.tag),d=`Value may be parsed as either ${l} or ${u}`;s(i,"TAG_RESOLVE_FAILED",d,!0)}}return o}function C_(r,e,t){if(e){t!=null||(t=e.length);for(let n=t-1;n>=0;--n){let i=e[n];switch(i.type){case"space":case"comment":case"newline":r-=i.source.length;continue}for(i=e[++n];(i==null?void 0:i.type)==="space";)r+=i.source.length,i=e[++n];break}}return r}var gT={composeNode:pf,composeEmptyNode:Ga};function pf(r,e,t,n){let i=r.atKey,{spaceBefore:s,comment:o,anchor:a,tag:c}=t,l,u=!0;switch(e.type){case"alias":l=bT(r,e,n),(a||c)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":l=ff(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=T_(gT,r,e,t,n),a&&(l.anchor=a.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);n(e,"RESOURCE_EXHAUSTION",f)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",d),u=!1}}return l!=null||(l=Ga(r,e.offset,void 0,null,t,n)),a&&l.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&r.options.stringKeys&&(!J(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(c!=null?c:e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),s&&(l.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?l.comment=o:l.commentBefore=o),r.options.keepSourceTokens&&u&&(l.srcToken=e),l}function Ga(r,e,t,n,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:C_(e,t,n),indent:-1,source:""},d=ff(r,u,a,l);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&l(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),s&&(d.comment=s,d.range[2]=c),d}function bT({options:r},{offset:e,source:t,end:n},i){let s=new kr(t.substring(1));s.source===""&&i(e,"BAD_ALIAS","Alias cannot be an empty string"),s.source.endsWith(":")&&i(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=gr(n,o,r.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}function M_(r,e,{offset:t,start:n,value:i,end:s},o){let a=Object.assign({_directives:e},r),c=new Ir(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=yr(n,{indicator:"doc-start",next:i!=null?i:s==null?void 0:s[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!u.hasNewline&&o(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?pf(l,i,u,o):Ga(l,u.end,n,null,u,o);let d=c.contents.range[2],f=gr(s,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,d,f.offset],c}function Vs(r){if(typeof r=="number")return[r,r+1];if(Array.isArray(r))return r.length===2?r:[r[0],r[1]];let{offset:e,source:t}=r;return[e,e+(typeof t=="string"?t.length:1)]}function N_(r){var i;let e="",t=!1,n=!1;for(let s=0;s{let o=Ti(t);i?this.warnings.push(new Pi(o,n,s)):this.errors.push(new jt(o,n,s))},this.directives=new tr({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:s}=l0(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment} -${n}`:n;else if(s||e.directives.docStart||!i)e.commentBefore=n;else if(ie(i)&&!i.flow&&i.items.length>0){let o=i.items[0];ee(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${n} -${a}`:n}else{let o=i.commentBefore;i.commentBefore=o?`${n} -${o}`:n}}if(t){for(let i=0;i{let i=Ti(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,s)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=c0(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new jt(Ti(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new jt(Ti(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=sr(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let n=this.doc.comment;this.doc.comment=n?`${n} -${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new jt(Ti(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),s=new br(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),s.range=[0,t,t],this.decorate(s,!1),yield s}}};var Bu=Symbol("break visit"),UT=Symbol("skip children"),d0=Symbol("remove item");function yn(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),u0(Object.freeze([]),r,e)}yn.BREAK=Bu;yn.SKIP=UT;yn.REMOVE=d0;yn.itemAtPath=(r,e)=>{let t=r;for(let[n,s]of e){let i=t==null?void 0:t[n];if(i&&"items"in i)t=i.items[s];else return}return t};yn.parentCollection=(r,e)=>{let t=yn.itemAtPath(r,e.slice(0,-1)),n=e[e.length-1][0],s=t==null?void 0:t[n];if(s&&"items"in s)return s;throw new Error("Parent collection not found")};function u0(r,e,t){let n=t(e,r);if(typeof n=="symbol")return n;for(let s of["key","value"]){let i=e[s];if(i&&"items"in i){for(let o=0;o{let o=Vs(t);s?this.warnings.push(new js(o,n,i)):this.errors.push(new Xt(o,n,i))},this.directives=new hr({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:i}=N_(this.prelude);if(n){let s=e.contents;if(t)e.comment=e.comment?`${e.comment} +${n}`:n;else if(i||e.directives.docStart||!s)e.commentBefore=n;else if(pe(s)&&!s.flow&&s.items.length>0){let o=s.items[0];ne(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${n} +${a}`:n}else{let o=s.commentBefore;s.commentBefore=o?`${n} +${o}`:n}}if(t){for(let s=0;s{let s=Vs(e);s[0]+=t,this.onError(s,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=M_(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new Xt(Vs(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){let n="Unexpected doc-end without preceding document";this.errors.push(new Xt(Vs(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=gr(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let n=this.doc.comment;this.doc.comment=n?`${n} +${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Xt(Vs(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let n=Object.assign({_directives:this.directives},this.options),i=new Ir(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,t,t],this.decorate(i,!1),yield i}}};var hf=Symbol("break visit"),_T=Symbol("skip children"),L_=Symbol("remove item");function An(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),D_(Object.freeze([]),r,e)}An.BREAK=hf;An.SKIP=_T;An.REMOVE=L_;An.itemAtPath=(r,e)=>{let t=r;for(let[n,i]of e){let s=t==null?void 0:t[n];if(s&&"items"in s)t=s.items[i];else return}return t};An.parentCollection=(r,e)=>{let t=An.itemAtPath(r,e.slice(0,-1)),n=e[e.length-1][0],i=t==null?void 0:t[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function D_(r,e,t){let n=t(e,r);if(typeof n=="symbol")return n;for(let i of["key","value"]){let s=e[i];if(s&&"items"in s){for(let o=0;o":return"block-scalar-header"}return null}function Ft(r){switch(r){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var p0=new Set("0123456789ABCDEFabcdef"),BT=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),La=new Set(",[]{}"),zT=new Set(` ,[]{} -\r `),Gu=r=>!r||zT.has(r),Ri=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){var s;if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=(s=this.next)!=null?s:"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===` +`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(r[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}function Qt(r){switch(r){case void 0:case" ":case` +`:case"\r":case" ":return!0;default:return!1}}var j_=new Set("0123456789ABCDEFabcdef"),vT=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ya=new Set(",[]{}"),$T=new Set(` ,[]{} +\r `),bf=r=>!r||$T.has(r),Bs=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){var i;if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=(i=this.next)!=null?i:"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===` `?!0:t==="\r"?this.buffer[e+1]===` -`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===" ";)t=this.buffer[++n+e];if(t==="\r"){let s=this.buffer[n+e+1];if(s===` -`||!s&&!this.atEnd)return e+n+1}return t===` -`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&Ft(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!Ft(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Ft(t)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Gu),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let s=this.getLine();if(s===null)return this.setNext("flow");if((n!==-1&&n"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>Ft(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let i=this.pos;n=this.buffer[i];++i)switch(n){case" ":t+=1;break;case` -`:e=i,t=0;break;case"\r":{let o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===` -`)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let i=this.continueScalar(e+1);if(i===-1)break;e=this.buffer.indexOf(` -`,i)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let s=e+1;for(n=this.buffer[s];n===" ";)n=this.buffer[++s];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===` -`;)n=this.buffer[++s];e=s-1}else if(!this.blockScalarKeep)do{let i=e-1,o=this.buffer[i];o==="\r"&&(o=this.buffer[--i]);let a=i;for(;o===" ";)o=this.buffer[--i];if(o===` -`&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield Na,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,s;for(;s=this.buffer[++n];)if(s===":"){let i=this.buffer[n+1];if(Ft(i)||e&&La.has(i))break;t=n}else if(Ft(s)){let i=this.buffer[n+1];if(s==="\r"&&(i===` -`?(n+=1,s=` -`,i=this.buffer[n+1]):t=n),i==="#"||e&&La.has(i))break;if(s===` -`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&La.has(s))break;t=n}return!s&&!this.atEnd?this.setNext("plain-scalar"):(yield Na,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(Gu),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,n=this.charAt(1);if(Ft(n)||t&&La.has(n)){t?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!Ft(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(BT.has(t))t=this.buffer[++e];else if(t==="%"&&p0.has(this.buffer[e+1])&&p0.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` +`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===" ";)t=this.buffer[++n+e];if(t==="\r"){let i=this.buffer[n+e+1];if(i===` +`||!i&&!this.atEnd)return e+n+1}return t===` +`||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){let n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&Qt(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!Qt(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Qt(t)){let n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(bf),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>Qt(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let s=this.pos;n=this.buffer[s];++s)switch(n){case" ":t+=1;break;case` +`:e=s,t=0;break;case"\r":{let o=this.buffer[s+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===` +`)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let s=this.continueScalar(e+1);if(s===-1)break;e=this.buffer.indexOf(` +`,s)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let i=e+1;for(n=this.buffer[i];n===" ";)n=this.buffer[++i];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===` +`;)n=this.buffer[++i];e=i-1}else if(!this.blockScalarKeep)do{let s=e-1,o=this.buffer[s];o==="\r"&&(o=this.buffer[--s]);let a=s;for(;o===" ";)o=this.buffer[--s];if(o===` +`&&s>=this.pos&&s+1+t>a)e=s;else break}while(!0);return yield Ja,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===":"){let s=this.buffer[n+1];if(Qt(s)||e&&Ya.has(s))break;t=n}else if(Qt(i)){let s=this.buffer[n+1];if(i==="\r"&&(s===` +`?(n+=1,i=` +`,s=this.buffer[n+1]):t=n),s==="#"||e&&Ya.has(s))break;if(i===` +`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Ya.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield Ja,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(bf),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,n=this.charAt(1);if(Qt(n)||t&&Ya.has(n)){t?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!Qt(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(vT.has(t))t=this.buffer[++e];else if(t==="%"&&j_.has(this.buffer[e+1])&&j_.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===` `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===` -`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");let s=t-this.pos;return s>0&&(yield this.buffer.substr(this.pos,s),this.pos=t),s}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};var Mi=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t>1;this.lineStarts[i]=0;)switch(r[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;((t=r[++e])==null?void 0:t.type)==="space";);return r.splice(e,r.length)}function qa(r,e){if(e.length<1e5)Array.prototype.push.apply(r,e);else for(let t=0;t0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&(e==null?void 0:e.type)!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e!=null?e:this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&m0(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{let s=n.items[n.items.length-1];if(s.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(s.sep)s.value=t;else{Object.assign(s,{key:t,sep:[]}),this.onKeyLine=!s.explicitKey;return}break}case"block-seq":{let s=n.items[n.items.length-1];s.value?n.items.push({start:[],value:t}):s.value=t;break}case"flow-collection":{let s=n.items[n.items.length-1];!s||s.value?n.items.push({start:[],key:t,sep:[]}):s.sep?s.value=t:Object.assign(s,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let s=t.items[t.items.length-1];s&&!s.sep&&!s.value&&s.start.length>0&&h0(s.start)===-1&&(t.indent===0||s.start.every(i=>i.type!=="comment"||i.indent0&&(yield this.buffer.substr(this.pos,i),this.pos=t),i}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};var zs=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t>1;this.lineStarts[s]=0;)switch(r[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;((t=r[++e])==null?void 0:t.type)==="space";);return r.splice(e,r.length)}function Qa(r,e){if(e.length<1e5)Array.prototype.push.apply(r,e);else for(let t=0;t0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&(e==null?void 0:e.type)!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e!=null?e:this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&V_(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{let i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=t;else{Object.assign(i,{key:t,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{let i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:t}):i.value=t;break}case"flow-collection":{let i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:t,sep:[]}):i.sep?i.value=t:Object.assign(i,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let i=t.items[t.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&F_(i.start)===-1&&(t.indent===0||i.start.every(s=>s.type!=="comment"||s.indent=e.indent){let s=!this.onKeyLine&&this.indent===e.indent,i=s&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",o=[];if(i&&t.sep&&!t.value){let a=[];for(let c=0;ce.indent&&(a.length=0);break;default:a.length=0}}a.length>=2&&(o=t.sep.splice(a[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(o.push(this.sourceToken),e.items.push({start:o}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):i||t.value?(o.push(this.sourceToken),e.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Wr(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(y0(t.key)&&!Wr(t.sep,"newline")){let a=us(t.start),c=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:c,sep:l}]})}else o.length>0?t.sep=t.sep.concat(o,this.sourceToken):t.sep.push(this.sourceToken);else if(Wr(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let a=us(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:o,key:null,sep:[this.sourceToken]}):Wr(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let a=this.flowScalar(this.type);i||t.value?(e.items.push({start:o,key:a,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(a):(Object.assign(t,{key:a,sep:[]}),this.onKeyLine=!0);return}default:{let a=this.startBlockValue(e);if(a){if(a.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Wr(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else s&&e.items.push({start:o});this.stack.push(a);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){var n;let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let s="end"in t.value?t.value.end:void 0,i=Array.isArray(s)?s[s.length-1]:void 0;(i==null?void 0:i.type)==="comment"?s==null||s.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2],i=(n=s==null?void 0:s.value)==null?void 0:n.end;if(Array.isArray(i)){qa(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||Wr(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let s=this.startBlockValue(e);if(s){this.stack.push(s);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while((n==null?void 0:n.type)==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:s,sep:[]}):t.sep?this.stack.push(s):Object.assign(t,{key:s,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let s=Da(n),i=us(s);m0(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(` +`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){var n;let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let i="end"in t.value?t.value.end:void 0,s=Array.isArray(i)?i[i.length-1]:void 0;(s==null?void 0:s.type)==="comment"?i==null||i.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let i=e.items[e.items.length-2],s=(n=i==null?void 0:i.value)==null?void 0:n.end;if(Array.isArray(s)){Qa(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,s=i&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",o=[];if(s&&t.sep&&!t.value){let a=[];for(let c=0;ce.indent&&(a.length=0);break;default:a.length=0}}a.length>=2&&(o=t.sep.splice(a[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(o.push(this.sourceToken),e.items.push({start:o}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(o.push(this.sourceToken),e.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(tn(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(U_(t.key)&&!tn(t.sep,"newline")){let a=wi(t.start),c=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:c,sep:l}]})}else o.length>0?t.sep=t.sep.concat(o,this.sourceToken):t.sep.push(this.sourceToken);else if(tn(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let a=wi(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||s?e.items.push({start:o,key:null,sep:[this.sourceToken]}):tn(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let a=this.flowScalar(this.type);s||t.value?(e.items.push({start:o,key:a,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(a):(Object.assign(t,{key:a,sep:[]}),this.onKeyLine=!0);return}default:{let a=this.startBlockValue(e);if(a){if(a.type==="block-seq"){if(!t.explicitKey&&t.sep&&!tn(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&e.items.push({start:o});this.stack.push(a);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){var n;let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let i="end"in t.value?t.value.end:void 0,s=Array.isArray(i)?i[i.length-1]:void 0;(s==null?void 0:s.type)==="comment"?i==null||i.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let i=e.items[e.items.length-2],s=(n=i==null?void 0:i.value)==null?void 0:n.end;if(Array.isArray(s)){Qa(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||tn(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while((n==null?void 0:n.type)==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let i=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:i,sep:[]}):t.sep?this.stack.push(i):Object.assign(t,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){let i=Xa(n),s=wi(i);V_(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(` `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(` -`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=Da(e),n=us(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=Da(e),n=us(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};function KT(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new Mi||null,prettyErrors:e}}function g0(r,e={}){let{lineCounter:t,prettyErrors:n}=KT(e),s=new Ci(t==null?void 0:t.addNewLine),i=new Oi(e),o=null;for(let a of i.compose(s.parse(r),!0,r.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new jt(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Lu(r,t)),o.warnings.forEach(Lu(r,t))),o}function Ni(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=g0(r,t);if(!s)return null;if(s.warnings.forEach(i=>ma(s.options.logLevel,i)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:n},t))}function Ju(r,e,t){var s;let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let i=Math.round(t);t=i<1?void 0:i>8?{indent:8}:{indent:i}}if(r===void 0){let{keepUndefined:i}=(s=t!=null?t:e)!=null?s:{};if(!i)return}return Mt(r)&&!n?r.toString(t):new br(r,n,t).toString(t)}function GT(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function ja(r,e,t=""){let n=GT(r),s=r==null?void 0:r.length,i=e!==void 0;if(!n||i&&s!==e){let o=t&&`"${t}" `,a=i?` of length ${e}`:"",c=n?`length=${s}`:`type=${typeof r}`,l=o+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function Yu(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function b0(r,e){ja(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length='+t)}function Gr(...r){for(let e=0;e>>e}function Va(r,e){return r<>>32-e>>>0}var JT=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",YT=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Ut(r){if(ja(r),JT)return r.toHex();let e="";for(let t=0;tr(i).update(s).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=s=>r(s),Object.assign(t,e),Object.freeze(t)}var w0=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Ha(r,e,t){return r&e^~r&t}function Ba(r,e,t){return r&e^r&t^e&t}var fs=class{constructor(e,t,n,s){O(this,"blockLen");O(this,"outputLen");O(this,"canXOF",!1);O(this,"padOffset");O(this,"isLE");O(this,"buffer");O(this,"view");O(this,"finished",!1);O(this,"length",0);O(this,"pos",0);O(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Fa(this.buffer)}update(e){Yu(this),ja(e);let{view:t,buffer:n,blockLen:s}=this,i=e.length;for(let o=0;os-o&&(this.process(n,0),o=0);for(let d=o;du.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d>>3,h=Vt(p,17)^Vt(p,19)^p>>>10;Jr[d]=h+Jr[d-7]+m+Jr[d-16]|0}let{A:n,B:s,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let f=Vt(a,6)^Vt(a,11)^Vt(a,25),p=u+f+Ha(a,c,l)+XT[d]+Jr[d]|0,h=(Vt(n,2)^Vt(n,13)^Vt(n,22))+Ba(n,s,i)|0;u=l,l=c,c=a,a=o+p|0,o=i,i=s,s=n,n=p+h|0}n=n+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,s,i,o,a,c,l,u)}roundClean(){Gr(Jr)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Gr(this.buffer)}},Qu=class extends Xu{constructor(){super(32);O(this,"A",wr[0]|0);O(this,"B",wr[1]|0);O(this,"C",wr[2]|0);O(this,"D",wr[3]|0);O(this,"E",wr[4]|0);O(this,"F",wr[5]|0);O(this,"G",wr[6]|0);O(this,"H",wr[7]|0)}};var ir=Ua(()=>new Qu,w0(1));var T=class extends Error{constructor(t,n){super(n);O(this,"code");this.code=t}};var Yr=new TextEncoder,QT=new Set(["null","true","false"]);function ZT(r){return Ut(ir(Yr.encode(r)))}function v0(r){return`sha256:${ZT(r)}`}function gn(r){if(Object.keys(r.frontmatter).length===0)return r.body;let e=Ju(r.frontmatter,{lineWidth:0}).trimEnd(),t=r.body?` +`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=Xa(e),n=wi(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=Xa(e),n=wi(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};function ST(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new zs||null,prettyErrors:e}}function B_(r,e={}){let{lineCounter:t,prettyErrors:n}=ST(e),i=new Hs(t==null?void 0:t.addNewLine),s=new Us(e),o=null;for(let a of s.compose(i.parse(r),!0,r.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Xt(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(of(r,t)),o.warnings.forEach(of(r,t))),o}function Ks(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let i=B_(r,t);if(!i)return null;if(i.warnings.forEach(s=>Ia(i.options.logLevel,s)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},t))}function _f(r,e,t){var i;let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let s=Math.round(t);t=s<1?void 0:s>8?{indent:8}:{indent:s}}if(r===void 0){let{keepUndefined:s}=(i=t!=null?t:e)!=null?i:{};if(!s)return}return Ht(r)&&!n?r.toString(t):new Ir(r,n,t).toString(t)}function AT(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function Za(r,e,t=""){let n=AT(r),i=r==null?void 0:r.length,s=e!==void 0;if(!n||s&&i!==e){let o=t&&`"${t}" `,a=s?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof r}`,l=o+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(l):new TypeError(l)}return r}function wf(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function z_(r,e){Za(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length='+t)}function rn(...r){for(let e=0;e>>e}function tc(r,e){return r<>>32-e>>>0}var kT=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",xT=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function qe(r){if(Za(r),kT)return r.toHex();let e="";for(let t=0;tr(s).update(i).digest(),n=r(void 0);return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.canXOF=n.canXOF,t.create=i=>r(i),Object.assign(t,e),Object.freeze(t)}var H_=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function nc(r,e,t){return r&e^~r&t}function ic(r,e,t){return r&e^r&t^e&t}var vi=class{constructor(e,t,n,i){T(this,"blockLen");T(this,"outputLen");T(this,"canXOF",!1);T(this,"padOffset");T(this,"isLE");T(this,"buffer");T(this,"view");T(this,"finished",!1);T(this,"length",0);T(this,"pos",0);T(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=ec(this.buffer)}update(e){wf(this),Za(e);let{view:t,buffer:n,blockLen:i}=this,s=e.length;for(let o=0;oi-o&&(this.process(n,0),o=0);for(let d=o;du.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d>>3,h=Zt(p,17)^Zt(p,19)^p>>>10;nn[d]=h+nn[d-7]+m+nn[d-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:l,H:u}=this;for(let d=0;d<64;d++){let f=Zt(a,6)^Zt(a,11)^Zt(a,25),p=u+f+nc(a,c,l)+PT[d]+nn[d]|0,h=(Zt(n,2)^Zt(n,13)^Zt(n,22))+ic(n,i,s)|0;u=l,l=c,c=a,a=o+p|0,o=s,s=i,i=n,n=p+h|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(n,i,s,o,a,c,l,u)}roundClean(){rn(nn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),rn(this.buffer)}},$f=class extends vf{constructor(){super(32);T(this,"A",Or[0]|0);T(this,"B",Or[1]|0);T(this,"C",Or[2]|0);T(this,"D",Or[3]|0);T(this,"E",Or[4]|0);T(this,"F",Or[5]|0);T(this,"G",Or[6]|0);T(this,"H",Or[7]|0)}};var Ye=rc(()=>new $f,H_(1));var S=class extends Error{constructor(t,n){super(n);T(this,"code");this.code=t}};var Tr=new TextEncoder,IT=new Set(["null","true","false"]);function OT(r){return qe(Ye(Tr.encode(r)))}function W_(r){return`sha256:${OT(r)}`}function kn(r){if(Object.keys(r.frontmatter).length===0)return r.body;let e=_f(r.frontmatter,{lineWidth:0}).trimEnd(),t=r.body?` ${r.body.replace(/^\n/,"")}`:"";return`--- ${e} --- -${t}`}function $0(r,e){let t=0,n=!1;for(let i in e.frontmatter){if(!Object.prototype.hasOwnProperty.call(e.frontmatter,i))continue;if(!n&&(n=!0,t=rt(r,`--- -`,t),t<0))return!1;let o=e.frontmatter[i];if(!/^[A-Za-z_][A-Za-z0-9_-]*$/u.test(i))return null;let a=_0(o);if(a!==null){if(t=rt(r,i,t),t<0||(t=rt(r,": ",t),t<0)||(t=rt(r,a,t),t<0)||(t=rt(r,` -`,t),t<0))return!1;continue}if(!Array.isArray(o))return null;if(o.length===0){if(t=rt(r,i,t),t<0||(t=rt(r,`: [] -`,t),t<0))return!1;continue}if(t=rt(r,i,t),t<0||(t=rt(r,`: -`,t),t<0))return!1;for(let c of o){let l=_0(c);if(l===null)return null;if(t=rt(r," - ",t),t<0||(t=rt(r,l,t),t<0)||(t=rt(r,` -`,t),t<0))return!1}}if(!n)return r===e.body;if(t=rt(r,`--- -`,t),t<0)return!1;if(!e.body)return t===r.length;let s=e.body.startsWith(` -`)?e.body.slice(1):e.body;return t=rt(r,` -`,t),t>=0&&r.startsWith(s,t)&&t+s.length===r.length}function _r(r,e){var s;let t=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)([\s\S]*)$/m);if(!t)return{frontmatter:{},body:r};let n;try{n=Ni(t[1])}catch(i){return{frontmatter:{},body:r}}return n===null&&t[1].trim()===""&&(n={}),!n||typeof n!="object"||Array.isArray(n)?{frontmatter:{},body:r}:{frontmatter:n,body:(s=t[2])!=null?s:""}}function _0(r){return typeof r=="boolean"||r===null||typeof r=="number"&&Number.isSafeInteger(r)?String(r):typeof r!="string"||!/^[A-Za-z][A-Za-z0-9 _.-]*$/u.test(r)||r.length<=5&&QT.has(r.toLowerCase())?null:r}function rt(r,e,t){return r.startsWith(e,t)?t+e.length:-1}function za(r,e){return!(r instanceof T)||r.code!=="invalid_frontmatter"?null:{path:e,code:"invalid_frontmatter",message:r.message}}function Ka(r,e){let t={...e};for(let n of Object.keys(r))n in e||(t[n]=null);return t}function Wa(r){let e=ir.create().update(Yr.encode(`mdbase-authority-manifest-v1 -`));for(let t of[...r].sort((n,s)=>n.kind!==s.kind?n.kind200)throw new He("invalid_mirror_name","Mirror name must contain between 1 and 200 characters.");if(!["read_only","read_write"].includes(e.mode))throw new He("invalid_mirror_mode","Mirror mode must be read-only or read-write.");if(e.collectionId!==void 0&&!$r.test(e.collectionId))throw new He("invalid_collection_id","Collection ID must be a UUID.");let i;try{i=await this.request({url:`${n}/v1/mirror-pairing-requests`,method:"POST",headers:{"content-type":"application/json"},body:{mirror_name:s,mode:e.mode,...e.collectionId?{collection_id:e.collectionId}:{}},...t.signal?{signal:t.signal}:{}})}catch(c){throw bn(t.signal),k0()}let o=A0(i,201);if(!hs(o)||!$r.test(lt(o.pairing_id))||!Di(o.pairing_secret)||!cO(o.expires_in)||Number(o.expires_in)*1e3>P0)throw Ht("Connect returned an invalid mirror approval.");let a=T0(n,lt(o.verification_uri),lt(o.pairing_id));return{controlUrl:n,pairingId:lt(o.pairing_id),refreshCredential:lt(o.pairing_secret),verificationUri:a,expiresAt:new Date(this.now()+Number(o.expires_in)*1e3).toISOString(),requested:{mirrorName:s,mode:e.mode,...e.collectionId?{collectionId:e.collectionId}:{}}}}async enroll(e,t){let n=await this.begin(e,t),{refreshCredential:s,...i}=n;return await t.onVerification(i),this.waitForApproval(n,t)}async waitForApproval(e,t={}){var o,a;sO(e,this.now());let n=x0(t.pollIntervalMs),s=Date.parse(e.expiresAt),i=0;for(;this.now()=500){let l=tf(c);if(await this.retry(s,(a=c.retryAfterMs)!=null?a:n,t,i,{code:l.code,message:l.message})===null)break;continue}throw tf(c)}throw new He("mirror_enrollment_expired","Mirror approval expired before it was completed.")}async renew(e,t={}){iO(e),bn(t.signal);let n;try{n=await this.request({url:E0(e.controlUrl,e.enrollmentId,"renew"),method:"POST",headers:{authorization:`Bearer ${e.refreshCredential}`},...t.signal?{signal:t.signal}:{}})}catch(i){throw bn(t.signal),k0()}let s={controlUrl:e.controlUrl,pairingId:e.enrollmentId,refreshCredential:e.refreshCredential,verificationUri:`${e.controlUrl}/mirror/${e.enrollmentId}`,expiresAt:new Date(this.now()+6e4).toISOString(),requested:{mirrorName:e.name,mode:e.mode,collectionId:e.collectionId}};return S0(s,A0(n,200),{replicaId:e.replicaId})}async retry(e,t,n,s,i){var l;let o=e-this.now();if(o<=0)return null;let a=Math.min(x0(t),o),c=new Date(this.now()+a).toISOString();return(l=n.onStatus)==null||l.call(n,{state:i?"retrying":"waiting_for_approval",attempt:s,expiresAt:new Date(e).toISOString(),retryAt:c,...i?{error:i}:{}}),await this.wait(a,n.signal),c}},He=class extends T{constructor(t,n,s){super(t,n);O(this,"status");this.status=s,this.name="MirrorEnrollmentError"}};function Sr(r){let e;try{e=new URL(r)}catch(n){throw new He("invalid_connect_url","Connect URL must be an absolute HTTPS origin.")}if(e.pathname!=="/"||e.search||e.hash||e.username||e.password)throw new He("invalid_connect_url","Connect URL must be an origin without credentials, path, query, or fragment.");let t=["localhost","127.0.0.1","[::1]","::1"].includes(e.hostname);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&t))throw new He("invalid_connect_url","Connect URL must use HTTPS outside loopback development.");return e.origin}async function nO(r){let e=await fetch(r.url,{method:r.method,headers:r.headers,...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.signal?{signal:r.signal}:{}}),t=await e.json().catch(()=>null),n=e.headers.get("retry-after");return{status:e.status,body:t,...n===null?{}:{retryAfterMs:oO(n)}}}function S0(r,e,t){if(!hs(e)||e.status!=="paired"||!hs(e.replica))throw Ht("Connect returned an invalid mirror enrollment.");let n=e.replica,s=lt(n.id),i=lt(n.collection_id),o=lt(n.name).trim(),a=n.mode,c=lt(e.token),l=lt(e.token_expires_at);if(!$r.test(s)||!$r.test(i)||!o||!["read_only","read_write"].includes(String(a))||!Di(c)||!R0(l))throw Ht("Connect returned invalid mirror credentials.");if(a!==r.requested.mode)throw Ht("Connect returned a mirror with a different access mode.");if(r.requested.collectionId&&i!==r.requested.collectionId)throw Ht("Connect returned a different collection.");if(t.mirrorName!==void 0&&o!==t.mirrorName)throw Ht("Connect returned a mirror with a different name.");if(t.replicaId!==void 0&&s!==t.replicaId)throw Ht("Connect returned a different mirror replica.");let u;try{u=I0(lt(e.sync_url),i)}catch(d){throw Ht("Connect returned an invalid authority sync URL.")}return{controlUrl:Sr(r.controlUrl),syncUrl:u,collectionId:i,replicaId:s,mode:a,name:o,enrollmentId:r.pairingId,accessToken:c,refreshCredential:r.refreshCredential,accessTokenExpiresAt:l}}function sO(r,e){Sr(r.controlUrl);let t=Date.parse(r.expiresAt);if(!$r.test(r.pairingId)||!Di(r.refreshCredential)||!Number.isFinite(t)||t-e>P0||!r.requested.mirrorName.trim()||r.requested.mirrorName.length>200||!["read_only","read_write"].includes(r.requested.mode)||r.requested.collectionId!==void 0&&!$r.test(r.requested.collectionId))throw new He("invalid_mirror_enrollment_session","Mirror enrollment session is invalid.");T0(r.controlUrl,r.verificationUri,r.pairingId)}function iO(r){if(Sr(r.controlUrl),I0(r.syncUrl,r.collectionId),!$r.test(r.collectionId)||!$r.test(r.replicaId)||!$r.test(r.enrollmentId)||!Di(r.accessToken)||!Di(r.refreshCredential)||!R0(r.accessTokenExpiresAt)||!r.name.trim()||r.name.length>200||!["read_only","read_write"].includes(r.mode))throw new He("invalid_mirror_enrollment","Stored mirror enrollment is invalid.")}function I0(r,e){let t=new URL(r),n=`/v1/authorities/${encodeURIComponent(e)}/sync`;if(!(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(t.hostname))||t.username||t.password||t.pathname.replace(/\/$/,"")!==n||t.search||t.hash)throw new Error("invalid sync URL");return`${t.origin}${n}`}function T0(r,e,t){let n;try{n=new URL(e)}catch(i){throw Ht("Connect returned an invalid mirror verification URI.")}let s=new URL(`/mirror/${encodeURIComponent(t)}`,r);if(n.origin!==s.origin||n.pathname!==s.pathname||n.search||n.hash||n.username||n.password)throw Ht("Connect returned an untrusted mirror verification URI.");return n.href}function E0(r,e,t){return`${Sr(r)}/v1/mirror-pairing-requests/${encodeURIComponent(e)}/${t}`}function A0(r,e){if(r.status!==e)throw tf(r);return r.body}function tf(r){let e=hs(r.body)&&hs(r.body.error)?r.body.error:{};return new He(lt(e.code)||"mirror_enrollment_request_failed",lt(e.message)||`Mirror enrollment request failed with status ${r.status}.`,r.status)}function Ht(r){return new He("invalid_mirror_enrollment_response",r)}function O0(r){return{code:"mirror_enrollment_unreachable",message:"Connect could not be reached for mirror enrollment."}}function k0(){let r=O0(void 0);return new He(r.code,r.message)}function x0(r=ef){return Number.isFinite(r)?Math.min(rO,Math.max(tO,Math.round(r))):ef}function oO(r){let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);return Number.isFinite(t)?Math.max(0,t-Date.now()):ef}function aO(r,e){return bn(e),new Promise((t,n)=>{let s=setTimeout(o,r),i=()=>{clearTimeout(s),e==null||e.removeEventListener("abort",i),n(new He("mirror_enrollment_cancelled","Mirror enrollment was cancelled."))};function o(){e==null||e.removeEventListener("abort",i),t()}e==null||e.addEventListener("abort",i,{once:!0})})}function bn(r){if(r!=null&&r.aborted)throw new He("mirror_enrollment_cancelled","Mirror enrollment was cancelled.")}function R0(r){let e=Date.parse(r);return Number.isFinite(e)}function cO(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function Di(r){return typeof r=="string"&&r.length>=16}function lt(r){return typeof r=="string"?r:""}function hs(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var qi=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),Xr=new Uint32Array(80),rf=class extends fs{constructor(){super(64,20,8,!1);O(this,"A",qi[0]|0);O(this,"B",qi[1]|0);O(this,"C",qi[2]|0);O(this,"D",qi[3]|0);O(this,"E",qi[4]|0)}get(){let{A:t,B:n,C:s,D:i,E:o}=this;return[t,n,s,i,o]}set(t,n,s,i,o){this.A=t|0,this.B=n|0,this.C=s|0,this.D=i|0,this.E=o|0}process(t,n){for(let l=0;l<16;l++,n+=4)Xr[l]=t.getUint32(n,!1);for(let l=16;l<80;l++)Xr[l]=Va(Xr[l-3]^Xr[l-8]^Xr[l-14]^Xr[l-16],1);let{A:s,B:i,C:o,D:a,E:c}=this;for(let l=0;l<80;l++){let u,d;l<20?(u=Ha(i,o,a),d=1518500249):l<40?(u=i^o^a,d=1859775393):l<60?(u=Ba(i,o,a),d=2400959708):(u=i^o^a,d=3395469782);let f=Va(s,5)+u+c+d+Xr[l]|0;c=a,a=o,o=Va(i,30),i=s,s=f}s=s+this.A|0,i=i+this.B|0,o=o+this.C|0,a=a+this.D|0,c=c+this.E|0,this.set(s,i,o,a,c)}roundClean(){Gr(Xr)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),Gr(this.buffer)}},M0=Ua(()=>new rf);var Qr=new TextEncoder;function sf(r){var l,u,d,f;let e=ps(r.collectionId,"Collection ID"),t=(l=r.sourceHead)!=null?l:0;if(!Number.isSafeInteger(t)||t<0)throw new ue("invalid_authority_snapshot","Source head must be a non-negative integer.");let n=new Set,s=r.resources.map(p=>{let m=nf(p.path);if(n.add(m)||L0(m),!["configuration","contract","schema","type","view"].includes(p.kind))throw new ue("invalid_authority_snapshot",`Unsupported collection resource kind for ${m}.`);return{path:m,kind:p.kind,revision:C0(p.document),document:p.document}}).sort(lO);if(((u=s[0])==null?void 0:u.path)!=="mdbase.yaml"||s[0].kind!=="configuration"||s.filter(({kind:p})=>p==="configuration").length!==1)throw new ue("invalid_authority_snapshot","A portable snapshot requires one mdbase.yaml configuration resource.");let i=r.records.map(p=>{let m=nf(p.path);return n.add(m)||L0(m),{record_id:p.recordId?ps(p.recordId,`Record ID for ${m}`):D0(e,m),path:m,document:p.document}}).sort((p,m)=>q0(p.path,m.path)),o=N0(s.flatMap(({path:p,revision:m})=>[p,m])),a=N0([...s.flatMap(({path:p,revision:m})=>["resource",p,m]),...i.flatMap(p=>["record",p.path,C0(p.document)])]),c=Wa([...s.map(({path:p,document:m})=>({kind:"resource",path:p,identity:"",document_hash:Ut(ir(Qr.encode(m)))})),...i.map(p=>({kind:"record",path:p.path,identity:p.record_id,document_hash:Ut(ir(Qr.encode(p.document)))}))]);return{protocol_version:1,collection_id:e,source_head:t,source_revision:a,manifest_digest:c,resources:{revision:o,spec_version:r.specVersion,types:(d=r.types)!=null?d:[],contracts:(f=r.contracts)!=null?f:[],documents:s},records:i}}function D0(r,e){let t=dO(ps(r,"Collection ID")),s=M0(new Uint8Array([...t,...Qr.encode(nf(e))])).slice(0,16);s[6]=s[6]&15|80,s[8]=s[8]&63|128;let i=Ut(s);return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function C0(r){return`sha256:${Ut(ir(Qr.encode(r)))}`}function N0(r){let e=ir.create();for(let t of r){let n=BigInt(Qr.encode(t).length),s=new Uint8Array(8);new DataView(s.buffer).setBigUint64(0,n),e.update(s),e.update(Qr.encode(t))}return`sha256:${Ut(e.digest())}`}function lO(r,e){return r.kind==="configuration"&&e.kind!=="configuration"?-1:e.kind==="configuration"&&r.kind!=="configuration"?1:q0(r.path,e.path)}function q0(r,e){let t=Qr.encode(r),n=Qr.encode(e),s=Math.min(t.length,n.length);for(let i=0;i!t||t==="."||t===".."))throw new ue("invalid_authority_snapshot",`Collection path is unsafe: ${r}`);return e}function L0(r){throw new ue("invalid_authority_snapshot",`Collection snapshot contains the path more than once: ${r}`)}function dO(r){return Uint8Array.from(r.replaceAll("-","").match(/../g).map(e=>Number.parseInt(e,16)))}var uO=/^sha256:[a-f0-9]{64}$/,fO=/^[a-f0-9]{64}$/,af=1500,cf=1440*60*1e3,pO=200,j0=8*1024*1024,hO=new TextEncoder,Ja=class{constructor(e={}){O(this,"request");O(this,"now");O(this,"wait");var t,n,s;this.request=(t=e.request)!=null?t:bO,this.now=(n=e.now)!=null?n:Date.now,this.wait=(s=e.wait)!=null?s:gO}async begin(e,t={}){var f,p;_n(t.signal);let n=Sr(e.controlUrl),s=ps(e.collectionId,"Collection ID"),i=of(e.displayName,"Collection name"),o=of(e.sourceName,"Source name"),a=(f=e.retainMirror)!=null?f:!0,c=a?of((p=e.mirrorName)!=null?p:o,"Mirror name"):void 0,l;try{l=await this.request({url:`${n}/v1/authority-adoptions`,method:"POST",headers:{"content-type":"application/json"},body:{collection_id:s,display_name:i,source_name:o,retain_mirror:a,...c?{mirror_name:c}:{}},...t.signal?{signal:t.signal}:{}})}catch(m){throw _n(t.signal),H0()}let u=yO(l,201);if(!Er(u)||!Li.test(dt(u.adoption_id))||!Y0(u.adoption_secret)||!$O(u.expires_in)||Number(u.expires_in)*1e3>cf)throw nt("Connect returned an invalid collection adoption request.");let d=G0(n,dt(u.verification_uri),dt(u.adoption_id));return{controlUrl:n,adoptionId:dt(u.adoption_id),credential:dt(u.adoption_secret),verificationUri:d,expiresAt:new Date(this.now()+Number(u.expires_in)*1e3).toISOString(),requested:{collectionId:s,displayName:i,sourceName:o,retainMirror:a,...c?{mirrorName:c}:{}}}}async start(e,t){let n=await this.begin(e,t),{credential:s,...i}=n;return await t.onVerification(i),{session:n,prepared:await this.waitForApproval(n,t)}}async waitForApproval(e,t={}){var o,a;ms(e,this.now());let n=B0(t.pollIntervalMs),s=Date.parse(e.expiresAt),i=0;for(;this.now()=500){let l=wn(c);if(!await this.retry(s,(a=c.retryAfterMs)!=null?a:n,i,t,{code:l.code,message:l.message}))break;continue}throw wn(c)}throw new ue("authority_adoption_expired","Collection adoption approval expired before upload began.")}async exchange(e,t={}){ms(e,this.now(),!0);let n=await this.controlRequest(e,"exchange","POST",{},t.signal);if(n.status===202)throw new ue("authority_adoption_pending","Collection adoption is still awaiting approval.",202);if(n.status!==200)throw wn(n);return V0(e,n.body)}async uploadSnapshot(e,t,n,s={}){ms(e,this.now(),!0),K0(e,t),F0(e,n);let i={protocol_version:1,collection_id:n.collection_id,source_head:n.source_head,source_revision:n.source_revision,manifest_digest:n.manifest_digest,resources:n.resources,record_count:n.records.length};await this.importRequest(t.import.manifest_url,"PUT",t.import.access_token,i,s.signal);let o=0,a=[],c=0;for(let l of n.records){let u=hO.encode(JSON.stringify(l)).length;if(u>j0)throw new ue("authority_adoption_record_too_large",`Record ${l.path} is too large to adopt.`);a.length>0&&(a.length===pO||c+u>j0)&&(await this.uploadPage(t.import,o,a,s.signal),o+=1,a=[],c=0),a.push(l),c+=u}a.length>0&&await this.uploadPage(t.import,o,a,s.signal),await this.importRequest(t.import.finalize_url,"POST",t.import.access_token,void 0,s.signal)}async complete(e,t,n={}){ms(e,this.now(),!0),F0(e,t);let s;try{s=await this.controlRequest(e,"complete","POST",{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head},n.signal)}catch(a){throw _n(n.signal),new vr("Connect could not confirm whether hosted authority activated.",{cause:a})}if(s.status>=500)throw new vr("Connect could not confirm whether hosted authority activated.");if(s.status!==200)throw wn(s);let i=s.body;if(!Er(i)||i.status!=="completed")throw nt("Connect returned an invalid adoption completion.");let o=W0(e,i.adoption);if(o.state!=="completed"||o.manifest_digest!==t.manifest_digest||o.source_revision!==t.source_revision||o.final_head!==t.source_head)throw nt("Connect completed a different adoption snapshot.");return{status:"completed",adoption:o}}async cancel(e,t={}){ms(e,this.now(),!0);let n=await this.controlRequest(e,void 0,"DELETE",void 0,t.signal);if(n.status!==200)throw wn(n)}mirrorEnrollmentSession(e,t){var n;if(ms(e,this.now(),!0),t.status!=="completed"||t.adoption.collection_id!==e.requested.collectionId)throw nt("Completed adoption does not belong to this session.");return e.requested.retainMirror?{controlUrl:e.controlUrl,pairingId:e.adoptionId,refreshCredential:e.credential,verificationUri:`${e.controlUrl}/mirror/${e.adoptionId}`,expiresAt:new Date(this.now()+cf).toISOString(),requested:{mirrorName:(n=e.requested.mirrorName)!=null?n:e.requested.sourceName,mode:"read_write",collectionId:e.requested.collectionId}}:null}async uploadPage(e,t,n,s){let i={protocol_version:1,page:t,records:n};await this.importRequest(e.records_url,"PUT",e.access_token,i,s)}async importRequest(e,t,n,s,i){let o;try{o=await this.request({url:e,method:t,headers:{authorization:`Bearer ${n}`,...s===void 0?{}:{"content-type":"application/json"}},...s===void 0?{}:{body:s},...i?{signal:i}:{}})}catch(a){throw _n(i),H0()}if(o.status<200||o.status>=300)throw wn(o)}controlRequest(e,t,n,s,i){return this.request({url:U0(e,t),method:n,headers:{authorization:`Bearer ${e.credential}`,...s===void 0?{}:{"content-type":"application/json"}},...s===void 0?{}:{body:s},...i?{signal:i}:{}})}async retry(e,t,n,s,i){var l;let o=e-this.now();if(o<=0)return!1;let a=Math.min(B0(t),o),c=new Date(this.now()+a).toISOString();return(l=s.onStatus)==null||l.call(s,{state:i?"retrying":"waiting_for_approval",attempt:n,expiresAt:new Date(e).toISOString(),retryAt:c,...i?{error:i}:{}}),await this.wait(a,s.signal),!0}};function ms(r,e,t=!1){Sr(r.controlUrl);let n=Date.parse(r.expiresAt);if(!Li.test(r.adoptionId)||!Y0(r.credential)||!Number.isFinite(n)||n-e>cf||!t&&n<=e||!Li.test(r.requested.collectionId)||!r.requested.displayName.trim()||!r.requested.sourceName.trim())throw new ue("invalid_authority_adoption_session","Stored collection adoption state is invalid.");G0(r.controlUrl,r.verificationUri,r.adoptionId)}function K0(r,e){if(e.status!=="ready"||e.adoption.id!==r.adoptionId||e.adoption.collection_id!==r.requested.collectionId)throw nt("Prepared adoption does not belong to this session.");for(let[t,n]of Object.entries(e.import))if(!n||t!=="access_token"&&!mO(n))throw nt("Connect returned an invalid authority import capability.")}function F0(r,e){var t;if(e.protocol_version!==1||e.collection_id!==r.requested.collectionId||!Number.isSafeInteger(e.source_head)||e.source_head<0||!uO.test(e.source_revision)||!fO.test(e.manifest_digest)||((t=e.resources.documents)==null?void 0:t.length)===0)throw new ue("invalid_authority_snapshot","Authority snapshot does not belong to this adoption.")}function V0(r,e){if(!Er(e)||!["ready","activating","completed"].includes(dt(e.status)))throw nt("Connect returned an invalid adoption exchange.");let t=W0(r,e.adoption);if(e.status==="completed")return{status:"completed",adoption:t};if(e.status==="activating")return{status:"activating",adoption:t};if(!Er(e.import)||!Er(e.staged))throw nt("Connect omitted the authority import capability.");let n=e.import,s=e.staged,i={status:"ready",adoption:t,import:{manifest_url:dt(n.manifest_url),records_url:dt(n.records_url),finalize_url:dt(n.finalize_url),access_token:dt(n.access_token)},staged:{state:s.state,manifest_digest:z0(s.manifest_digest),source_revision:z0(s.source_revision),source_head:vO(s.source_head)}};if(K0(r,i),!["receiving","uploaded"].includes(i.staged.state))throw nt("Connect returned an invalid staged import state.");return i}function W0(r,e){if(!Er(e))throw nt("Connect omitted collection adoption state.");let t=e;if(t.id!==r.adoptionId||t.collection_id!==r.requested.collectionId||!["requested","approved","prepared","activating","completed","cancelled","expired"].includes(t.state)||!Number.isSafeInteger(t.authority_epoch)||t.authority_epoch<2||!_O(t.expires_at))throw nt("Connect returned invalid collection adoption state.");return t}function mO(r){try{let e=new URL(r);return(e.protocol==="https:"||e.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(e.hostname))&&!e.username&&!e.password&&!e.search&&!e.hash&&/^\/v1\/authority-imports\/[0-9a-f-]+\/(manifest|records|finalize)$/i.test(e.pathname)}catch(e){return!1}}function G0(r,e,t){let n;try{n=new URL(e)}catch(i){throw nt("Connect returned an invalid adoption verification URI.")}let s=new URL(`/adopt/${encodeURIComponent(t)}`,r);if(n.origin!==s.origin||n.pathname!==s.pathname||n.search||n.hash||n.username||n.password)throw nt("Connect returned an untrusted adoption verification URI.");return n.href}function U0(r,e){let t=e?`/${e}`:"";return`${Sr(r.controlUrl)}/v1/authority-adoptions/${encodeURIComponent(r.adoptionId)}${t}`}function of(r,e){let t=r.trim();if(!t||t.length>200)throw new ue("invalid_authority_adoption",`${e} must contain between 1 and 200 characters.`);return t}function yO(r,e){if(r.status!==e)throw wn(r);return r.body}function wn(r){let e=Er(r.body)&&Er(r.body.error)?r.body.error:{};return new ue(dt(e.code)||"authority_adoption_request_failed",dt(e.message)||`Collection adoption request failed with status ${r.status}.`,r.status)}function nt(r){return new ue("invalid_authority_adoption_response",r)}function J0(r){return{code:"authority_adoption_unreachable",message:"Connect could not be reached for collection adoption."}}function H0(){let r=J0(void 0);return new ue(r.code,r.message)}function B0(r=af){return Number.isFinite(r)?Math.min(3e4,Math.max(250,Math.round(r))):af}function gO(r,e){return _n(e),new Promise((t,n)=>{let s=setTimeout(o,r),i=()=>{clearTimeout(s),e==null||e.removeEventListener("abort",i),n(new ue("authority_adoption_cancelled","Collection adoption was cancelled."))};function o(){e==null||e.removeEventListener("abort",i),t()}e==null||e.addEventListener("abort",i,{once:!0})})}function _n(r){if(r!=null&&r.aborted)throw new ue("authority_adoption_cancelled","Collection adoption was cancelled.")}async function bO(r){let e=await fetch(r.url,{method:r.method,headers:r.headers,...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.signal?{signal:r.signal}:{}}),t=await e.json().catch(()=>({})),n=e.headers.get("retry-after");return{status:e.status,body:t,...n?{retryAfterMs:wO(n)}:{}}}function wO(r){let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);return Number.isFinite(t)?Math.max(0,t-Date.now()):af}function _O(r){return Number.isFinite(Date.parse(r))}function z0(r){return r===null?null:dt(r)}function vO(r){return r===null?null:typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:Number.NaN}function $O(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function Y0(r){return typeof r=="string"&&r.length>=16}function dt(r){return typeof r=="string"?r:""}function Er(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var SO=/(?:^|\/)(?:\.{1,2}|)(?:\/|$)/u,EO=/[\p{Cc}:]/u,AO=/[. ](?:\/|$)/u,kO=/(?:^|\/)(?:CON|PRN|AUX|NUL|COM[1-9¹²³]|LPT[1-9¹²³])(?:\.|\/|$)/iu;function Ar(r){if(!r||r.startsWith("/")||r.includes("\\")||SO.test(r)||EO.test(r)||AO.test(r)||kO.test(r))throw new T("invalid_path",`Mirror received an unsafe path: ${r}.`)}function $t(r){return Ar(r),ys(r)}function ys(r){return/^[\x20-\x7e]+$/u.test(r)?/[A-Z]/u.test(r)?r.toLowerCase():r:r.normalize("NFC").toLowerCase().normalize("NFC")}var lf=64,xO=new TextEncoder,Fi=Object.freeze({digest:r=>Ut(ir(xO.encode(r))),randomId:()=>{var r;if(typeof((r=globalThis.crypto)==null?void 0:r.randomUUID)!="function")throw new T("mirror_random_unavailable","This runtime must provide crypto.randomUUID() or a MirrorRuntime adapter.");return globalThis.crypto.randomUUID()},now:()=>new Date().toISOString()});var ji=class{constructor(){O(this,"held",!1)}async runExclusive(e){if(this.held)throw new T("mirror_folder_in_use","Another mdbase mirror process is already using this folder.");this.held=!0;try{return await e()}finally{this.held=!1}}};function X0(r,e,t){var s,i,o,a,c;if(r.protocol_version!==1||r.replica_id!==e)throw new Error;if((s=r.resources)!=null||(r.resources={}),(i=r.pending)!=null||(r.pending=[]),(o=r.conflicts)!=null||(r.conflicts={}),(a=r.mode)!=null||(r.mode="read_only"),r.mode!==t)throw new T("mirror_mode_mismatch",`Mirror metadata belongs to a ${r.mode.replace("_","-")} replica.`);let n=[];for(let[l,u]of Object.entries(r.records))if(n.push($t(u.path)),u.record&&(u.record.record_id!==l||u.record.path!==u.path))throw new Error;for(let[l,u]of Object.entries(r.resources)){if(Ar(l),l!==u.path)throw new Error;n.push($t(u.path))}n.sort();for(let l=1;ll.kind==="configuration"&&l.path==="mdbase.yaml");if(n.length!==1)throw new T("invalid_snapshot","Hosted snapshot requires exactly one canonical mdbase.yaml resource.");let s=tw(n[0].document,e),i=(c=nw(n[0].document).settings)!=null?c:{},o=gs(i.types_folder,"_types"),a=gs(i.contracts_folder,"_contracts");for(let l of r){let u=l.path.split(".").at(-1),d=l.path.split("/"),f=d.some(m=>m.startsWith(".")),p=!1;if(l.kind==="configuration")p=l.path==="mdbase.yaml";else if(l.kind==="type")p=df(l.path,o)&&u==="md"&&Z0(l.document,l.path)==="mdbase.type";else if(l.kind==="contract")p=df(l.path,a)&&u==="md"&&Z0(l.document,l.path)==="mdbase.contract";else if(l.kind==="schema"){let m=IO(l.document);p=!f&&u==="json"&&d.some(h=>h==="schemas"||h==="_schemas")&&m!==null}else l.kind==="view"&&(p=!f&&u==="base");if(!p)throw new T("invalid_snapshot",`Hosted resource ${l.path} is not valid for kind ${l.kind}.`)}return s}function ew(r){return{reservedFolders:new Set(["_types","_contracts","_types/_migrations",".mdbase"]),resourcePaths:r}}function tw(r,e){var i;let t=(i=nw(r).settings)!=null?i:{},n=gs(t.types_folder,"_types");return{reservedFolders:new Set([n,gs(t.contracts_folder,"_contracts"),gs(t.migrations_folder,`${n}/_migrations`),gs(t.cache_folder,".mdbase",!0)]),resourcePaths:e}}async function rw(r,e){if(r.length===0)return ew(new Set);let t=await e();if(t===null)throw new T("invalid_mirror_state","Mirror collection configuration is missing.");return tw(t,new Set(r))}function st(r,e){if(Ar(r),/(?:^|\/)\./u.test(r)||e.resourcePaths.has(r)||PO(r,e.reservedFolders)||!r.endsWith(".md"))throw new T("invalid_record_path",`Mirror record path ${r} is outside the configured record namespace.`)}function PO(r,e){for(let t of e)if(df(r,t))return!0;return!1}function Xa(r,e){return r.filter(t=>{try{return st(t,e),!0}catch(n){return!1}})}function nw(r){let e;try{e=Ni(r)}catch(n){throw new T("invalid_snapshot","Hosted mdbase.yaml is not valid YAML.")}if(!e||typeof e!="object"||Array.isArray(e))throw new T("invalid_snapshot","Hosted mdbase.yaml requires an object document.");let t=e;if(typeof t.spec_version!="string")throw new T("invalid_snapshot","Hosted mdbase.yaml requires spec_version.");return t}function gs(r,e,t=!1){let n=typeof r=="string"?r:e;if(Ar(n),!t&&n.split("/").some(s=>s.startsWith(".")))throw new T("invalid_snapshot",`Collection control folder ${n} must not be hidden.`);return n}function df(r,e){return r===e||r.startsWith(`${e}/`)}function IO(r){try{let e=JSON.parse(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}catch(e){return null}}function Z0(r,e){try{return _r(r,e).frontmatter.kind}catch(t){return null}}var St=class extends T{constructor(t,n){super("mirror_diverged",`Local edits at ${n} must be resolved before the mirror can continue.`);O(this,"recordId");O(this,"path");this.recordId=t,this.path=n}},Qa=class extends T{constructor(t){super("mirror_initialization_conflict",`Existing files differ from remote Markdown: ${t.join(", ")}. Move or reconcile them before syncing.`);O(this,"paths");this.paths=t}};async function uf(r,e,t,n){var s;for(let[i,o]of Object.entries(r.records)){st(o.path,e);let a=await t.read(o.path);if(a===null||n(a)!==o.hash)throw new St(i,o.path)}for(let[i,o]of Object.entries((s=r.resources)!=null?s:{})){let a=await t.read(o.path);if(a===null||n(a)!==o.hash)throw new St(`resource:${i}`,o.path)}}function kr(r){return ys(r)}function sw(r,e,t,n){let s=kr(r);for(let i of t)if(kr(i)===s)throw new T("invalid_record_path",`Mirror record path ${r} aliases authority resource ${i} on a supported filesystem.`);for(let[i,o]of n)if((i!==e||o.path!==r)&&kr(o.path)===s)throw new T("invalid_record_path",`Mirror record paths ${o.path} and ${r} alias on a supported filesystem.`)}function Za(r){let e=new Map;for(let t of r){let n=kr(t),s=e.get(n);if(s!==void 0&&s!==t)throw new T("invalid_record_path",`Mirror paths ${s} and ${t} alias on a supported filesystem.`);e.set(n,t)}}function iw(r,e,t){var c,l,u,d,f,p;let n=new Set;for(let m in(c=t.conflicts)!=null?c:{})Object.prototype.hasOwnProperty.call(t.conflicts,m)&&n.add(m);if(Object.keys((l=t.local_issues)!=null?l:{}).length>0)for(let m in t.records){if(!Object.prototype.hasOwnProperty.call(t.records,m))continue;let h=t.records[m];(u=t.local_issues)!=null&&u[h.path]&&n.add(m)}let s=new Set;for(let m of r)m.type==="put"&&(st(m.record.path,e),n.has(m.record.record_id)||s.add($t(m.record.path)));let i=new Map;for(let m in(d=t.resources)!=null?d:{}){if(!Object.prototype.hasOwnProperty.call(t.resources,m))continue;let h=$t(m);s.has(h)&&i.set(h,{path:m,recordId:null})}for(let m in t.records){if(!Object.prototype.hasOwnProperty.call(t.records,m))continue;let h=t.records[m],y=$t(h.path);s.has(y)&&i.set(y,{path:h.path,recordId:m})}let o=new Map,a=m=>{var h,y;return o.has(m)?o.get(m):(y=(h=t.records[m])==null?void 0:h.path)!=null?y:null};for(let m of r){let h=m.type==="put"?m.record.record_id:m.record_id;if(n.has(h))continue;if(m.type==="remove"){let _=a(h);if(_!==null){let I=$t(_);((f=i.get(I))==null?void 0:f.recordId)===h&&i.delete(I)}o.set(h,null);continue}let y=$t(m.record.path),b=i.get(y);if(b!==void 0&&(b.recordId!==h||b.path!==m.record.path))throw new T("invalid_record_path",`Mirror paths ${b.path} and ${m.record.path} alias on a supported filesystem.`);let g=a(h);if(g!==null){let _=$t(g);((p=i.get(_))==null?void 0:p.recordId)===h&&i.delete(_)}i.set(y,{path:m.record.path,recordId:h}),o.set(h,m.record.path)}}async function ow({replicaId:r,state:e,pathPolicy:t,fileSystem:n,runtime:s}){var y,b,g,_,I,v;let i=new Set(Object.keys((y=e.resources)!=null?y:{}));for(let[S,k]of Object.entries((b=e.resources)!=null?b:{})){let $=await n.read(S);if($===null||s.digest($)!==k.hash)throw new St(`resource:${S}`,S)}let o=Xa(await n.listMarkdown(i),t);Za([...i,...o]);let a=new Map(Object.entries(e.records).map(([S,k])=>[k.path,S])),c=new Map;for(let S of o){let k=await n.read(S);if(k===null)continue;let $=s.digest(k),P=a.get(S),w=P!==void 0&&((g=e.records[P])==null?void 0:g.hash)===$;c.set(S,w?{hash:$}:{document:k,hash:$})}let l=new Set([...c.keys()].filter(S=>!a.has(S))),u=new Set(Object.entries(e.records).filter(([,S])=>!c.has(S.path)).map(([S])=>S)),d=[],f={},p=(S,k,$)=>{try{return _r(S,k)}catch(P){let w=za(P,k);if(!w)throw P;return f[k]={...w,hash:$},null}},m=new Map,h=(S,k,$)=>{let P=s.randomId(),w=m.get(S.record_id);d.push({mutation:{...S,mutation_id:P,replica_id:r,scope_epoch:e.scope_epoch,created_at:s.now(),...w?{causal_predecessor:w}:{}},local_path:k,local_hash:$}),m.set(S.record_id,P)};for(let S of[...u]){if((_=e.conflicts)!=null&&_[S]){u.delete(S);continue}let k=e.records[S],$=[...l].filter(w=>{var N;return((N=c.get(w))==null?void 0:N.hash)===k.hash});if($.length!==1)continue;let P=$[0];h({operation:"rename",record_id:S,base_revision:k.revision,input:{path:P}},P,c.get(P).hash),u.delete(S),l.delete(P)}for(let[S,k]of Object.entries(e.records)){if((I=e.conflicts)!=null&&I[S]||u.has(S))continue;let $=c.get(k.path);if(!$||$.hash===k.hash)continue;let P=k.record;if(!P)throw new T("mirror_state_upgrade_required","Run a receive sync before editing this older writable mirror.");let w=p($.document,k.path,$.hash);w&&h({operation:"update",record_id:S,base_revision:k.revision,input:{patch:Ka(P.frontmatter,w.frontmatter),body:w.body}},k.path,$.hash)}for(let S of u){if((v=e.conflicts)!=null&&v[S])continue;let k=e.records[S];h({operation:"delete",record_id:S,base_revision:k.revision,input:{}},k.path,null)}for(let S of l){let k=c.get(S),$=p(k.document,S,k.hash);$&&h({operation:"create",record_id:s.randomId(),input:{path:S,frontmatter:$.frontmatter,body:$.body}},S,k.hash)}return{pending:d,localIssues:f}}var bs=class{constructor(e,t,n){O(this,"pathPolicy");O(this,"digest");O(this,"recordIds",new Set);O(this,"physicalPaths",new Set);this.pathPolicy=e,this.digest=n;for(let s of t)this.physicalPaths.add(ys(s.path))}validate(e){let t=e.document,n=e;if(st(n.path,this.pathPolicy),this.recordIds.has(n.record_id))throw new T("invalid_snapshot",`Hosted snapshot repeats record identity ${n.record_id}.`);this.recordIds.add(n.record_id);let s=ys(n.path);if(this.physicalPaths.has(s))throw new T("invalid_snapshot",`Hosted record path ${n.path} aliases another snapshot path on a supported filesystem.`);this.physicalPaths.add(s);let i=this.digest(t);if(n.revision.length!==7+i.length||!n.revision.startsWith("sha256:")||!n.revision.endsWith(i))throw new T("invalid_snapshot",`Hosted record ${n.path} does not match its declared revision.`);if($0(t,n)!==!0&&t!==gn(n)){let a;try{a=_r(t,n.path)}catch(c){throw new T("invalid_snapshot",`Hosted record ${n.path} is not valid Markdown.`)}if(!ff(a.frontmatter,n.frontmatter)||!TO(a.body,n.body))throw new T("invalid_snapshot",`Hosted record ${n.path} does not match its declared document.`)}return{record:n,document:t,hash:i}}};function aw(r){if(!Object.prototype.hasOwnProperty.call(r,"document"))return r;let{document:e,...t}=r;return t}async function ec(r,e,t){let n,s=new Set;do{let i=await r.snapshot(e.snapshot_id,n);if(i.protocol_version!==1||i.snapshot_id!==e.snapshot_id||i.scope_epoch!==e.scope_epoch||i.cursor!==e.head)throw new T("invalid_snapshot","Authority snapshot boundary changed during download.");if(await t(i.records),n=i.next_page,n!==void 0&&s.has(n))throw new T("invalid_snapshot","Authority snapshot repeated a page cursor.");n!==void 0&&s.add(n)}while(n)}function TO(r,e){return r===e||r.startsWith(` +${t}`}function G_(r,e){let t=0,n=!1;for(let s in e.frontmatter){if(!Object.prototype.hasOwnProperty.call(e.frontmatter,s))continue;if(!n&&(n=!0,t=mt(r,`--- +`,t),t<0))return!1;let o=e.frontmatter[s];if(!/^[A-Za-z_][A-Za-z0-9_-]*$/u.test(s))return null;let a=K_(o);if(a!==null){if(t=mt(r,s,t),t<0||(t=mt(r,": ",t),t<0)||(t=mt(r,a,t),t<0)||(t=mt(r,` +`,t),t<0))return!1;continue}if(!Array.isArray(o))return null;if(o.length===0){if(t=mt(r,s,t),t<0||(t=mt(r,`: [] +`,t),t<0))return!1;continue}if(t=mt(r,s,t),t<0||(t=mt(r,`: +`,t),t<0))return!1;for(let c of o){let l=K_(c);if(l===null)return null;if(t=mt(r," - ",t),t<0||(t=mt(r,l,t),t<0)||(t=mt(r,` +`,t),t<0))return!1}}if(!n)return r===e.body;if(t=mt(r,`--- +`,t),t<0)return!1;if(!e.body)return t===r.length;let i=e.body.startsWith(` +`)?e.body.slice(1):e.body;return t=mt(r,` +`,t),t>=0&&r.startsWith(i,t)&&t+i.length===r.length}function Rr(r,e){var i;let t=r.match(/^---[ \t]*\r?\n([\s\S]*?)^---[ \t]*(?:\r?\n|$)([\s\S]*)$/m);if(!t)return{frontmatter:{},body:r};let n;try{n=Ks(t[1])}catch(s){return{frontmatter:{},body:r}}return n===null&&t[1].trim()===""&&(n={}),!n||typeof n!="object"||Array.isArray(n)?{frontmatter:{},body:r}:{frontmatter:n,body:(i=t[2])!=null?i:""}}function K_(r){return typeof r=="boolean"||r===null||typeof r=="number"&&Number.isSafeInteger(r)?String(r):typeof r!="string"||!/^[A-Za-z][A-Za-z0-9 _.-]*$/u.test(r)||r.length<=5&&IT.has(r.toLowerCase())?null:r}function mt(r,e,t){return r.startsWith(e,t)?t+e.length:-1}function sc(r,e){return!(r instanceof S)||r.code!=="invalid_frontmatter"?null:{path:e,code:"invalid_frontmatter",message:r.message}}function oc(r,e){let t={...e};for(let n of Object.keys(r))n in e||(t[n]=null);return t}function ac(r){let e=Ye.create().update(Tr.encode(`mdbase-authority-manifest-v2 +`));for(let t of[...r].sort((n,i)=>n.kind!==i.kind?n.kinde.type==="file_put"||e.type==="file_remove"))throw new S("file_sync_unsupported","This replica cannot materialize collection file changes yet. Upgrade it before continuing sync.")}function J_(r){Ef([r])}var Y=class extends S{constructor(t,n,i,s){super(t,n);T(this,"status");this.status=i,this.name="AuthorityAdoptionError",(s==null?void 0:s.cause)!==void 0&&(this.cause=s.cause)}},Cr=class extends Y{constructor(t,n){super("authority_adoption_outcome_unknown",t,void 0,n);T(this,"sourceMustRemainFenced",!0);this.name="AuthorityAdoptionOutcomeUnknownError"}};var $i=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function xn(r,e){if(!$i.test(r))throw new Y("invalid_authority_adoption",`${e} must be a UUID.`);return r.toLowerCase()}var Ws=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),sn=new Uint32Array(80),Af=class extends vi{constructor(){super(64,20,8,!1);T(this,"A",Ws[0]|0);T(this,"B",Ws[1]|0);T(this,"C",Ws[2]|0);T(this,"D",Ws[3]|0);T(this,"E",Ws[4]|0)}get(){let{A:t,B:n,C:i,D:s,E:o}=this;return[t,n,i,s,o]}set(t,n,i,s,o){this.A=t|0,this.B=n|0,this.C=i|0,this.D=s|0,this.E=o|0}process(t,n){for(let l=0;l<16;l++,n+=4)sn[l]=t.getUint32(n,!1);for(let l=16;l<80;l++)sn[l]=tc(sn[l-3]^sn[l-8]^sn[l-14]^sn[l-16],1);let{A:i,B:s,C:o,D:a,E:c}=this;for(let l=0;l<80;l++){let u,d;l<20?(u=nc(s,o,a),d=1518500249):l<40?(u=s^o^a,d=1859775393):l<60?(u=ic(s,o,a),d=2400959708):(u=s^o^a,d=3395469782);let f=tc(i,5)+u+c+d+sn[l]|0;c=a,a=o,o=tc(s,30),s=i,i=f}i=i+this.A|0,s=s+this.B|0,o=o+this.C|0,a=a+this.D|0,c=c+this.E|0,this.set(i,s,o,a,c)}roundClean(){rn(sn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),rn(this.buffer)}},lc=rc(()=>new Af);var RT=1e4,CT=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,MT=new TextEncoder;async function X_(r,e,t,n,i){var h,y,b;let s=LT(n,t.media_type);if(s.size!==t.size||await DT(s,i.signal)!==t.content_digest)throw new Y("authority_adoption_file_changed",`File bytes no longer match the fenced snapshot for ${t.path}.`);let o=qT(e.import_id,t),a=await kf(r,`${e.files_url}/uploads`,e.access_token,{protocol_version:1,type:"open_authority_import_file_upload",transfer_id:o,file_id:t.file_id},i.signal);if(FT(a,o,t.size),a.strategy.kind!=="object_put"&&a.strategy.kind!=="object_multipart")throw yt("Connect returned an incompatible authority import file strategy.");let c=a.strategy.kind==="object_put"?Math.max(1,t.size):a.strategy.part_size,l=a.strategy.kind==="object_put"?1:Math.ceil(t.size/c);if(l>RT)throw yt("Authority import returned too many file parts.");let u=new Set(a.received),d=new Map(((h=a.uploaded_parts)!=null?h:[]).map(g=>[g.part_number-1,g]));if(a.received.length===l&&await Y_(r,e,t,o,[...d.values()],i.signal))return;let f=Array(l);for(let[g,_]of d)f[g]=_;let p=[...u].reduce((g,_)=>g+Math.min(c,Math.max(0,t.size-_*c)),0);for(let g=0;gg!==void 0);if(!await Y_(r,e,t,o,m,i.signal))throw new Y("authority_adoption_file_upload_incomplete",`Connect could not commit ${t.path}.`)}async function Y_(r,e,t,n,i,s){try{let o=await kf(r,`${e.files_url}/uploads/${encodeURIComponent(n)}/commit`,e.access_token,{protocol_version:1,type:"commit_file_upload",transfer_id:n,...i.length>0?{parts:i}:{}},s);if(o.protocol_version!==1||o.type!=="file_upload_committed"||o.transfer_id!==n||!zT(o.file,t))throw yt("Connect returned an invalid authority import file receipt.");return!0}catch(o){if(i.length===0&&o instanceof Y&&o.code==="file_upload_incomplete")return!1;throw o}}async function kf(r,e,t,n,i){let s;try{s=await r({url:e,method:"POST",headers:{authorization:`Bearer ${t}`,"content-type":"application/json"},body:n,...i?{signal:i}:{}})}catch(o){throw dc(i),new Y("authority_adoption_unreachable","Connect could not be reached for collection adoption.")}if(s.status<200||s.status>=300)throw HT(s);return s.body}async function NT(r,e,t,n){UT(e.url);let i;try{i=await r({url:e.url,method:"PUT",headers:BT(e.headers),body:t,rawBody:!0,...n?{signal:n}:{}})}catch(s){throw dc(n),new Y("authority_adoption_unreachable","Connect could not be reached for collection adoption.")}if(i.status<200||i.status>=300)throw new Y("authority_adoption_object_upload_failed","Object storage rejected an authority import file part.",i.status);return i}function LT(r,e){if(r instanceof Blob)return r;if(r instanceof ArrayBuffer)return new Blob([r],{type:e});let t=new Uint8Array(r.buffer,r.byteOffset,r.byteLength).slice();return new Blob([t],{type:e})}async function DT(r,e){let t=Ye.create(),n=r.stream().getReader();try{for(;;){dc(e);let i=await n.read();if(i.done)break;t.update(i.value)}}finally{n.releaseLock()}return`sha256:${qe(t.digest())}`}function qT(r,e){let t=jT(r),n=MT.encode(`mdbase-authority-import-file-v1\0${e.file_id}\0${e.revision}\0${e.content_digest}`),i=lc(new Uint8Array([...t,...n])).slice(0,16);i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=qe(i);return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function jT(r){if(!CT.test(r))throw yt("Authority import ID is invalid.");return Uint8Array.from(r.replaceAll("-","").match(/../g).map(e=>Number.parseInt(e,16)))}function FT(r,e,t){var a;let n=r==null?void 0:r.strategy;if((r==null?void 0:r.protocol_version)!==1||r.type!=="file_transfer"||r.transfer_id!==e||r.direction!=="upload"||r.protection!=="transport_tls"||r.total_size!==t||!Array.isArray(r.received)||!n||!["object_put","object_multipart"].includes(n.kind)||n.kind==="object_multipart"&&(!Number.isSafeInteger(n.part_size)||n.part_size<=0))throw yt("Connect returned an invalid authority import file session.");if(n.kind!=="object_put"&&n.kind!=="object_multipart")throw yt("Connect returned an invalid authority import file strategy.");let i=n.kind==="object_put"?Math.max(1,t):n.part_size,s=n.kind==="object_put"?1:Math.ceil(t/i);if(new Set(r.received).size!==r.received.length||r.received.some(c=>!Number.isSafeInteger(c)||c<0||c>=s))throw yt("Connect returned invalid authority import file progress.");let o=(a=r.uploaded_parts)!=null?a:[];if(!Array.isArray(o)||o.some((c,l)=>!Number.isSafeInteger(c==null?void 0:c.part_number)||c.part_number<1||c.part_number>s||typeof c.etag!="string"||c.etag.length===0||c.etag.length>255||l>0&&o[l-1].part_number>=c.part_number)||(n.kind==="object_multipart"?o.length!==r.received.length||o.some((c,l)=>c.part_number-1!==r.received[l]):o.length!==0))throw yt("Connect returned invalid authority import part receipts.")}function VT(r,e,t,n,i){if((r==null?void 0:r.protocol_version)!==1||r.type!=="file_part"||r.transfer_id!==e||r.part_index!==t||r.offset!==n||r.content_length!==i||r.method.toUpperCase()!=="PUT"||!Number.isFinite(Date.parse(r.expires_at))||!xf(r.headers))throw yt("Connect returned an invalid prepared authority import file part.")}function UT(r){let e;try{e=new URL(r)}catch(t){throw yt("Connect returned an invalid object storage URL.")}if(e.protocol!=="https:"&&!(e.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(e.hostname))||e.username||e.password||e.hash)throw yt("Connect returned an unsafe object storage URL.")}function BT(r){let e={};for(let[t,n]of Object.entries(r)){if(["authorization","cookie","host","proxy-authorization"].includes(t.toLowerCase()))throw yt("Connect returned unsafe object storage headers.");if(/\r|\n/.test(t)||/\r|\n/.test(n))throw yt("Connect returned invalid object storage headers.");e[t]=n}return e}function zT(r,e){return r.file_id===e.file_id&&r.path===e.path&&r.revision===e.revision&&r.content_digest===e.content_digest&&r.size===e.size&&r.media_type===e.media_type&&r.media_class===e.media_class&&r.modified_at===e.modified_at}function HT(r){let e=xf(r.body)&&xf(r.body.error)?r.body.error:{};return new Y(typeof e.code=="string"?e.code:"authority_adoption_request_failed",typeof e.message=="string"?e.message:`Collection adoption request failed with status ${r.status}.`,r.status)}function yt(r){return new Y("invalid_authority_adoption_response",r)}function dc(r){if(r!=null&&r.aborted)throw new Y("authority_adoption_cancelled","Collection adoption was cancelled.")}function xf(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var Pf=1500,KT=250,WT=3e4,nw=1440*60*1e3,Mr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,uc=class{constructor(e={}){T(this,"request");T(this,"now");T(this,"wait");var t,n,i;this.request=(t=e.request)!=null?t:GT,this.now=(n=e.now)!=null?n:Date.now,this.wait=(i=e.wait)!=null?i:QT}async begin(e,t={}){Pn(t.signal);let n=Nr(e.controlUrl),i=e.mirrorName.trim();if(!i||i.length>200)throw new Xe("invalid_mirror_name","Mirror name must contain between 1 and 200 characters.");if(!["read_only","read_write"].includes(e.mode))throw new Xe("invalid_mirror_mode","Mirror mode must be read-only or read-write.");if(e.collectionId!==void 0&&!Mr.test(e.collectionId))throw new Xe("invalid_collection_id","Collection ID must be a UUID.");let s;try{s=await this.request({url:`${n}/v1/mirror-pairing-requests`,method:"POST",headers:{"content-type":"application/json"},body:{mirror_name:i,mode:e.mode,...e.collectionId?{collection_id:e.collectionId}:{}},...t.signal?{signal:t.signal}:{}})}catch(c){throw Pn(t.signal),tw()}let o=ew(s,201);if(!Si(o)||!Mr.test($t(o.pairing_id))||!Gs(o.pairing_secret)||!ZT(o.expires_in)||Number(o.expires_in)*1e3>nw)throw er("Connect returned an invalid mirror approval.");let a=sw(n,$t(o.verification_uri),$t(o.pairing_id));return{controlUrl:n,pairingId:$t(o.pairing_id),refreshCredential:$t(o.pairing_secret),verificationUri:a,expiresAt:new Date(this.now()+Number(o.expires_in)*1e3).toISOString(),requested:{mirrorName:i,mode:e.mode,...e.collectionId?{collectionId:e.collectionId}:{}}}}async enroll(e,t){let n=await this.begin(e,t),{refreshCredential:i,...s}=n;return await t.onVerification(s),this.waitForApproval(n,t)}async waitForApproval(e,t={}){var o,a;JT(e,this.now());let n=rw(t.pollIntervalMs),i=Date.parse(e.expiresAt),s=0;for(;this.now()=500){let l=If(c);if(await this.retry(i,(a=c.retryAfterMs)!=null?a:n,t,s,{code:l.code,message:l.message})===null)break;continue}throw If(c)}throw new Xe("mirror_enrollment_expired","Mirror approval expired before it was completed.")}async renew(e,t={}){YT(e),Pn(t.signal);let n;try{n=await this.request({url:Z_(e.controlUrl,e.enrollmentId,"renew"),method:"POST",headers:{authorization:`Bearer ${e.refreshCredential}`},...t.signal?{signal:t.signal}:{}})}catch(s){throw Pn(t.signal),tw()}let i={controlUrl:e.controlUrl,pairingId:e.enrollmentId,refreshCredential:e.refreshCredential,verificationUri:`${e.controlUrl}/mirror/${e.enrollmentId}`,expiresAt:new Date(this.now()+6e4).toISOString(),requested:{mirrorName:e.name,mode:e.mode,collectionId:e.collectionId}};return Q_(i,ew(n,200),{replicaId:e.replicaId})}async retry(e,t,n,i,s){var l;let o=e-this.now();if(o<=0)return null;let a=Math.min(rw(t),o),c=new Date(this.now()+a).toISOString();return(l=n.onStatus)==null||l.call(n,{state:s?"retrying":"waiting_for_approval",attempt:i,expiresAt:new Date(e).toISOString(),retryAt:c,...s?{error:s}:{}}),await this.wait(a,n.signal),c}},Xe=class extends S{constructor(t,n,i){super(t,n);T(this,"status");this.status=i,this.name="MirrorEnrollmentError"}};function Nr(r){let e;try{e=new URL(r)}catch(n){throw new Xe("invalid_connect_url","Connect URL must be an absolute HTTPS origin.")}if(e.pathname!=="/"||e.search||e.hash||e.username||e.password)throw new Xe("invalid_connect_url","Connect URL must be an origin without credentials, path, query, or fragment.");let t=["localhost","127.0.0.1","[::1]","::1"].includes(e.hostname);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&t))throw new Xe("invalid_connect_url","Connect URL must use HTTPS outside loopback development.");return e.origin}async function GT(r){let e=await fetch(r.url,{method:r.method,headers:r.headers,...r.body===void 0?{}:{body:JSON.stringify(r.body)},...r.signal?{signal:r.signal}:{}}),t=await e.json().catch(()=>null),n=e.headers.get("retry-after");return{status:e.status,body:t,...n===null?{}:{retryAfterMs:XT(n)}}}function Q_(r,e,t){if(!Si(e)||e.status!=="paired"||!Si(e.replica))throw er("Connect returned an invalid mirror enrollment.");let n=e.replica,i=$t(n.id),s=$t(n.collection_id),o=$t(n.name).trim(),a=n.mode,c=$t(e.token),l=$t(e.token_expires_at);if(!Mr.test(i)||!Mr.test(s)||!o||!["read_only","read_write"].includes(String(a))||!Gs(c)||!aw(l))throw er("Connect returned invalid mirror credentials.");if(a!==r.requested.mode)throw er("Connect returned a mirror with a different access mode.");if(r.requested.collectionId&&s!==r.requested.collectionId)throw er("Connect returned a different collection.");if(t.mirrorName!==void 0&&o!==t.mirrorName)throw er("Connect returned a mirror with a different name.");if(t.replicaId!==void 0&&i!==t.replicaId)throw er("Connect returned a different mirror replica.");let u;try{u=iw($t(e.sync_url),s)}catch(d){throw er("Connect returned an invalid authority sync URL.")}return{controlUrl:Nr(r.controlUrl),syncUrl:u,collectionId:s,replicaId:i,mode:a,name:o,enrollmentId:r.pairingId,accessToken:c,refreshCredential:r.refreshCredential,accessTokenExpiresAt:l}}function JT(r,e){Nr(r.controlUrl);let t=Date.parse(r.expiresAt);if(!Mr.test(r.pairingId)||!Gs(r.refreshCredential)||!Number.isFinite(t)||t-e>nw||!r.requested.mirrorName.trim()||r.requested.mirrorName.length>200||!["read_only","read_write"].includes(r.requested.mode)||r.requested.collectionId!==void 0&&!Mr.test(r.requested.collectionId))throw new Xe("invalid_mirror_enrollment_session","Mirror enrollment session is invalid.");sw(r.controlUrl,r.verificationUri,r.pairingId)}function YT(r){if(Nr(r.controlUrl),iw(r.syncUrl,r.collectionId),!Mr.test(r.collectionId)||!Mr.test(r.replicaId)||!Mr.test(r.enrollmentId)||!Gs(r.accessToken)||!Gs(r.refreshCredential)||!aw(r.accessTokenExpiresAt)||!r.name.trim()||r.name.length>200||!["read_only","read_write"].includes(r.mode))throw new Xe("invalid_mirror_enrollment","Stored mirror enrollment is invalid.")}function iw(r,e){let t=new URL(r),n=`/v1/authorities/${encodeURIComponent(e)}/sync`;if(!(t.protocol==="https:"||t.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(t.hostname))||t.username||t.password||t.pathname.replace(/\/$/,"")!==n||t.search||t.hash)throw new Error("invalid sync URL");return`${t.origin}${n}`}function sw(r,e,t){let n;try{n=new URL(e)}catch(s){throw er("Connect returned an invalid mirror verification URI.")}let i=new URL(`/mirror/${encodeURIComponent(t)}`,r);if(n.origin!==i.origin||n.pathname!==i.pathname||n.search||n.hash||n.username||n.password)throw er("Connect returned an untrusted mirror verification URI.");return n.href}function Z_(r,e,t){return`${Nr(r)}/v1/mirror-pairing-requests/${encodeURIComponent(e)}/${t}`}function ew(r,e){if(r.status!==e)throw If(r);return r.body}function If(r){let e=Si(r.body)&&Si(r.body.error)?r.body.error:{};return new Xe($t(e.code)||"mirror_enrollment_request_failed",$t(e.message)||`Mirror enrollment request failed with status ${r.status}.`,r.status)}function er(r){return new Xe("invalid_mirror_enrollment_response",r)}function ow(r){return{code:"mirror_enrollment_unreachable",message:"Connect could not be reached for mirror enrollment."}}function tw(){let r=ow(void 0);return new Xe(r.code,r.message)}function rw(r=Pf){return Number.isFinite(r)?Math.min(WT,Math.max(KT,Math.round(r))):Pf}function XT(r){let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);return Number.isFinite(t)?Math.max(0,t-Date.now()):Pf}function QT(r,e){return Pn(e),new Promise((t,n)=>{let i=setTimeout(o,r),s=()=>{clearTimeout(i),e==null||e.removeEventListener("abort",s),n(new Xe("mirror_enrollment_cancelled","Mirror enrollment was cancelled."))};function o(){e==null||e.removeEventListener("abort",s),t()}e==null||e.addEventListener("abort",s,{once:!0})})}function Pn(r){if(r!=null&&r.aborted)throw new Xe("mirror_enrollment_cancelled","Mirror enrollment was cancelled.")}function aw(r){let e=Date.parse(r);return Number.isFinite(e)}function ZT(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function Gs(r){return typeof r=="string"&&r.length>=16}function $t(r){return typeof r=="string"?r:""}function Si(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var eR=/(?:^|\/)(?:\.{1,2}|)(?:\/|$)/u,tR=/[\p{Cc}:]/u,rR=/[. ](?:\/|$)/u,nR=/(?:^|\/)(?:CON|PRN|AUX|NUL|COM[1-9¹²³]|LPT[1-9¹²³])(?:\.|\/|$)/iu;function gt(r){if(!r||r.startsWith("/")||r.includes("\\")||eR.test(r)||tR.test(r)||rR.test(r)||nR.test(r))throw new S("invalid_path",`Mirror received an unsafe path: ${r}.`)}function Le(r){return gt(r),Ei(r)}function Ei(r){return/^[\x20-\x7e]+$/u.test(r)?/[A-Z]/u.test(r)?r.toLowerCase():r:r.normalize("NFC").toLowerCase().normalize("NFC")}var lw=new Set(["image","audio","video","pdf","other"]),cw=["image","audio","video","pdf","other"],iR=new Set([".mdbase",".git","node_modules","_contracts","_schemas","_types","_views"]),sR=/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu,oR=/^sha256:[0-9a-f]{64}$/u,aR=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,cR=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/u;function pc(r){var s,o;let e={file_classes:[...(s=r==null?void 0:r.file_classes)!=null?s:[]],excluded_folders:[...(o=r==null?void 0:r.excluded_folders)!=null?o:[]]};if(e.excluded_folders.length>100)throw new S("invalid_file_materialization","Selective sync supports at most 100 excluded folders.");let t=new Set;for(let a of e.file_classes){if(!lw.has(a)||t.has(a))throw new S("invalid_file_materialization","Selected file media classes must be valid and unique.");t.add(a)}let n=new Set,i=new Set;for(let a of e.excluded_folders){Ai(a,!0);let c=Le(a);if(n.has(a)||i.has(c))throw new S("invalid_file_materialization","Excluded folders must be unique on portable filesystems.");n.add(a),i.add(c)}return e.file_classes.sort((a,c)=>cw.indexOf(a)-cw.indexOf(c)),e.excluded_folders.sort((a,c)=>Le(a).localeCompare(Le(c))),e}function tr(r,e){let t=Le(e);return!r.excluded_folders.some(n=>{let i=Le(n);return t===i||t.startsWith(`${i}/`)})}function on(r,e){return r.file_classes.includes(e.media_class)&&tr(r,e.path)}function Of(r){let e=r.includes(".")?r.slice(r.lastIndexOf(".")+1).toLowerCase():"";return["avif","bmp","gif","jpeg","jpg","png","svg","webp"].includes(e)?"image":["flac","m4a","mp3","oga","ogg","opus","wav"].includes(e)?"audio":["3gp","mkv","mov","mp4","webm"].includes(e)?"video":e==="pdf"?"pdf":"other"}function hc(r,e){return r.file_classes.includes(Of(e))&&tr(r,e)}function St(r){if(Ai(r.path,!1),typeof r.file_id!="string"||!aR.test(r.file_id)||typeof r.revision!="string"||!r.revision||r.revision.length>255||!oR.test(r.content_digest)||!Number.isSafeInteger(r.size)||r.size<0||!lw.has(r.media_class)||typeof r.modified_at!="string"||!cR.test(r.modified_at)||!Number.isFinite(Date.parse(r.modified_at))||r.media_type!==void 0&&(typeof r.media_type!="string"||!r.media_type||r.media_type.length>255))throw new S("invalid_snapshot",`Collection file ${r.path} has invalid metadata.`)}function Ai(r,e){if(gt(r),r.length>1024)throw new S("invalid_file_path","Collection file paths cannot exceed 1024 characters.");if(r.split("/").some(i=>i.startsWith(".")||/[<>"|?*]/u.test(i)||sR.test(i)||iR.has(i.toLowerCase()))||!e&&/\.md$/iu.test(r))throw new S("invalid_file_path",`Collection file path ${r} is hidden, reserved, or non-portable.`)}async function Js(r,e,t){let n,i=new Set;do{let s=await r.fileSnapshot(e.snapshot_id,n);if(s.protocol_version!==1||s.type!=="file_snapshot_page"||s.snapshot_id!==e.snapshot_id||s.scope_epoch!==e.scope_epoch||s.cursor!==e.head)throw new S("invalid_snapshot","Authority file snapshot boundary changed during download.");for(let o of s.files)St(o);if(await t(s.files),n=s.next_page,n!==void 0&&i.has(n))throw new S("invalid_snapshot","Authority file snapshot repeated a page cursor.");n!==void 0&&i.add(n)}while(n)}function Oe(r,e){return(r==null?void 0:r.size)===e.size&&r.content_digest===e.content_digest}async function*fc(r,e){let t=Ye.create(),n=0;for await(let i of r){if(!(i instanceof Uint8Array)||i.byteLength===0){if(i instanceof Uint8Array&&i.byteLength===0)continue;throw new S("file_integrity_failed","A file transport returned invalid bytes.")}if(n+=i.byteLength,!Number.isSafeInteger(n)||n>e.size)throw new S("file_integrity_failed",`Downloaded bytes for ${e.path} are oversized.`);t.update(i),yield i}if(n!==e.size||`sha256:${qe(t.digest())}`!==e.content_digest)throw new S("file_integrity_failed",`Downloaded bytes for ${e.path} failed integrity verification.`)}async function*mc(r,e,t){let n=Ye.create(),i=0;for await(let s of r){if(!(s instanceof Uint8Array))throw new S("file_integrity_failed",`Local bytes for ${t} are invalid.`);if(s.byteLength!==0){if(i+=s.byteLength,!Number.isSafeInteger(i)||i>e.size)throw new S("pending_local_changed",`Local file ${t} changed while being staged.`);n.update(s),yield s}}if(i!==e.size||`sha256:${qe(n.digest())}`!==e.content_digest)throw new S("pending_local_changed",`Local file ${t} changed while being staged.`)}async function Ys(r,e,t){if(St(t),await e.has(t.content_digest))try{for await(let n of fc(e.read(t.content_digest),t));return}catch(n){await e.remove(t.content_digest)}try{await e.write(t.content_digest,fc(r.downloadFile(t),t))}catch(n){throw await e.remove(t.content_digest).catch(()=>{}),n}if(!await e.has(t.content_digest))throw new S("file_integrity_failed","The verified file blob was not persisted.")}var an=new TextEncoder;function Cf(r){var d,f,p,m,h;let e=xn(r.collectionId,"Collection ID"),t=(d=r.sourceHead)!=null?d:0;if(!Number.isSafeInteger(t)||t<0)throw new Y("invalid_authority_snapshot","Source head must be a non-negative integer.");let n=new Set,i=r.resources.map(y=>{let b=yc(y.path);if(n.add(b)||Tf(b),!["configuration","contract","schema","type","view"].includes(y.kind))throw new Y("invalid_authority_snapshot",`Unsupported collection resource kind for ${b}.`);return{path:b,kind:y.kind,revision:dw(y.document),document:y.document}}).sort(dR);if(((f=i[0])==null?void 0:f.path)!=="mdbase.yaml"||i[0].kind!=="configuration"||i.filter(({kind:y})=>y==="configuration").length!==1)throw new Y("invalid_authority_snapshot","A portable snapshot requires one mdbase.yaml configuration resource.");let s=r.records.map(y=>{let b=yc(y.path);return n.add(b)||Tf(b),{record_id:y.recordId?xn(y.recordId,`Record ID for ${b}`):fw(e,b),path:b,document:y.document}}).sort((y,b)=>Rf(y.path,b.path)),o=new Set,a=((p=r.files)!=null?p:[]).map(y=>{let b=yc(y.path);n.add(b)||Tf(b);let g=xn(y.file_id,`File ID for ${b}`);if(!o.add(g))throw new Y("invalid_authority_snapshot",`Collection snapshot contains file ID more than once: ${g}`);return lR(y,b),{...y,file_id:g,path:b}}).sort((y,b)=>Rf(y.path,b.path)),c=uw(i.flatMap(({path:y,revision:b})=>[y,b])),l=uw([...i.flatMap(({path:y,revision:b})=>["resource",y,b]),...s.flatMap(y=>["record",y.path,dw(y.document)]),...a.flatMap(y=>{var b;return["file",y.path,y.file_id,y.revision,y.content_digest,String(y.size),(b=y.media_type)!=null?b:"",y.media_class]})]),u=ac([...i.map(({path:y,document:b})=>({kind:"resource",path:y,identity:"",document_hash:qe(Ye(an.encode(b)))})),...s.map(y=>({kind:"record",path:y.path,identity:y.record_id,document_hash:qe(Ye(an.encode(y.document)))})),...a.map(y=>({kind:"file",path:y.path,identity:y.file_id,document_hash:cc(y)}))]);return{protocol_version:1,collection_id:e,source_head:t,source_revision:l,manifest_digest:u,resources:{revision:c,spec_version:r.specVersion,types:(m=r.types)!=null?m:[],contracts:(h=r.contracts)!=null?h:[],documents:i},records:s,files:a}}function lR(r,e){try{St({...r,path:e})}catch(t){throw new Y("invalid_authority_snapshot",`File descriptor is invalid for ${e}.`)}if(r.media_class!==Of(e))throw new Y("invalid_authority_snapshot",`File media class does not match its path for ${e}.`)}function fw(r,e){let t=uR(xn(r,"Collection ID")),i=lc(new Uint8Array([...t,...an.encode(yc(e))])).slice(0,16);i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=qe(i);return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function dw(r){return`sha256:${qe(Ye(an.encode(r)))}`}function uw(r){let e=Ye.create();for(let t of r){let n=BigInt(an.encode(t).length),i=new Uint8Array(8);new DataView(i.buffer).setBigUint64(0,n),e.update(i),e.update(an.encode(t))}return`sha256:${qe(e.digest())}`}function dR(r,e){return r.kind==="configuration"&&e.kind!=="configuration"?-1:e.kind==="configuration"&&r.kind!=="configuration"?1:Rf(r.path,e.path)}function Rf(r,e){let t=an.encode(r),n=an.encode(e),i=Math.min(t.length,n.length);for(let s=0;s!t||t==="."||t===".."))throw new Y("invalid_authority_snapshot",`Collection path is unsafe: ${r}`);return e}function Tf(r){throw new Y("invalid_authority_snapshot",`Collection snapshot contains the path more than once: ${r}`)}function uR(r){return Uint8Array.from(r.replaceAll("-","").match(/../g).map(e=>Number.parseInt(e,16)))}var fR=/^sha256:[a-f0-9]{64}$/,pR=/^[a-f0-9]{64}$/,Nf=1500,Lf=1440*60*1e3,hR=200,pw=8*1024*1024,mR=new TextEncoder,gc=class{constructor(e={}){T(this,"request");T(this,"now");T(this,"wait");var t,n,i;this.request=(t=e.request)!=null?t:_R,this.now=(n=e.now)!=null?n:Date.now,this.wait=(i=e.wait)!=null?i:bR}async begin(e,t={}){var f,p;On(t.signal);let n=Nr(e.controlUrl),i=xn(e.collectionId,"Collection ID"),s=Mf(e.displayName,"Collection name"),o=Mf(e.sourceName,"Source name"),a=(f=e.retainMirror)!=null?f:!0,c=a?Mf((p=e.mirrorName)!=null?p:o,"Mirror name"):void 0,l;try{l=await this.request({url:`${n}/v1/authority-adoptions`,method:"POST",headers:{"content-type":"application/json"},body:{collection_id:i,display_name:s,source_name:o,retain_mirror:a,...c?{mirror_name:c}:{}},...t.signal?{signal:t.signal}:{}})}catch(m){throw On(t.signal),gw()}let u=gR(l,201);if(!Lr(u)||!$i.test(ot(u.adoption_id))||!Df(u.adoption_secret)||!SR(u.expires_in)||Number(u.expires_in)*1e3>Lf)throw at("Connect returned an invalid collection adoption request.");let d=$w(n,ot(u.verification_uri),ot(u.adoption_id));return{controlUrl:n,adoptionId:ot(u.adoption_id),credential:ot(u.adoption_secret),verificationUri:d,expiresAt:new Date(this.now()+Number(u.expires_in)*1e3).toISOString(),requested:{collectionId:i,displayName:s,sourceName:o,retainMirror:a,...c?{mirrorName:c}:{}}}}async start(e,t){let n=await this.begin(e,t),{credential:i,...s}=n;return await t.onVerification(s),{session:n,prepared:await this.waitForApproval(n,t)}}async waitForApproval(e,t={}){var o,a;ki(e,this.now());let n=bw(t.pollIntervalMs),i=Date.parse(e.expiresAt),s=0;for(;this.now()=500){let l=In(c);if(!await this.retry(i,(a=c.retryAfterMs)!=null?a:n,s,t,{code:l.code,message:l.message}))break;continue}throw In(c)}throw new Y("authority_adoption_expired","Collection adoption approval expired before upload began.")}async exchange(e,t={}){ki(e,this.now(),!0);let n=await this.controlRequest(e,"exchange","POST",{},t.signal);if(n.status===202)throw new Y("authority_adoption_pending","Collection adoption is still awaiting approval.",202);if(n.status!==200)throw In(n);return mw(e,n.body)}async uploadSnapshot(e,t,n,i={}){ki(e,this.now(),!0),ww(e,t),hw(e,n);let s={protocol_version:1,collection_id:n.collection_id,source_head:n.source_head,source_revision:n.source_revision,manifest_digest:n.manifest_digest,resources:n.resources,record_count:n.records.length,file_count:n.files.length,files:n.files};await this.importRequest(t.import.manifest_url,"PUT",t.import.access_token,s,i.signal);let o=0,a=[],c=0;for(let l of n.records){let u=mR.encode(JSON.stringify(l)).length;if(u>pw)throw new Y("authority_adoption_record_too_large",`Record ${l.path} is too large to adopt.`);a.length>0&&(a.length===hR||c+u>pw)&&(await this.uploadPage(t.import,o,a,i.signal),o+=1,a=[],c=0),a.push(l),c+=u}a.length>0&&await this.uploadPage(t.import,o,a,i.signal);for(let l of n.files){if(!i.fileSource)throw new Y("authority_adoption_file_source_required",`File bytes are required to adopt ${l.path}.`);let u=await i.fileSource(l);await X_(this.request,t.import,l,u,i)}await this.importRequest(t.import.finalize_url,"POST",t.import.access_token,void 0,i.signal)}async complete(e,t,n={}){ki(e,this.now(),!0),hw(e,t);let i;try{i=await this.controlRequest(e,"complete","POST",{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head},n.signal)}catch(a){throw On(n.signal),new Cr("Connect could not confirm whether hosted authority activated.",{cause:a})}if(i.status>=500)throw new Cr("Connect could not confirm whether hosted authority activated.");if(i.status!==200)throw In(i);let s=i.body;if(!Lr(s)||s.status!=="completed")throw at("Connect returned an invalid adoption completion.");let o=vw(e,s.adoption);if(o.state!=="completed"||o.manifest_digest!==t.manifest_digest||o.source_revision!==t.source_revision||o.final_head!==t.source_head)throw at("Connect completed a different adoption snapshot.");return{status:"completed",adoption:o}}async cancel(e,t={}){ki(e,this.now(),!0);let n=await this.controlRequest(e,void 0,"DELETE",void 0,t.signal);if(n.status!==200)throw In(n)}mirrorEnrollmentSession(e,t){var n;if(ki(e,this.now(),!0),t.status!=="completed"||t.adoption.collection_id!==e.requested.collectionId)throw at("Completed adoption does not belong to this session.");return e.requested.retainMirror?{controlUrl:e.controlUrl,pairingId:e.adoptionId,refreshCredential:e.credential,verificationUri:`${e.controlUrl}/mirror/${e.adoptionId}`,expiresAt:new Date(this.now()+Lf).toISOString(),requested:{mirrorName:(n=e.requested.mirrorName)!=null?n:e.requested.sourceName,mode:"read_write",collectionId:e.requested.collectionId}}:null}async uploadPage(e,t,n,i){let s={protocol_version:1,page:t,records:n};await this.importRequest(e.records_url,"PUT",e.access_token,s,i)}async importRequest(e,t,n,i,s){let o;try{o=await this.request({url:e,method:t,headers:{authorization:`Bearer ${n}`,...i===void 0?{}:{"content-type":"application/json"}},...i===void 0?{}:{body:i},...s?{signal:s}:{}})}catch(a){throw On(s),gw()}if(o.status<200||o.status>=300)throw In(o)}controlRequest(e,t,n,i,s){return this.request({url:yw(e,t),method:n,headers:{authorization:`Bearer ${e.credential}`,...i===void 0?{}:{"content-type":"application/json"}},...i===void 0?{}:{body:i},...s?{signal:s}:{}})}async retry(e,t,n,i,s){var l;let o=e-this.now();if(o<=0)return!1;let a=Math.min(bw(t),o),c=new Date(this.now()+a).toISOString();return(l=i.onStatus)==null||l.call(i,{state:s?"retrying":"waiting_for_approval",attempt:n,expiresAt:new Date(e).toISOString(),retryAt:c,...s?{error:s}:{}}),await this.wait(a,i.signal),!0}};function ki(r,e,t=!1){Nr(r.controlUrl);let n=Date.parse(r.expiresAt);if(!$i.test(r.adoptionId)||!Df(r.credential)||!Number.isFinite(n)||n-e>Lf||!t&&n<=e||!$i.test(r.requested.collectionId)||!r.requested.displayName.trim()||!r.requested.sourceName.trim())throw new Y("invalid_authority_adoption_session","Stored collection adoption state is invalid.");$w(r.controlUrl,r.verificationUri,r.adoptionId)}function ww(r,e){if(e.status!=="ready"||e.adoption.id!==r.adoptionId||e.adoption.collection_id!==r.requested.collectionId)throw at("Prepared adoption does not belong to this session.");let t=e.import;if(!$i.test(t.import_id)||!Df(t.access_token))throw at("Connect returned an invalid authority import capability.");let n=[[t.manifest_url,"manifest"],[t.records_url,"records"],[t.files_url,"files"],[t.finalize_url,"finalize"]],i;for(let[s,o]of n){let a=yR(s,t.import_id,o);if(!a||i!==void 0&&a.origin!==i)throw at("Connect returned an invalid authority import capability.");i=a.origin}}function hw(r,e){var t;if(e.protocol_version!==1||e.collection_id!==r.requested.collectionId||!Number.isSafeInteger(e.source_head)||e.source_head<0||!fR.test(e.source_revision)||!pR.test(e.manifest_digest)||((t=e.resources.documents)==null?void 0:t.length)===0||!Array.isArray(e.files))throw new Y("invalid_authority_snapshot","Authority snapshot does not belong to this adoption.")}function mw(r,e){if(!Lr(e)||!["ready","activating","completed"].includes(ot(e.status)))throw at("Connect returned an invalid adoption exchange.");let t=vw(r,e.adoption);if(e.status==="completed")return{status:"completed",adoption:t};if(e.status==="activating")return{status:"activating",adoption:t};if(!Lr(e.import)||!Lr(e.staged))throw at("Connect omitted the authority import capability.");let n=e.import,i=e.staged,s={status:"ready",adoption:t,import:{import_id:ot(n.import_id),manifest_url:ot(n.manifest_url),records_url:ot(n.records_url),files_url:ot(n.files_url),finalize_url:ot(n.finalize_url),access_token:ot(n.access_token)},staged:{state:i.state,manifest_digest:_w(i.manifest_digest),source_revision:_w(i.source_revision),source_head:$R(i.source_head)}};if(ww(r,s),!["receiving","uploaded"].includes(s.staged.state))throw at("Connect returned an invalid staged import state.");return s}function vw(r,e){if(!Lr(e))throw at("Connect omitted collection adoption state.");let t=e;if(t.id!==r.adoptionId||t.collection_id!==r.requested.collectionId||!["requested","approved","prepared","activating","completed","cancelled","expired"].includes(t.state)||!Number.isSafeInteger(t.authority_epoch)||t.authority_epoch<2||!vR(t.expires_at))throw at("Connect returned invalid collection adoption state.");return t}function yR(r,e,t){try{let n=new URL(r);return(n.protocol==="https:"||n.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(n.hostname))&&!n.username&&!n.password&&!n.search&&!n.hash&&n.pathname===`/v1/authority-imports/${e}/${t}`?n:null}catch(n){return null}}function $w(r,e,t){let n;try{n=new URL(e)}catch(s){throw at("Connect returned an invalid adoption verification URI.")}let i=new URL(`/adopt/${encodeURIComponent(t)}`,r);if(n.origin!==i.origin||n.pathname!==i.pathname||n.search||n.hash||n.username||n.password)throw at("Connect returned an untrusted adoption verification URI.");return n.href}function yw(r,e){let t=e?`/${e}`:"";return`${Nr(r.controlUrl)}/v1/authority-adoptions/${encodeURIComponent(r.adoptionId)}${t}`}function Mf(r,e){let t=r.trim();if(!t||t.length>200)throw new Y("invalid_authority_adoption",`${e} must contain between 1 and 200 characters.`);return t}function gR(r,e){if(r.status!==e)throw In(r);return r.body}function In(r){let e=Lr(r.body)&&Lr(r.body.error)?r.body.error:{};return new Y(ot(e.code)||"authority_adoption_request_failed",ot(e.message)||`Collection adoption request failed with status ${r.status}.`,r.status)}function at(r){return new Y("invalid_authority_adoption_response",r)}function Sw(r){return{code:"authority_adoption_unreachable",message:"Connect could not be reached for collection adoption."}}function gw(){let r=Sw(void 0);return new Y(r.code,r.message)}function bw(r=Nf){return Number.isFinite(r)?Math.min(3e4,Math.max(250,Math.round(r))):Nf}function bR(r,e){return On(e),new Promise((t,n)=>{let i=setTimeout(o,r),s=()=>{clearTimeout(i),e==null||e.removeEventListener("abort",s),n(new Y("authority_adoption_cancelled","Collection adoption was cancelled."))};function o(){e==null||e.removeEventListener("abort",s),t()}e==null||e.addEventListener("abort",s,{once:!0})})}function On(r){if(r!=null&&r.aborted)throw new Y("authority_adoption_cancelled","Collection adoption was cancelled.")}async function _R(r){let e=await fetch(r.url,{method:r.method,headers:r.headers,redirect:"error",...r.body===void 0?{}:{body:r.rawBody?r.body:JSON.stringify(r.body)},...r.signal?{signal:r.signal}:{}}),t=await e.json().catch(()=>({})),n=e.headers.get("retry-after");return{status:e.status,body:t,headers:Object.fromEntries(e.headers.entries()),...n?{retryAfterMs:wR(n)}:{}}}function wR(r){let e=Number(r);if(Number.isFinite(e)&&e>=0)return e*1e3;let t=Date.parse(r);return Number.isFinite(t)?Math.max(0,t-Date.now()):Nf}function vR(r){return Number.isFinite(Date.parse(r))}function _w(r){return r===null?null:ot(r)}function $R(r){return r===null?null:typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:Number.NaN}function SR(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function Df(r){return typeof r=="string"&&r.length>=16}function ot(r){return typeof r=="string"?r:""}function Lr(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var qf=64,ER=new TextEncoder,Qs=Object.freeze({digest:r=>qe(Ye(ER.encode(r))),randomId:()=>{var r;if(typeof((r=globalThis.crypto)==null?void 0:r.randomUUID)!="function")throw new S("mirror_random_unavailable","This runtime must provide crypto.randomUUID() or a MirrorRuntime adapter.");return globalThis.crypto.randomUUID()},now:()=>new Date().toISOString()});var Xs=class{constructor(){T(this,"held",!1)}async runExclusive(e){if(this.held)throw new S("mirror_folder_in_use","Another mdbase mirror process is already using this folder.");this.held=!0;try{return await e()}finally{this.held=!1}}};function Ew(r,e,t){var i,s,o,a,c,l,u,d;if(r.protocol_version!==1||r.replica_id!==e)throw new Error;if((i=r.resources)!=null||(r.resources={}),(s=r.files)!=null||(r.files={}),r.selective_sync=pc(r.selective_sync),(o=r.pending)!=null||(r.pending=[]),(a=r.pending_files)!=null||(r.pending_files=[]),(c=r.conflicts)!=null||(r.conflicts={}),(l=r.file_conflicts)!=null||(r.file_conflicts={}),(u=r.mode)!=null||(r.mode="read_only"),r.mode!==t)throw new S("mirror_mode_mismatch",`Mirror metadata belongs to a ${r.mode.replace("_","-")} replica.`);let n=[];for(let[f,p]of Object.entries(r.records))if(n.push(Le(p.path)),p.record&&(p.record.record_id!==f||p.record.path!==p.path))throw new Error;for(let[f,p]of Object.entries(r.resources)){if(gt(f),f!==p.path)throw new Error;n.push(Le(p.path))}for(let[f,p]of Object.entries(r.files)){if(St(p.file),p.file.file_id!==f)throw new Error;n.push(Le(p.file.path))}n.sort();for(let f=1;fl.kind==="configuration"&&l.path==="mdbase.yaml");if(n.length!==1)throw new S("invalid_snapshot","Hosted snapshot requires exactly one canonical mdbase.yaml resource.");let i=Pw(n[0].document,e),s=(c=Ow(n[0].document).settings)!=null?c:{},o=xi(s.types_folder,"_types"),a=xi(s.contracts_folder,"_contracts");for(let l of r){let u=l.path.split(".").at(-1),d=l.path.split("/"),f=d.some(m=>m.startsWith(".")),p=!1;if(l.kind==="configuration")p=l.path==="mdbase.yaml";else if(l.kind==="type")p=jf(l.path,o)&&u==="md"&&kw(l.document,l.path)==="mdbase.type";else if(l.kind==="contract")p=jf(l.path,a)&&u==="md"&&kw(l.document,l.path)==="mdbase.contract";else if(l.kind==="schema"){let m=kR(l.document);p=!f&&u==="json"&&d.some(h=>h==="schemas"||h==="_schemas")&&m!==null}else l.kind==="view"&&(p=!f&&u==="base");if(!p)throw new S("invalid_snapshot",`Hosted resource ${l.path} is not valid for kind ${l.kind}.`)}return i}function xw(r){return{reservedFolders:new Set(["_types","_contracts","_types/_migrations",".mdbase"]),resourcePaths:r}}function Pw(r,e){var s;let t=(s=Ow(r).settings)!=null?s:{},n=xi(t.types_folder,"_types");return{reservedFolders:new Set([n,xi(t.contracts_folder,"_contracts"),xi(t.migrations_folder,`${n}/_migrations`),xi(t.cache_folder,".mdbase",!0)]),resourcePaths:e}}async function Iw(r,e){if(r.length===0)return xw(new Set);let t=await e();if(t===null)throw new S("invalid_mirror_state","Mirror collection configuration is missing.");return Pw(t,new Set(r))}function bt(r,e){if(gt(r),/(?:^|\/)\./u.test(r)||e.resourcePaths.has(r)||AR(r,e.reservedFolders)||!r.endsWith(".md"))throw new S("invalid_record_path",`Mirror record path ${r} is outside the configured record namespace.`)}function AR(r,e){for(let t of e)if(jf(r,t))return!0;return!1}function _c(r,e){return r.filter(t=>{try{return bt(t,e),!0}catch(n){return!1}})}function Ow(r){let e;try{e=Ks(r)}catch(n){throw new S("invalid_snapshot","Hosted mdbase.yaml is not valid YAML.")}if(!e||typeof e!="object"||Array.isArray(e))throw new S("invalid_snapshot","Hosted mdbase.yaml requires an object document.");let t=e;if(typeof t.spec_version!="string")throw new S("invalid_snapshot","Hosted mdbase.yaml requires spec_version.");return t}function xi(r,e,t=!1){let n=typeof r=="string"?r:e;if(gt(n),!t&&n.split("/").some(i=>i.startsWith(".")))throw new S("invalid_snapshot",`Collection control folder ${n} must not be hidden.`);return n}function jf(r,e){return r===e||r.startsWith(`${e}/`)}function kR(r){try{let e=JSON.parse(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}catch(e){return null}}function kw(r,e){try{return Rr(r,e).frontmatter.kind}catch(t){return null}}var Qe=class extends S{constructor(t,n){super("mirror_diverged",`Local edits at ${n} must be resolved before the mirror can continue.`);T(this,"recordId");T(this,"path");this.recordId=t,this.path=n}},wc=class extends S{constructor(t){super("mirror_initialization_conflict",`Existing files differ from remote Markdown: ${t.join(", ")}. Move or reconcile them before syncing.`);T(this,"paths");this.paths=t}};async function vc(r,e,t,n){var i,s;for(let[o,a]of Object.entries(r.records)){bt(a.path,e);let c=await t.read(a.path);if(c===null||n(c)!==a.hash)throw new Qe(o,a.path)}for(let[o,a]of Object.entries((i=r.resources)!=null?i:{})){let c=await t.read(a.path);if(c===null||n(c)!==a.hash)throw new Qe(`resource:${o}`,a.path)}for(let[o,a]of Object.entries((s=r.files)!=null?s:{})){let c=await t.inspectBinary(a.file.path);if(!Oe(c,a.file))throw new Qe(o,a.file.path)}}function ue(r){return Ei(r)}function Tw(r,e,t,n,i=[]){let s=ue(r);for(let o of t)if(ue(o)===s)throw new S("invalid_record_path",`Mirror record path ${r} aliases authority resource ${o} on a supported filesystem.`);for(let[o,a]of n)if((o!==e||a.path!==r)&&ue(a.path)===s)throw new S("invalid_record_path",`Mirror record paths ${a.path} and ${r} alias on a supported filesystem.`);for(let[,o]of i)if(ue(o.file.path)===s)throw new S("invalid_record_path",`Mirror record path ${r} aliases collection file ${o.file.path} on a supported filesystem.`)}function Rw(r,e,t){var i,s;let n=ue(r);for(let o of Object.values((i=t.resources)!=null?i:{}))if(ue(o.path)===n)throw new S("invalid_file_path",`Collection file ${r} aliases authority resource ${o.path}.`);for(let o of Object.values(t.records))if(ue(o.path)===n)throw new S("invalid_file_path",`Collection file ${r} aliases record ${o.path}.`);for(let[o,a]of Object.entries((s=t.files)!=null?s:{}))if((o!==e||a.file.path!==r)&&ue(a.file.path)===n)throw new S("invalid_file_path",`Collection files ${a.file.path} and ${r} alias on a supported filesystem.`)}function rr(r){let e=new Map;for(let t of r){let n=ue(t),i=e.get(n);if(i!==void 0&&i!==t)throw new S("invalid_record_path",`Mirror paths ${i} and ${t} alias on a supported filesystem.`);e.set(n,t)}}function Cw(r,e,t){var c,l,u,d,f,p;Ef(r);let n=new Set;for(let m in(c=t.conflicts)!=null?c:{})Object.prototype.hasOwnProperty.call(t.conflicts,m)&&n.add(m);if(Object.keys((l=t.local_issues)!=null?l:{}).length>0)for(let m in t.records){if(!Object.prototype.hasOwnProperty.call(t.records,m))continue;let h=t.records[m];(u=t.local_issues)!=null&&u[h.path]&&n.add(m)}let i=new Set;for(let m of r)m.type==="put"&&(bt(m.record.path,e),n.has(m.record.record_id)||i.add(Le(m.record.path)));let s=new Map;for(let m in(d=t.resources)!=null?d:{}){if(!Object.prototype.hasOwnProperty.call(t.resources,m))continue;let h=Le(m);i.has(h)&&s.set(h,{path:m,recordId:null})}for(let m in t.records){if(!Object.prototype.hasOwnProperty.call(t.records,m))continue;let h=t.records[m],y=Le(h.path);i.has(y)&&s.set(y,{path:h.path,recordId:m})}let o=new Map,a=m=>{var h,y;return o.has(m)?o.get(m):(y=(h=t.records[m])==null?void 0:h.path)!=null?y:null};for(let m of r){let h=m.type==="put"?m.record.record_id:m.record_id;if(n.has(h))continue;if(m.type==="remove"){let _=a(h);if(_!==null){let k=Le(_);((f=s.get(k))==null?void 0:f.recordId)===h&&s.delete(k)}o.set(h,null);continue}let y=Le(m.record.path),b=s.get(y);if(b!==void 0&&(b.recordId!==h||b.path!==m.record.path))throw new S("invalid_record_path",`Mirror paths ${b.path} and ${m.record.path} alias on a supported filesystem.`);let g=a(h);if(g!==null){let _=Le(g);((p=s.get(_))==null?void 0:p.recordId)===h&&s.delete(_)}s.set(y,{path:m.record.path,recordId:h}),o.set(h,m.record.path)}}async function Mw({replicaId:r,state:e,pathPolicy:t,fileSystem:n,runtime:i,pathSelected:s=()=>!0}){var b,g,_,k,v,E,O;let o=new Set(Object.keys((b=e.resources)!=null?b:{}));for(let[w,x]of Object.entries((g=e.resources)!=null?g:{})){let $=await n.read(w);if($===null||i.digest($)!==x.hash)throw new Qe(`resource:${w}`,w)}let a=_c(await n.listMarkdown(o),t).filter(s);rr([...o,...a,...Object.values((_=e.files)!=null?_:{}).map(w=>w.file.path)]);let c=new Map(Object.entries(e.records).map(([w,x])=>[x.path,w])),l=new Map;for(let w of a){let x=await n.read(w);if(x===null)continue;let $=i.digest(x),L=c.get(w),F=L!==void 0&&((k=e.records[L])==null?void 0:k.hash)===$;l.set(w,F?{hash:$}:{document:x,hash:$})}let u=new Set([...l.keys()].filter(w=>!c.has(w))),d=new Set(Object.entries(e.records).filter(([,w])=>!l.has(w.path)).map(([w])=>w)),f=[],p={},m=(w,x,$)=>{try{return Rr(w,x)}catch(L){let F=sc(L,x);if(!F)throw L;return p[x]={...F,hash:$},null}},h=new Map,y=(w,x,$)=>{let L=i.randomId(),F=h.get(w.record_id);f.push({mutation:{...w,mutation_id:L,replica_id:r,scope_epoch:e.scope_epoch,created_at:i.now(),...F?{causal_predecessor:F}:{}},local_path:x,local_hash:$}),h.set(w.record_id,L)};for(let w of[...d]){if((v=e.conflicts)!=null&&v[w]){d.delete(w);continue}let x=e.records[w],$=[...u].filter(F=>{var z;return((z=l.get(F))==null?void 0:z.hash)===x.hash});if($.length!==1)continue;let L=$[0];y({operation:"rename",record_id:w,base_revision:x.revision,input:{path:L}},L,l.get(L).hash),d.delete(w),u.delete(L)}for(let[w,x]of Object.entries(e.records)){if((E=e.conflicts)!=null&&E[w]||d.has(w))continue;let $=l.get(x.path);if(!$||$.hash===x.hash)continue;let L=x.record;if(!L)throw new S("mirror_state_upgrade_required","Run a receive sync before editing this older writable mirror.");let F=m($.document,x.path,$.hash);F&&y({operation:"update",record_id:w,base_revision:x.revision,input:{patch:oc(L.frontmatter,F.frontmatter),body:F.body}},x.path,$.hash)}for(let w of d){if((O=e.conflicts)!=null&&O[w])continue;let x=e.records[w];y({operation:"delete",record_id:w,base_revision:x.revision,input:{}},x.path,null)}for(let w of u){let x=l.get(w),$=m(x.document,w,x.hash);$&&y({operation:"create",record_id:i.randomId(),input:{path:w,frontmatter:$.frontmatter,body:$.body}},w,x.hash)}return{pending:f,localIssues:p}}async function Dw(r){var f,p,m,h,y,b;let{state:e,fileSystem:t,blobStore:n,selectiveSync:i,runtime:s}=r;if(i.file_classes.length===0)return;if(!t.listBinary||!t.readBinary||!n)throw new S("writable_file_storage_unavailable","Writable selected files require binary enumeration, streaming, and blob-store adapters.");let o=new Set([...Object.values(e.records).map(g=>g.path),...Object.values((f=e.resources)!=null?f:{}).map(g=>g.path)]),a=(await t.listBinary(o)).filter(g=>hc(i,g));for(let g of a)Ai(g,!1);rr([...o,...a,...Object.values((p=e.files)!=null?p:{}).map(g=>g.file.path)]);let c=new Map;for(let g of a){let _=await t.inspectBinary(g);_&&c.set(g,_)}let l=new Set(a),u=new Set;for(let[g,_]of Object.entries((m=e.files)!=null?m:{}))c.has(_.file.path)?l.delete(_.file.path):(h=e.file_conflicts)!=null&&h[g]||u.add(g);let d=[];for(let g of[...u]){let _=e.files[g].file,k=[...l].filter(O=>{let w=c.get(O);return w.size===_.size&&w.content_digest===_.content_digest});if(k.length!==1)continue;let v=k[0],E=c.get(v);d.push({operation:"move",mutation_id:s.randomId(),file_id:g,from_path:_.path,path:v,base_revision:_.revision,...E}),u.delete(g),l.delete(v)}for(let[g,_]of Object.entries((y=e.files)!=null?y:{})){if(u.has(g)||(b=e.file_conflicts)!=null&&b[g])continue;let k=c.get(_.file.path);!k||Oe(k,_.file)||(await Lw(t,n,_.file.path,k),d.push({operation:"upload",transfer_id:s.randomId(),file_id:g,path:_.file.path,base_revision:_.file.revision,...k,..._.file.media_type?{media_type:_.file.media_type}:{}}))}for(let g of u){let _=e.files[g].file;d.push({operation:"delete",mutation_id:s.randomId(),file_id:g,path:_.path,base_revision:_.revision})}for(let g of l){let _=c.get(g);await Lw(t,n,g,_),d.push({operation:"upload",transfer_id:s.randomId(),path:g,..._})}e.pending_files.push(...d)}async function qw(r,e,t,n){var i,s;if(((s=(i=r.pending_files)==null?void 0:i.length)!=null?s:0)!==0){if(!t)throw new S("writable_file_transport_unavailable","Writable file mutations require a durable content-addressed blob store.");for(;r.pending_files.length>0;){let o=r.pending_files[0];try{if(o.operation==="upload"){if(o.after_mutation_id)throw new S("invalid_mirror_state","A file upload's prerequisite mutation is missing.");if(!e.uploadFile)throw Ff("upload");let a=await e.uploadFile({protocol_version:1,type:"open_file_upload",transfer_id:o.transfer_id,path:o.path,size:o.size,content_digest:o.content_digest,...o.media_type?{media_type:o.media_type}:{},...o.base_revision?{if_revision:o.base_revision}:{}},t.read(o.content_digest));if(St(a.file),a.transfer_id!==o.transfer_id||a.file.path!==o.path||a.file.size!==o.size||a.file.content_digest!==o.content_digest||o.file_id!==void 0&&a.file.file_id!==o.file_id)throw new S("invalid_sync_response","Authority returned an invalid file upload receipt.");r.files[a.file.file_id]={file:a.file}}else if(o.operation==="move"){if(!e.moveFile)throw Ff("move");let a=await e.moveFile({protocol_version:1,type:"move_file",mutation_id:o.mutation_id,file_id:o.file_id,if_revision:o.base_revision,from_path:o.from_path,path:o.path,update_references:!1});if(St(a.file),a.mutation_id!==o.mutation_id||a.file.file_id!==o.file_id||a.file.path!==o.path)throw new S("invalid_sync_response","Authority returned an invalid file move receipt.");r.files[o.file_id]={file:a.file};for(let c of r.pending_files)c.operation==="upload"&&c.after_mutation_id===o.mutation_id&&(c.file_id=a.file.file_id,c.base_revision=a.file.revision,delete c.after_mutation_id)}else{if(!e.deleteFile)throw Ff("delete");let a=await e.deleteFile({protocol_version:1,type:"delete_file",mutation_id:o.mutation_id,file_id:o.file_id,if_revision:o.base_revision,path:o.path});if(a.mutation_id!==o.mutation_id||a.file_id!==o.file_id||a.previous_path!==o.path)throw new S("invalid_sync_response","Authority returned an invalid file delete receipt.");delete r.files[o.file_id]}delete r.file_conflicts[Nw(o)],r.pending_files.shift(),await n()}catch(a){let c=a instanceof Error?a:new Error(String(a)),l=Nw(o);throw r.file_conflicts[l]={file_id:l,path:o.path,code:xR(a),message:c.message},await n(),a}}}}function xR(r){return r instanceof S||r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:"file_mutation_failed"}function Nw(r){return r.operation==="upload"&&!r.file_id?`new:${r.path}`:r.file_id}function Ff(r){return new S("writable_file_transport_unavailable",`This authority transport cannot ${r} collection files.`)}async function Lw(r,e,t,n){if(await e.has(n.content_digest))try{for await(let s of mc(e.read(n.content_digest),n,t));return}catch(s){await e.remove(n.content_digest)}let i=await r.readBinary(t);if(!i)throw new S("pending_local_changed",`Local file ${t} disappeared while being staged.`);try{await e.write(n.content_digest,mc(i,n,t));for await(let s of mc(e.read(n.content_digest),n,t));}catch(s){throw await e.remove(n.content_digest).catch(()=>{}),s}}var Pi=class{constructor(e,t,n){T(this,"pathPolicy");T(this,"digest");T(this,"recordIds",new Set);T(this,"physicalPaths",new Set);this.pathPolicy=e,this.digest=n;for(let i of t)this.physicalPaths.add(Ei(i.path))}validate(e){let t=e.document,n=e;if(bt(n.path,this.pathPolicy),this.recordIds.has(n.record_id))throw new S("invalid_snapshot",`Hosted snapshot repeats record identity ${n.record_id}.`);this.recordIds.add(n.record_id);let i=Ei(n.path);if(this.physicalPaths.has(i))throw new S("invalid_snapshot",`Hosted record path ${n.path} aliases another snapshot path on a supported filesystem.`);this.physicalPaths.add(i);let s=this.digest(t);if(n.revision.length!==7+s.length||!n.revision.startsWith("sha256:")||!n.revision.endsWith(s))throw new S("invalid_snapshot",`Hosted record ${n.path} does not match its declared revision.`);if(G_(t,n)!==!0&&t!==kn(n)){let a;try{a=Rr(t,n.path)}catch(c){throw new S("invalid_snapshot",`Hosted record ${n.path} is not valid Markdown.`)}if(!Vf(a.frontmatter,n.frontmatter)||!PR(a.body,n.body))throw new S("invalid_snapshot",`Hosted record ${n.path} does not match its declared document.`)}return{record:n,document:t,hash:s}}};function jw(r){if(!Object.prototype.hasOwnProperty.call(r,"document"))return r;let{document:e,...t}=r;return t}async function $c(r,e,t){let n,i=new Set;do{let s=await r.snapshot(e.snapshot_id,n);if(s.protocol_version!==1||s.snapshot_id!==e.snapshot_id||s.scope_epoch!==e.scope_epoch||s.cursor!==e.head)throw new S("invalid_snapshot","Authority snapshot boundary changed during download.");if(await t(s.records),n=s.next_page,n!==void 0&&i.has(n))throw new S("invalid_snapshot","Authority snapshot repeated a page cursor.");n!==void 0&&i.add(n)}while(n)}function PR(r,e){return r===e||r.startsWith(` `)&&r.slice(1)===e||e.startsWith(` -`)&&e.slice(1)===r}function ff(r,e){if(r===e)return!0;if(Array.isArray(r)||Array.isArray(e))return Array.isArray(r)&&Array.isArray(e)&&r.length===e.length&&r.every((s,i)=>ff(s,e[i]));if(!r||!e||typeof r!="object"||typeof e!="object")return!1;let t=Object.entries(r),n=e;return t.length===Object.keys(n).length&&t.every(([s,i])=>Object.prototype.hasOwnProperty.call(n,s)&&ff(i,n[s]))}var tc=class{constructor(e,t,n){O(this,"fileSystem");O(this,"runtime");O(this,"mode");this.fileSystem=e,this.runtime=t,this.mode=n}async recordPathPolicy(e){var t;return rw(Object.keys((t=e.resources)!=null?t:{}),()=>this.fileSystem.read("mdbase.yaml"))}async put(e,t,n={}){var p,m,h;let{managedState:s=e,acceptedHash:i,preserveAcceptedDocument:o=!1,materialized:a,physicalPathPreflighted:c=!1}=n;st(t.path,await this.recordPathPolicy(e)),a===void 0&&!c&&sw(t.path,t.record_id,Object.keys((p=e.resources)!=null?p:{}),Object.entries(e.records));let l=(m=a==null?void 0:a.document)!=null?m:gn(t),u=await this.fileSystem.read(t.path),d=s==null?void 0:s.records[t.record_id];if(u!==null&&u!==l){let y=this.runtime.digest(u);if(!(d!==void 0&&d.path===t.path&&y===d.hash)&&(i===void 0||y!==i))throw new St(t.record_id,t.path)}d&&d.path!==t.path&&await this.remove(s,t.record_id,d.path);let f=o&&typeof i=="string"&&u!==null&&this.runtime.digest(u)===i?i:null;f===null&&await this.fileSystem.write(t.path,l),e.records[t.record_id]={path:t.path,revision:t.revision,hash:(h=f!=null?f:a==null?void 0:a.hash)!=null?h:this.runtime.digest(l),...this.mode==="read_write"?{record:aw(t)}:{}}}async remove(e,t,n){var a;let s=e.records[t],i=(a=s==null?void 0:s.path)!=null?a:n;st(i,await this.recordPathPolicy(e));let o=await this.fileSystem.read(i);if(o!==null&&s&&this.runtime.digest(o)!==s.hash)throw new St(t,s.path);o!==null&&await this.fileSystem.remove(i),delete e.records[t]}async putResource(e,t,n){var o,a;let s=await this.fileSystem.read(t.path),i=(o=n==null?void 0:n.resources)==null?void 0:o[t.path];if(s!==null&&s!==t.document&&(!i||this.runtime.digest(s)!==i.hash))throw new St(`resource:${t.path}`,t.path);await this.fileSystem.write(t.path,t.document),(a=e.resources)!=null||(e.resources={}),e.resources[t.path]={path:t.path,revision:t.revision,hash:this.runtime.digest(t.document)}}async removeResource(e,t,n){let s=await this.fileSystem.read(t);if(s!==null&&this.runtime.digest(s)!==n.hash)throw new St(`resource:${t}`,t);s!==null&&await this.fileSystem.remove(t),e.resources&&delete e.resources[t]}};async function pf(r,e,t){let n=await e.openSession();if(n.replica_id!==r||n.mode!==t)throw new T("invalid_mirror_session",`Filesystem mirror requires its own ${t.replace("_","-")} replica.`);return n}async function cw(r,e){var v,S,k,$,P;let{replicaId:t,transport:n,mode:s,fileSystem:i,runtime:o,materializer:a,reportProgress:c}=r,l=await pf(t,n,s),u=(v=l.resources.documents)!=null?v:[],d=Ya(u),f=new bs(d,u,o.digest),p={protocol_version:1,replica_id:t,scope_epoch:l.scope_epoch,cursor:l.head,records:{},resources:{},mode:s,pending:[],conflicts:{},local_issues:{}},m=new Map;if(e){for(let w of Object.values((S=e.resources)!=null?S:{}))m.set(kr(w.path),w);for(let w of Object.values(e.records))m.set(kr(w.path),w)}let h=[];for(let w of u){let N=await i.read(w.path),j=e?m.get(kr(w.path)):void 0;if(j&&j.path!==w.path)throw new T("invalid_record_path",`Mirror paths ${j.path} and ${w.path} alias on a supported filesystem.`);N!==null&&N!==w.document&&(!j||o.digest(N)!==j.hash)&&h.push(w.path)}let y=[],b=e?new Set:null;if(await ec(n,l,async w=>{for(let N of w){let j=f.validate(N),{document:H,record:A}=j,x=await i.read(A.path),_e=e?m.get(kr(A.path)):void 0;if(_e&&_e.path!==A.path)throw new T("invalid_record_path",`Mirror paths ${_e.path} and ${A.path} alias on a supported filesystem.`);x!==null&&x!==H&&(!_e||o.digest(x)!==_e.hash)&&h.push(A.path),b==null||b.add(A.record_id),y.push(j)}}),e){for(let[N,j]of Object.entries(e.records)){if(b.has(N))continue;let H=await i.read(j.path);H!==null&&o.digest(H)!==j.hash&&h.push(j.path)}let w=new Set(u.map(N=>N.path));for(let N of Object.values((k=e.resources)!=null?k:{})){if(w.has(N.path))continue;let j=await i.read(N.path);j!==null&&o.digest(j)!==N.hash&&h.push(N.path)}}if(h.length)throw new Qa([...new Set(h)].sort());let g=u.length+y.length,_=0,I=()=>{_+=1,c({phase:"applying",completed:_,total:g,done:_===g})};for(let w of u)await a.putResource(p,w,e),I();for(let w of y)await a.put(p,w.record,{managedState:e,materialized:w}),I();if(e){for(let[w,N]of Object.entries(e.records))p.records[w]||await a.remove(e,w,N.path);for(let[w,N]of Object.entries(($=e.resources)!=null?$:{}))(P=p.resources)!=null&&P[w]||await a.removeResource(e,w,N)}return p.last_synced_at=o.now(),p}var vn=class{constructor(e,t,n,s="read_only"){O(this,"replicaId");O(this,"transport");O(this,"mode");O(this,"stateStore");O(this,"fileSystem");O(this,"lease");O(this,"runtime");O(this,"materializer");O(this,"onProgress");var i,o;this.replicaId=e,this.transport=t,this.mode=s,this.stateStore=n.stateStore,this.fileSystem=n.fileSystem,this.lease=(i=n.lease)!=null?i:new ji,this.runtime=(o=n.runtime)!=null?o:Fi,this.materializer=new tc(this.fileSystem,this.runtime,this.mode),this.onProgress=n.onProgress}async sync(){await this.lease.runExclusive(()=>this.syncUnlocked())}async syncUnlocked(){var n,s;let e=await this.readState();if(!e){await this.rebuild(),this.mode==="read_write"&&await this.syncUnlocked();return}this.mode==="read_write"?(await this.flushPending(e),await this.captureLocalChanges(e),await this.flushPending(e)):await uf(e,await this.currentRecordPathPolicy(e),this.fileSystem,this.runtime.digest);let t=0;for(;;){let i=await this.transport.changes(e.cursor,200);if(i.scope_epoch!==e.scope_epoch||i.reset_required){await this.rebuild(e);return}i.events.some(o=>o.type==="put")&&iw(i.events,await this.currentRecordPathPolicy(e),e);for(let o of i.events){let a=o.type==="put"?o.record.record_id:o.record_id,c=e.records[a],l=c==null?void 0:c.path;this.mode==="read_write"&&o.type==="put"&&(c==null?void 0:c.record)!==void 0&&c.path===o.record.path&&c.revision===o.record.revision||l&&((n=e.local_issues)!=null&&n[l])||((s=e.conflicts)!=null&&s[a]?Q0(e,o):o.type==="put"?await this.materializer.put(e,o.record,{physicalPathPreflighted:!0}):await this.materializer.remove(e,o.record_id,o.previous_path)),t+=1,this.reportProgress({phase:"applying",completed:t,total:null,done:!1})}if(e.cursor=i.cursor,!i.has_more){e.last_synced_at=this.runtime.now(),await this.writeState(e),t>0&&this.reportProgress({phase:"applying",completed:t,total:null,done:!0});return}await this.writeState(e)}}async status(){var i,o,a,c,l,u,d,f,p,m,h,y;let e=await this.readState();if(!e)return{state:"not_initialized",mode:this.mode,pending:0,conflicts:[],local_issues:[],cursor:null,last_synced_at:null};let t=[];for(let[b,g]of Object.entries((i=e.conflicts)!=null?i:{})){let _=e.records[b],I=(o=e.pending)==null?void 0:o.find(v=>v.mutation.record_id===b);g.status==="conflicted"?t.push({record_id:b,path:(u=(l=(a=I==null?void 0:I.local_path)!=null?a:_==null?void 0:_.path)!=null?l:(c=g.conflict.current)==null?void 0:c.path)!=null?u:null,kind:"conflicted",message:"Local and remote changes need a decision."}):g.status==="rejected"&&t.push({record_id:b,path:(f=(d=I==null?void 0:I.local_path)!=null?d:_==null?void 0:_.path)!=null?f:null,kind:"rejected",message:g.error.message})}let n=Object.values((p=e.local_issues)!=null?p:{}).map(({path:b,code:g,message:_})=>({path:b,code:g,message:_})).sort((b,g)=>b.path.localeCompare(g.path)),s=(h=(m=e.pending)==null?void 0:m.length)!=null?h:0;return{state:t.length||n.length?"attention":s?"changes_waiting":"up_to_date",mode:this.mode,pending:s,conflicts:t,local_issues:n,cursor:e.cursor,last_synced_at:(y=e.last_synced_at)!=null?y:null}}async authorityPromotionManifest(){return this.lease.runExclusive(()=>this.authorityPromotionManifestUnlocked())}async authorityPromotionManifestUnlocked(){var i,o,a,c,l,u;if(this.mode!=="read_write")throw new T("promotion_requires_writable_mirror","Only a two-way full collection mirror can become the local source of truth.");let e=await this.readState();if(!e)throw new T("promotion_not_initialized","Synchronize this folder before moving the source of truth.");if(((o=(i=e.pending)==null?void 0:i.length)!=null?o:0)>0||Object.keys((a=e.conflicts)!=null?a:{}).length>0||Object.keys((c=e.local_issues)!=null?c:{}).length>0)throw new T("promotion_not_converged","Upload or resolve every local change before moving the source of truth.");await uf(e,await this.currentRecordPathPolicy(e),this.fileSystem,this.runtime.digest);let t=new Set(Object.keys((l=e.resources)!=null?l:{})),n=new Set(Object.values(e.records).map(d=>d.path)),s=(await this.fileSystem.listMarkdown(t)).filter(d=>!n.has(d));if(s.length>0)throw new T("promotion_unmanaged_files",`Synchronize unmanaged Markdown before promotion: ${s.join(", ")}.`);return{cursor:e.cursor,digest:Wa([...Object.entries((u=e.resources)!=null?u:{}).map(([d,f])=>({kind:"resource",path:d,identity:"",document_hash:Zu(f.hash)})),...Object.entries(e.records).map(([d,f])=>({kind:"record",path:f.path,identity:d,document_hash:Zu(f.hash)}))])}}async previewInitialization(){var p;if(await this.readState())return{already_initialized:!0,download_documents:0,upload_documents:0,unchanged_documents:0,collisions:[],local_issues:[]};let e=await pf(this.replicaId,this.transport,this.mode),t=(p=e.resources.documents)!=null?p:[],n=Ya(t),s=new bs(n,t,this.runtime.digest),i=new Set,o=0,a=0,c=[],l=async(m,h)=>{i.add(m);let y=await this.fileSystem.read(m);y===null?o+=1:y===h?a+=1:c.push(m)};for(let m of t)await l(m.path,m.document);await ec(this.transport,e,async m=>{for(let h of m){let y=s.validate(h);await l(y.record.path,y.document)}});let u=await this.fileSystem.listMarkdown(new Set(t.map(m=>m.path))),d=[],f=0;if(this.mode==="read_write"){let m=Xa(u,n);Za([...i,...m]);for(let h of m.filter(y=>!i.has(y))){let y=await this.fileSystem.read(h);if(y!==null)try{_r(y,h),f+=1}catch(b){let g=za(b,h);if(!g)throw b;d.push(g)}}}return{already_initialized:!1,download_documents:o,upload_documents:f,unchanged_documents:a,collisions:c,local_issues:d.sort((m,h)=>m.path.localeCompare(h.path))}}async rebuild(e){let t=await cw({replicaId:this.replicaId,transport:this.transport,mode:this.mode,fileSystem:this.fileSystem,runtime:this.runtime,materializer:this.materializer,reportProgress:n=>this.reportProgress(n)},e);await this.writeState(t)}async resolveConflict(e,t){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,t))}async resolveConflictUnlocked(e,t){var o,a,c,l,u;if(this.mode!=="read_write")throw new T("mirror_read_only","Receive-only mirrors do not contain writable conflicts.");let n=await this.readState(),s=(o=n==null?void 0:n.conflicts)==null?void 0:o[e];if(!n||!s)throw new T("mirror_conflict_not_found","Writable mirror conflict was not found.");let i=((a=n.pending)!=null?a:[]).filter(d=>d.mutation.record_id===e);if(t==="remote"){let d=s.status==="conflicted"?s.conflict.current:(c=n.records[e])==null?void 0:c.record;await this.installRemoteResolution(n,e,d,i),n.pending=((l=n.pending)!=null?l:[]).filter(f=>f.mutation.record_id!==e)}else if(s.status==="rejected")n.pending=((u=n.pending)!=null?u:[]).filter(d=>d.mutation.record_id!==e);else{if(s.status!=="conflicted")throw new T("invalid_mirror_state","Mirror conflict metadata is invalid.");let d=i.at(-1);if(!d)throw new T("conflict_mutation_missing","The local change for this sync issue is unavailable.");let f=s.conflict.current,p=await this.fileSystem.read(d.local_path),m=this.localResolutionMutations(n,e,d.local_path,p,f),h=n.pending.findIndex(y=>y.mutation.record_id===e);n.pending=n.pending.filter(y=>y.mutation.record_id!==e),n.pending.splice(h<0?n.pending.length:h,0,...m),f?n.records[e]={path:f.path,revision:f.revision,hash:this.runtime.digest(gn(f)),record:f}:delete n.records[e]}delete n.conflicts[e],await this.writeState(n)}async installRemoteResolution(e,t,n,s){let i=await this.currentRecordPathPolicy(e),o=new Set(s.map(c=>c.local_path));if(n){st(n.path,i);for(let l of o)st(l,i),l!==n.path&&await this.fileSystem.read(l)!==null&&await this.fileSystem.remove(l);let c=await this.fileSystem.read(n.path);await this.materializer.put(e,n,{managedState:e,acceptedHash:c===null?null:this.runtime.digest(c)});return}let a=e.records[t];a&&o.add(a.path);for(let c of o)st(c,i),await this.fileSystem.read(c)!==null&&await this.fileSystem.remove(c);delete e.records[t]}localResolutionMutations(e,t,n,s,i){let o=[],a,c=(d,f)=>{let p=this.runtime.randomId();o.push({mutation:{...d,mutation_id:p,replica_id:this.replicaId,scope_epoch:e.scope_epoch,created_at:this.runtime.now(),...a?{causal_predecessor:a}:{}},local_path:n,local_hash:f}),a=p};if(s===null)return i&&c({operation:"delete",record_id:t,base_revision:i.revision,input:{}},null),o;let l=_r(s,n),u=this.runtime.digest(s);return i?(s!==gn(i)&&c({operation:"update",record_id:t,base_revision:i.revision,input:{patch:Ka(i.frontmatter,l.frontmatter),body:l.body}},u),n!==i.path&&c({operation:"rename",record_id:t,base_revision:i.revision,input:{path:n}},u),o):(c({operation:"create",record_id:t,input:{path:n,frontmatter:l.frontmatter,body:l.body}},u),o)}async captureLocalChanges(e){let{pending:t,localIssues:n}=await ow({replicaId:this.replicaId,state:e,pathPolicy:await this.currentRecordPathPolicy(e),fileSystem:this.fileSystem,runtime:this.runtime});e.local_issues=n,t.length&&(e.pending.push(...t),await this.writeState(e))}async flushPending(e){var a,c,l;let t=(a=e.pending)!=null?a:e.pending=[],n=0,s=0,i=t.filter(u=>{var d;return!((d=e.conflicts)!=null&&d[u.mutation.record_id])}).length,o=0;for(;n=lf&&(await this.writeState(e),s=0);continue}(l=e.conflicts)!=null||(e.conflicts={}),e.conflicts[u.mutation.record_id]=p,s+=1,s>=lf&&(await this.writeState(e),s=0),n+=1}s>0&&await this.writeState(e),i>0&&this.reportProgress({phase:"uploading",completed:o,total:i,done:!0})}async readState(){let e=await this.stateStore.read();if(e===null)return null;try{return X0(e,this.replicaId,this.mode)}catch(t){throw t instanceof T?t:new T("invalid_mirror_state","Mirror metadata is corrupt or belongs to another replica.")}}async writeState(e){await this.stateStore.write(e)}reportProgress(e){var t;(t=this.onProgress)==null||t.call(this,e)}async currentRecordPathPolicy(e){return this.materializer.recordPathPolicy(e)}};var Vi=class extends vn{constructor(e,t,n){super(e,t,n,"read_write")}};var Ui=".mdbase/connect-role.json",Hi=".mdbase/authority-adoption.json",Bi=".mdbase/authority-adoption-snapshot.json",OO="mdbase-obsidian-connect",ws="mirrors",RO="mdbase-connect-access-",MO="mdbase-connect-refresh-",CO="mdbase-connect-adoption-",NO=300*1e3,dw=[".git/",".obsidian/",".trash/",".mdbase/"],zi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function it(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function _f(r,e){if(e!=null)return e;if(!r.trim())return{};try{return JSON.parse(r)}catch(t){return{}}}function uw(r){var s;let e=(s=r["retry-after"])!=null?s:r["Retry-After"];if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let n=Date.parse(e);if(Number.isFinite(n))return Math.max(0,n-Date.now())}function LO(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Enrollment cancelled.","AbortError");let e=await(0,le.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Enrollment cancelled.","AbortError");return{status:e.status,body:_f(e.text,e.json),retryAfterMs:uw(e.headers)}}}function DO(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await(0,le.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");return{status:e.status,body:_f(e.text,e.json),retryAfterMs:uw(e.headers)}}}var yf=class{constructor(e,t){this.accessToken=t;let n;try{n=new URL(e)}catch(s){throw new T("invalid_sync_url","Sync URL must be an absolute authority endpoint.")}if(!(n.protocol==="https:"||n.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(n.hostname))||n.username||n.password||n.search||n.hash||!/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync\/?$/i.test(n.pathname))throw new T("invalid_sync_url","Sync URL must identify one authority sync endpoint.");this.syncUrl=n.href.replace(/\/$/,"")}openSession(){return this.request("POST","sessions")}snapshot(e,t){let n=new URLSearchParams({snapshot_id:e});return t&&n.set("page",t),this.request("GET",`snapshot?${n.toString()}`)}changes(e,t=200){let n=new URLSearchParams({after:String(e),limit:String(t)});return this.request("GET",`changes?${n.toString()}`)}mutate(e){return this.request("POST","mutations",e)}async request(e,t,n){let s=await(0,le.requestUrl)({url:`${this.syncUrl}/${t}`,method:e,headers:{authorization:`Bearer ${this.accessToken}`},body:n===void 0?void 0:JSON.stringify(n),contentType:n===void 0?void 0:"application/json",throw:!1}),i=_f(s.text,s.json);if(s.status<200||s.status>=300){let o=it(i)&&it(i.error)?i.error:{};throw new T(typeof o.code=="string"?o.code:"sync_failed",typeof o.message=="string"?o.message:`Sync request failed (${s.status}).`)}return i}};function hf(r){let e=hi(r);if(e===".mdbase"||dw.some(t=>e.startsWith(t)))throw new T("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${e}`);return e}async function rc(r,e){let t=(0,le.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n="";for(let s of t.split("/")){n=n?`${n}/${s}`:s;let i=r.getAbstractFileByPath(n);if(!(i instanceof le.TFolder)){if(i)throw new T("mirror_path_collision",`A file blocks the mirror folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}var gf=class{constructor(e){this.vault=e}async read(e){let t=hf(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof le.TFile))throw new T("mirror_path_collision",`Expected a file at ${t}.`);return this.vault.cachedRead(n)}async write(e,t){let n=hf(e),s=n.lastIndexOf("/");s>=0&&await rc(this.vault,n.slice(0,s));let i=this.vault.getAbstractFileByPath(n);if(i instanceof le.TFolder)throw new T("mirror_path_collision",`A folder blocks the mirror file ${n}.`);i instanceof le.TFile?await this.vault.modify(i,t):await this.vault.create(n,t)}async remove(e){let t=hf(e),n=this.vault.getAbstractFileByPath(t);if(n!=null){if(!(n instanceof le.TFile))throw new T("mirror_path_collision",`Expected a file at ${t}.`);await this.vault.delete(n,!0)}}async listMarkdown(e){return this.vault.getMarkdownFiles().map(t=>(0,le.normalizePath)(t.path)).filter(t=>!e.has(t)).filter(t=>!dw.some(n=>t.startsWith(n))).sort()}},bf=class{constructor(e){this.key=e;this.database=null}async read(){let e=await this.open();return new Promise((t,n)=>{let s=e.transaction(ws,"readonly").objectStore(ws).get(this.key);s.onsuccess=()=>{var i;return t((i=s.result)!=null?i:null)},s.onerror=()=>n(s.error)})}async write(e){let t=await this.open();await new Promise((n,s)=>{let i=t.transaction(ws,"readwrite");i.objectStore(ws).put(e,this.key),i.oncomplete=()=>n(),i.onerror=()=>s(i.error),i.onabort=()=>s(i.error)})}open(){var e;if(typeof indexedDB=="undefined")throw new T("storage_unavailable","IndexedDB is required for persistent mirror state.");return(e=this.database)!=null||(this.database=new Promise((t,n)=>{let s=indexedDB.open(OO,1);s.onupgradeneeded=()=>{s.result.objectStoreNames.contains(ws)||s.result.createObjectStore(ws)},s.onerror=()=>n(s.error),s.onsuccess=()=>t(s.result)})),this.database}},_s=class _s{constructor(e){this.key=e}async runExclusive(e){if(_s.active.has(this.key))throw new T("mirror_busy","A mirror operation is already running for this vault.");_s.active.add(this.key);try{return await e()}finally{_s.active.delete(this.key)}}};_s.active=new Set;var wf=_s,nc=class{constructor(e,t,n={}){this.app=e;this.settingsHost=t;this.options=n;this.progress=null;this.adoptionMarker=null;var s,i,o;this.fileSystem=(s=n.fileSystem)!=null?s:new gf(e.vault),this.enrollmentClient=(i=n.enrollmentClient)!=null?i:new Ga({request:LO()}),this.adoptionClient=(o=n.adoptionClient)!=null?o:new Ja({request:DO()})}async initialize(){if(this.adoptionMarker=await this.readAdoptionMarker(),this.adoptionMarker&&this.settingsHost.getMirrorProfile())throw new T("authority_adoption_state_conflict","This vault contains both an authority-adoption checkpoint and a mirror profile.")}getProgress(){return this.progress?{...this.progress}:null}getAdoptionMarker(){return this.adoptionMarker?JSON.parse(JSON.stringify(this.adoptionMarker)):null}assertLocalAuthorityWritable(){if(this.adoptionMarker&&["fenced","activating","adopted"].includes(this.adoptionMarker.phase))throw new T("local_authority_fenced",this.adoptionMarker.phase==="adopted"?"Hosted mdbase is now authoritative. Finish reconnecting this vault as its mirror before editing.":"This local authority is frozen while its exact snapshot is adopted by hosted mdbase.")}async adoptLocalCollection(e,t){if(this.settingsHost.getMirrorProfile())throw new T("mirror_already_configured","This vault already mirrors a collection authority.");if(this.adoptionMarker)return this.resumeAdoption(t);let n=await this.ensurePortableCollectionIdentity(),s=await this.adoptionClient.begin({controlUrl:e.controlUrl,collectionId:n.collectionId,displayName:n.displayName,sourceName:e.mirrorName,retainMirror:!0,mirrorName:e.mirrorName},t);return await this.storeAdoptionSecret(s),await this.writeAdoptionMarker({version:1,phase:"waiting_for_approval",session:mf(s),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(mf(s)),this.runAdoptionWithRecovery(s,t)}async resumeAdoption(e={}){var i,o,a;let t=(i=this.adoptionMarker)!=null?i:await this.readAdoptionMarker();if(!t)throw new T("authority_adoption_not_found","This vault has no collection-adoption checkpoint.");this.adoptionMarker=t;let n=this.app.secretStorage.getSecret(this.adoptionSecretId(t.session.adoptionId));if(!n)throw new T("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");let s={...t.session,credential:n};return t.phase==="waiting_for_approval"&&await((o=e.onVerification)==null?void 0:o.call(e,mf(s))),this.runAdoptionWithRecovery(s,{...e,onVerification:(a=e.onVerification)!=null?a:(()=>{})})}async cancelAdoption(e){var s;let t=(s=this.adoptionMarker)!=null?s:await this.readAdoptionMarker();if(!t)return;if(["activating","adopted"].includes(t.phase))throw new T("authority_adoption_activation_started","Hosted activation has started and must be resumed; it can no longer be cancelled.");let n=this.app.secretStorage.getSecret(this.adoptionSecretId(t.session.adoptionId));if(!n)throw new T("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");await this.adoptionClient.cancel({...t.session,credential:n},{signal:e}),await this.clearAdoptionCheckpoint(t.session.adoptionId)}async enroll(e,t){let n=await this.assertCanBecomeMirror(e.collectionId),s=await this.enrollmentClient.enroll({...e,...n?{collectionId:n}:{}},t),i=await this.markMirror(s.collectionId);try{await this.persistEnrollment(s)}catch(o){if(i)try{await this.app.vault.adapter.remove(Ui)}catch(a){throw new T("enrollment_recovery_required",`Enrollment settings could not be saved and the temporary role marker could not be removed: ${o instanceof Error?o.message:String(o)}`)}throw o}return this.requireProfile()}async preview(){return(await this.createMirror()).previewInitialization()}async status(){let e=this.settingsHost.getMirrorProfile();return e?(await this.assertMirror(e.collectionId),(await this.createMirror()).status()):null}async sync(e){let t=await this.createMirror(n=>{this.progress=n,e==null||e({...n})});try{return await t.sync(),t.status()}finally{this.progress=null}}async resolveConflict(e,t){let n=await this.createMirror();return await n.resolveConflict(e,t),n.status()}async runAdoption(e,t){let n=this.requireAdoptionMarker(e.adoptionId),s=null;if(n.phase==="adopted"){let i=await this.adoptionClient.exchange(e,t);if(i.status!=="completed")throw new T("authority_adoption_state_conflict","The local checkpoint says adoption completed, but Connect does not.");s=i}else if(n.phase==="activating"){let i=await this.readAdoptionSnapshot(n),o=await this.adoptionClient.exchange(e,t);s=o.status==="completed"?o:await this.adoptionClient.complete(e,i,t)}else if(n.phase==="fenced"){let i=await this.readAdoptionSnapshot(n),o=await this.adoptionClient.exchange(e,t);o.status==="completed"?s=o:(o.status==="ready"&&await this.adoptionClient.uploadSnapshot(e,o,i,t),await this.updateAdoptionPhase("activating",i),s=await this.adoptionClient.complete(e,i,t))}else{let i=n.phase==="waiting_for_approval"?await this.adoptionClient.waitForApproval(e,t):await this.requirePreparedAdoption(e,t),o=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.updateAdoptionPhase("uploading"),await this.adoptionClient.uploadSnapshot(e,i,o,t);let a=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.writeAdoptionSnapshot(a),await this.updateAdoptionPhase("fenced",a);let c=await this.requirePreparedAdoption(e,t);await this.adoptionClient.uploadSnapshot(e,c,a,t),await this.updateAdoptionPhase("activating",a),s=await this.adoptionClient.complete(e,a,t)}return await this.updateAdoptionPhase("adopted"),this.finishRetainedMirror(e,s,t)}async runAdoptionWithRecovery(e,t){try{return await this.runAdoption(e,t)}catch(n){throw qO(n)?(await this.adoptionClient.cancel(e,{signal:t.signal}).catch(()=>{}),await this.clearAdoptionCheckpoint(e.adoptionId),new T(n.code,"This adoption ended before hosted activation. The vault remains the writable local authority; start a new adoption to try again.")):n}}async requirePreparedAdoption(e,t){let n=await this.adoptionClient.exchange(e,t);if(n.status==="ready")return n;throw n.status==="activating"?new vr("Hosted authority activation has already started. Resume using the saved fenced snapshot."):new T("authority_adoption_already_completed","Hosted authority has already adopted this collection.")}async finishRetainedMirror(e,t,n){var a,c;let s,i=this.adoptionClient.mirrorEnrollmentSession(e,t);if(!i)throw new T("authority_adoption_mirror_missing","Hosted authority activated without retaining this vault as a mirror.");try{s=await this.enrollmentClient.waitForApproval(i,{signal:n.signal,onStatus:l=>{var u;return(u=n.onStatus)==null?void 0:u.call(n,{...l,state:l.state})}})}catch(l){if((a=n.signal)!=null&&a.aborted)throw l;s=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,collectionId:e.requested.collectionId,mirrorName:(c=e.requested.mirrorName)!=null?c:e.requested.sourceName,mode:"read_write"},{signal:n.signal,onVerification:n.onVerification})}let o=await this.markMirror(s.collectionId);try{await this.persistEnrollment(s)}catch(l){throw o&&await this.app.vault.adapter.remove(Ui),l}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async captureAuthoritySnapshot(e){let t=await Zn(this.app.vault);if(!t)throw new T("invalid_collection_configuration","A valid mdbase.yaml is required.");let n=await this.app.vault.adapter.read("mdbase.yaml"),s=(0,le.parseYaml)(n),i=[{path:"mdbase.yaml",kind:"configuration",document:n}],o=`${(0,le.normalizePath)(t.settings.types_folder)}/`,a=this.app.vault.getMarkdownFiles().filter(u=>(0,le.normalizePath)(u.path).startsWith(o)).sort((u,d)=>u.path.localeCompare(d.path));for(let u of a)i.push({path:(0,le.normalizePath)(u.path),kind:"type",document:await this.app.vault.cachedRead(u)});let c=jO(s);if(c.length){let u=c.map(f=>(0,lw.default)(f,{dot:!0})),d=FO(this.app.vault).filter(f=>f.extension==="base").filter(f=>u.some(p=>p((0,le.normalizePath)(f.path)))).sort((f,p)=>f.path.localeCompare(p.path));for(let f of d)i.push({path:(0,le.normalizePath)(f.path),kind:"view",document:await this.app.vault.cachedRead(f)})}let l=[];for(let u of this.app.vault.getMarkdownFiles().sort((d,f)=>d.path.localeCompare(f.path))){let d=(0,le.normalizePath)(u.path);if(mi(d,t))continue;let f=await this.app.vault.cachedRead(u);l.push({path:d,document:f})}return sf({collectionId:e,sourceHead:0,specVersion:t.spec_version,resources:i,records:l})}async ensurePortableCollectionIdentity(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))throw new T("collection_not_initialized","Initialize an mdbase collection before hosting it.");let e=await this.app.vault.adapter.read("mdbase.yaml"),t;try{t=(0,le.parseYaml)(e)}catch(o){throw new T("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!it(t))throw new T("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let n=it(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,s;if(n===void 0){s=crypto.randomUUID();let o=it(t["x-mdbase-connect"])?t["x-mdbase-connect"]:{};t["x-mdbase-connect"]={...o,collection_id:s},await this.app.vault.adapter.write("mdbase.yaml",(0,le.stringifyYaml)(t))}else if(typeof n=="string"&&zi.test(n))s=n;else throw new T("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");let i=typeof t.name=="string"&&t.name.trim()?t.name.trim():this.app.vault.getName();return{collectionId:s,displayName:i}}async createMirror(e){var o,a,c,l,u,d,f,p,m;let t=this.requireProfile();await this.assertMirror(t.collectionId);let n=await this.freshAccessToken(t),s=(c=(a=(o=this.options).transportFactory)==null?void 0:a.call(o,t,n))!=null?c:new yf(t.syncUrl,n),i={stateStore:(d=(u=(l=this.options).stateStoreFactory)==null?void 0:u.call(l,t))!=null?d:new bf(`${t.collectionId}:${t.replicaId}`),fileSystem:this.fileSystem,lease:(m=(p=(f=this.options).leaseFactory)==null?void 0:p.call(f,t))!=null?m:new wf(`${t.collectionId}:${t.replicaId}`),onProgress:e};return t.mode==="read_write"?new Vi(t.replicaId,s,i):new vn(t.replicaId,s,i)}requireProfile(){let e=this.settingsHost.getMirrorProfile();if(!e)throw new T("mirror_not_configured","This vault is not connected to a collection authority.");return e}accessSecretId(e){return`${RO}${e.toLowerCase()}`}refreshSecretId(e){return`${MO}${e.toLowerCase()}`}adoptionSecretId(e){return`${CO}${e.toLowerCase()}`}async storeAdoptionSecret(e){this.app.secretStorage.setSecret(this.adoptionSecretId(e.adoptionId),e.credential)}async persistEnrollment(e){this.app.secretStorage.setSecret(this.accessSecretId(e.collectionId),e.accessToken),this.app.secretStorage.setSecret(this.refreshSecretId(e.collectionId),e.refreshCredential),await this.settingsHost.saveMirrorProfile({version:1,syncUrl:e.syncUrl,controlUrl:e.controlUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessTokenExpiresAt:e.accessTokenExpiresAt})}async freshAccessToken(e){let t=this.accessSecretId(e.collectionId),n=this.app.secretStorage.getSecret(t),s=Date.parse(e.accessTokenExpiresAt);if(n&&Number.isFinite(s)&&s-Date.now()>NO)return n;let i=this.app.secretStorage.getSecret(this.refreshSecretId(e.collectionId));if(!i)throw new T("mirror_credentials_missing","The mirror refresh credential is missing. Re-enroll this vault.");let o=await this.enrollmentClient.renew({controlUrl:e.controlUrl,syncUrl:e.syncUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessToken:n!=null?n:"",refreshCredential:i,accessTokenExpiresAt:e.accessTokenExpiresAt});return await this.persistEnrollment(o),o.accessToken}async assertCanBecomeMirror(e){var o;let t=await this.readMarker(),n=await this.readPortableCollectionId();if(n&&!t)throw new T("local_authority_requires_transfer","This vault has a local Connect identity. Transfer authority explicitly before using it as a mirror.");if(n&&(t==null?void 0:t.collection_id)!==n)throw new T("mirror_identity_conflict","The vault identity and mirror role marker identify different collections.");let s=this.settingsHost.getMirrorProfile(),i=(o=s==null?void 0:s.collectionId)!=null?o:e;if(t&&i&&t.collection_id!==i)throw new T("mirror_identity_conflict","This vault is already marked as a different mirror.");if(!t&&!s&&await this.app.vault.adapter.exists("mdbase.yaml"))throw new T("existing_collection_requires_transfer","This vault already contains an mdbase collection. Connect an empty vault, or transfer collection authority explicitly.");return i!=null?i:t==null?void 0:t.collection_id}async readPortableCollectionId(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))return null;let e;try{e=(0,le.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch(s){throw new T("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!it(e))throw new T("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let t=e["x-mdbase-connect"];if(t===void 0)return null;if(!it(t))throw new T("invalid_collection_configuration","x-mdbase-connect must be a YAML mapping.");let n=t.collection_id;if(n===void 0)return null;if(typeof n!="string"||!zi.test(n))throw new T("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");return n}async markMirror(e){let t=await this.readMarker();if(t){if(t.collection_id!==e)throw new T("mirror_identity_conflict","This vault already mirrors a different collection authority.");return!1}return await rc(this.app.vault,".mdbase"),await this.app.vault.adapter.write(Ui,`${JSON.stringify({version:1,role:"mirror",collection_id:e},null,2)} -`),!0}async assertMirror(e){let t=await this.readMarker();if(!t||t.collection_id!==e)throw new T("mirror_marker_missing","The vault's mirror role marker is missing or does not match this connection.")}async readMarker(){if(!await this.app.vault.adapter.exists(Ui))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(Ui))}catch(t){throw new T("invalid_mirror_marker","The mirror role marker is corrupt.")}if(!it(e)||e.version!==1||e.role!=="mirror"||typeof e.collection_id!="string"||!zi.test(e.collection_id))throw new T("invalid_mirror_marker","The mirror role marker is invalid.");return e}requireAdoptionMarker(e){if(!this.adoptionMarker||this.adoptionMarker.session.adoptionId!==e)throw new T("authority_adoption_state_conflict","The collection-adoption checkpoint does not match this approval.");return this.adoptionMarker}async updateAdoptionPhase(e,t){if(!this.adoptionMarker)throw new T("authority_adoption_not_found","Collection-adoption checkpoint is missing.");await this.writeAdoptionMarker({...this.adoptionMarker,phase:e,...t?{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head}:{}})}async writeAdoptionMarker(e){await rc(this.app.vault,".mdbase"),await this.app.vault.adapter.write(Hi,`${JSON.stringify(e,null,2)} -`),this.adoptionMarker=e}async readAdoptionMarker(){if(!await this.app.vault.adapter.exists(Hi))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(Hi))}catch(t){throw new T("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is corrupt.")}if(!VO(e))throw new T("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is invalid.");return e}async writeAdoptionSnapshot(e){await rc(this.app.vault,".mdbase"),await this.app.vault.adapter.write(Bi,JSON.stringify(e))}async readAdoptionSnapshot(e){if(!await this.app.vault.adapter.exists(Bi))throw new T("authority_adoption_snapshot_missing","The fenced authority snapshot is missing; hosted activation cannot be resumed safely.");let t;try{t=JSON.parse(await this.app.vault.adapter.read(Bi))}catch(n){throw new T("invalid_authority_adoption_snapshot","The fenced authority snapshot is corrupt.")}if(t.collection_id!==e.session.requested.collectionId||t.manifest_digest!==e.manifest_digest||t.source_revision!==e.source_revision||t.source_head!==e.source_head)throw new T("authority_adoption_snapshot_mismatch","The fenced authority snapshot does not match its durable checkpoint.");return t}async clearAdoptionCheckpoint(e){await this.app.vault.adapter.exists(Hi)&&await this.app.vault.adapter.remove(Hi),await this.app.vault.adapter.exists(Bi)&&await this.app.vault.adapter.remove(Bi),this.app.secretStorage.setSecret(this.adoptionSecretId(e),""),this.adoptionMarker=null}};function mf(r){let{credential:e,...t}=r;return t}function qO(r){return r instanceof ue&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function jO(r){if(!it(r))return[];let e=r["x-obsidian"];return!it(e)||!it(e.bases)||!Array.isArray(e.bases.include)?[]:e.bases.include.filter(t=>typeof t=="string")}function FO(r){var s;let e=(s=r.getFiles)==null?void 0:s.call(r);if(e)return e;let t=[],n=i=>{for(let o of i.children)o instanceof le.TFile?t.push(o):o instanceof le.TFolder&&n(o)};return n(r.getRoot()),t}function VO(r){if(!it(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!it(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&zi.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&it(e.requested)&&typeof e.requested.collectionId=="string"&&zi.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.manifest_digest===null||typeof r.manifest_digest=="string")&&(r.source_revision===null||typeof r.source_revision=="string")&&(r.source_head===null||Number.isSafeInteger(r.source_head))}var Je=require("obsidian");var Ji="0.3.0",UO=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),HO=new Set(["type","required","default","description","values","items","fields","min","max","min_length","max_length","pattern","unique","deprecated","generated","computed","target","validate_exists","tn_role","tn_completed_values"]);function we(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Re(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function xr(r){return Fi.digest(r)}function $n(r){return Array.isArray(r)?`[${r.map($n).join(",")}]`:we(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${$n(r[e])}`).join(",")}}`:JSON.stringify(r)}function vf(r){if(Array.isArray(r))return r.map(vf);if(!we(r))return r;let e={};for(let[t,n]of Object.entries(r)){let s=vf(n);s!=null&&(Array.isArray(s)&&s.length===0||we(s)&&Object.keys(s).length===0||(e[t]=s))}return e}function vs(r){return[...new Set(r)]}function BO(r){return we(r.fields)?Object.values(r.fields).some(e=>we(e)&&(typeof e.tn_role=="string"||Array.isArray(e.tn_completed_values))):!1}function $f(r,e,t){let n=we(e)?e:{},s={},i={},o=[],a;switch(n.type){case"any":a={};break;case"string":case"integer":case"number":case"boolean":a={type:n.type};break;case"date":case"datetime":case"time":a={type:"string",format:n.type==="datetime"?"date-time":n.type};break;case"enum":a={enum:Array.isArray(n.values)?Re(n.values):[]};break;case"link":a={type:"string"},s[r]={target_type:typeof n.target=="string"?n.target:r.endsWith("Parent")||r.endsWith("uid")?"task":"any",validate_exists:n.validate_exists===!0};break;case"list":{let c=$f(`${r}[]`,n.items,t);a={type:"array",items:c.schema},Object.assign(s,c.links),Object.assign(i,c.legacy),o.push(...c.unsupported);break}case"object":{let c={},l=[];for(let[u,d]of Object.entries(we(n.fields)?n.fields:{})){let f=$f(`${r}.${u}`,d,t);c[u]=f.schema,Object.assign(s,f.links),Object.assign(i,f.legacy),o.push(...f.unsupported),we(d)&&d.required===!0&&l.push(u)}t&&r==="blockedBy[]"&&l.push("uid"),a={type:"object",additionalProperties:Object.keys(c).length===0,properties:c,...l.length?{required:vs(l)}:{}};break}default:a={},o.push(`${r}.type`);break}t&&r==="title"&&(a.minLength=1,a.description="Short summary of the task."),typeof n.description=="string"&&(a.description=n.description),typeof n.min=="number"&&(n.type==="string"?a.minLength=n.min:n.type==="list"?a.minItems=n.min:a.minimum=n.min),typeof n.max=="number"&&(n.type==="string"?a.maxLength=n.max:n.type==="list"?a.maxItems=n.max:a.maximum=n.max),typeof n.min_length=="number"&&(a.minLength=n.min_length),typeof n.max_length=="number"&&(a.maxLength=n.max_length),typeof n.pattern=="string"&&(a.pattern=n.pattern),n.deprecated===!0&&(a.deprecated=!0),n.default!==void 0&&(a.default=Re(n.default)),n.computed!==void 0&&o.push(`${r}.computed`);for(let[c,l]of Object.entries(n)){let u=t&&(c==="tn_role"||c==="tn_completed_values");(!HO.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!u)&&(i[`${r}.${c}`]=Re(l))}return{schema:a,links:s,legacy:i,unsupported:o}}function Ki(r,e,t,n){let s=we(r[e])?r[e]:{},i=we(s.set)?s.set:{};i[t]=n,s.set=i,r[e]=s}function zO(r,e,t){if(t==="now")Ki(r,"on_create",e,{now:!0});else if(t==="now_on_write")Ki(r,"on_update",e,{now:!0});else if(t==="uuid")Ki(r,"on_create",e,{uuid:!0});else if(t==="ulid")Ki(r,"on_create",e,{ulid:!0});else if(we(t)&&t.transform==="slugify"&&typeof t.from=="string")Ki(r,"on_create",e,{slugify:t.from});else return!1;return!0}function KO(r){var t;let e=r.match(/^(.*\/)?\{title\}\.md$/);return e?{runtime:"tasknotes",template:"{{title}}",folder:((t=e[1])!=null?t:"").replace(/\/$/,""),generated_by:"tasknotes.filename.create"}:{runtime:"tasknotes",template:r,generated_by:"tasknotes.filename.create"}}function WO(r,e,t){var S;if(t.kind==="mdbase.type"||t.schema!==void 0)throw new Error(`${r} already looks like a v0.3 type.`);if(typeof t.name!="string"||!we(t.fields))throw new Error(`${r} is not a v0.2 type with a name and fields.`);let n=BO(t),s=t.name.trim().toLowerCase(),i={type:{const:s}},o=[],a={},c={},l=[],u={},d={},f=[],p=[],m={},h={},y={};for(let[k,$]of Object.entries(t.fields)){let P=we($)?$:{},w=$f(k,P,n);i[k]=w.schema,Object.assign(c,w.links),Object.assign(d,w.legacy),f.push(...w.unsupported),P.required===!0&&o.push(k),P.default!==void 0&&(a[k]=Re(P.default)),P.unique===!0&&l.push({field:k,scope:"collection"}),P.generated!==void 0&&zO(u,k,P.generated)&&p.push(k),typeof P.tn_role=="string"&&(m[P.tn_role]=k),Array.isArray(P.tn_completed_values)&&(h.completed_values=Re(P.tn_completed_values))}a.status!==void 0&&(h.default=Re(a.status)),a.priority!==void 0&&(y.default=Re(a.priority));let b=typeof t.display_name_key=="string"&&Object.prototype.hasOwnProperty.call(t.fields,t.display_name_key)?t.display_name_key:void 0,g={...b?{display:{name_field:b}}:{},read_defaults:a,links:c,unique:l};typeof t.path_pattern=="string"&&(g.path=n?KO(t.path_pattern):{pattern:t.path_pattern});let _={};for(let[k,$]of Object.entries(t))UO.has(k)||(_[k]=Re($));Object.keys(d).length&&(_.fields=d);let I=vf({kind:"mdbase.type",name:s,version:1,description:typeof t.description=="string"?t.description:void 0,match:we(t.match)?Re(t.match):void 0,schema:{dialect:"json-schema-2020-12",value:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",additionalProperties:t.strict!==!0,properties:i,...o.length?{required:vs(o)}:{}}},collection:g,lifecycle:u,...n?{"x-tasknotes":{contract:"tasknotes.task",version:1,field_roles:m,status:h,priority:y,archive:{tags_field:(S=m.tags)!=null?S:"tags",archived_tag:"archived"}}}:{},...Object.keys(_).length?{"x-legacy-v0.2":_}:{}}),v=[];t.extends!==void 0&&f.push("extends");for(let k of vs(f).sort())v.push({path:r,code:"migration_lossy",message:`${k} cannot be expressed as canonical v0.3 write behavior and was retained as legacy metadata where possible.`,severity:"lossy"});return n&&v.push({path:r,code:"path_policy_runtime_owned",message:"TaskNotes filename behavior is recorded as TaskNotes runtime metadata.",severity:"warning"}),t.strict!==!0&&v.push({path:r,code:"additional_properties_true",message:"The migrated schema allows additional properties because the source type was not strict.",severity:"warning"}),typeof t.display_name_key=="string"&&!b&&v.push({path:r,code:"display_field_missing",message:`The display field '${t.display_name_key}' is not declared, so collection.display was omitted.`,severity:"warning"}),{target:I,summary:{path:r,name:s,fieldsConverted:Object.keys(t.fields).length,requiredFields:vs(o),defaultsMoved:Object.keys(a),generatedFieldsMoved:vs(p),linksMoved:Object.keys(c),taskNotes:n},diagnostics:v}}function GO(r){let e=Re(r);e.spec_version=Ji;let t=we(e.settings)?e.settings:{};if(e.settings=t,!Array.isArray(t.record_extensions)){let n=Array.isArray(t.extensions)?t.extensions.map(String).map(s=>s.replace(/^\./,"")):[];t.record_extensions=vs(["md",...n])}return Array.isArray(t.explicit_type_keys)||(t.explicit_type_keys=["type","types"]),typeof t.include_subfolders!="boolean"&&(t.include_subfolders=!0),t.validation===void 0&&typeof t.default_validation=="string"&&(t.validation=t.default_validation),t.validation===void 0&&typeof e.default_validation=="string"&&(t.validation=e.default_validation),delete t.default_validation,delete t.extensions,delete e.default_validation,e}function fw(r,e){let t=we(r.settings)?r.settings:{};return{spec_version:e,name:typeof r.name=="string"?r.name:void 0,description:typeof r.description=="string"?r.description:void 0,settings:{types_folder:typeof t.types_folder=="string"?t.types_folder:"_types",explicit_type_keys:Array.isArray(t.explicit_type_keys)?t.explicit_type_keys.filter(n=>typeof n=="string"):["type","types"],default_strict:t.default_strict===!0,include_subfolders:t.include_subfolders!==!1,exclude:Array.isArray(t.exclude)?t.exclude.filter(n=>typeof n=="string"):["_types",".obsidian",".git",".mdbase"]}}}function JO(r,e){var n,s;let t={};for(let[i,o]of Object.entries(we(e.fields)?e.fields:{}))we(o)&&(t[i]=Re(o));return{name:typeof e.name=="string"?e.name:(s=(n=r.split("/").pop())==null?void 0:n.replace(/\.md$/,""))!=null?s:"type",fields:t,match:we(e.match)?Re(e.match):void 0,filePath:r,specProfile:"v0.2"}}function YO(r,e){var s,i;let t=we(e.schema)?e.schema:{},n=we(t.value)?t.value:{};return{name:typeof e.name=="string"?e.name:(i=(s=r.split("/").pop())==null?void 0:s.replace(/\.md$/,""))!=null?i:"type",fields:pn(n),match:we(e.match)?Re(e.match):void 0,collection:we(e.collection)?Re(e.collection):void 0,schema:Re(n),filePath:r,specProfile:"v0.3"}}function XO(r,e,t){let n=Re(r);for(let s of e){let i=t.get(s);if(i)for(let[o,a]of Object.entries(i.fields))!(o in n)&&a.default!==void 0&&(n[o]=Re(a.default))}return n}function QO(r,e,t){var s,i;let n=Re(r);for(let o of e){let a=t.get(o);if(a)for(let[c,l]of Object.entries((i=(s=a.collection)==null?void 0:s.read_defaults)!=null?i:{}))c in n||(n[c]=Re(l))}return n}async function ZO(r,e){let t=(0,Je.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n="";for(let s of t.split("/")){n=n?`${n}/${s}`:s;let i=r.getAbstractFileByPath(n);if(!(i instanceof Je.TFolder)){if(i)throw new Error(`A file blocks folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}async function sc(r,e,t){let n=(0,Je.normalizePath)(e),s=n.lastIndexOf("/");if(s>=0&&await ZO(r,n.slice(0,s)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let i=r.getAbstractFileByPath(n);if(i instanceof Je.TFolder)throw new Error(`A folder blocks file ${n}.`);i instanceof Je.TFile?await r.modify(i,t):await r.create(n,t)}async function Gi(r,e){let t=(0,Je.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof Je.TFile)return r.cachedRead(n);if(await r.adapter.exists(t))return r.adapter.read(t);throw new Error(`File not found: ${e}`)}async function pw(r){var I;let e=await Gi(r,"mdbase.yaml"),t=(0,Je.parseYaml)(e);if(!we(t))throw new Error("mdbase.yaml must contain a YAML mapping.");let n=typeof t.spec_version=="string"?t.spec_version:"";if(!/^0\.2(?:\.\d+)?$/.test(n))throw new Error(n===Ji?"This collection is already mdbase v0.3.":`Expected an mdbase v0.2.x collection, found ${JSON.stringify(n)}.`);let s=we(t.settings)?t.settings:{},i=typeof s.types_folder=="string"?(0,Je.normalizePath)(s.types_folder):"_types",o=`${i}/`,a=[],c=[],l=[],u=GO(t),d=`${(0,Je.stringifyYaml)(u).trimEnd()} -`;a.push({path:"mdbase.yaml",sourceDigest:xr(e),targetDigest:xr(d),source:e,target:d});let f=new Map,p=new Map;for(let v of r.getMarkdownFiles().filter(S=>S.path.startsWith(o)).sort((S,k)=>S.path.localeCompare(k.path))){let S=await r.cachedRead(v),k=_t(S);if(!k.hasFrontmatter||k.error)throw new Error(`Cannot migrate ${v.path}: ${(I=k.error)!=null?I:"frontmatter is missing"}.`);let $=WO(v.path,n,k.frontmatter),P=JO(v.path,k.frontmatter),w=YO(v.path,$.target);f.set(P.name,P),p.set(w.name,w);let N=`${at($.target,k.body)} -`;a.push({path:v.path,sourceDigest:xr(S),targetDigest:xr(N),source:S,target:N}),c.push($.summary),l.push(...$.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${i}.`);let m=0,h=0,y=fw(t,n),b=fw(u,Ji),g=r.getMarkdownFiles().filter(v=>!v.path.startsWith(o)).filter(v=>!v.path.startsWith(".mdbase/")).sort((v,S)=>v.path.localeCompare(S.path));for(let[v,S]of g.entries()){let k=_t(await r.cachedRead(S));if(k.error){h+=1;continue}let $=es(S.path,k.frontmatter,y,f),P=es(S.path,k.frontmatter,b,p),w=XO(k.frontmatter,$,f),N=QO(k.frontmatter,P,p);($n($.slice().sort())!==$n(P.slice().sort())||$n(w)!==$n(N))&&l.push({path:S.path,code:"effective_read_changed",message:"The proposed v0.3 types would change this record's resolved types or effective default values.",severity:"lossy"}),m+=1,v>0&&v%250===0&&await new Promise(j=>setTimeout(j,0))}let _=xr($n({sourceVersion:n,operations:a.map(({path:v,sourceDigest:S,targetDigest:k})=>({path:v,sourceDigest:S,targetDigest:k})),diagnostics:l}));return{planVersion:1,analysisId:_,sourceVersion:n,targetVersion:Ji,createdAt:new Date().toISOString(),backupLocation:`.mdbase/migrations/v02-to-v03-${_.slice(0,12)}`,operations:a,typeSummaries:c,diagnostics:l,applicable:!l.some(v=>v.severity==="lossy"),recordFilesRewritten:0,recordsVerified:m,recordsSkipped:h}}async function Wi(r,e,t){await sc(r,e,`${JSON.stringify(t,null,2)} -`)}async function hw(r,e,t={}){if(e.planVersion!==1||e.targetVersion!==Ji)throw new Error("Unsupported migration plan.");if(!e.applicable&&!t.allowLossy)throw new Error("This migration has lossy diagnostics. Review them and explicitly allow lossy migration.");for(let i of e.operations){let o=await Gi(r,i.path);if(xr(o)!==i.sourceDigest)throw new Error(`${i.path} changed after migration analysis. Run the review again.`)}let n=`${e.backupLocation}/manifest.json`,s={manifest_version:1,analysis_id:e.analysisId,source_version:e.sourceVersion,target_version:e.targetVersion,status:"prepared",created_at:new Date().toISOString(),written:[],files:e.operations.map(i=>({path:i.path,source_digest:i.sourceDigest,target_digest:i.targetDigest,backup_path:`${e.backupLocation}/files/${i.path}`}))};for(let i of e.operations)await sc(r,`${e.backupLocation}/files/${i.path}`,i.source);await Wi(r,n,s),s.status="applying",await Wi(r,n,s);try{for(let i of e.operations){let o=await Gi(r,i.path);if(xr(o)!==i.sourceDigest)throw new Error(`${i.path} changed during migration.`);s.written.push(i.path),await Wi(r,n,s),await sc(r,i.path,i.target);let a=await Gi(r,i.path);if(xr(a)!==i.targetDigest)throw new Error(`${i.path} did not verify after write.`)}return s.status="applied",s.completed_at=new Date().toISOString(),await Wi(r,n,s),{applied:!0,restored:!1,manifestPath:n,written:[...s.written]}}catch(i){let o=[];for(let a of[...s.written].reverse()){let c=e.operations.find(l=>l.path===a);if(!c){o.push(a);continue}try{await sc(r,a,c.source),xr(await Gi(r,a))!==c.sourceDigest&&o.push(a)}catch(l){o.push(a)}}s.status=o.length?"recovery_required":"rolled_back",s.error=i instanceof Error?i.message:String(i),s.manual_recovery_paths=o.length?o:void 0,s.completed_at=new Date().toISOString();try{await Wi(r,n,s)}catch(a){}return{applied:!1,restored:o.length===0,manifestPath:n,written:[...s.written],error:s.error}}}var ic=require("obsidian");function xe(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function or(r){return JSON.parse(JSON.stringify(r))}var eR=new Set(["file","formula","this"]);function tR(r){let e=r.trim();if(!e)throw new Error("Type name is required.");if(!/^[A-Za-z]/.test(e))throw new Error("Type name must start with a letter.");if(e.length>=64)throw new Error("Type name must be shorter than 64 characters.");if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(e))throw new Error("Type name may contain only letters, numbers, hyphens, and underscores.");if(eR.has(e.toLowerCase()))throw new Error(`Type name '${e}' is reserved.`);return e}function Sf(){return{specProfile:"v0.3",originalFrontmatter:{},name:"",description:"",extendsType:"",displayNameKey:"",strictMode:!1,pathPattern:"",filenamePattern:"",matchPathGlob:"",matchFieldsPresent:"",matchWhere:"",fields:[{name:"title",definition:{type:"string",required:!0}}],body:`# Type +`)&&e.slice(1)===r}function Vf(r,e){if(r===e)return!0;if(Array.isArray(r)||Array.isArray(e))return Array.isArray(r)&&Array.isArray(e)&&r.length===e.length&&r.every((i,s)=>Vf(i,e[s]));if(!r||!e||typeof r!="object"||typeof e!="object")return!1;let t=Object.entries(r),n=e;return t.length===Object.keys(n).length&&t.every(([i,s])=>Object.prototype.hasOwnProperty.call(n,i)&&Vf(s,n[i]))}var Sc=class{constructor(e,t,n,i){T(this,"fileSystem");T(this,"runtime");T(this,"mode");T(this,"blobStore");this.fileSystem=e,this.runtime=t,this.mode=n,this.blobStore=i}async recordPathPolicy(e){var t;return Iw(Object.keys((t=e.resources)!=null?t:{}),()=>this.fileSystem.read("mdbase.yaml"))}async put(e,t,n={}){var p,m,h,y;let{managedState:i=e,acceptedHash:s,preserveAcceptedDocument:o=!1,materialized:a,physicalPathPreflighted:c=!1}=n;bt(t.path,await this.recordPathPolicy(e)),a===void 0&&!c&&Tw(t.path,t.record_id,Object.keys((p=e.resources)!=null?p:{}),Object.entries(e.records),Object.entries((m=e.files)!=null?m:{}));let l=(h=a==null?void 0:a.document)!=null?h:kn(t),u=await this.fileSystem.read(t.path),d=i==null?void 0:i.records[t.record_id];if(u!==null&&u!==l){let b=this.runtime.digest(u);if(!(d!==void 0&&d.path===t.path&&b===d.hash)&&(s===void 0||b!==s))throw new Qe(t.record_id,t.path)}d&&d.path!==t.path&&await this.remove(i,t.record_id,d.path);let f=o&&typeof s=="string"&&u!==null&&this.runtime.digest(u)===s?s:null;f===null&&await this.fileSystem.write(t.path,l),e.records[t.record_id]={path:t.path,revision:t.revision,hash:(y=f!=null?f:a==null?void 0:a.hash)!=null?y:this.runtime.digest(l),...this.mode==="read_write"?{record:jw(t)}:{}}}async putFile(e,t,n=e){var p,m,h,y;if(St(t),!this.blobStore)throw new S("file_storage_unavailable","Selected collection files require a content-addressed blob store adapter.");Rw(t.path,t.file_id,e),(p=e.files)!=null||(e.files={});let i=(m=n.files)==null?void 0:m[t.file_id],s=await this.fileSystem.inspectBinary(t.path),o=ue(t.path),a=Object.values((h=n.files)!=null?h:{}).find(b=>ue(b.file.path)===o),c=[...Object.values((y=n.resources)!=null?y:{}),...Object.values(n.records)].find(b=>ue(b.path)===o),l=c?await this.fileSystem.read(t.path):null,u=(i==null?void 0:i.file.path)===t.path&&Oe(s,i.file),d=a!==void 0&&Oe(s,a.file),f=c!==void 0&&l!==null&&this.runtime.digest(l)===c.hash;if(s!==null&&!Oe(s,t)&&!u&&!d&&!f)throw new Qe(t.file_id,t.path);if(i&&i.file.path!==t.path){let b=await this.fileSystem.inspectBinary(i.file.path);if(b!==null&&!Oe(b,i.file))throw new Qe(t.file_id,i.file.path)}Oe(s,t)||await this.fileSystem.writeBinary(t.path,fc(this.blobStore.read(t.content_digest),t)),i&&i.file.path!==t.path&&await this.fileSystem.remove(i.file.path),e.files[t.file_id]={file:t}}async removeFile(e,t){var s;let n=(s=e.files)==null?void 0:s[t];if(!n)return;let i=await this.fileSystem.inspectBinary(n.file.path);if(i!==null&&!Oe(i,n.file))throw new Qe(t,n.file.path);i!==null&&await this.fileSystem.remove(n.file.path),delete e.files[t]}async remove(e,t,n){var a;let i=e.records[t],s=(a=i==null?void 0:i.path)!=null?a:n;bt(s,await this.recordPathPolicy(e));let o=await this.fileSystem.read(s);if(o!==null&&i&&this.runtime.digest(o)!==i.hash)throw new Qe(t,i.path);o!==null&&await this.fileSystem.remove(s),delete e.records[t]}async putResource(e,t,n){var o,a;let i=await this.fileSystem.read(t.path),s=(o=n==null?void 0:n.resources)==null?void 0:o[t.path];if(i!==null&&i!==t.document&&(!s||this.runtime.digest(i)!==s.hash))throw new Qe(`resource:${t.path}`,t.path);await this.fileSystem.write(t.path,t.document),(a=e.resources)!=null||(e.resources={}),e.resources[t.path]={path:t.path,revision:t.revision,hash:this.runtime.digest(t.document)}}async removeResource(e,t,n){let i=await this.fileSystem.read(t);if(i!==null&&this.runtime.digest(i)!==n.hash)throw new Qe(`resource:${t}`,t);i!==null&&await this.fileSystem.remove(t),e.resources&&delete e.resources[t]}};async function Fw(r){var d,f,p,m,h,y,b,g,_,k,v;let{state:e,selectiveSync:t,fileSystem:n,pathPolicy:i,digest:s}=r;if(t.excluded_folders.length>0||t.file_classes.length!==5)throw new S("promotion_incomplete_file_projection","Moving the source of truth requires every collection file class with no excluded folders.");if(((f=(d=e.pending)==null?void 0:d.length)!=null?f:0)>0||((m=(p=e.pending_files)==null?void 0:p.length)!=null?m:0)>0||Object.keys((h=e.conflicts)!=null?h:{}).length>0||Object.keys((y=e.file_conflicts)!=null?y:{}).length>0||Object.keys((b=e.local_issues)!=null?b:{}).length>0)throw new S("promotion_not_converged","Upload or resolve every local change before moving the source of truth.");await vc(e,i,n,s);let o=new Set(Object.keys((g=e.resources)!=null?g:{})),a=new Set(Object.values(e.records).map(E=>E.path)),c=(await n.listMarkdown(o)).filter(E=>!a.has(E));if(c.length>0)throw new S("promotion_unmanaged_files",`Synchronize unmanaged Markdown before promotion: ${c.join(", ")}.`);if(!n.listBinary)throw new S("promotion_file_scan_unavailable","Moving the source of truth requires binary file enumeration.");let l=new Set(Object.values((_=e.files)!=null?_:{}).map(E=>E.file.path)),u=(await n.listBinary(new Set([...o,...a]))).filter(E=>!l.has(E));if(u.length>0)throw new S("promotion_unmanaged_files",`Synchronize unmanaged files before moving the source of truth: ${u.join(", ")}.`);return{cursor:e.cursor,digest:ac([...Object.entries((k=e.resources)!=null?k:{}).map(([E,O])=>({kind:"resource",path:E,identity:"",document_hash:Sf(O.hash)})),...Object.entries(e.records).map(([E,O])=>({kind:"record",path:O.path,identity:E,document_hash:Sf(O.hash)})),...Object.values((v=e.files)!=null?v:{}).map(({file:E})=>({kind:"file",path:E.path,identity:E.file_id,document_hash:cc(E)}))])}}async function Ec(r,e,t){let n=await e.openSession();if(n.replica_id!==r||n.mode!==t)throw new S("invalid_mirror_session",`Filesystem mirror requires its own ${t.replace("_","-")} replica.`);return n}async function Vw(r,e){var L,F,z,P,I,ke,ce,de,Et,Ze,Lt,fo,cn;let{replicaId:t,transport:n,mode:i,fileSystem:s,runtime:o,materializer:a,blobStore:c,selectiveSync:l,reportProgress:u}=r,d=await Ec(t,n,i),f=(L=d.resources.documents)!=null?L:[],p=bc(f),m=new Pi(p,f,o.digest),h={protocol_version:1,replica_id:t,scope_epoch:d.scope_epoch,cursor:d.head,records:{},resources:{},files:{},selective_sync:l,mode:i,pending:[],pending_files:[],conflicts:{},file_conflicts:{},local_issues:{}},y=new Map,b=new Map;if(e){for(let U of Object.values((F=e.resources)!=null?F:{}))y.set(ue(U.path),U);for(let U of Object.values(e.records))y.set(ue(U.path),U);for(let U of Object.values((z=e.files)!=null?z:{}))b.set(ue(U.file.path),U.file)}let g=[];for(let U of f){let M=await s.read(U.path),te=e?y.get(ue(U.path)):void 0,et=e?b.get(ue(U.path)):void 0;if(te&&te.path!==U.path)throw new S("invalid_record_path",`Mirror paths ${te.path} and ${U.path} alias on a supported filesystem.`);M!==null&&M!==U.document&&(!te||o.digest(M)!==te.hash)&&(!et||!Oe(await s.inspectBinary(U.path),et))&&g.push(U.path)}let _=[],k=e?new Set:null;await $c(n,d,async U=>{for(let M of U){let te=m.validate(M),{document:et,record:R}=te;if(!tr(l,R.path))continue;let fe=await s.read(R.path),C=e?y.get(ue(R.path)):void 0,X=e?b.get(ue(R.path)):void 0;if(C&&C.path!==R.path)throw new S("invalid_record_path",`Mirror paths ${C.path} and ${R.path} alias on a supported filesystem.`);fe!==null&&fe!==et&&(!C||o.digest(fe)!==C.hash)&&(!X||!Oe(await s.inspectBinary(R.path),X))&&g.push(R.path),k==null||k.add(R.record_id),_.push(te)}});let v=[],E=new Set;await Js(n,d,async U=>{for(let M of U)if(on(l,M)){if(E.has(M.file_id))throw new S("invalid_snapshot",`Hosted snapshot repeats file identity ${M.file_id}.`);E.add(M.file_id),v.push(M)}}),rr([...f.map(U=>U.path),..._.map(({record:U})=>U.path),...v.map(U=>U.path)]);for(let U of v){let M=await s.inspectBinary(U.path),te=(P=e==null?void 0:e.files)==null?void 0:P[U.file_id],et=b.get(ue(U.path)),R=y.get(ue(U.path)),fe=R?await s.read(U.path):null;M!==null&&!Oe(M,U)&&(!te||te.file.path!==U.path||!Oe(M,te.file))&&(!et||!Oe(M,et))&&(!R||fe===null||o.digest(fe)!==R.hash)&&g.push(U.path)}if(e){for(let[M,te]of Object.entries(e.records)){if(k.has(M))continue;let et=await s.read(te.path);et!==null&&o.digest(et)!==te.hash&&g.push(te.path)}let U=new Set(f.map(M=>M.path));for(let M of Object.values((I=e.resources)!=null?I:{})){if(U.has(M.path))continue;let te=await s.read(M.path);te!==null&&o.digest(te)!==M.hash&&g.push(M.path)}for(let[M,te]of Object.entries((ke=e.files)!=null?ke:{})){if(E.has(M))continue;let et=await s.inspectBinary(te.file.path);et!==null&&!Oe(et,te.file)&&g.push(te.file.path)}}if(g.length)throw new wc([...new Set(g)].sort());if(v.length>0&&!c)throw new S("file_storage_unavailable","Selected collection files require a content-addressed blob store adapter.");let O=0;for(let U of v)await Ys(n,c,U),O+=1,u({phase:"downloading",completed:O,total:v.length,done:O===v.length});let w=f.length+_.length+v.length,x=0,$=()=>{x+=1,u({phase:"applying",completed:x,total:w,done:x===w})};for(let U of f)await a.putResource(h,U,e),$();for(let U of _)await a.put(h,U.record,{managedState:e,materialized:U}),$();for(let U of v)await a.putFile(h,U,e),$();if(e){let U=new Set([...Object.values((ce=h.resources)!=null?ce:{}).map(M=>ue(M.path)),...Object.values(h.records).map(M=>ue(M.path)),...Object.values((de=h.files)!=null?de:{}).map(M=>ue(M.file.path))]);for(let[M,te]of Object.entries(e.records))!h.records[M]&&!U.has(ue(te.path))&&await a.remove(e,M,te.path);for(let[M,te]of Object.entries((Et=e.resources)!=null?Et:{}))!((Ze=h.resources)!=null&&Ze[M])&&!U.has(ue(te.path))&&await a.removeResource(e,M,te);for(let M of Object.keys((Lt=e.files)!=null?Lt:{})){let te=(fo=e.files)==null?void 0:fo[M];te&&!((cn=h.files)!=null&&cn[M])&&!U.has(ue(te.file.path))&&await a.removeFile(e,M)}}return h.last_synced_at=o.now(),h}var Tn=class{constructor(e,t,n,i="read_only"){T(this,"replicaId");T(this,"transport");T(this,"mode");T(this,"stateStore");T(this,"fileSystem");T(this,"blobStore");T(this,"selectiveSync");T(this,"lease");T(this,"runtime");T(this,"materializer");T(this,"onProgress");var s,o;this.replicaId=e,this.transport=t,this.mode=i,this.stateStore=n.stateStore,this.fileSystem=n.fileSystem,this.blobStore=n.blobStore,this.selectiveSync=pc(n.selectiveSync),this.lease=(s=n.lease)!=null?s:new Xs,this.runtime=(o=n.runtime)!=null?o:Qs,this.materializer=new Sc(this.fileSystem,this.runtime,this.mode,this.blobStore),this.onProgress=n.onProgress}async sync(){await this.lease.runExclusive(async()=>{await this.syncUnlocked(),await this.pruneFileBlobs()})}async syncUnlocked(){var n,i,s,o,a,c,l,u;let e=await this.readState();if(!e){await this.rebuild(),this.mode==="read_write"&&await this.syncUnlocked();return}if(JSON.stringify(e.selective_sync)!==JSON.stringify(this.selectiveSync)){if(this.mode==="read_write"&&(((i=(n=e.pending)==null?void 0:n.length)!=null?i:0)>0||((o=(s=e.pending_files)==null?void 0:s.length)!=null?o:0)>0||Object.keys((a=e.conflicts)!=null?a:{}).length>0||Object.keys((c=e.file_conflicts)!=null?c:{}).length>0))throw new S("selective_sync_pending_changes","Upload pending Markdown changes before changing selective sync.");await this.rebuild(e);return}this.mode==="read_write"?(await this.flushPending(e),await this.flushPendingFiles(e),await this.captureLocalChanges(e),await this.flushPending(e),await this.flushPendingFiles(e)):await vc(e,await this.currentRecordPathPolicy(e),this.fileSystem,this.runtime.digest);let t=0;for(;;){let d=await this.transport.changes(e.cursor,200);if(d.scope_epoch!==e.scope_epoch||d.reset_required){await this.rebuild(e);return}for(let p of d.events)p.type==="file_put"&&St(p.file);let f=d.events.filter(p=>p.type==="remove"||p.type==="put"&&tr(this.selectiveSync,p.record.path));f.some(p=>p.type==="put")&&Cw(f,await this.currentRecordPathPolicy(e),e),this.preflightProjectedPaths(e,d.events);for(let p of d.events)if(p.type==="file_put"&&on(this.selectiveSync,p.file)){if(!this.blobStore)throw new S("file_storage_unavailable","Selected collection files require a content-addressed blob store adapter.");await Ys(this.transport,this.blobStore,p.file)}for(let p of d.events){if(p.type==="file_put"){on(this.selectiveSync,p.file)?await this.materializer.putFile(e,p.file):await this.materializer.removeFile(e,p.file.file_id),t+=1,this.reportProgress({phase:"applying",completed:t,total:null,done:!1});continue}if(p.type==="file_remove"){await this.materializer.removeFile(e,p.file_id),t+=1,this.reportProgress({phase:"applying",completed:t,total:null,done:!1});continue}let m=p.type==="put"?p.record.record_id:p.record_id,h=e.records[m],y=h==null?void 0:h.path;this.mode==="read_write"&&p.type==="put"&&(h==null?void 0:h.record)!==void 0&&h.path===p.record.path&&h.revision===p.record.revision||y&&((l=e.local_issues)!=null&&l[y])||((u=e.conflicts)!=null&&u[m]?Aw(e,p):p.type==="put"&&tr(this.selectiveSync,p.record.path)?await this.materializer.put(e,p.record,{physicalPathPreflighted:!0}):p.type==="put"?e.records[p.record.record_id]&&await this.materializer.remove(e,p.record.record_id,p.record.path):await this.materializer.remove(e,p.record_id,p.previous_path)),t+=1,this.reportProgress({phase:"applying",completed:t,total:null,done:!1})}if(e.cursor=d.cursor,!d.has_more){e.last_synced_at=this.runtime.now(),await this.writeState(e),t>0&&this.reportProgress({phase:"applying",completed:t,total:null,done:!0});return}await this.writeState(e)}}async status(){var a,c,l,u,d,f,p,m,h,y,b,g,_,k,v;let e=await this.readState();if(!e)return{state:"not_initialized",mode:this.mode,pending:0,pending_files:0,conflicts:[],file_conflicts:[],local_issues:[],cursor:null,last_synced_at:null};let t=[];for(let[E,O]of Object.entries((a=e.conflicts)!=null?a:{})){let w=e.records[E],x=(c=e.pending)==null?void 0:c.find($=>$.mutation.record_id===E);O.status==="conflicted"?t.push({record_id:E,path:(f=(d=(l=x==null?void 0:x.local_path)!=null?l:w==null?void 0:w.path)!=null?d:(u=O.conflict.current)==null?void 0:u.path)!=null?f:null,kind:"conflicted",message:"Local and remote changes need a decision."}):O.status==="rejected"&&t.push({record_id:E,path:(m=(p=x==null?void 0:x.local_path)!=null?p:w==null?void 0:w.path)!=null?m:null,kind:"rejected",message:O.error.message})}let n=Object.values((h=e.local_issues)!=null?h:{}).map(({path:E,code:O,message:w})=>({path:E,code:O,message:w})).sort((E,O)=>E.path.localeCompare(O.path)),i=(b=(y=e.pending)==null?void 0:y.length)!=null?b:0,s=(_=(g=e.pending_files)==null?void 0:g.length)!=null?_:0,o=Object.values((k=e.file_conflicts)!=null?k:{}).sort((E,O)=>E.path.localeCompare(O.path));return{state:t.length||o.length||n.length?"attention":i||s?"changes_waiting":"up_to_date",mode:this.mode,pending:i+s,pending_files:s,conflicts:t,file_conflicts:o,local_issues:n,cursor:e.cursor,last_synced_at:(v=e.last_synced_at)!=null?v:null}}async authorityPromotionManifest(){return this.lease.runExclusive(()=>this.authorityPromotionManifestUnlocked())}async authorityPromotionManifestUnlocked(){if(this.mode!=="read_write")throw new S("promotion_requires_writable_mirror","Only a two-way full collection mirror can become the local source of truth.");let e=await this.readState();if(!e)throw new S("promotion_not_initialized","Synchronize this folder before moving the source of truth.");return Fw({state:e,selectiveSync:this.selectiveSync,fileSystem:this.fileSystem,pathPolicy:await this.currentRecordPathPolicy(e),digest:this.runtime.digest})}async previewInitialization(){var y;if(await this.readState())return{already_initialized:!0,download_documents:0,upload_documents:0,unchanged_documents:0,download_files:0,upload_files:0,unchanged_files:0,collisions:[],local_issues:[]};let e=await Ec(this.replicaId,this.transport,this.mode),t=(y=e.resources.documents)!=null?y:[],n=bc(t),i=new Pi(n,t,this.runtime.digest),s=new Set,o=0,a=0,c=[],l=async(b,g)=>{s.add(b);let _=await this.fileSystem.read(b);_===null?o+=1:_===g?a+=1:c.push(b)};for(let b of t)await l(b.path,b.document);await $c(this.transport,e,async b=>{for(let g of b){let _=i.validate(g);tr(this.selectiveSync,_.record.path)&&await l(_.record.path,_.document)}});let u=0,d=0,f=0;await Js(this.transport,e,async b=>{for(let g of b){if(!on(this.selectiveSync,g))continue;s.add(g.path);let _=await this.fileSystem.inspectBinary(g.path);_===null?u+=1:Oe(_,g)?f+=1:c.push(g.path)}}),rr(s);let p=(await this.fileSystem.listMarkdown(new Set(t.map(b=>b.path)))).filter(b=>tr(this.selectiveSync,b)),m=[],h=0;if(this.mode==="read_write"){let b=_c(p,n);rr([...s,...b]);for(let g of b.filter(_=>!s.has(_))){let _=await this.fileSystem.read(g);if(_!==null)try{Rr(_,g),h+=1}catch(k){let v=sc(k,g);if(!v)throw k;m.push(v)}}if(this.fileSystem.listBinary){let g=new Set([...t.map(k=>k.path),...s]),_=(await this.fileSystem.listBinary(g)).filter(k=>hc(this.selectiveSync,k));for(let k of _)Ai(k,!1),s.has(k)||(d+=1);rr([...s,...b,..._])}}return{already_initialized:!1,download_documents:o,upload_documents:h,unchanged_documents:a,download_files:u,upload_files:d,unchanged_files:f,collisions:c,local_issues:m.sort((b,g)=>b.path.localeCompare(g.path))}}async rebuild(e){let t=await Vw({replicaId:this.replicaId,transport:this.transport,mode:this.mode,fileSystem:this.fileSystem,runtime:this.runtime,materializer:this.materializer,blobStore:this.blobStore,selectiveSync:this.selectiveSync,reportProgress:n=>this.reportProgress(n)},e);await this.writeState(t)}async resolveConflict(e,t){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,t))}async resolveFileConflict(e,t){await this.lease.runExclusive(()=>this.resolveFileConflictUnlocked(e,t))}async resolveFileConflictUnlocked(e,t){var d,f,p,m;if(this.mode!=="read_write")throw new S("mirror_read_only","Receive-only mirrors do not contain writable file conflicts.");let n=await this.readState(),i=(d=n==null?void 0:n.file_conflicts)==null?void 0:d[e];if(!n||!i)throw new S("mirror_file_conflict_not_found","Writable file conflict was not found.");let s=((f=n.pending_files)!=null?f:[]).filter(h=>h.operation==="upload"&&!h.file_id?`new:${h.path}`===e:h.file_id===e);if(s.length!==1)throw new S("invalid_mirror_state","Writable file conflict has no unique pending mutation.");let o=s[0],a=await this.currentAuthorityFiles(),c=e.startsWith("new:")?void 0:a.find(h=>h.file_id===e),l=a.find(h=>ue(h.path)===ue(o.path)),u=c!=null?c:l;if(n.pending_files=n.pending_files.filter(h=>h!==o),t==="remote"){let h=new Set([o.path]);o.operation==="move"&&h.add(o.from_path);let y=o.operation==="upload"&&!o.file_id||(m=(p=n.files)==null?void 0:p[o.file_id])==null?void 0:m.file;y&&h.add(y.path);for(let b of h)await this.fileSystem.inspectBinary(b)!==null&&await this.fileSystem.remove(b);if(u&&on(this.selectiveSync,u)){if(!this.blobStore)throw new S("file_storage_unavailable","File conflict resolution requires a blob store.");await Ys(this.transport,this.blobStore,u),await this.materializer.putFile(n,u)}else y&&delete n.files[y.file_id]}else this.queueLocalFileResolution(n,o,c,l);delete n.file_conflicts[e],await this.writeState(n)}queueLocalFileResolution(e,t,n,i){if(n&&i&&n.file_id!==i.file_id)throw new S("file_resolution_ambiguous","The authority changed this file and another file now occupies the local destination.");let s=n!=null?n:i;if(s?e.files[s.file_id]={file:s}:(t.operation!=="upload"||t.file_id)&&delete e.files[t.file_id],t.operation==="delete"){if(!s)return;e.pending_files.push({operation:"delete",mutation_id:this.runtime.randomId(),file_id:s.file_id,path:s.path,base_revision:s.revision});return}if(t.operation==="move"){if(!s)throw new S("file_resolution_source_missing","The authority deleted this file; restore it as a new file to keep the local bytes.");e.pending_files.push({...t,mutation_id:this.runtime.randomId(),file_id:s.file_id,from_path:s.path,base_revision:s.revision});return}if(!s||s.path===t.path){e.pending_files.push({...t,transfer_id:this.runtime.randomId(),...s?{file_id:s.file_id,base_revision:s.revision}:{file_id:void 0,base_revision:void 0}});return}let o=this.runtime.randomId();e.pending_files.push({operation:"move",mutation_id:o,file_id:s.file_id,from_path:s.path,path:t.path,base_revision:s.revision,content_digest:s.content_digest,size:s.size},{...t,transfer_id:this.runtime.randomId(),file_id:s.file_id,base_revision:s.revision,after_mutation_id:o})}async currentAuthorityFiles(){let e=await Ec(this.replicaId,this.transport,this.mode),t=[];return await Js(this.transport,e,async n=>{t.push(...n)}),t}async resolveConflictUnlocked(e,t){var o,a,c,l,u;if(this.mode!=="read_write")throw new S("mirror_read_only","Receive-only mirrors do not contain writable conflicts.");let n=await this.readState(),i=(o=n==null?void 0:n.conflicts)==null?void 0:o[e];if(!n||!i)throw new S("mirror_conflict_not_found","Writable mirror conflict was not found.");let s=((a=n.pending)!=null?a:[]).filter(d=>d.mutation.record_id===e);if(t==="remote"){let d=i.status==="conflicted"?i.conflict.current:(c=n.records[e])==null?void 0:c.record;await this.installRemoteResolution(n,e,d,s),n.pending=((l=n.pending)!=null?l:[]).filter(f=>f.mutation.record_id!==e)}else if(i.status==="rejected")n.pending=((u=n.pending)!=null?u:[]).filter(d=>d.mutation.record_id!==e);else{if(i.status!=="conflicted")throw new S("invalid_mirror_state","Mirror conflict metadata is invalid.");let d=s.at(-1);if(!d)throw new S("conflict_mutation_missing","The local change for this sync issue is unavailable.");let f=i.conflict.current,p=await this.fileSystem.read(d.local_path),m=this.localResolutionMutations(n,e,d.local_path,p,f),h=n.pending.findIndex(y=>y.mutation.record_id===e);n.pending=n.pending.filter(y=>y.mutation.record_id!==e),n.pending.splice(h<0?n.pending.length:h,0,...m),f?n.records[e]={path:f.path,revision:f.revision,hash:this.runtime.digest(kn(f)),record:f}:delete n.records[e]}delete n.conflicts[e],await this.writeState(n)}async installRemoteResolution(e,t,n,i){let s=await this.currentRecordPathPolicy(e),o=new Set(i.map(c=>c.local_path));if(n){bt(n.path,s);for(let l of o)bt(l,s),l!==n.path&&await this.fileSystem.read(l)!==null&&await this.fileSystem.remove(l);let c=await this.fileSystem.read(n.path);await this.materializer.put(e,n,{managedState:e,acceptedHash:c===null?null:this.runtime.digest(c)});return}let a=e.records[t];a&&o.add(a.path);for(let c of o)bt(c,s),await this.fileSystem.read(c)!==null&&await this.fileSystem.remove(c);delete e.records[t]}localResolutionMutations(e,t,n,i,s){let o=[],a,c=(d,f)=>{let p=this.runtime.randomId();o.push({mutation:{...d,mutation_id:p,replica_id:this.replicaId,scope_epoch:e.scope_epoch,created_at:this.runtime.now(),...a?{causal_predecessor:a}:{}},local_path:n,local_hash:f}),a=p};if(i===null)return s&&c({operation:"delete",record_id:t,base_revision:s.revision,input:{}},null),o;let l=Rr(i,n),u=this.runtime.digest(i);return s?(i!==kn(s)&&c({operation:"update",record_id:t,base_revision:s.revision,input:{patch:oc(s.frontmatter,l.frontmatter),body:l.body}},u),n!==s.path&&c({operation:"rename",record_id:t,base_revision:s.revision,input:{path:n}},u),o):(c({operation:"create",record_id:t,input:{path:n,frontmatter:l.frontmatter,body:l.body}},u),o)}async captureLocalChanges(e){var a,c;let t=e.pending.length,n=e.pending_files.length,i=JSON.stringify((a=e.local_issues)!=null?a:{}),{pending:s,localIssues:o}=await Mw({replicaId:this.replicaId,state:e,pathPolicy:await this.currentRecordPathPolicy(e),fileSystem:this.fileSystem,runtime:this.runtime,pathSelected:l=>tr(this.selectiveSync,l)});e.local_issues=o,e.pending.push(...s),await Dw({state:e,fileSystem:this.fileSystem,blobStore:this.blobStore,selectiveSync:this.selectiveSync,runtime:this.runtime}),(e.pending.length!==t||e.pending_files.length!==n||JSON.stringify((c=e.local_issues)!=null?c:{})!==i)&&await this.writeState(e)}async flushPendingFiles(e){await qw(e,this.transport,this.blobStore,()=>this.writeState(e))}async flushPending(e){var a,c,l;let t=(a=e.pending)!=null?a:e.pending=[],n=0,i=0,s=t.filter(u=>{var d;return!((d=e.conflicts)!=null&&d[u.mutation.record_id])}).length,o=0;for(;n=qf&&(await this.writeState(e),i=0);continue}(l=e.conflicts)!=null||(e.conflicts={}),e.conflicts[u.mutation.record_id]=p,i+=1,i>=qf&&(await this.writeState(e),i=0),n+=1}i>0&&await this.writeState(e),s>0&&this.reportProgress({phase:"uploading",completed:o,total:s,done:!0})}async readState(){let e=await this.stateStore.read();if(e===null)return null;try{return Ew(e,this.replicaId,this.mode)}catch(t){throw t instanceof S?t:new S("invalid_mirror_state","Mirror metadata is corrupt or belongs to another replica.")}}async writeState(e){await this.stateStore.write(e)}async pruneFileBlobs(){var n,i;if(!this.blobStore)return;let e=await this.readState();if(!e)return;let t=new Set;for(let s of Object.values((n=e.files)!=null?n:{}))t.add(s.file.content_digest);for(let s of(i=e.pending_files)!=null?i:[])"content_digest"in s&&t.add(s.content_digest);await this.blobStore.prune(t)}reportProgress(e){var t;(t=this.onProgress)==null||t.call(this,e)}async currentRecordPathPolicy(e){return this.materializer.recordPathPolicy(e)}preflightProjectedPaths(e,t){var s,o;let n=new Map(Object.entries(e.records).map(([a,c])=>[a,c.path])),i=new Map(Object.entries((s=e.files)!=null?s:{}).map(([a,c])=>[a,c.file.path]));for(let a of t)a.type==="put"?tr(this.selectiveSync,a.record.path)?n.set(a.record.record_id,a.record.path):n.delete(a.record.record_id):a.type==="remove"?n.delete(a.record_id):a.type==="file_put"?on(this.selectiveSync,a.file)?i.set(a.file.file_id,a.file.path):i.delete(a.file.file_id):i.delete(a.file_id);rr([...Object.keys((o=e.resources)!=null?o:{}),...n.values(),...i.values()])}};var Zs=class extends Tn{constructor(e,t,n){super(e,t,n,"read_write")}};var eo=".mdbase/connect-role.json",to=".mdbase/authority-adoption.json",ro=".mdbase/authority-adoption-snapshot.json",IR="mdbase-obsidian-connect",Ii="mirrors",OR="mdbase-connect-access-",TR="mdbase-connect-refresh-",RR="mdbase-connect-adoption-",CR=300*1e3,Bf=[".git/",".obsidian/",".trash/",".mdbase/"],no=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ze(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Ac(r,e){if(e!=null)return e;if(!r.trim())return{};try{return JSON.parse(r)}catch(t){return{}}}function Bw(r){var i;let e=(i=r["retry-after"])!=null?i:r["Retry-After"];if(!e)return;let t=Number(e);if(Number.isFinite(t)&&t>=0)return t*1e3;let n=Date.parse(e);if(Number.isFinite(n))return Math.max(0,n-Date.now())}function MR(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Enrollment cancelled.","AbortError");let e=await(0,ae.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Enrollment cancelled.","AbortError");return{status:e.status,body:Ac(e.text,e.json),retryAfterMs:Bw(e.headers)}}}function NR(){return async r=>{var t,n;if((t=r.signal)!=null&&t.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await(0,ae.requestUrl)({url:r.url,method:r.method,headers:r.headers,body:r.body===void 0?void 0:JSON.stringify(r.body),contentType:r.body===void 0?void 0:"application/json",throw:!1});if((n=r.signal)!=null&&n.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");return{status:e.status,body:Ac(e.text,e.json),retryAfterMs:Bw(e.headers)}}}var zf=class{constructor(e,t){this.accessToken=t;let n;try{n=new URL(e)}catch(i){throw new S("invalid_sync_url","Sync URL must be an absolute authority endpoint.")}if(!(n.protocol==="https:"||n.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(n.hostname))||n.username||n.password||n.search||n.hash||!/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync\/?$/i.test(n.pathname))throw new S("invalid_sync_url","Sync URL must identify one authority sync endpoint.");this.syncUrl=n.href.replace(/\/$/,""),this.filesUrl=this.syncUrl.replace(/\/sync$/,"/files")}openSession(){return this.request("POST","sessions")}snapshot(e,t){let n=new URLSearchParams({snapshot_id:e});return t&&n.set("page",t),this.request("GET",`snapshot?${n.toString()}`)}fileSnapshot(e,t){let n=new URLSearchParams({snapshot_id:e});return t&&n.set("page",t),this.request("GET",`files/snapshot?${n.toString()}`)}async*downloadFile(e){let t=crypto.randomUUID();try{let n=await this.fileRequest("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:t,file_id:e.file_id,revision:e.revision}),i=ze(n.strategy)?n.strategy:{},s=i.part_size;if(n.protocol_version!==1||n.type!=="file_transfer"||n.transfer_id!==t||n.direction!=="download"||n.protection!=="transport_tls"||n.total_size!==e.size||i.kind!=="object_ranges"||!Number.isSafeInteger(s)||s<=0)throw new S("invalid_sync_response","The authority returned an incompatible file download session.");let o=Math.ceil(e.size/s);for(let a=0;a=300){let u=Ac(l.text,l.json),d=ze(u)&&ze(u.error)?u.error:{};throw new S(typeof d.code=="string"?d.code:"file_download_failed",typeof d.message=="string"?d.message:`File download failed (${l.status}).`)}if(l.arrayBuffer.byteLength!==c)throw new S("file_integrity_failed","The authority returned a file part with the wrong length.");yield new Uint8Array(l.arrayBuffer)}}finally{await this.fileRequest("DELETE",`transfers/${encodeURIComponent(t)}`).catch(()=>{})}}changes(e,t=200){let n=new URLSearchParams({after:String(e),limit:String(t)});return this.request("GET",`changes?${n.toString()}`)}mutate(e){return this.request("POST","mutations",e)}request(e,t,n){return this.requestAt(this.syncUrl,e,t,n)}fileRequest(e,t,n){return this.requestAt(this.filesUrl,e,t,n)}async requestAt(e,t,n,i){let s=await(0,ae.requestUrl)({url:`${e}/${n}`,method:t,headers:{authorization:`Bearer ${this.accessToken}`},body:i===void 0?void 0:JSON.stringify(i),contentType:i===void 0?void 0:"application/json",throw:!1}),o=Ac(s.text,s.json);if(s.status<200||s.status>=300){let a=ze(o)&&ze(o.error)?o.error:{};throw new S(typeof a.code=="string"?a.code:"sync_failed",typeof a.message=="string"?a.message:`Sync request failed (${s.status}).`)}return o}};function Oi(r){let e=As(r);if(e===".mdbase"||Bf.some(t=>e.startsWith(t)))throw new S("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${e}`);return e}async function io(r,e){let t=(0,ae.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n="";for(let i of t.split("/")){n=n?`${n}/${i}`:i;let s=r.getAbstractFileByPath(n);if(!(s instanceof ae.TFolder)){if(s)throw new S("mirror_path_collision",`A file blocks the mirror folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}var Hf=class{constructor(e){this.vault=e}async read(e){let t=Oi(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof ae.TFile))throw new S("mirror_path_collision",`Expected a file at ${t}.`);return this.vault.cachedRead(n)}async write(e,t){let n=Oi(e),i=n.lastIndexOf("/");i>=0&&await io(this.vault,n.slice(0,i));let s=this.vault.getAbstractFileByPath(n);if(s instanceof ae.TFolder)throw new S("mirror_path_collision",`A folder blocks the mirror file ${n}.`);s instanceof ae.TFile?await this.vault.modify(s,t):await this.vault.create(n,t)}async remove(e){let t=Oi(e),n=this.vault.getAbstractFileByPath(t);if(n!=null){if(!(n instanceof ae.TFile))throw new S("mirror_path_collision",`Expected a file at ${t}.`);await this.vault.delete(n,!0)}}async listMarkdown(e){return this.vault.getMarkdownFiles().map(t=>(0,ae.normalizePath)(t.path)).filter(t=>!e.has(t)).filter(t=>!Bf.some(n=>t.startsWith(n))).sort()}async inspectBinary(e){let t=Oi(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof ae.TFile))throw new S("mirror_path_collision",`Expected a file at ${t}.`);let i=await this.vault.readBinary(n),s=await crypto.subtle.digest("SHA-256",i),o=Array.from(new Uint8Array(s),a=>a.toString(16).padStart(2,"0")).join("");return{size:i.byteLength,content_digest:`sha256:${o}`}}async writeBinary(e,t){let n=Oi(e),i=[],s=0;for await(let u of t){if(!(u instanceof Uint8Array)||!Number.isSafeInteger(s+u.byteLength))throw new S("invalid_file_materialization","The binary file stream is invalid or too large.");i.push(u),s+=u.byteLength}let o=new Uint8Array(s),a=0;for(let u of i)o.set(u,a),a+=u.byteLength;let c=n.lastIndexOf("/");c>=0&&await io(this.vault,n.slice(0,c));let l=this.vault.getAbstractFileByPath(n);if(l instanceof ae.TFolder)throw new S("mirror_path_collision",`A folder blocks the mirror file ${n}.`);l instanceof ae.TFile?await this.vault.modifyBinary(l,o.buffer):await this.vault.createBinary(n,o.buffer)}async listBinary(e){return this.vault.getFiles().map(t=>(0,ae.normalizePath)(t.path)).filter(t=>!t.toLowerCase().endsWith(".md")).filter(t=>!e.has(t)).filter(t=>!Bf.some(n=>t.startsWith(n))).sort()}async readBinary(e){let t=Oi(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof ae.TFile))throw new S("mirror_path_collision",`Expected a file at ${t}.`);let i=new Uint8Array(await this.vault.readBinary(n));return(async function*(){yield i})()}},Kf=class{constructor(e){this.key=e;this.database=null}async read(){let e=await this.open();return new Promise((t,n)=>{let i=e.transaction(Ii,"readonly").objectStore(Ii).get(this.key);i.onsuccess=()=>{var s;return t((s=i.result)!=null?s:null)},i.onerror=()=>n(i.error)})}async write(e){let t=await this.open();await new Promise((n,i)=>{let s=t.transaction(Ii,"readwrite");s.objectStore(Ii).put(e,this.key),s.oncomplete=()=>n(),s.onerror=()=>i(s.error),s.onabort=()=>i(s.error)})}open(){var e;if(typeof indexedDB=="undefined")throw new S("storage_unavailable","IndexedDB is required for persistent mirror state.");return(e=this.database)!=null||(this.database=new Promise((t,n)=>{let i=indexedDB.open(IR,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Ii)||i.result.createObjectStore(Ii)},i.onerror=()=>n(i.error),i.onsuccess=()=>t(i.result)})),this.database}},Ti=class Ti{constructor(e){this.key=e}async runExclusive(e){if(Ti.active.has(this.key))throw new S("mirror_busy","A mirror operation is already running for this vault.");Ti.active.add(this.key);try{return await e()}finally{Ti.active.delete(this.key)}}};Ti.active=new Set;var Wf=Ti,kc=class{constructor(e,t,n={}){this.app=e;this.settingsHost=t;this.options=n;this.progress=null;this.adoptionMarker=null;var i,s,o;this.fileSystem=(i=n.fileSystem)!=null?i:new Hf(e.vault),this.enrollmentClient=(s=n.enrollmentClient)!=null?s:new uc({request:MR()}),this.adoptionClient=(o=n.adoptionClient)!=null?o:new gc({request:NR()})}async initialize(){if(this.adoptionMarker=await this.readAdoptionMarker(),this.adoptionMarker&&this.settingsHost.getMirrorProfile())throw new S("authority_adoption_state_conflict","This vault contains both an authority-adoption checkpoint and a mirror profile.")}getProgress(){return this.progress?{...this.progress}:null}getAdoptionMarker(){return this.adoptionMarker?JSON.parse(JSON.stringify(this.adoptionMarker)):null}assertLocalAuthorityWritable(){if(this.adoptionMarker&&["fenced","activating","adopted"].includes(this.adoptionMarker.phase))throw new S("local_authority_fenced",this.adoptionMarker.phase==="adopted"?"Hosted mdbase is now authoritative. Finish reconnecting this vault as its mirror before editing.":"This local authority is frozen while its exact snapshot is adopted by hosted mdbase.")}async adoptLocalCollection(e,t){if(this.settingsHost.getMirrorProfile())throw new S("mirror_already_configured","This vault already mirrors a collection authority.");if(this.adoptionMarker)return this.resumeAdoption(t);let n=await this.ensurePortableCollectionIdentity(),i=await this.adoptionClient.begin({controlUrl:e.controlUrl,collectionId:n.collectionId,displayName:n.displayName,sourceName:e.mirrorName,retainMirror:!0,mirrorName:e.mirrorName},t);return await this.storeAdoptionSecret(i),await this.writeAdoptionMarker({version:1,phase:"waiting_for_approval",session:Uf(i),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(Uf(i)),this.runAdoptionWithRecovery(i,t)}async resumeAdoption(e={}){var s,o,a;let t=(s=this.adoptionMarker)!=null?s:await this.readAdoptionMarker();if(!t)throw new S("authority_adoption_not_found","This vault has no collection-adoption checkpoint.");this.adoptionMarker=t;let n=this.app.secretStorage.getSecret(this.adoptionSecretId(t.session.adoptionId));if(!n)throw new S("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");let i={...t.session,credential:n};return t.phase==="waiting_for_approval"&&await((o=e.onVerification)==null?void 0:o.call(e,Uf(i))),this.runAdoptionWithRecovery(i,{...e,onVerification:(a=e.onVerification)!=null?a:(()=>{})})}async cancelAdoption(e){var i;let t=(i=this.adoptionMarker)!=null?i:await this.readAdoptionMarker();if(!t)return;if(["activating","adopted"].includes(t.phase))throw new S("authority_adoption_activation_started","Hosted activation has started and must be resumed; it can no longer be cancelled.");let n=this.app.secretStorage.getSecret(this.adoptionSecretId(t.session.adoptionId));if(!n)throw new S("authority_adoption_credentials_missing","The collection-adoption credential is missing from Obsidian's secret store.");await this.adoptionClient.cancel({...t.session,credential:n},{signal:e}),await this.clearAdoptionCheckpoint(t.session.adoptionId)}async enroll(e,t){let n=await this.assertCanBecomeMirror(e.collectionId),i=await this.enrollmentClient.enroll({...e,...n?{collectionId:n}:{}},t),s=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i)}catch(o){if(s)try{await this.app.vault.adapter.remove(eo)}catch(a){throw new S("enrollment_recovery_required",`Enrollment settings could not be saved and the temporary role marker could not be removed: ${o instanceof Error?o.message:String(o)}`)}throw o}return this.requireProfile()}async preview(){return(await this.createMirror()).previewInitialization()}async status(){let e=this.settingsHost.getMirrorProfile();return e?(await this.assertMirror(e.collectionId),(await this.createMirror()).status()):null}async sync(e){let t=await this.createMirror(n=>{this.progress=n,e==null||e({...n})});try{return await t.sync(),t.status()}finally{this.progress=null}}async resolveConflict(e,t){let n=await this.createMirror();return await n.resolveConflict(e,t),n.status()}async runAdoption(e,t){let n=this.requireAdoptionMarker(e.adoptionId),i=null;if(n.phase==="adopted"){let s=await this.adoptionClient.exchange(e,t);if(s.status!=="completed")throw new S("authority_adoption_state_conflict","The local checkpoint says adoption completed, but Connect does not.");i=s}else if(n.phase==="activating"){let s=await this.readAdoptionSnapshot(n),o=await this.adoptionClient.exchange(e,t);i=o.status==="completed"?o:await this.adoptionClient.complete(e,s,t)}else if(n.phase==="fenced"){let s=await this.readAdoptionSnapshot(n),o=await this.adoptionClient.exchange(e,t);o.status==="completed"?i=o:(o.status==="ready"&&await this.adoptionClient.uploadSnapshot(e,o,s,t),await this.updateAdoptionPhase("activating",s),i=await this.adoptionClient.complete(e,s,t))}else{let s=n.phase==="waiting_for_approval"?await this.adoptionClient.waitForApproval(e,t):await this.requirePreparedAdoption(e,t),o=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.updateAdoptionPhase("uploading"),await this.adoptionClient.uploadSnapshot(e,s,o,t);let a=await this.captureAuthoritySnapshot(e.requested.collectionId);await this.writeAdoptionSnapshot(a),await this.updateAdoptionPhase("fenced",a);let c=await this.requirePreparedAdoption(e,t);await this.adoptionClient.uploadSnapshot(e,c,a,t),await this.updateAdoptionPhase("activating",a),i=await this.adoptionClient.complete(e,a,t)}return await this.updateAdoptionPhase("adopted"),this.finishRetainedMirror(e,i,t)}async runAdoptionWithRecovery(e,t){try{return await this.runAdoption(e,t)}catch(n){throw LR(n)?(await this.adoptionClient.cancel(e,{signal:t.signal}).catch(()=>{}),await this.clearAdoptionCheckpoint(e.adoptionId),new S(n.code,"This adoption ended before hosted activation. The vault remains the writable local authority; start a new adoption to try again.")):n}}async requirePreparedAdoption(e,t){let n=await this.adoptionClient.exchange(e,t);if(n.status==="ready")return n;throw n.status==="activating"?new Cr("Hosted authority activation has already started. Resume using the saved fenced snapshot."):new S("authority_adoption_already_completed","Hosted authority has already adopted this collection.")}async finishRetainedMirror(e,t,n){var a,c;let i,s=this.adoptionClient.mirrorEnrollmentSession(e,t);if(!s)throw new S("authority_adoption_mirror_missing","Hosted authority activated without retaining this vault as a mirror.");try{i=await this.enrollmentClient.waitForApproval(s,{signal:n.signal,onStatus:l=>{var u;return(u=n.onStatus)==null?void 0:u.call(n,{...l,state:l.state})}})}catch(l){if((a=n.signal)!=null&&a.aborted)throw l;i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,collectionId:e.requested.collectionId,mirrorName:(c=e.requested.mirrorName)!=null?c:e.requested.sourceName,mode:"read_write"},{signal:n.signal,onVerification:n.onVerification})}let o=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i)}catch(l){throw o&&await this.app.vault.adapter.remove(eo),l}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async captureAuthoritySnapshot(e){let t=await ci(this.app.vault);if(!t)throw new S("invalid_collection_configuration","A valid mdbase.yaml is required.");let n=await this.app.vault.adapter.read("mdbase.yaml"),i=(0,ae.parseYaml)(n),s=[{path:"mdbase.yaml",kind:"configuration",document:n}],o=`${(0,ae.normalizePath)(t.settings.types_folder)}/`,a=this.app.vault.getMarkdownFiles().filter(u=>(0,ae.normalizePath)(u.path).startsWith(o)).sort((u,d)=>u.path.localeCompare(d.path));for(let u of a)s.push({path:(0,ae.normalizePath)(u.path),kind:"type",document:await this.app.vault.cachedRead(u)});let c=DR(i);if(c.length){let u=c.map(f=>(0,Uw.default)(f,{dot:!0})),d=qR(this.app.vault).filter(f=>f.extension==="base").filter(f=>u.some(p=>p((0,ae.normalizePath)(f.path)))).sort((f,p)=>f.path.localeCompare(p.path));for(let f of d)s.push({path:(0,ae.normalizePath)(f.path),kind:"view",document:await this.app.vault.cachedRead(f)})}let l=[];for(let u of this.app.vault.getMarkdownFiles().sort((d,f)=>d.path.localeCompare(f.path))){let d=(0,ae.normalizePath)(u.path);if(ks(d,t))continue;let f=await this.app.vault.cachedRead(u);l.push({path:d,document:f})}return Cf({collectionId:e,sourceHead:0,specVersion:t.spec_version,resources:s,records:l})}async ensurePortableCollectionIdentity(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))throw new S("collection_not_initialized","Initialize an mdbase collection before hosting it.");let e=await this.app.vault.adapter.read("mdbase.yaml"),t;try{t=(0,ae.parseYaml)(e)}catch(o){throw new S("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!ze(t))throw new S("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let n=ze(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,i;if(n===void 0){i=crypto.randomUUID();let o=ze(t["x-mdbase-connect"])?t["x-mdbase-connect"]:{};t["x-mdbase-connect"]={...o,collection_id:i},await this.app.vault.adapter.write("mdbase.yaml",(0,ae.stringifyYaml)(t))}else if(typeof n=="string"&&no.test(n))i=n;else throw new S("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");let s=typeof t.name=="string"&&t.name.trim()?t.name.trim():this.app.vault.getName();return{collectionId:i,displayName:s}}async createMirror(e){var o,a,c,l,u,d,f,p,m;let t=this.requireProfile();await this.assertMirror(t.collectionId);let n=await this.freshAccessToken(t),i=(c=(a=(o=this.options).transportFactory)==null?void 0:a.call(o,t,n))!=null?c:new zf(t.syncUrl,n),s={stateStore:(d=(u=(l=this.options).stateStoreFactory)==null?void 0:u.call(l,t))!=null?d:new Kf(`${t.collectionId}:${t.replicaId}`),fileSystem:this.fileSystem,lease:(m=(p=(f=this.options).leaseFactory)==null?void 0:p.call(f,t))!=null?m:new Wf(`${t.collectionId}:${t.replicaId}`),onProgress:e};return t.mode==="read_write"?new Zs(t.replicaId,i,s):new Tn(t.replicaId,i,s)}requireProfile(){let e=this.settingsHost.getMirrorProfile();if(!e)throw new S("mirror_not_configured","This vault is not connected to a collection authority.");return e}accessSecretId(e){return`${OR}${e.toLowerCase()}`}refreshSecretId(e){return`${TR}${e.toLowerCase()}`}adoptionSecretId(e){return`${RR}${e.toLowerCase()}`}async storeAdoptionSecret(e){this.app.secretStorage.setSecret(this.adoptionSecretId(e.adoptionId),e.credential)}async persistEnrollment(e){this.app.secretStorage.setSecret(this.accessSecretId(e.collectionId),e.accessToken),this.app.secretStorage.setSecret(this.refreshSecretId(e.collectionId),e.refreshCredential),await this.settingsHost.saveMirrorProfile({version:1,syncUrl:e.syncUrl,controlUrl:e.controlUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessTokenExpiresAt:e.accessTokenExpiresAt})}async freshAccessToken(e){let t=this.accessSecretId(e.collectionId),n=this.app.secretStorage.getSecret(t),i=Date.parse(e.accessTokenExpiresAt);if(n&&Number.isFinite(i)&&i-Date.now()>CR)return n;let s=this.app.secretStorage.getSecret(this.refreshSecretId(e.collectionId));if(!s)throw new S("mirror_credentials_missing","The mirror refresh credential is missing. Re-enroll this vault.");let o=await this.enrollmentClient.renew({controlUrl:e.controlUrl,syncUrl:e.syncUrl,collectionId:e.collectionId,replicaId:e.replicaId,mode:e.mode,name:e.name,enrollmentId:e.enrollmentId,accessToken:n!=null?n:"",refreshCredential:s,accessTokenExpiresAt:e.accessTokenExpiresAt});return await this.persistEnrollment(o),o.accessToken}async assertCanBecomeMirror(e){var o;let t=await this.readMarker(),n=await this.readPortableCollectionId();if(n&&!t)throw new S("local_authority_requires_transfer","This vault has a local Connect identity. Transfer authority explicitly before using it as a mirror.");if(n&&(t==null?void 0:t.collection_id)!==n)throw new S("mirror_identity_conflict","The vault identity and mirror role marker identify different collections.");let i=this.settingsHost.getMirrorProfile(),s=(o=i==null?void 0:i.collectionId)!=null?o:e;if(t&&s&&t.collection_id!==s)throw new S("mirror_identity_conflict","This vault is already marked as a different mirror.");if(!t&&!i&&await this.app.vault.adapter.exists("mdbase.yaml"))throw new S("existing_collection_requires_transfer","This vault already contains an mdbase collection. Connect an empty vault, or transfer collection authority explicitly.");return s!=null?s:t==null?void 0:t.collection_id}async readPortableCollectionId(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))return null;let e;try{e=(0,ae.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch(i){throw new S("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!ze(e))throw new S("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let t=e["x-mdbase-connect"];if(t===void 0)return null;if(!ze(t))throw new S("invalid_collection_configuration","x-mdbase-connect must be a YAML mapping.");let n=t.collection_id;if(n===void 0)return null;if(typeof n!="string"||!no.test(n))throw new S("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");return n}async markMirror(e){let t=await this.readMarker();if(t){if(t.collection_id!==e)throw new S("mirror_identity_conflict","This vault already mirrors a different collection authority.");return!1}return await io(this.app.vault,".mdbase"),await this.app.vault.adapter.write(eo,`${JSON.stringify({version:1,role:"mirror",collection_id:e},null,2)} +`),!0}async assertMirror(e){let t=await this.readMarker();if(!t||t.collection_id!==e)throw new S("mirror_marker_missing","The vault's mirror role marker is missing or does not match this connection.")}async readMarker(){if(!await this.app.vault.adapter.exists(eo))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(eo))}catch(t){throw new S("invalid_mirror_marker","The mirror role marker is corrupt.")}if(!ze(e)||e.version!==1||e.role!=="mirror"||typeof e.collection_id!="string"||!no.test(e.collection_id))throw new S("invalid_mirror_marker","The mirror role marker is invalid.");return e}requireAdoptionMarker(e){if(!this.adoptionMarker||this.adoptionMarker.session.adoptionId!==e)throw new S("authority_adoption_state_conflict","The collection-adoption checkpoint does not match this approval.");return this.adoptionMarker}async updateAdoptionPhase(e,t){if(!this.adoptionMarker)throw new S("authority_adoption_not_found","Collection-adoption checkpoint is missing.");await this.writeAdoptionMarker({...this.adoptionMarker,phase:e,...t?{manifest_digest:t.manifest_digest,source_revision:t.source_revision,source_head:t.source_head}:{}})}async writeAdoptionMarker(e){await io(this.app.vault,".mdbase"),await this.app.vault.adapter.write(to,`${JSON.stringify(e,null,2)} +`),this.adoptionMarker=e}async readAdoptionMarker(){if(!await this.app.vault.adapter.exists(to))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(to))}catch(t){throw new S("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is corrupt.")}if(!jR(e))throw new S("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is invalid.");return e}async writeAdoptionSnapshot(e){await io(this.app.vault,".mdbase"),await this.app.vault.adapter.write(ro,JSON.stringify(e))}async readAdoptionSnapshot(e){if(!await this.app.vault.adapter.exists(ro))throw new S("authority_adoption_snapshot_missing","The fenced authority snapshot is missing; hosted activation cannot be resumed safely.");let t;try{t=JSON.parse(await this.app.vault.adapter.read(ro))}catch(n){throw new S("invalid_authority_adoption_snapshot","The fenced authority snapshot is corrupt.")}if(t.collection_id!==e.session.requested.collectionId||t.manifest_digest!==e.manifest_digest||t.source_revision!==e.source_revision||t.source_head!==e.source_head)throw new S("authority_adoption_snapshot_mismatch","The fenced authority snapshot does not match its durable checkpoint.");return t}async clearAdoptionCheckpoint(e){await this.app.vault.adapter.exists(to)&&await this.app.vault.adapter.remove(to),await this.app.vault.adapter.exists(ro)&&await this.app.vault.adapter.remove(ro),this.app.secretStorage.setSecret(this.adoptionSecretId(e),""),this.adoptionMarker=null}};function Uf(r){let{credential:e,...t}=r;return t}function LR(r){return r instanceof Y&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function DR(r){if(!ze(r))return[];let e=r["x-obsidian"];return!ze(e)||!ze(e.bases)||!Array.isArray(e.bases.include)?[]:e.bases.include.filter(t=>typeof t=="string")}function qR(r){var i;let e=(i=r.getFiles)==null?void 0:i.call(r);if(e)return e;let t=[],n=s=>{for(let o of s.children)o instanceof ae.TFile?t.push(o):o instanceof ae.TFolder&&n(o)};return n(r.getRoot()),t}function jR(r){if(!ze(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!ze(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&no.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&ze(e.requested)&&typeof e.requested.collectionId=="string"&&no.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.manifest_digest===null||typeof r.manifest_digest=="string")&&(r.source_revision===null||typeof r.source_revision=="string")&&(r.source_head===null||Number.isSafeInteger(r.source_head))}var ct=require("obsidian");var co="0.3.0",FR=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),VR=new Set(["type","required","default","description","values","items","fields","min","max","min_length","max_length","pattern","unique","deprecated","generated","computed","target","validate_exists","tn_role","tn_completed_values"]);function Se(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function De(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function Dr(r){return Qs.digest(r)}function Rn(r){return Array.isArray(r)?`[${r.map(Rn).join(",")}]`:Se(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Rn(r[e])}`).join(",")}}`:JSON.stringify(r)}function Gf(r){if(Array.isArray(r))return r.map(Gf);if(!Se(r))return r;let e={};for(let[t,n]of Object.entries(r)){let i=Gf(n);i!=null&&(Array.isArray(i)&&i.length===0||Se(i)&&Object.keys(i).length===0||(e[t]=i))}return e}function Ri(r){return[...new Set(r)]}function UR(r){return Se(r.fields)?Object.values(r.fields).some(e=>Se(e)&&(typeof e.tn_role=="string"||Array.isArray(e.tn_completed_values))):!1}function Jf(r,e,t){let n=Se(e)?e:{},i={},s={},o=[],a;switch(n.type){case"any":a={};break;case"string":case"integer":case"number":case"boolean":a={type:n.type};break;case"date":case"datetime":case"time":a={type:"string",format:n.type==="datetime"?"date-time":n.type};break;case"enum":a={enum:Array.isArray(n.values)?De(n.values):[]};break;case"link":a={type:"string"},i[r]={target_type:typeof n.target=="string"?n.target:r.endsWith("Parent")||r.endsWith("uid")?"task":"any",validate_exists:n.validate_exists===!0};break;case"list":{let c=Jf(`${r}[]`,n.items,t);a={type:"array",items:c.schema},Object.assign(i,c.links),Object.assign(s,c.legacy),o.push(...c.unsupported);break}case"object":{let c={},l=[];for(let[u,d]of Object.entries(Se(n.fields)?n.fields:{})){let f=Jf(`${r}.${u}`,d,t);c[u]=f.schema,Object.assign(i,f.links),Object.assign(s,f.legacy),o.push(...f.unsupported),Se(d)&&d.required===!0&&l.push(u)}t&&r==="blockedBy[]"&&l.push("uid"),a={type:"object",additionalProperties:Object.keys(c).length===0,properties:c,...l.length?{required:Ri(l)}:{}};break}default:a={},o.push(`${r}.type`);break}t&&r==="title"&&(a.minLength=1,a.description="Short summary of the task."),typeof n.description=="string"&&(a.description=n.description),typeof n.min=="number"&&(n.type==="string"?a.minLength=n.min:n.type==="list"?a.minItems=n.min:a.minimum=n.min),typeof n.max=="number"&&(n.type==="string"?a.maxLength=n.max:n.type==="list"?a.maxItems=n.max:a.maximum=n.max),typeof n.min_length=="number"&&(a.minLength=n.min_length),typeof n.max_length=="number"&&(a.maxLength=n.max_length),typeof n.pattern=="string"&&(a.pattern=n.pattern),n.deprecated===!0&&(a.deprecated=!0),n.default!==void 0&&(a.default=De(n.default)),n.computed!==void 0&&o.push(`${r}.computed`);for(let[c,l]of Object.entries(n)){let u=t&&(c==="tn_role"||c==="tn_completed_values");(!VR.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!u)&&(s[`${r}.${c}`]=De(l))}return{schema:a,links:i,legacy:s,unsupported:o}}function so(r,e,t,n){let i=Se(r[e])?r[e]:{},s=Se(i.set)?i.set:{};s[t]=n,i.set=s,r[e]=i}function BR(r,e,t){if(t==="now")so(r,"on_create",e,{now:!0});else if(t==="now_on_write")so(r,"on_update",e,{now:!0});else if(t==="uuid")so(r,"on_create",e,{uuid:!0});else if(t==="ulid")so(r,"on_create",e,{ulid:!0});else if(Se(t)&&t.transform==="slugify"&&typeof t.from=="string")so(r,"on_create",e,{slugify:t.from});else return!1;return!0}function zR(r){var t;let e=r.match(/^(.*\/)?\{title\}\.md$/);return e?{runtime:"tasknotes",template:"{{title}}",folder:((t=e[1])!=null?t:"").replace(/\/$/,""),generated_by:"tasknotes.filename.create"}:{runtime:"tasknotes",template:r,generated_by:"tasknotes.filename.create"}}function HR(r,e,t){var E;if(t.kind==="mdbase.type"||t.schema!==void 0)throw new Error(`${r} already looks like a v0.3 type.`);if(typeof t.name!="string"||!Se(t.fields))throw new Error(`${r} is not a v0.2 type with a name and fields.`);let n=UR(t),i=t.name.trim().toLowerCase(),s={type:{const:i}},o=[],a={},c={},l=[],u={},d={},f=[],p=[],m={},h={},y={};for(let[O,w]of Object.entries(t.fields)){let x=Se(w)?w:{},$=Jf(O,x,n);s[O]=$.schema,Object.assign(c,$.links),Object.assign(d,$.legacy),f.push(...$.unsupported),x.required===!0&&o.push(O),x.default!==void 0&&(a[O]=De(x.default)),x.unique===!0&&l.push({field:O,scope:"collection"}),x.generated!==void 0&&BR(u,O,x.generated)&&p.push(O),typeof x.tn_role=="string"&&(m[x.tn_role]=O),Array.isArray(x.tn_completed_values)&&(h.completed_values=De(x.tn_completed_values))}a.status!==void 0&&(h.default=De(a.status)),a.priority!==void 0&&(y.default=De(a.priority));let b=typeof t.display_name_key=="string"&&Object.prototype.hasOwnProperty.call(t.fields,t.display_name_key)?t.display_name_key:void 0,g={...b?{display:{name_field:b}}:{},read_defaults:a,links:c,unique:l};typeof t.path_pattern=="string"&&(g.path=n?zR(t.path_pattern):{pattern:t.path_pattern});let _={};for(let[O,w]of Object.entries(t))FR.has(O)||(_[O]=De(w));Object.keys(d).length&&(_.fields=d);let k=Gf({kind:"mdbase.type",name:i,version:1,description:typeof t.description=="string"?t.description:void 0,match:Se(t.match)?De(t.match):void 0,schema:{dialect:"json-schema-2020-12",value:{$schema:"https://json-schema.org/draft/2020-12/schema",type:"object",additionalProperties:t.strict!==!0,properties:s,...o.length?{required:Ri(o)}:{}}},collection:g,lifecycle:u,...n?{"x-tasknotes":{contract:"tasknotes.task",version:1,field_roles:m,status:h,priority:y,archive:{tags_field:(E=m.tags)!=null?E:"tags",archived_tag:"archived"}}}:{},...Object.keys(_).length?{"x-legacy-v0.2":_}:{}}),v=[];t.extends!==void 0&&f.push("extends");for(let O of Ri(f).sort())v.push({path:r,code:"migration_lossy",message:`${O} cannot be expressed as canonical v0.3 write behavior and was retained as legacy metadata where possible.`,severity:"lossy"});return n&&v.push({path:r,code:"path_policy_runtime_owned",message:"TaskNotes filename behavior is recorded as TaskNotes runtime metadata.",severity:"warning"}),t.strict!==!0&&v.push({path:r,code:"additional_properties_true",message:"The migrated schema allows additional properties because the source type was not strict.",severity:"warning"}),typeof t.display_name_key=="string"&&!b&&v.push({path:r,code:"display_field_missing",message:`The display field '${t.display_name_key}' is not declared, so collection.display was omitted.`,severity:"warning"}),{target:k,summary:{path:r,name:i,fieldsConverted:Object.keys(t.fields).length,requiredFields:Ri(o),defaultsMoved:Object.keys(a),generatedFieldsMoved:Ri(p),linksMoved:Object.keys(c),taskNotes:n},diagnostics:v}}function KR(r){let e=De(r);e.spec_version=co;let t=Se(e.settings)?e.settings:{};if(e.settings=t,!Array.isArray(t.record_extensions)){let n=Array.isArray(t.extensions)?t.extensions.map(String).map(i=>i.replace(/^\./,"")):[];t.record_extensions=Ri(["md",...n])}return Array.isArray(t.explicit_type_keys)||(t.explicit_type_keys=["type","types"]),typeof t.include_subfolders!="boolean"&&(t.include_subfolders=!0),t.validation===void 0&&typeof t.default_validation=="string"&&(t.validation=t.default_validation),t.validation===void 0&&typeof e.default_validation=="string"&&(t.validation=e.default_validation),delete t.default_validation,delete t.extensions,delete e.default_validation,e}function zw(r,e){let t=Se(r.settings)?r.settings:{};return{spec_version:e,name:typeof r.name=="string"?r.name:void 0,description:typeof r.description=="string"?r.description:void 0,settings:{types_folder:typeof t.types_folder=="string"?t.types_folder:"_types",explicit_type_keys:Array.isArray(t.explicit_type_keys)?t.explicit_type_keys.filter(n=>typeof n=="string"):["type","types"],default_strict:t.default_strict===!0,include_subfolders:t.include_subfolders!==!1,exclude:Array.isArray(t.exclude)?t.exclude.filter(n=>typeof n=="string"):["_types",".obsidian",".git",".mdbase"]}}}function WR(r,e){var n,i;let t={};for(let[s,o]of Object.entries(Se(e.fields)?e.fields:{}))Se(o)&&(t[s]=De(o));return{name:typeof e.name=="string"?e.name:(i=(n=r.split("/").pop())==null?void 0:n.replace(/\.md$/,""))!=null?i:"type",fields:t,match:Se(e.match)?De(e.match):void 0,filePath:r,specProfile:"v0.2"}}function GR(r,e){var i,s;let t=Se(e.schema)?e.schema:{},n=Se(t.value)?t.value:{};return{name:typeof e.name=="string"?e.name:(s=(i=r.split("/").pop())==null?void 0:i.replace(/\.md$/,""))!=null?s:"type",fields:$n(n),match:Se(e.match)?De(e.match):void 0,collection:Se(e.collection)?De(e.collection):void 0,schema:De(n),filePath:r,specProfile:"v0.3"}}function JR(r,e,t){let n=De(r);for(let i of e){let s=t.get(i);if(s)for(let[o,a]of Object.entries(s.fields))!(o in n)&&a.default!==void 0&&(n[o]=De(a.default))}return n}function YR(r,e,t){var i,s;let n=De(r);for(let o of e){let a=t.get(o);if(a)for(let[c,l]of Object.entries((s=(i=a.collection)==null?void 0:i.read_defaults)!=null?s:{}))c in n||(n[c]=De(l))}return n}async function XR(r,e){let t=(0,ct.normalizePath)(e).replace(/\/+$/,"");if(!t)return;let n="";for(let i of t.split("/")){n=n?`${n}/${i}`:i;let s=r.getAbstractFileByPath(n);if(!(s instanceof ct.TFolder)){if(s)throw new Error(`A file blocks folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}async function xc(r,e,t){let n=(0,ct.normalizePath)(e),i=n.lastIndexOf("/");if(i>=0&&await XR(r,n.slice(0,i)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let s=r.getAbstractFileByPath(n);if(s instanceof ct.TFolder)throw new Error(`A folder blocks file ${n}.`);s instanceof ct.TFile?await r.modify(s,t):await r.create(n,t)}async function ao(r,e){let t=(0,ct.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof ct.TFile)return r.cachedRead(n);if(await r.adapter.exists(t))return r.adapter.read(t);throw new Error(`File not found: ${e}`)}async function Hw(r){var k;let e=await ao(r,"mdbase.yaml"),t=(0,ct.parseYaml)(e);if(!Se(t))throw new Error("mdbase.yaml must contain a YAML mapping.");let n=typeof t.spec_version=="string"?t.spec_version:"";if(!/^0\.2(?:\.\d+)?$/.test(n))throw new Error(n===co?"This collection is already mdbase v0.3.":`Expected an mdbase v0.2.x collection, found ${JSON.stringify(n)}.`);let i=Se(t.settings)?t.settings:{},s=typeof i.types_folder=="string"?(0,ct.normalizePath)(i.types_folder):"_types",o=`${s}/`,a=[],c=[],l=[],u=KR(t),d=`${(0,ct.stringifyYaml)(u).trimEnd()} +`;a.push({path:"mdbase.yaml",sourceDigest:Dr(e),targetDigest:Dr(d),source:e,target:d});let f=new Map,p=new Map;for(let v of r.getMarkdownFiles().filter(E=>E.path.startsWith(o)).sort((E,O)=>E.path.localeCompare(O.path))){let E=await r.cachedRead(v),O=Ct(E);if(!O.hasFrontmatter||O.error)throw new Error(`Cannot migrate ${v.path}: ${(k=O.error)!=null?k:"frontmatter is missing"}.`);let w=HR(v.path,n,O.frontmatter),x=WR(v.path,O.frontmatter),$=GR(v.path,w.target);f.set(x.name,x),p.set($.name,$);let L=`${wt(w.target,O.body)} +`;a.push({path:v.path,sourceDigest:Dr(E),targetDigest:Dr(L),source:E,target:L}),c.push(w.summary),l.push(...w.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${s}.`);let m=0,h=0,y=zw(t,n),b=zw(u,co),g=r.getMarkdownFiles().filter(v=>!v.path.startsWith(o)).filter(v=>!v.path.startsWith(".mdbase/")).sort((v,E)=>v.path.localeCompare(E.path));for(let[v,E]of g.entries()){let O=Ct(await r.cachedRead(E));if(O.error){h+=1;continue}let w=li(E.path,O.frontmatter,y,f),x=li(E.path,O.frontmatter,b,p),$=JR(O.frontmatter,w,f),L=YR(O.frontmatter,x,p);(Rn(w.slice().sort())!==Rn(x.slice().sort())||Rn($)!==Rn(L))&&l.push({path:E.path,code:"effective_read_changed",message:"The proposed v0.3 types would change this record's resolved types or effective default values.",severity:"lossy"}),m+=1,v>0&&v%250===0&&await new Promise(F=>setTimeout(F,0))}let _=Dr(Rn({sourceVersion:n,operations:a.map(({path:v,sourceDigest:E,targetDigest:O})=>({path:v,sourceDigest:E,targetDigest:O})),diagnostics:l}));return{planVersion:1,analysisId:_,sourceVersion:n,targetVersion:co,createdAt:new Date().toISOString(),backupLocation:`.mdbase/migrations/v02-to-v03-${_.slice(0,12)}`,operations:a,typeSummaries:c,diagnostics:l,applicable:!l.some(v=>v.severity==="lossy"),recordFilesRewritten:0,recordsVerified:m,recordsSkipped:h}}async function oo(r,e,t){await xc(r,e,`${JSON.stringify(t,null,2)} +`)}async function Kw(r,e,t={}){if(e.planVersion!==1||e.targetVersion!==co)throw new Error("Unsupported migration plan.");if(!e.applicable&&!t.allowLossy)throw new Error("This migration has lossy diagnostics. Review them and explicitly allow lossy migration.");for(let s of e.operations){let o=await ao(r,s.path);if(Dr(o)!==s.sourceDigest)throw new Error(`${s.path} changed after migration analysis. Run the review again.`)}let n=`${e.backupLocation}/manifest.json`,i={manifest_version:1,analysis_id:e.analysisId,source_version:e.sourceVersion,target_version:e.targetVersion,status:"prepared",created_at:new Date().toISOString(),written:[],files:e.operations.map(s=>({path:s.path,source_digest:s.sourceDigest,target_digest:s.targetDigest,backup_path:`${e.backupLocation}/files/${s.path}`}))};for(let s of e.operations)await xc(r,`${e.backupLocation}/files/${s.path}`,s.source);await oo(r,n,i),i.status="applying",await oo(r,n,i);try{for(let s of e.operations){let o=await ao(r,s.path);if(Dr(o)!==s.sourceDigest)throw new Error(`${s.path} changed during migration.`);i.written.push(s.path),await oo(r,n,i),await xc(r,s.path,s.target);let a=await ao(r,s.path);if(Dr(a)!==s.targetDigest)throw new Error(`${s.path} did not verify after write.`)}return i.status="applied",i.completed_at=new Date().toISOString(),await oo(r,n,i),{applied:!0,restored:!1,manifestPath:n,written:[...i.written]}}catch(s){let o=[];for(let a of[...i.written].reverse()){let c=e.operations.find(l=>l.path===a);if(!c){o.push(a);continue}try{await xc(r,a,c.source),Dr(await ao(r,a))!==c.sourceDigest&&o.push(a)}catch(l){o.push(a)}}i.status=o.length?"recovery_required":"rolled_back",i.error=s instanceof Error?s.message:String(s),i.manual_recovery_paths=o.length?o:void 0,i.completed_at=new Date().toISOString();try{await oo(r,n,i)}catch(a){}return{applied:!1,restored:o.length===0,manifestPath:n,written:[...i.written],error:i.error}}}var Pc=require("obsidian");function Te(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function br(r){return JSON.parse(JSON.stringify(r))}var QR=new Set(["file","formula","this"]);function ZR(r){let e=r.trim();if(!e)throw new Error("Type name is required.");if(!/^[A-Za-z]/.test(e))throw new Error("Type name must start with a letter.");if(e.length>=64)throw new Error("Type name must be shorter than 64 characters.");if(!/^[A-Za-z][A-Za-z0-9_-]*$/.test(e))throw new Error("Type name may contain only letters, numbers, hyphens, and underscores.");if(QR.has(e.toLowerCase()))throw new Error(`Type name '${e}' is reserved.`);return e}function Yf(){return{specProfile:"v0.3",originalFrontmatter:{},name:"",description:"",extendsType:"",displayNameKey:"",strictMode:!1,pathPattern:"",filenamePattern:"",matchPathGlob:"",matchFieldsPresent:"",matchWhere:"",fields:[{name:"title",definition:{type:"string",required:!0}}],body:`# Type -Describe the type and intended usage.`,extraFrontmatter:{}}}function rR(r){return xe(r)?Object.entries(r).filter(e=>xe(e[1])).map(([e,t])=>({name:e,definition:or(t)})):[]}function nR(r){return Object.fromEntries(r.map(e=>[e.name,e.definition]))}function sR(r,e){let t=e.split("."),n=r,s;for(let[i,o]of t.entries()){let a=o.match(/^([^\[\]]+)((?:\[\])*)$/);if(!a||(s=n[a[1]],!s))return null;let c=a[2].length/2;for(let l=0;l{if(e.selectors.add(s),n.type==="link"&&e.links.set(s,{target_type:typeof n.target=="string"&&n.target.trim()?n.target.trim():"any",validate_exists:n.validate_exists===!0}),n.type==="list"&&n.items&&t(n.items,`${s}[]`),n.type==="object"&&n.fields)for(let[i,o]of Object.entries(n.fields))t(o,`${s}.${i}`)};for(let[n,s]of Object.entries(r))t(s,n);return e}function oc(r,e,t){let n=r.kind==="mdbase.type",s=n&&xe(r.schema)?r.schema:{},i=xe(s.value)?s.value:{},o=typeof s.ref=="string"?s.ref:"",a=n&&xe(r.collection)?r.collection:{},c=xe(a.display)?a.display:{},l=xe(a.path)?a.path:{},u=rR(n?pn(i):r.fields);n&&iR(u,a.links);let d=xe(r.match)?r.match:{},f=n?i.additionalProperties===!1:r.strict,p=new Set(["name","description","extends","display_name_key","strict","path_pattern","filename_pattern","match","fields"]),m={};for(let[y,b]of Object.entries(r))p.has(y)||(m[y]=or(b));let h="";if(d.where!==void 0)try{h=(0,ic.stringifyYaml)(d.where).trim()}catch(y){h=""}return{specProfile:n?"v0.3":"v0.2",originalFrontmatter:or(r),name:typeof r.name=="string"&&r.name.trim()?r.name:t,description:typeof r.description=="string"?r.description:"",extendsType:typeof r.extends=="string"?r.extends:"",displayNameKey:n?typeof c.name_field=="string"?c.name_field:"":typeof r.display_name_key=="string"?r.display_name_key:"",strictMode:f==="warn"?"warn":f===!0,pathPattern:n?typeof l.pattern=="string"?l.pattern:"":typeof r.path_pattern=="string"?r.path_pattern:"",filenamePattern:n?"":typeof r.filename_pattern=="string"?r.filename_pattern:"",matchPathGlob:typeof d.path_glob=="string"?d.path_glob:"",matchFieldsPresent:Array.isArray(d.fields_present)?d.fields_present.map(String).join(", "):"",matchWhere:h,fields:u.length||o?u:Sf().fields,body:e.trim()||`# ${t} +Describe the type and intended usage.`,extraFrontmatter:{}}}function eC(r){return Te(r)?Object.entries(r).filter(e=>Te(e[1])).map(([e,t])=>({name:e,definition:br(t)})):[]}function tC(r){return Object.fromEntries(r.map(e=>[e.name,e.definition]))}function rC(r,e){let t=e.split("."),n=r,i;for(let[s,o]of t.entries()){let a=o.match(/^([^\[\]]+)((?:\[\])*)$/);if(!a||(i=n[a[1]],!i))return null;let c=a[2].length/2;for(let l=0;l{if(e.selectors.add(i),n.type==="link"&&e.links.set(i,{target_type:typeof n.target=="string"&&n.target.trim()?n.target.trim():"any",validate_exists:n.validate_exists===!0}),n.type==="list"&&n.items&&t(n.items,`${i}[]`),n.type==="object"&&n.fields)for(let[s,o]of Object.entries(n.fields))t(o,`${i}.${s}`)};for(let[n,i]of Object.entries(r))t(i,n);return e}function Ic(r,e,t){let n=r.kind==="mdbase.type",i=n&&Te(r.schema)?r.schema:{},s=Te(i.value)?i.value:{},o=typeof i.ref=="string"?i.ref:"",a=n&&Te(r.collection)?r.collection:{},c=Te(a.display)?a.display:{},l=Te(a.path)?a.path:{},u=eC(n?$n(s):r.fields);n&&nC(u,a.links);let d=Te(r.match)?r.match:{},f=n?s.additionalProperties===!1:r.strict,p=new Set(["name","description","extends","display_name_key","strict","path_pattern","filename_pattern","match","fields"]),m={};for(let[y,b]of Object.entries(r))p.has(y)||(m[y]=br(b));let h="";if(d.where!==void 0)try{h=(0,Pc.stringifyYaml)(d.where).trim()}catch(y){h=""}return{specProfile:n?"v0.3":"v0.2",originalFrontmatter:br(r),name:typeof r.name=="string"&&r.name.trim()?r.name:t,description:typeof r.description=="string"?r.description:"",extendsType:typeof r.extends=="string"?r.extends:"",displayNameKey:n?typeof c.name_field=="string"?c.name_field:"":typeof r.display_name_key=="string"?r.display_name_key:"",strictMode:f==="warn"?"warn":f===!0,pathPattern:n?typeof l.pattern=="string"?l.pattern:"":typeof r.path_pattern=="string"?r.path_pattern:"",filenamePattern:n?"":typeof r.filename_pattern=="string"?r.filename_pattern:"",matchPathGlob:typeof d.path_glob=="string"?d.path_glob:"",matchFieldsPresent:Array.isArray(d.fields_present)?d.fields_present.map(String).join(", "):"",matchWhere:h,fields:u.length||o?u:Yf().fields,body:e.trim()||`# ${t} -Type definition for ${t}.`,extraFrontmatter:m,...o?{readOnlyReason:`This type uses schema.ref (${o}). Edit the referenced JSON Schema file directly.`}:{}}}function Yi(r){if(r.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection before editing.");if(r.readOnlyReason)throw new Error(r.readOnlyReason);let e=r.originalFrontmatter?or(r.originalFrontmatter):{},t=xe(e.schema)?e.schema:{},n=xe(t.value)?t.value:{},s=Object.create(null);for(let h of r.fields){let y=h.name.trim();if(!y)throw new Error("Every field needs a name.");if(Object.prototype.hasOwnProperty.call(s,y))throw new Error(`Duplicate field name: ${y}`);s[y]=or(h.definition)}let i=tR(r.name),o={...e,kind:"mdbase.type",name:i,version:typeof e.version=="number"?e.version:1,schema:{...t,dialect:"json-schema-2020-12",value:yu(s,n,r.strictMode===!0)}};delete o.schema.ref,r.description.trim()?o.description=r.description.trim():delete o.description;let a=xe(o.match)?or(o.match):{};r.matchPathGlob.trim()?a.path_glob=r.matchPathGlob.trim():delete a.path_glob;let c=r.matchFieldsPresent.split(",").map(h=>h.trim()).filter(Boolean);if(c.length?a.fields_present=c:delete a.fields_present,r.matchWhere.trim()){let h=(0,ic.parseYaml)(r.matchWhere);if(!xe(h))throw new Error("Match where must be a YAML mapping.");a.where=h}else delete a.where;Object.keys(a).length?o.match=a:delete o.match;let l=xe(o.collection)?or(o.collection):{},u=xe(l.display)?or(l.display):{};if(r.displayNameKey.trim()?u.name_field=r.displayNameKey.trim():delete u.name_field,Object.keys(u).length?l.display=u:delete l.display,r.pathPattern.trim()){let h=xe(l.path)?l.path:{};l.path={...h,pattern:r.pathPattern.trim()}}else if(xe(l.path)&&typeof l.path.pattern=="string"){let h={...l.path};delete h.pattern,Object.keys(h).length?l.path=h:delete l.path}let d=xe(l.links)?or(l.links):{},f=or(d),p=mw(s),m=mw(pn(n));for(let h of new Set([...m.selectors,...p.selectors]))delete f[h];for(let[h,y]of p.links)f[h]={...xe(d[h])?d[h]:{},target_type:y.target_type,validate_exists:y.validate_exists};Object.keys(f).length?l.links=f:delete l.links,Object.keys(l).length?o.collection=l:delete o.collection;for(let h of["fields","strict","extends","display_name_key","path_pattern","filename_pattern"])delete o[h];return o}var Se=require("obsidian");var $s="mdbase-frontmatter",yw=` +Type definition for ${t}.`,extraFrontmatter:m,...o?{readOnlyReason:`This type uses schema.ref (${o}). Edit the referenced JSON Schema file directly.`}:{}}}function lo(r){if(r.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection before editing.");if(r.readOnlyReason)throw new Error(r.readOnlyReason);let e=r.originalFrontmatter?br(r.originalFrontmatter):{},t=Te(e.schema)?e.schema:{},n=Te(t.value)?t.value:{},i=Object.create(null);for(let h of r.fields){let y=h.name.trim();if(!y)throw new Error("Every field needs a name.");if(Object.prototype.hasOwnProperty.call(i,y))throw new Error(`Duplicate field name: ${y}`);i[y]=br(h.definition)}let s=ZR(r.name),o={...e,kind:"mdbase.type",name:s,version:typeof e.version=="number"?e.version:1,schema:{...t,dialect:"json-schema-2020-12",value:ju(i,n,r.strictMode===!0)}};delete o.schema.ref,r.description.trim()?o.description=r.description.trim():delete o.description;let a=Te(o.match)?br(o.match):{};r.matchPathGlob.trim()?a.path_glob=r.matchPathGlob.trim():delete a.path_glob;let c=r.matchFieldsPresent.split(",").map(h=>h.trim()).filter(Boolean);if(c.length?a.fields_present=c:delete a.fields_present,r.matchWhere.trim()){let h=(0,Pc.parseYaml)(r.matchWhere);if(!Te(h))throw new Error("Match where must be a YAML mapping.");a.where=h}else delete a.where;Object.keys(a).length?o.match=a:delete o.match;let l=Te(o.collection)?br(o.collection):{},u=Te(l.display)?br(l.display):{};if(r.displayNameKey.trim()?u.name_field=r.displayNameKey.trim():delete u.name_field,Object.keys(u).length?l.display=u:delete l.display,r.pathPattern.trim()){let h=Te(l.path)?l.path:{};l.path={...h,pattern:r.pathPattern.trim()}}else if(Te(l.path)&&typeof l.path.pattern=="string"){let h={...l.path};delete h.pattern,Object.keys(h).length?l.path=h:delete l.path}let d=Te(l.links)?br(l.links):{},f=br(d),p=Ww(i),m=Ww($n(n));for(let h of new Set([...m.selectors,...p.selectors]))delete f[h];for(let[h,y]of p.links)f[h]={...Te(d[h])?d[h]:{},target_type:y.target_type,validate_exists:y.validate_exists};Object.keys(f).length?l.links=f:delete l.links,Object.keys(l).length?o.collection=l:delete o.collection;for(let h of["fields","strict","extends","display_name_key","path_pattern","filename_pattern"])delete o[h];return o}var Ae=require("obsidian");var Ci="mdbase-frontmatter",Gw=` @@ -189,13 +189,13 @@ Type definition for ${t}.`,extraFrontmatter:m,...o?{readOnlyReason:`This type us -`;var En="mdbase-workspace-view",oR=["string","integer","number","boolean","date","datetime","time","enum","link","list","object","any"];function Sn(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Ef(r){return JSON.parse(JSON.stringify(r))}function gw(r){return typeof r.type=="string"?r.type:"any"}function aR(r){if(!Object.prototype.hasOwnProperty.call(r,"field"))return"field";let e=2;for(;Object.prototype.hasOwnProperty.call(r,`field${e}`);)e+=1;return`field${e}`}function bw(r,e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,writable:!0,value:t})}function cR(r,e){if(!r)return["A new type definition will be created."];let t=[];r.name!==e.name&&t.push(`Rename type from ${r.name} to ${e.name}.`),(r.matchPathGlob!==e.matchPathGlob||r.matchFieldsPresent!==e.matchFieldsPresent||r.matchWhere!==e.matchWhere)&&t.push("Membership rules changed; different records may match this type.");let n=new Map(r.fields.map(c=>[c.name,c])),s=new Map(e.fields.map(c=>[c.name,c])),i=[...n.keys()].filter(c=>!s.has(c)),o=[...s.keys()].filter(c=>!n.has(c));o.length&&t.push(`Add ${o.length} field${o.length===1?"":"s"}: ${o.join(", ")}.`),i.length&&t.push(`Remove ${i.length} field${i.length===1?"":"s"}: ${i.join(", ")}.`);let a=[...s.entries()].filter(([c,l])=>{var u;return l.definition.required===!0&&((u=n.get(c))==null?void 0:u.definition.required)!==!0}).map(([c])=>c);return a.length&&t.push(`New required fields may invalidate records: ${a.join(", ")}.`),t.length||t.push("Metadata, schema details, or documentation changed."),t}function Et(r,e,t,n,s={}){var l;let i=r.createDiv({cls:"mdbase-form-row"}),o=i.createEl("label",{text:e}),a=`mdbase-${Math.random().toString(36).slice(2)}`;o.htmlFor=a,s.description&&i.createDiv({cls:"mdbase-form-description",text:s.description});let c=s.multiline?i.createEl("textarea"):i.createEl("input",{type:"text"});return c.id=a,c.value=t,c.placeholder=(l=s.placeholder)!=null?l:"",c.addEventListener("input",()=>n(c.value)),c}function Me(r,e,t){let n=r.createDiv({cls:"mdbase-status-row"});n.createSpan({cls:"mdbase-status-label",text:e}),n.createSpan({cls:"mdbase-status-value",text:t})}function lR(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}var ac=class extends Se.ItemView{constructor(t,n){super(t);this.host=n;this.destination="types";this.editorMode="design";this.schema=null;this.query="";this.selectedPath=null;this.model=null;this.originalModel=null;this.yamlDraft="";this.dirty=!1;this.busy=!1;this.migrationPlan=null;this.allowLossy=!1;this.mirrorStatus=null;this.mirrorPreview=null;this.mirrorProgress=null;this.transientMessage="";this.issueQuery="";this.issueSeverity="all";this.issueLimit=250;this.enrollmentVerification="";this.enrollmentAbort=null}getViewType(){return En}getDisplayText(){return"mdbase"}getIcon(){return $s}async onOpen(){this.containerEl.addClass("mdbase-workspace"),await this.refresh(!0)}async onClose(){var t;(t=this.enrollmentAbort)==null||t.abort(),this.enrollmentAbort=null}async refresh(t=!1){try{this.schema=await this.host.loadWorkspaceSchema(t),this.selectedPath&&!this.typeEntries().some(n=>n.filePath===this.selectedPath)&&(this.selectedPath=null,this.model=null,this.originalModel=null),!this.selectedPath&&this.typeEntries().length&&!Se.Platform.isMobile&&(this.selectedPath=this.typeEntries()[0].filePath),this.selectedPath&&(!this.model||t)&&await this.selectType(this.selectedPath,!1),this.destination==="sync"&&await this.refreshMirrorStatus(),this.render()}catch(n){this.transientMessage=n instanceof Error?n.message:String(n),this.render()}}showDestination(t){this.destination=t,t==="sync"?this.refreshMirrorStatus().then(()=>this.render()):this.render()}typeEntries(){return this.schema?[...this.schema.types.values()].sort((t,n)=>t.name.localeCompare(n.name)):[]}render(){let t=this.containerEl;t.empty(),t.addClass("mdbase-workspace");let n=t.createDiv({cls:"mdbase-shell"});this.renderTopbar(n),this.transientMessage&&n.createDiv({cls:"mdbase-inline-message",text:this.transientMessage}).setAttr("role","status");let s=n.createDiv({cls:"mdbase-workspace-content"});this.destination==="types"?this.renderTypes(s):this.destination==="sync"?this.renderSync(s):this.renderIssues(s)}renderTopbar(t){let n=t.createDiv({cls:"mdbase-topbar"}),s=n.createDiv({cls:"mdbase-identity"}),i=s.createSpan({cls:"mdbase-mark"});i.setAttr("aria-hidden","true"),(0,Se.setIcon)(i,$s),s.createSpan({cls:"mdbase-title",text:"mdbase"});let o=n.createDiv({cls:"mdbase-nav"});o.setAttr("role","tablist");for(let[a,c]of[["types","Types"],["sync","Sync"],["issues","Issues"]]){let l=o.createEl("button",{text:c});if(l.addClass("mdbase-nav-button"),l.setAttr("role","tab"),l.setAttr("aria-selected",String(this.destination===a)),this.destination===a&&l.addClass("is-active"),a==="issues"&&this.host.getIssues().length){let u=this.host.getIssues().length;l.createSpan({cls:"mdbase-count",text:lR(u)}).setAttr("title",`${u} issues`)}l.onclick=()=>this.showDestination(a)}}renderTypes(t){if(!this.schema){let s=t.createDiv({cls:"mdbase-empty-state"});s.createEl("h2",{text:"Start an mdbase collection"}),s.createEl("p",{text:"Initialize this vault as a local v0.3 collection, or use Sync to connect an empty vault to a collection authority."});let i=s.createDiv({cls:"mdbase-actions"}),o=i.createEl("button",{text:"Initialize local collection"});o.addClass("mod-cta"),o.disabled=this.busy||this.host.getMirrorProfile()!==null,o.onclick=()=>void this.perform(async()=>{await this.host.initializeCollection(),await this.refresh(!0)});let a=i.createEl("button",{text:"Connect collection authority"});a.onclick=()=>this.showDestination("sync");return}this.schema.config.spec_version.startsWith("0.2.")&&this.renderLegacyBanner(t);let n=t.createDiv({cls:"mdbase-types-layout"});this.model&&n.addClass("has-selection"),this.renderTypeList(n),this.renderTypeEditor(n)}renderLegacyBanner(t){var o;let n=t.createDiv({cls:"mdbase-legacy-banner"}),s=n.createDiv();s.createEl("strong",{text:`mdbase ${(o=this.schema)==null?void 0:o.config.spec_version} compatibility mode`}),s.createEl("p",{text:"Types are readable and validation remains available, but authoring is disabled until a reviewed v0.3 migration."});let i=n.createEl("button",{text:this.migrationPlan?"Review migration":"Analyze migration"});i.disabled=this.busy||this.host.getMirrorProfile()!==null,i.onclick=()=>void this.perform(async()=>{this.migrationPlan=await this.host.analyzeMigration(),this.render()}),this.host.getMirrorProfile()&&n.createDiv({cls:"mdbase-form-description",text:"Hosted resources must be migrated at the collection authority."}),this.migrationPlan&&this.renderMigrationReview(t,this.migrationPlan)}renderMigrationReview(t,n){let s=t.createDiv({cls:"mdbase-migration-review"}),i=s.createDiv({cls:"mdbase-section-header"});i.createEl("h3",{text:"Migration review"}),i.createSpan({cls:"mdbase-spec-badge",text:`${n.sourceVersion} \u2192 ${n.targetVersion}`});let o=s.createDiv({cls:"mdbase-status-list"});Me(o,"Files replaced",String(n.operations.length)),Me(o,"Type definitions",String(n.typeSummaries.length)),Me(o,"Record reads verified",String(n.recordsVerified)),n.recordsSkipped&&Me(o,"Records skipped",String(n.recordsSkipped)),Me(o,"Record files rewritten","0"),Me(o,"Recovery backup",n.backupLocation);let a=s.createDiv({cls:"mdbase-review-list"});n.diagnostics.length||a.createDiv({cls:"mdbase-review-ok",text:"No migration diagnostics."});for(let d of n.diagnostics.slice(0,250)){let f=a.createDiv({cls:"mdbase-review-item"});f.setAttr("data-severity",d.severity),f.createDiv({cls:"mdbase-review-code",text:`${d.severity} \xB7 ${d.path}`}),f.createDiv({text:d.message})}if(n.diagnostics.length>250&&a.createDiv({cls:"mdbase-form-description",text:`Showing 250 of ${n.diagnostics.length} diagnostics.`}),!n.applicable){let d=s.createEl("label",{cls:"mdbase-consent"}),f=d.createEl("input",{type:"checkbox"});f.checked=this.allowLossy,f.onchange=()=>{this.allowLossy=f.checked,this.render()},d.createSpan({text:"I reviewed the lossy diagnostics and want to apply this migration."})}let c=s.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Apply migration"});l.addClass("mod-warning"),l.disabled=this.busy||!n.applicable&&!this.allowLossy,l.onclick=()=>void this.perform(async()=>{await this.host.applyMigration(n,this.allowLossy),this.migrationPlan=null,this.allowLossy=!1,this.model=null,this.originalModel=null,await this.refresh(!0)});let u=c.createEl("button",{text:"Close review"});u.onclick=()=>{this.migrationPlan=null,this.render()}}renderTypeList(t){var u,d,f,p;let n=t.createDiv({cls:"mdbase-type-list-pane"}),s=n.createDiv({cls:"mdbase-pane-header"});s.createEl("h2",{text:"Types"});let i=s.createEl("button");i.setAttr("aria-label","Create type"),(0,Se.setIcon)(i,"plus"),i.disabled=((d=(u=this.schema)==null?void 0:u.config.spec_version.startsWith("0.2."))!=null?d:!0)||((f=this.host.getMirrorProfile())==null?void 0:f.mode)==="read_only",i.onclick=()=>this.createType();let o=n.createEl("input",{type:"search"});o.addClass("mdbase-type-search"),o.placeholder="Search types",o.setAttr("aria-label","Search types"),o.value=this.query,o.oninput=()=>{this.query=o.value,this.render();let m=this.containerEl.querySelector(".mdbase-type-search");m==null||m.focus(),m==null||m.setSelectionRange(m.value.length,m.value.length)};let a=n.createDiv({cls:"mdbase-type-list"}),c=this.query.trim().toLowerCase(),l=this.typeEntries().filter(m=>{var h;return`${m.name} ${(h=m.description)!=null?h:""} ${m.filePath}`.toLowerCase().includes(c)});if(!l.length){a.createDiv({cls:"mdbase-empty-list",text:c?"No matching types.":"No type definitions."});return}for(let m of l){let h=a.createEl("button",{cls:"mdbase-type-row"});m.filePath===this.selectedPath&&h.addClass("is-active"),h.setAttr("aria-current",m.filePath===this.selectedPath?"true":"false"),h.createSpan({cls:"mdbase-type-name",text:m.name}),h.createSpan({cls:"mdbase-type-meta",text:`${Object.keys(m.fields).length} fields \xB7 ${(p=m.specProfile)!=null?p:"v0.2"}`}),h.onclick=()=>void this.selectType(m.filePath)}}renderTypeEditor(t){var h,y,b,g;let n=t.createDiv({cls:"mdbase-type-editor-pane"});if(!this.model){let _=n.createDiv({cls:"mdbase-empty-state"});_.createEl("h2",{text:"Choose a type"}),_.createEl("p",{text:"Select a type definition from the list to inspect or edit it."});return}let s=((h=this.host.getMirrorProfile())==null?void 0:h.mode)==="read_only",i=this.model.specProfile==="v0.2"||s||!!this.model.readOnlyReason,o=(y=this.model.readOnlyReason)!=null?y:s?"This mirror has read-only access. Re-enroll it with write access before editing types.":"This v0.2 type is read-only. Review and apply a collection migration before editing.",a=n.createDiv({cls:"mdbase-editor-header"}),c=a.createEl("button",{cls:"mdbase-mobile-back"});c.setAttr("aria-label","Back to type list"),(0,Se.setIcon)(c,"arrow-left"),c.onclick=()=>{if(this.dirty){new Se.Notice("Save or discard the current type changes before going back.");return}this.selectedPath=null,this.model=null,this.originalModel=null,this.render()};let l=a.createDiv(),u=l.createDiv({cls:"mdbase-editor-title-line"});u.createEl("h2",{text:this.model.name||"Untitled type"}),u.createSpan({cls:"mdbase-spec-badge",text:(b=this.model.specProfile)!=null?b:"v0.2"}),this.dirty&&u.createSpan({cls:"mdbase-dirty",text:"Unsaved"}),l.createDiv({cls:"mdbase-editor-path",text:(g=this.selectedPath)!=null?g:"New type"});let d=a.createDiv({cls:"mdbase-editor-actions"});if(this.selectedPath){let _=d.createEl("button",{text:"Open source"});_.onclick=()=>void this.host.openFileByPath(this.selectedPath)}let f=d.createEl("button",{text:"Save"});f.addClass("mod-cta"),f.disabled=i||!this.dirty||this.busy,f.onclick=()=>void this.saveCurrentType(),i&&n.createDiv({cls:"mdbase-readonly-note",text:o});let p=n.createDiv({cls:"mdbase-mode-switch"});p.setAttr("role","tablist");for(let[_,I]of[["design","Design"],["yaml","YAML"]]){let v=p.createEl("button",{text:I});v.setAttr("role","tab"),v.setAttr("aria-selected",String(this.editorMode===_)),this.editorMode===_&&v.addClass("is-active"),v.onclick=()=>this.switchEditorMode(_)}let m=n.createDiv({cls:"mdbase-editor-document"});this.editorMode==="design"?this.renderDesignEditor(m,this.model,i):this.renderYamlEditor(m,i)}renderDesignEditor(t,n,s){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Identity"});let o=Et(i,"Name",n.name,S=>{n.name=S,this.markDirty()},{description:"Stable type name used by collection records."});o.disabled=s;let a=Et(i,"Description",n.description,S=>{n.description=S,this.markDirty()},{multiline:!0});a.disabled=s;let c=Et(i,"Display field",n.displayNameKey,S=>{n.displayNameKey=S,this.markDirty()},{placeholder:"title"});c.disabled=s;let l=i.createEl("label",{cls:"mdbase-checkbox-row"}),u=l.createEl("input",{type:"checkbox"});u.checked=n.strictMode===!0,u.disabled=s,u.onchange=()=>{n.strictMode=u.checked,this.markDirty()},l.createSpan({text:"Reject undeclared fields"});let d=t.createEl("section",{cls:"mdbase-editor-section"});d.createEl("h3",{text:"Membership"});let f=Et(d,"Path glob",n.matchPathGlob,S=>{n.matchPathGlob=S,this.markDirty()},{placeholder:"Projects/**/*.md"});f.disabled=s;let p=Et(d,"Fields present",n.matchFieldsPresent,S=>{n.matchFieldsPresent=S,this.markDirty()},{description:"Comma-separated frontmatter keys."});p.disabled=s;let m=Et(d,"Where",n.matchWhere,S=>{n.matchWhere=S,this.markDirty()},{multiline:!0,description:"YAML predicate, including contains and nested equality conditions.",placeholder:`tags: - contains: task`});m.disabled=s;let h=t.createEl("section",{cls:"mdbase-editor-section"}),y=h.createDiv({cls:"mdbase-section-header"});y.createEl("h3",{text:"Fields"});let b=y.createEl("button",{text:"Add field"});b.disabled=s,b.onclick=()=>{n.fields.push({name:"",definition:{type:"string"}}),this.markDirty(!0)};let g=h.createDiv({cls:"mdbase-fields"});for(let[S,k]of n.fields.entries())this.renderFieldRow(g,k,S,s);n.fields.length||g.createDiv({cls:"mdbase-empty-list",text:"No fields declared."});let _=t.createEl("section",{cls:"mdbase-editor-section"});_.createEl("h3",{text:"Placement"});let I=Et(_,"Path pattern",n.pathPattern,S=>{n.pathPattern=S,this.markDirty()},{placeholder:"Notes/{title}.md"});I.disabled=s;let v=t.createEl("section",{cls:"mdbase-editor-section mdbase-change-review"});if(v.createEl("h3",{text:"Change review"}),!this.dirty)v.createEl("p",{text:"No pending changes."});else{let S=v.createEl("ul");for(let k of cR(this.originalModel,n))S.createEl("li",{text:k})}}renderFieldRow(t,n,s,i){this.renderFieldDefinition(t,n.definition,{name:n.name,nameLabel:`Field ${s+1} name`,onNameInput:o=>{n.name=o,this.markDirty()},required:n.definition.required===!0,onRequiredChange:o=>{n.definition.required=o,this.markDirty()},onRemove:()=>{var o;(o=this.model)==null||o.fields.splice(s,1),this.markDirty(!0)},readOnly:i,depth:0})}renderFieldDefinition(t,n,s){var u;let i=t.createDiv({cls:"mdbase-field-node"});i.setAttr("data-depth",String(s.depth));let o=i.createDiv({cls:"mdbase-field-row"});if(s.staticLabel)o.createDiv({cls:"mdbase-field-role",text:s.staticLabel});else{let d=o.createEl("input",{type:"text",cls:"mdbase-field-name-control"});d.setAttr("aria-label",s.nameLabel),d.placeholder="fieldName",d.value=(u=s.name)!=null?u:"",d.disabled=s.readOnly,s.onNameInput&&(d.oninput=()=>{var f;return(f=s.onNameInput)==null?void 0:f.call(s,d.value)}),s.onNameCommit&&(d.onchange=()=>{var f;return(f=s.onNameCommit)==null?void 0:f.call(s,d.value,d)})}let a=o.createEl("select",{cls:"mdbase-field-type-control"});a.setAttr("aria-label",`${s.name||s.staticLabel||"Field"} type`);for(let d of oR){let f=d==="any"?"Any value":d[0].toUpperCase()+d.slice(1);a.createEl("option",{value:d,text:f})}a.value=gw(n),a.disabled=s.readOnly,a.onchange=()=>{n.type=a.value,a.value==="list"&&!Sn(n.items)&&(n.items={type:"string"}),a.value==="object"&&!Sn(n.fields)&&(n.fields={}),a.value==="enum"&&!Array.isArray(n.values)&&(n.values=[]),this.markDirty(!0)};let c=o.createEl("input",{type:"text",cls:"mdbase-field-description-control"});if(c.setAttr("aria-label",`${s.name||s.staticLabel||"Field"} description`),c.placeholder="Description",c.value=typeof n.description=="string"?n.description:"",c.disabled=s.readOnly,c.oninput=()=>{c.value?n.description=c.value:delete n.description,this.markDirty()},s.onRequiredChange){let d=o.createEl("label",{cls:"mdbase-field-required"}),f=d.createEl("input",{type:"checkbox"});f.checked=s.required===!0,f.disabled=s.readOnly,f.onchange=()=>{var p;return(p=s.onRequiredChange)==null?void 0:p.call(s,f.checked)},d.createSpan({text:"Required"})}if(s.onRemove){let d=o.createEl("button",{cls:"mdbase-field-remove"});d.setAttr("aria-label",`Remove ${s.name||s.staticLabel||"field"}`),(0,Se.setIcon)(d,"trash-2"),d.disabled=s.readOnly,d.onclick=s.onRemove}let l=gw(n);l==="enum"&&this.renderEnumFieldDetails(i,n,s),l==="link"&&this.renderLinkFieldDetails(i,n,s),l==="list"&&this.renderListFieldDetails(i,n,s),l==="object"&&this.renderObjectFieldDetails(i,n,s)}renderEnumFieldDetails(t,n,s){let i=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=i.createEl("label",{text:"Allowed values"}),a=i.createEl("input",{type:"text"});a.setAttr("aria-label",`${s.name||s.staticLabel||"Enum"} allowed values`),a.placeholder="draft, published, archived",a.value=Array.isArray(n.values)?n.values.map(String).join(", "):"",a.disabled=s.readOnly,a.oninput=()=>{n.values=a.value.split(",").map(c=>c.trim()).filter(Boolean),this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`}renderLinkFieldDetails(t,n,s){let i=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=i.createEl("label",{text:"Target type"}),a=i.createEl("input",{type:"text"});a.setAttr("aria-label",`${s.name||s.staticLabel||"Link"} target type`),a.placeholder="Any type",a.value=typeof n.target=="string"?n.target:"",a.disabled=s.readOnly,a.oninput=()=>{a.value.trim()?n.target=a.value.trim():delete n.target,this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`;let c=i.createEl("label",{cls:"mdbase-field-required"}),l=c.createEl("input",{type:"checkbox"});l.checked=n.validate_exists===!0,l.disabled=s.readOnly,l.onchange=()=>{n.validate_exists=l.checked,this.markDirty()},c.createSpan({text:"Validate target exists"})}renderListFieldDetails(t,n,s){let i=t.createDiv({cls:"mdbase-field-children"});i.createDiv({cls:"mdbase-field-children-label",text:"List items"});let o=Sn(n.items)?n.items:{type:"any"};!Sn(n.items)&&!s.readOnly&&(n.items=o),this.renderFieldDefinition(i,o,{staticLabel:"Item",nameLabel:"List item",readOnly:s.readOnly,depth:s.depth+1})}renderObjectFieldDetails(t,n,s){let i=t.createDiv({cls:"mdbase-field-children"}),o=i.createDiv({cls:"mdbase-field-children-header"});o.createDiv({cls:"mdbase-field-children-label",text:"Object fields"});let a=o.createEl("button",{text:"Add nested field"});a.disabled=s.readOnly;let c=Sn(n.fields)?n.fields:{};!Sn(n.fields)&&!s.readOnly&&(n.fields=c),a.onclick=()=>{let d=aR(c);bw(c,d,{type:"string"}),this.markDirty(!0)};let l=i.createDiv({cls:"mdbase-nested-fields"}),u=Object.entries(c).filter(d=>Sn(d[1]));if(!u.length){l.createDiv({cls:"mdbase-empty-list",text:"No nested fields."});return}for(let[d,f]of u){let p=d;this.renderFieldDefinition(l,f,{name:p,nameLabel:`${p} nested field name`,onNameCommit:(m,h)=>{let y=m.trim();if(!y){new Se.Notice("Nested field name is required."),h.value=p;return}if(y!==p&&Object.prototype.hasOwnProperty.call(c,y)){new Se.Notice(`Nested field already exists: ${y}`),h.value=p;return}y!==p&&(delete c[p],bw(c,y,f),p=y,this.markDirty())},required:f.required===!0,onRequiredChange:m=>{f.required=m,this.markDirty()},onRemove:()=>{delete c[p],this.markDirty(!0)},readOnly:s.readOnly,depth:s.depth+1})}}renderYamlEditor(t,n){let s=t.createEl("section",{cls:"mdbase-editor-section mdbase-yaml-section"});s.createEl("h3",{text:"Canonical type document"}),s.createEl("p",{cls:"mdbase-form-description",text:"Unknown v0.3 extensions are preserved. Invalid YAML is never normalized or saved."});let i=s.createEl("textarea",{cls:"mdbase-yaml-editor"});i.setAttr("aria-label","Type definition YAML"),i.value=this.yamlDraft,i.disabled=n,i.spellcheck=!1,i.oninput=()=>{this.yamlDraft=i.value,this.markDirty(!1)}}renderSync(t){var f,p,m,h,y,b;let n=t.createDiv({cls:"mdbase-sync-document"}),s=n.createDiv({cls:"mdbase-document-header"});s.createEl("h2",{text:"Sync"}),s.createEl("p",{text:"Connect this vault to a collection authority and keep ordinary Markdown mirrored locally."});let i=this.host.getMirrorProfile();if(!i){this.renderEnrollment(n);return}let o=n.createEl("section",{cls:"mdbase-editor-section"});o.createEl("h3",{text:"Collection authority"});let a=o.createDiv({cls:"mdbase-status-list"});if(Me(a,"Name",i.name),Me(a,"Collection",i.collectionId),Me(a,"Access",i.mode==="read_write"?"Read and write":"Read only"),Me(a,"Provider",i.syncUrl),Me(a,"State",(p=(f=this.mirrorStatus)==null?void 0:f.state.replace(/_/g," "))!=null?p:"Checking"),Me(a,"Last synced",(h=(m=this.mirrorStatus)==null?void 0:m.last_synced_at)!=null?h:"Never"),this.mirrorProgress){let g=this.mirrorProgress.total,_=o.createEl("progress");_.max=g!=null?g:1,_.value=g==null?0:this.mirrorProgress.completed,g==null&&_.removeAttribute("value"),o.createDiv({cls:"mdbase-progress-label",text:`${this.mirrorProgress.phase}: ${this.mirrorProgress.completed}${g==null?"":` of ${g}`}`})}let c=o.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Preview"});l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{this.mirrorPreview=await this.host.connectSync.preview(),this.render()});let u=c.createEl("button",{text:"Sync now"});u.addClass("mod-cta"),u.disabled=this.busy,u.onclick=()=>void this.perform(async()=>{this.mirrorStatus=await this.host.connectSync.sync(g=>{this.mirrorProgress=g,this.render()}),this.mirrorProgress=null,this.transientMessage="Sync completed and the local checkpoint was verified.",await this.refresh(!0)}),this.mirrorPreview&&this.renderMirrorPreview(n,this.mirrorPreview),(y=this.mirrorStatus)!=null&&y.conflicts.length&&this.renderConflicts(n,this.mirrorStatus),(b=this.mirrorStatus)!=null&&b.local_issues.length&&this.renderLocalMirrorIssues(n,this.mirrorStatus);let d=n.createEl("section",{cls:"mdbase-editor-section"});d.createEl("h3",{text:"Mirror ownership"}),d.createEl("p",{text:"Use this plugin as the only sync owner for this vault. Obsidian protects concurrent operations inside the app; a separate desktop mirror process cannot share that mobile-safe lease."})}renderEnrollment(t){if(this.schema||this.host.connectSync.getAdoptionMarker()){this.renderLocalAdoption(t);return}let n=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});if(n.createEl("h3",{text:"Connect collection authority"}),n.createEl("p",{text:"Connect will open an approval page. Credentials are stored in Obsidian's secret store and never written into this vault."}),this.enrollmentVerification){let d=n.createDiv({cls:"mdbase-approval-link"});d.createSpan({text:"Approval page: "});let f=d.createEl("a",{text:"Open Connect",href:this.enrollmentVerification});f.setAttr("target","_blank"),f.setAttr("rel","noopener noreferrer")}let s="https://connect.mdbase.dev",i="Obsidian",o="",a="read_write";Et(n,"Connect URL",s,d=>{s=d},{placeholder:"https://connect.mdbase.dev"}),Et(n,"Mirror name",i,d=>{i=d}),Et(n,"Collection ID",o,d=>{o=d},{description:"Optional. Leave blank to choose during approval."});let c=n.createDiv({cls:"mdbase-form-row"});c.createEl("label",{text:"Access"});let l=c.createEl("select");l.createEl("option",{value:"read_write",text:"Read and write"}),l.createEl("option",{value:"read_only",text:"Read only"}),l.value=a,l.onchange=()=>{a=l.value==="read_only"?"read_only":"read_write"};let u=n.createEl("button",{text:"Open Connect approval"});u.addClass("mod-cta"),u.disabled=this.busy,u.onclick=()=>void this.perform(async()=>{var f;(f=this.enrollmentAbort)==null||f.abort();let d=new AbortController;this.enrollmentAbort=d;try{await this.host.connectSync.enroll({controlUrl:s,mirrorName:i,mode:a,...o.trim()?{collectionId:o.trim()}:{}},{signal:d.signal,onVerification:p=>{this.enrollmentVerification=p.verificationUri,this.transientMessage="Approve the mirror in the Connect page. This view will keep waiting securely.",window.open(p.verificationUri,"_blank","noopener,noreferrer"),this.render()},onStatus:p=>{this.transientMessage=p.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying enrollment (attempt ${p.attempt}).`,this.render()}}),this.enrollmentVerification="",this.transientMessage="Mirror enrolled. Preview before the first sync.",await this.refreshMirrorStatus(),this.render()}finally{this.enrollmentAbort===d&&(this.enrollmentAbort=null)}})}renderLocalAdoption(t){var u,d;let n=this.host.connectSync.getAdoptionMarker(),s=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});s.createEl("h3",{text:"Host this local collection"}),s.createEl("p",{text:n?"This vault has a durable adoption checkpoint. Resume it without creating another hosted collection.":"Hosted mdbase will adopt an exact snapshot and become the collection authority. This vault will then continue as a read-write mirror."});let i=this.enrollmentVerification||(n==null?void 0:n.session.verificationUri);if(i){let f=s.createDiv({cls:"mdbase-approval-link"});f.createSpan({text:"Approval page: "});let p=f.createEl("a",{text:"Open Connect",href:i});p.setAttr("target","_blank"),p.setAttr("rel","noopener noreferrer")}let o=(u=n==null?void 0:n.session.controlUrl)!=null?u:"https://connect.mdbase.dev",a=(d=n==null?void 0:n.session.requested.mirrorName)!=null?d:"Obsidian";if(!n)Et(s,"Connect URL",o,f=>{o=f},{placeholder:"https://connect.mdbase.dev"}),Et(s,"Mirror name",a,f=>{a=f});else{let f=s.createDiv({cls:"mdbase-status-list"});Me(f,"Collection",n.session.requested.collectionId),Me(f,"Phase",n.phase.replace(/_/g," ")),Me(f,"Connect",n.session.controlUrl)}let c=s.createDiv({cls:"mdbase-inline-message"});c.createEl("strong",{text:"Authority cut-over: "}),c.appendText("once final staging begins, plugin-managed local edits pause until hosted activation is confirmed. The checkpoint survives app restarts and uncertain network responses.");let l=s.createEl("button",{text:n?"Resume adoption":"Approve and host collection"});if(l.addClass("mod-cta"),l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{var h;(h=this.enrollmentAbort)==null||h.abort();let f=new AbortController;this.enrollmentAbort=f;let p=y=>{this.enrollmentVerification=y.verificationUri,this.transientMessage="Approve the authority move in Connect, then return here. This checkpoint is safe to resume.",this.render()},m=y=>{this.transientMessage=y.state==="waiting_for_approval"?"Waiting for authority-move approval in Connect\u2026":`Connect is retrying (attempt ${y.attempt}).`,this.render()};try{n?await this.host.connectSync.resumeAdoption({signal:f.signal,onVerification:p,onStatus:m}):await this.host.connectSync.adoptLocalCollection({controlUrl:o,mirrorName:a},{signal:f.signal,onVerification:p,onStatus:m}),this.enrollmentVerification="",this.transientMessage="Hosted mdbase is authoritative and this vault is now its read-write mirror.",await this.refresh(!0)}finally{this.enrollmentAbort===f&&(this.enrollmentAbort=null)}}),n&&!["activating","adopted"].includes(n.phase)){let f=s.createEl("button",{text:"Cancel adoption"});f.disabled=this.busy,f.onclick=()=>void this.perform(async()=>{await this.host.connectSync.cancelAdoption(),this.enrollmentVerification="",this.transientMessage="Collection adoption cancelled. This vault remains the local authority.",await this.refresh(!0)})}}renderMirrorPreview(t,n){let s=t.createEl("section",{cls:"mdbase-editor-section"});s.createEl("h3",{text:"Sync preview"});let i=s.createDiv({cls:"mdbase-status-list"});if(Me(i,"Download documents",String(n.download_documents)),Me(i,"Upload documents",String(n.upload_documents)),Me(i,"Unchanged documents",String(n.unchanged_documents)),n.collisions.length){s.createDiv({cls:"mdbase-inline-error",text:`${n.collisions.length} path collision${n.collisions.length===1?"":"s"} must be resolved before sync.`});let o=s.createEl("ul");for(let a of n.collisions.slice(0,100))o.createEl("li",{text:a})}if(n.local_issues.length){s.createDiv({cls:"mdbase-inline-error",text:`${n.local_issues.length} local file${n.local_issues.length===1?"":"s"} cannot be uploaded until its frontmatter is fixed.`});let o=s.createEl("ul");for(let a of n.local_issues.slice(0,100))o.createEl("li",{text:`${a.path}: ${a.message}`})}}renderConflicts(t,n){var i;let s=t.createEl("section",{cls:"mdbase-editor-section"});s.createEl("h3",{text:"Conflicts"});for(let o of n.conflicts){let a=s.createDiv({cls:"mdbase-conflict-row"}),c=a.createDiv();c.createEl("strong",{text:(i=o.path)!=null?i:o.record_id}),c.createDiv({text:o.message});let l=a.createDiv({cls:"mdbase-actions"});for(let u of["local","remote"]){let d=l.createEl("button",{text:u==="local"?"Keep local":"Use remote"});d.disabled=this.busy,d.onclick=()=>void this.perform(async()=>{this.mirrorStatus=await this.host.connectSync.resolveConflict(o.record_id,u),this.render()})}}}renderLocalMirrorIssues(t,n){let s=t.createEl("section",{cls:"mdbase-editor-section"});s.createEl("h3",{text:"Local files needing attention"}),s.createEl("p",{text:"These files remain untouched and unsynced. Other valid Markdown continues to synchronize."});for(let i of n.local_issues){let o=s.createDiv({cls:"mdbase-conflict-row"}),a=o.createDiv();a.createEl("strong",{text:i.path}),a.createDiv({text:i.message});let l=o.createDiv({cls:"mdbase-actions"}).createEl("button",{text:"Open file"});l.disabled=this.busy,l.onclick=()=>void this.host.openFileByPath(i.path)}}renderIssues(t){var b;let n=t.createDiv({cls:"mdbase-issues-document"}),s=this.host.getIssues(),i=new Set(s.map(g=>g.path)).size,o=n.createDiv({cls:"mdbase-document-header"}),a=o.createDiv();a.createEl("h2",{text:"Issues"}),a.createEl("p",{text:s.length?`${s.length.toLocaleString()} validation issues in ${i.toLocaleString()} files.`:"The collection has no current validation issues."});let c=o.createEl("button",{text:"Validate collection"});c.disabled=this.busy,c.onclick=()=>void this.perform(async()=>{await this.host.validateCollection(),this.render()});let l=n.createDiv({cls:"mdbase-issue-controls"}),u=l.createEl("select");u.setAttr("aria-label","Issue severity"),u.createEl("option",{value:"all",text:"All severities"}),u.createEl("option",{value:"error",text:"Errors"}),u.createEl("option",{value:"warn",text:"Warnings"}),u.value=this.issueSeverity,u.onchange=()=>{this.issueSeverity=u.value==="error"||u.value==="warn"?u.value:"all",this.issueLimit=250,this.render()};let d=l.createEl("input",{type:"search"});d.setAttr("aria-label","Filter issues"),d.placeholder="Filter by path, code, field, or message",d.value=this.issueQuery,d.oninput=()=>{this.issueQuery=d.value,this.issueLimit=250,this.render();let g=this.containerEl.querySelector(".mdbase-issue-controls input[type='search']");g==null||g.focus(),g==null||g.setSelectionRange(g.value.length,g.value.length)};let f=this.issueQuery.trim().toLowerCase(),p=s.filter(g=>{var _;return this.issueSeverity!=="all"&&g.severity!==this.issueSeverity?!1:f?`${g.path} ${g.code} ${(_=g.field)!=null?_:""} ${g.message}`.toLowerCase().includes(f):!0}),m=new Set(p.map(g=>g.path)).size;if(n.createDiv({cls:"mdbase-issues-summary",text:p.length===s.length?`Showing ${Math.min(p.length,this.issueLimit).toLocaleString()} of ${p.length.toLocaleString()} issues`:`${p.length.toLocaleString()} matching issues in ${m.toLocaleString()} files`}),!p.length){n.createDiv({cls:"mdbase-empty-state",text:"No validation issues."});return}let h=p.slice(0,this.issueLimit),y=new Map;for(let g of h)y.set(g.path,[...(b=y.get(g.path))!=null?b:[],g]);for(let[g,_]of y){let I=n.createEl("section",{cls:"mdbase-issue-group"}),v=I.createDiv({cls:"mdbase-issue-group-header"}),S=v.createEl("button",{cls:"mdbase-issue-file-button"});(0,Se.setIcon)(S.createSpan({cls:"mdbase-issue-file-icon"}),"file-text"),S.createSpan({cls:"mdbase-issue-file-path",text:g}),S.onclick=()=>void this.host.openFileByPath(g),v.createSpan({cls:"mdbase-issue-file-count",text:`${_.length} ${_.length===1?"issue":"issues"}`});for(let k of _){let $=I.createEl("button",{cls:"mdbase-issue-row"});$.setAttr("data-severity",k.severity),$.setAttr("aria-label",`${k.severity==="warn"?"Warning":"Error"}: ${k.message}`),$.createSpan({cls:"mdbase-issue-indicator"}).setAttr("aria-hidden","true");let P=$.createDiv({cls:"mdbase-issue-metadata"});P.createEl("code",{text:k.code}),P.createDiv({cls:"mdbase-issue-context",text:`${k.severity==="warn"?"Warning":"Error"}${k.field?` \xB7 ${k.field}`:""}`}),$.createDiv({cls:"mdbase-issue-row-message",text:k.message}),$.onclick=()=>void this.host.openFileByPath(k.path,k.field)}}if(p.length>h.length){let g=n.createEl("button",{cls:"mdbase-load-more",text:`Load ${Math.min(250,p.length-h.length)} more`});g.onclick=()=>{this.issueLimit+=250,this.render()}}}async selectType(t,n=!0){if(n&&this.dirty&&t!==this.selectedPath){new Se.Notice("Save or discard the current type changes before switching.");return}let s=await this.host.loadTypeModel(t);this.selectedPath=t,this.model=s,this.originalModel=Ef(s),this.yamlDraft=`${at(ww(s),s.body)} -`,this.dirty=!1,this.editorMode="design",this.render()}createType(){if(this.dirty){new Se.Notice("Save or discard the current type changes before creating another type.");return}let t=Sf();this.selectedPath=null,this.model=t,this.originalModel=null,this.yamlDraft=`${at(Yi(t),t.body)} -`,this.dirty=!0,this.editorMode="design",this.render()}switchEditorMode(t){if(!(!this.model||t===this.editorMode)){if(t==="yaml")try{this.yamlDraft=`${at(ww(this.model),this.model.body)} -`}catch(n){new Se.Notice(n instanceof Error?n.message:String(n));return}else if(!this.readYamlDraftIntoModel())return;this.editorMode=t,this.render()}}readYamlDraftIntoModel(){var n,s;let t=_t(this.yamlDraft);if(!t.hasFrontmatter||t.error)return new Se.Notice(`Invalid type YAML: ${(n=t.error)!=null?n:"frontmatter is missing"}`),!1;if(t.frontmatter.kind!=="mdbase.type")return new Se.Notice("Canonical v0.3 type YAML requires kind: mdbase.type."),!1;try{return this.model=oc(t.frontmatter,t.body,((s=this.model)==null?void 0:s.name)||"type"),!0}catch(i){return new Se.Notice(i instanceof Error?i.message:String(i)),!1}}async saveCurrentType(){if(!(!this.model||this.model.specProfile!=="v0.3"||this.model.readOnlyReason)&&!(this.editorMode==="yaml"&&!this.readYamlDraftIntoModel())){if(!this.model.name.trim()){new Se.Notice("Type name is required.");return}await this.perform(async()=>{let t=await this.host.saveTypeModel(this.model,this.selectedPath);this.selectedPath=t.path,this.originalModel=Ef(this.model),this.dirty=!1,this.transientMessage=`Saved ${t.path}.`,await this.refresh(!0)})}}markDirty(t=!1){var o,a;if(this.dirty=!0,t){this.render();return}let n=this.containerEl.querySelector(".mdbase-editor-title-line");n&&!n.querySelector(".mdbase-dirty")&&n.createSpan({cls:"mdbase-dirty",text:"Unsaved"});let s=this.containerEl.querySelector(".mdbase-editor-actions .mod-cta");s&&((o=this.model)==null?void 0:o.specProfile)==="v0.3"&&!this.model.readOnlyReason&&((a=this.host.getMirrorProfile())==null?void 0:a.mode)!=="read_only"&&(s.disabled=!1);let i=this.containerEl.querySelector(".mdbase-change-review");if(i){let c=i.querySelector("p");c&&c.setText("Pending changes. Review details after leaving the current field.")}}async refreshMirrorStatus(){try{this.mirrorStatus=await this.host.connectSync.status()}catch(t){this.mirrorStatus=null,this.transientMessage=t instanceof Error?t.message:String(t)}}async perform(t){if(!this.busy){this.busy=!0,this.transientMessage="",this.render();try{await t()}catch(n){let s=n instanceof Error?n.message:String(n);this.transientMessage=s,new Se.Notice(s)}finally{this.busy=!1,this.render()}}}};function ww(r){var e;return r.specProfile==="v0.3"&&!r.readOnlyReason?Yi(r):Ef((e=r.originalFrontmatter)!=null?e:{name:r.name,fields:Object.fromEntries(r.fields.map(t=>[t.name,t.definition]))})}var Ss="mdbase-issues-view",dR={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null};function uR(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return e.version===1&&typeof e.syncUrl=="string"&&typeof e.controlUrl=="string"&&typeof e.collectionId=="string"&&typeof e.replicaId=="string"&&(e.mode==="read_only"||e.mode==="read_write")&&typeof e.name=="string"&&typeof e.enrollmentId=="string"&&typeof e.accessTokenExpiresAt=="string"}function fR(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Xi=class extends L.Modal{constructor(t,n,s="",i=""){super(t);this.resolvePromise=null;this.settled=!1;this.title=n,this.placeholder=s,this.defaultValue=i}openAndGetValue(){return new Promise(t=>{this.settled=!1,this.resolvePromise=t,this.open()})}onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h3",{text:this.title});let n=t.createEl("input",{type:"text"});n.placeholder=this.placeholder,n.value=this.defaultValue,n.addClass("prompt-input");let s=t.createDiv({cls:"modal-button-container"}),i=s.createEl("button",{text:"Cancel"}),o=s.createEl("button",{text:"OK"});o.addClass("mod-cta"),i.onclick=()=>{this.finish(null),this.close()},o.onclick=()=>{this.finish(n.value.trim()),this.close()},n.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),this.finish(n.value.trim()),this.close()),a.key==="Escape"&&(a.preventDefault(),this.finish(null),this.close())}),window.setTimeout(()=>n.focus(),0)}onClose(){this.settled||this.finish(null),this.contentEl.empty()}finish(t){var n;this.settled||(this.settled=!0,(n=this.resolvePromise)==null||n.call(this,t),this.resolvePromise=null)}},Af=class extends L.SuggestModal{constructor(t,n,s){super(t);this.resultHandled=!1;this.typeDefs=[...n].sort((i,o)=>i.name.localeCompare(o.name)),this.onResult=s,this.setPlaceholder("Type to search..."),this.setInstructions([{command:"\u2191\u2193",purpose:"navigate"},{command:"\u21B5",purpose:"select"},{command:"esc",purpose:"cancel"}]),this.containerEl.addClass("mdbase-type-picker-modal"),this.titleEl.setText("Select type definition")}getSuggestions(t){let n=t.trim().toLowerCase();return n?this.typeDefs.filter(s=>{var a,c,l;let i=(c=(a=s.match)==null?void 0:a.path_glob)!=null?c:"";return`${s.name} ${(l=s.display_name_key)!=null?l:""} ${s.filePath} ${i}`.toLowerCase().includes(n)}).slice(0,100):this.typeDefs.slice(0,100)}renderSuggestion(t,n){var o,a;let s=n.createDiv({cls:"mdbase-type-picker-suggestion"});s.createDiv({cls:"mdbase-type-picker-name",text:t.name});let i=s.createDiv({cls:"mdbase-type-picker-meta"});i.createSpan({cls:"mdbase-type-picker-path",text:t.filePath}),i.createSpan({cls:"mdbase-type-picker-count",text:`${Object.keys((o=t.fields)!=null?o:{}).length} fields`}),(a=t.match)!=null&&a.path_glob&&s.createDiv({cls:"mdbase-type-picker-match",text:`match: ${t.match.path_glob}`})}onChooseSuggestion(t){this.resultHandled=!0,this.onResult({type:"selected",typeDef:t})}onClose(){window.setTimeout(()=>{this.resultHandled||this.onResult({type:"cancelled"})},0),super.onClose()}};function pR(r,e){return new Promise(t=>{new Af(r,e,s=>{if(s.type==="selected"){t(s.typeDef);return}t(null)}).open()})}var kf=class extends L.ItemView{constructor(t,n){super(t);this.severityFilter="all";this.query="";this.plugin=n}getViewType(){return Ss}getDisplayText(){return"mdbase issues"}getIcon(){return"shield-alert"}async onOpen(){this.containerEl.empty(),this.containerEl.addClass("mdbase-issues-view"),this.render()}render(){var m;let t=this.containerEl;t.empty(),t.addClass("mdbase-issues-view");let n=t.createDiv({cls:"mdbase-issues-header"});n.createEl("h3",{text:"mdbase Issues"});let i=n.createDiv({cls:"mdbase-issues-header-actions"}).createEl("button",{text:"Refresh"});i.addClass("mod-cta"),i.onclick=()=>{this.plugin.runCollectionValidation(!1)};let o=t.createDiv({cls:"mdbase-issues-controls"}),a=o.createEl("select");a.addClass("mdbase-issues-severity"),a.createEl("option",{value:"all",text:"All severities"}),a.createEl("option",{value:"error",text:"Errors only"}),a.createEl("option",{value:"warn",text:"Warnings only"}),a.value=this.severityFilter,a.onchange=()=>{let h=a.value;(h==="error"||h==="warn"||h==="all")&&(this.severityFilter=h),this.render()};let c=o.createEl("input",{type:"search"});c.addClass("mdbase-issues-query"),c.placeholder="Filter by path, code, message, field",c.value=this.query,c.oninput=()=>{this.query=c.value,this.render()};let l=this.plugin.getIssues(),u=this.query.trim().toLowerCase(),d=l.filter(h=>{var b;return this.severityFilter!=="all"&&h.severity!==this.severityFilter?!1:u?`${h.path} ${h.code} ${h.message} ${(b=h.field)!=null?b:""}`.toLowerCase().includes(u):!0}),f=d.slice(0,500);if(t.createDiv({cls:"mdbase-issues-count",text:d.length>f.length?`Showing ${f.length} of ${d.length} matching issues`:d.length===l.length?`${d.length} issue${d.length===1?"":"s"}`:`${d.length} of ${l.length} issue${l.length===1?"":"s"}`}),d.length===0){t.createDiv({cls:"mdbase-empty",text:l.length===0?"No validation issues.":"No issues match current filters."});return}let p=new Map;for(let h of f){let y=(m=p.get(h.path))!=null?m:[];y.push(h),p.set(h.path,y)}for(let[h,y]of p.entries()){t.createDiv({cls:"mdbase-issue-file",text:h});for(let b of y){let g=t.createDiv({cls:"mdbase-issue-item"});g.setAttr("data-severity",b.severity),g.createDiv({cls:"mdbase-issue-code",text:`${b.severity.toUpperCase()} \xB7 ${b.code}${b.field?` \xB7 ${b.field}`:""}`}),g.createDiv({cls:"mdbase-issue-message",text:b.message});let _=g.createDiv({cls:"mdbase-issue-actions"}),I=_.createEl("button",{text:b.field?"Open field":"Open file"});I.onclick=S=>{S.stopPropagation(),this.plugin.openIssue(b)};let v=this.plugin.getQuickFixLabel(b);if(v){let S=_.createEl("button",{text:v});S.onclick=k=>{k.stopPropagation(),this.plugin.applyQuickFix(b)}}g.onclick=()=>{this.plugin.openIssue(b)}}}}},xf=class extends L.PluginSettingTab{constructor(e,t){super(e,t),this.plugin=t}display(){let{containerEl:e}=this;e.empty(),e.createEl("h2",{text:"mdbase settings"}),new L.Setting(e).setName("Validate on save").setDesc("Run mdbase validation when a markdown file is modified.").addToggle(t=>t.setValue(this.plugin.settings.validateOnSave).onChange(async n=>{this.plugin.settings.validateOnSave=n,await this.plugin.saveSettings()})),new L.Setting(e).setName("Validate on file open").setDesc("Validate the active note when opened.").addToggle(t=>t.setValue(this.plugin.settings.validateOnOpen).onChange(async n=>{this.plugin.settings.validateOnOpen=n,await this.plugin.saveSettings()})),new L.Setting(e).setName("Show notices on save").setDesc("Display a notice when save-time validation finds issues.").addToggle(t=>t.setValue(this.plugin.settings.showNoticeOnSave).onChange(async n=>{this.plugin.settings.showNoticeOnSave=n,await this.plugin.saveSettings()})),new L.Setting(e).setName("Allow local application interoperability").setDesc("Allow installed Obsidian plugins to exchange validated mdbase events and actions in this vault. Contracts establish compatibility; this switch is the separate user grant.").addToggle(t=>t.setValue(this.plugin.settings.interopEnabled).onChange(async n=>{this.plugin.settings.interopEnabled=n,await this.plugin.saveSettings()}))}},cc=class extends L.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.sortedIssuesCache=null;this.schemaCache=null;this.schemaLoadPromise=null;this.pendingSaveValidations=new Map;this.saveValidationDebounceMs=250;this.connectSync=new nc(t,{getMirrorProfile:()=>this.getMirrorProfile(),saveMirrorProfile:async s=>{this.settings.mirrorProfile=s,await this.saveSettings()}}),this.interopBridge=new Xo(t,()=>{var s;return((s=this.settings)==null?void 0:s.interopEnabled)===!0}),this.api={apiVersion:1,interop:this.interopBridge,getInteropStatus:()=>{var s;return{enabled:((s=this.settings)==null?void 0:s.interopEnabled)===!0,profileVersion:"0.1"}}}}async onload(){await this.loadSettings(),await this.connectSync.initialize(),(0,L.addIcon)($s,yw),this.statusBarEl=this.addStatusBarItem(),this.updateStatusBar(),this.registerView(En,n=>new ac(n,this)),this.registerView(Ss,n=>new kf(n,this)),this.addSettingTab(new xf(this.app,this)),this.addRibbonIcon($s,"Open mdbase",()=>void this.openWorkspace()),this.addCommand({id:"mdbase-open",name:"mdbase: Open workspace",callback:()=>void this.openWorkspace()}),this.addCommand({id:"mdbase-initialize-collection",name:"mdbase: Initialize collection",callback:()=>void this.initializeCollectionCommand()}),this.addCommand({id:"mdbase-create-type",name:"mdbase: Create type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-type",name:"mdbase: Edit type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-current-type",name:"mdbase: Edit current type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-create-note-from-type",name:"mdbase: Create note from type",callback:()=>void this.createNoteFromTypeCommand()}),this.addCommand({id:"mdbase-validate-current-note",name:"mdbase: Validate current note",callback:()=>void this.validateCurrentNoteCommand()}),this.addCommand({id:"mdbase-validate-collection",name:"mdbase: Validate collection",callback:()=>void this.runCollectionValidation(!0)}),this.addCommand({id:"mdbase-open-issues-view",name:"mdbase: Open issues view",callback:()=>void this.openWorkspace("issues")}),this.addCommand({id:"mdbase-sync",name:"mdbase: Sync collection authority",callback:()=>void this.syncHostedCollectionCommand()}),this.addCommand({id:"mdbase-open-sync",name:"mdbase: Open sync",callback:()=>void this.openWorkspace("sync")}),this.registerEvent(this.app.vault.on("modify",n=>{n instanceof L.TFile&&this.onVaultModify(n)})),this.registerEvent(this.app.vault.on("rename",(n,s)=>{n instanceof L.TFile&&this.onVaultRename(n,s)})),this.registerEvent(this.app.vault.on("delete",n=>{n instanceof L.TFile&&this.onVaultDelete(n)})),this.registerEvent(this.app.vault.on("create",n=>{n instanceof L.TFile&&this.onVaultCreate(n)})),this.registerEvent(this.app.workspace.on("file-open",n=>{this.settings.validateOnOpen&&(!(n instanceof L.TFile)||n.extension!=="md"||this.validateFileAndStore(n,"open"))}));let t=this.app.workspace.getActiveFile();t&&this.settings.validateOnOpen&&this.validateFileAndStore(t,"open")}async onunload(){await this.interopBridge.dispose(),this.app.workspace.getLeavesOfType(En).forEach(t=>t.detach()),this.app.workspace.getLeavesOfType(Ss).forEach(t=>t.detach()),this.clearAllPendingSaveValidations()}async loadSettings(){this.settings=Object.assign({},dR,await this.loadData()),uR(this.settings.mirrorProfile)||(this.settings.mirrorProfile=null)}async saveSettings(){await this.saveData(this.settings)}getIssues(){var t;return(t=this.sortedIssuesCache)!=null||(this.sortedIssuesCache=Array.from(this.issueMap.values()).flat().sort((n,s)=>n.path.localeCompare(s.path)||n.severity.localeCompare(s.severity)||n.code.localeCompare(s.code))),this.sortedIssuesCache}getMirrorProfile(){return this.settings.mirrorProfile?{...this.settings.mirrorProfile}:null}async loadWorkspaceSchema(t=!1){return this.getConfigAndTypes(t)}async loadTypeModel(t){var i;let n=this.app.vault.getAbstractFileByPath((0,L.normalizePath)(t));if(!(n instanceof L.TFile))throw new Error(`Type file not found: ${t}`);let s=_t(await this.app.vault.cachedRead(n));if(!s.hasFrontmatter||s.error)throw new Error(`Invalid type frontmatter: ${(i=s.error)!=null?i:"frontmatter is missing"}`);return oc(s.frontmatter,s.body,n.basename)}async saveTypeModel(t,n){var a;if(this.connectSync.assertLocalAuthorityWritable(),((a=this.getMirrorProfile())==null?void 0:a.mode)==="read_only")throw new Error("This mirror has read-only access. Re-enroll it with write access before editing types.");let s=await Zn(this.app.vault);if(!s)throw new Error("No mdbase.yaml found.");if(!s.spec_version.startsWith("0.3."))throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let i=n?this.app.vault.getAbstractFileByPath((0,L.normalizePath)(n)):null;if(i!=null&&!(i instanceof L.TFile))throw new Error(`Type file not found: ${n}`);let o=await this.writeTypeDefinition(s,t,i);return this.refreshWorkspaceViews(!0),o}async initializeCollection(){this.connectSync.assertLocalAuthorityWritable(),await this.initializeCollectionCommand(),this.refreshWorkspaceViews(!0)}async validateCollection(){await this.runCollectionValidation(!1)}analyzeMigration(){if(this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");return pw(this.app.vault)}async applyMigration(t,n){var i,o;if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");let s=await hw(this.app.vault,t,{allowLossy:n});if(!s.applied)throw new Error(s.restored?`Migration failed and all writes were rolled back. ${(i=s.error)!=null?i:""}`.trim():`Migration needs manual recovery. See ${s.manifestPath}. ${(o=s.error)!=null?o:""}`.trim());this.invalidateSchemaCache(),new L.Notice(`Migrated to mdbase v0.3. Recovery manifest: ${s.manifestPath}`),this.refreshWorkspaceViews(!0)}async openIssue(t){await this.openFileByPath(t.path,t.field)}getQuickFixLabel(t){return["unknown_field","schema_additional_properties"].includes(t.code)&&t.field?"Remove field":["missing_required","schema_required"].includes(t.code)&&t.field?"Add placeholder":null}async applyQuickFix(t){this.connectSync.assertLocalAuthorityWritable();let n=this.app.vault.getAbstractFileByPath(t.path);if(!(n instanceof L.TFile)){new L.Notice(`File not found: ${t.path}`);return}let s=await this.app.vault.cachedRead(n),i=_t(s);if(i.error){new L.Notice(`Cannot apply quick fix: invalid frontmatter (${i.error})`);return}if(["unknown_field","schema_additional_properties"].includes(t.code)&&t.field){let o=ra(t.field);if(!(o in i.frontmatter)){new L.Notice(`Field '${o}' not found in frontmatter.`);return}delete i.frontmatter[o],await this.app.vault.modify(n,`${at(i.frontmatter,i.body)} -`),new L.Notice(`Removed '${o}' from ${n.basename}`),await this.validateFileAndStore(n,"manual");return}if(["missing_required","schema_required"].includes(t.code)&&t.field){let o=ra(t.field);i.frontmatter[o]===void 0&&(i.frontmatter[o]="TODO");let a=i.hasFrontmatter?i.body:s;await this.app.vault.modify(n,`${at(i.frontmatter,a)} -`),new L.Notice(`Added placeholder '${o}' to ${n.basename}`),await this.validateFileAndStore(n,"manual");return}new L.Notice("No quick fix available for this issue.")}async openFileByPath(t,n){let s=this.app.vault.getAbstractFileByPath(t);if(!(s instanceof L.TFile)){new L.Notice(`File not found: ${t}`);return}await this.app.workspace.getLeaf(!0).openFile(s),n&&this.revealFrontmatterField(s,n)}revealFrontmatterField(t,n){let s=this.app.workspace.getMostRecentLeaf();if(!s||!(s.view instanceof L.MarkdownView))return;let i=s.view;if(!(i.file instanceof L.TFile)||i.file.path!==t.path)return;let o=i.editor,a=o.lineCount();if(a<3)return;let c=ra(n),l=new RegExp(`^\\s*${fR(c)}\\s*:`);if(o.getLine(0).trim()==="---")for(let u=1;ui.severity==="error").length,s=t.length-n;if(t.length===0){this.statusBarEl.setText("mdbase: no issues");return}this.statusBarEl.setText(`mdbase: ${n} error${n===1?"":"s"}, ${s} warning${s===1?"":"s"}`)}async openIssuesView(){var s;let t=this.app.workspace.getLeavesOfType(Ss)[0];if(t){this.app.workspace.revealLeaf(t),t.view.render();return}let n=(s=this.app.workspace.getRightLeaf(!1))!=null?s:this.app.workspace.getLeaf(!0);await n.setViewState({type:Ss,active:!0}),this.app.workspace.revealLeaf(n)}async openWorkspace(t="types"){let n=this.app.workspace.getLeavesOfType(En)[0];if(n){this.app.workspace.revealLeaf(n);let o=n.view;o.showDestination(t),await o.refresh();return}let s=this.app.workspace.getLeaf(!0);await s.setViewState({type:En,active:!0}),this.app.workspace.revealLeaf(s),s.view.showDestination(t)}refreshWorkspaceViews(t=!1){for(let n of this.app.workspace.getLeavesOfType(En))n.view.refresh(t)}refreshIssueViews(){this.updateStatusBar();for(let t of this.app.workspace.getLeavesOfType(Ss))t.view.render();this.refreshWorkspaceViews()}setFileIssues(t,n){n.length===0?this.issueMap.delete(t):this.issueMap.set(t,n),this.sortedIssuesCache=null,this.refreshIssueViews()}clearFileIssues(t){this.issueMap.has(t)&&(this.issueMap.delete(t),this.sortedIssuesCache=null,this.refreshIssueViews())}moveFileIssues(t,n){let s=this.issueMap.get(t);s&&(this.issueMap.delete(t),this.issueMap.set(n,s.map(i=>({...i,path:n}))),this.sortedIssuesCache=null,this.refreshIssueViews())}clearAllPendingSaveValidations(){for(let t of this.pendingSaveValidations.values())window.clearTimeout(t);this.pendingSaveValidations.clear()}clearPendingSaveValidation(t){let n=this.pendingSaveValidations.get(t);n!=null&&(window.clearTimeout(n),this.pendingSaveValidations.delete(t))}scheduleSaveValidation(t){this.clearPendingSaveValidation(t.path);let n=window.setTimeout(()=>{this.pendingSaveValidations.delete(t.path),this.validateFileAndStore(t,"save")},this.saveValidationDebounceMs);this.pendingSaveValidations.set(t.path,n)}isSchemaRelevantPath(t){let n=(0,L.normalizePath)(t);if(n==="mdbase.yaml")return!0;let s=new Set(["_types"]);this.schemaCache&&s.add((0,L.normalizePath)(this.schemaCache.config.settings.types_folder));for(let i of s)if(n===i||n.startsWith(`${i}/`))return!0;return!1}invalidateSchemaCache(){this.schemaCache=null,this.schemaLoadPromise=null}async getConfigAndTypes(t=!1){if(t&&this.invalidateSchemaCache(),this.schemaCache)return this.schemaCache;if(this.schemaLoadPromise)return this.schemaLoadPromise;this.schemaLoadPromise=(async()=>{let n=await Zn(this.app.vault);if(!n)return null;let s=await _b(this.app.vault,n);return{config:n,types:s}})();try{let n=await this.schemaLoadPromise;return n&&(this.schemaCache=n),n}finally{this.schemaLoadPromise=null}}async requireConfigAndTypes(t={}){var i,o;let n=(i=t.background)!=null?i:!1,s=await this.getConfigAndTypes((o=t.forceReload)!=null?o:!1);return s?(s.types.size===0&&!n&&new L.Notice(`No types found in ${s.config.settings.types_folder}`),s):(n||new L.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}onVaultModify(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),this.settings.validateOnSave&&t.extension==="md"&&this.scheduleSaveValidation(t)}onVaultRename(t,n){(this.isSchemaRelevantPath(n)||this.isSchemaRelevantPath(t.path))&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(n),this.moveFileIssues(n,t.path),this.settings.validateOnSave&&this.scheduleSaveValidation(t))}onVaultDelete(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(t.path),this.clearFileIssues(t.path))}onVaultCreate(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews())}async validateFileAndStore(t,n){let s=await this.requireConfigAndTypes({background:n!=="manual"});if(!s)return n!=="manual"&&this.clearFileIssues(t.path),[];let i=await bu(this.app.vault,t,s.config,s.types);return this.setFileIssues(t.path,i),n==="save"&&this.settings.showNoticeOnSave&&i.length>0&&new L.Notice(`mdbase: ${i.length} issue${i.length===1?"":"s"} in ${t.basename}`),i}async initializeCollectionCommand(){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()){new L.Notice("This vault is configured as a mirror. Sync it instead of initializing a local collection.");return}let{created:t}=await gb(this.app.vault);if(this.invalidateSchemaCache(),t.length===0){new L.Notice("mdbase collection already initialized.");return}new L.Notice(`Initialized mdbase collection: ${t.join(", ")}`)}async syncHostedCollectionCommand(){if(!this.getMirrorProfile()){await this.openWorkspace("sync");return}try{let t=await this.connectSync.sync();this.invalidateSchemaCache(),this.refreshWorkspaceViews(!0);let n=t.conflicts.length+t.local_issues.length;new L.Notice(n?`Sync completed with ${n} item${n===1?"":"s"} needing attention.`:"mdbase sync completed.")}catch(t){new L.Notice(`mdbase sync failed: ${t instanceof Error?t.message:String(t)}`),await this.openWorkspace("sync")}}async createNoteFromTypeCommand(){var u,d;this.connectSync.assertLocalAuthorityWritable();let t=await this.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new L.Notice("No type definitions found.");return}let n=await pR(this.app,Array.from(t.types.values()));if(!n)return;let s=Sb(n,t.config),i=Eb(n,s);for(let[f,p]of i){let m=`Required field: ${f}`,h=await new Xi(this.app,m,(u=p.type)!=null?u:"string").openAndGetValue();if(h==null)return;if(h.trim().length===0){new L.Notice(`Field '${f}' is required.`);return}try{s[f]=wu(h,p)}catch(y){new L.Notice(`Invalid value for ${f}: ${y instanceof Error?y.message:String(y)}`);return}}let o=(d=n.display_name_key)!=null?d:"title";if(s[o]==null){let f=await new Xi(this.app,`Optional ${o} (used for filename)`,"").openAndGetValue();f&&f.trim().length>0&&(s[o]=f.trim())}let a=await kb(this.app.vault,n,s),c=await new Xi(this.app,"Note path","Relative path in vault",a).openAndGetValue();if(c==null)return;let l=(0,L.normalizePath)(c.trim().length>0?c.trim():a);l.endsWith(".md")||(l=`${l}.md`);try{let f=await xb(this.app.vault,l,s);await this.app.workspace.getLeaf(!0).openFile(f),new L.Notice(`Created note: ${f.path}`),await this.validateFileAndStore(f,"manual")}catch(f){new L.Notice(f instanceof Error?f.message:String(f))}}async validateCurrentNoteCommand(){let t=this.app.workspace.getActiveFile();if(!(t instanceof L.TFile)||t.extension!=="md"){new L.Notice("Open a markdown note first.");return}let n=await this.validateFileAndStore(t,"manual");n.length===0?new L.Notice("No issues in current note."):(new L.Notice(`Found ${n.length} issue${n.length===1?"":"s"} in current note.`),await this.openIssuesView())}async runCollectionValidation(t){var o;let n=await this.requireConfigAndTypes({background:!1});if(!n)return;let s=await $b(this.app.vault,n.config,n.types),i=new Map;for(let a of s){let c=(o=i.get(a.path))!=null?o:[];c.push(a),i.set(a.path,c)}if(this.issueMap=i,this.sortedIssuesCache=null,this.refreshIssueViews(),t)if(s.length===0)new L.Notice("Collection validation passed with no issues.");else{let a=s.filter(l=>l.severity==="error").length,c=s.length-a;new L.Notice(`Collection validation: ${a} error(s), ${c} warning(s)`),await this.openIssuesView()}}async ensureFolderExists(t){let n=(0,L.normalizePath)(t).replace(/\/+$/,"");if(!n)return;let s=n.split("/"),i="";for(let o of s)i=i?`${i}/${o}`:o,await this.app.vault.adapter.exists(i)||await this.app.vault.createFolder(i)}async writeTypeDefinition(t,n,s){let i=n.name.trim();if(!i)throw new Error("Type name is required.");if(!t.spec_version.startsWith("0.3.")||n.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let o=Yi(n),a=n.body.trim()||`# ${i} +`;var Mn="mdbase-workspace-view",iC=["string","integer","number","boolean","date","datetime","time","enum","link","list","object","any"];function Cn(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Xf(r){return JSON.parse(JSON.stringify(r))}function Jw(r){return typeof r.type=="string"?r.type:"any"}function sC(r){if(!Object.prototype.hasOwnProperty.call(r,"field"))return"field";let e=2;for(;Object.prototype.hasOwnProperty.call(r,`field${e}`);)e+=1;return`field${e}`}function Yw(r,e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,writable:!0,value:t})}function oC(r,e){if(!r)return["A new type definition will be created."];let t=[];r.name!==e.name&&t.push(`Rename type from ${r.name} to ${e.name}.`),(r.matchPathGlob!==e.matchPathGlob||r.matchFieldsPresent!==e.matchFieldsPresent||r.matchWhere!==e.matchWhere)&&t.push("Membership rules changed; different records may match this type.");let n=new Map(r.fields.map(c=>[c.name,c])),i=new Map(e.fields.map(c=>[c.name,c])),s=[...n.keys()].filter(c=>!i.has(c)),o=[...i.keys()].filter(c=>!n.has(c));o.length&&t.push(`Add ${o.length} field${o.length===1?"":"s"}: ${o.join(", ")}.`),s.length&&t.push(`Remove ${s.length} field${s.length===1?"":"s"}: ${s.join(", ")}.`);let a=[...i.entries()].filter(([c,l])=>{var u;return l.definition.required===!0&&((u=n.get(c))==null?void 0:u.definition.required)!==!0}).map(([c])=>c);return a.length&&t.push(`New required fields may invalidate records: ${a.join(", ")}.`),t.length||t.push("Metadata, schema details, or documentation changed."),t}function Nt(r,e,t,n,i={}){var l;let s=r.createDiv({cls:"mdbase-form-row"}),o=s.createEl("label",{text:e}),a=`mdbase-${Math.random().toString(36).slice(2)}`;o.htmlFor=a,i.description&&s.createDiv({cls:"mdbase-form-description",text:i.description});let c=i.multiline?s.createEl("textarea"):s.createEl("input",{type:"text"});return c.id=a,c.value=t,c.placeholder=(l=i.placeholder)!=null?l:"",c.addEventListener("input",()=>n(c.value)),c}function je(r,e,t){let n=r.createDiv({cls:"mdbase-status-row"});n.createSpan({cls:"mdbase-status-label",text:e}),n.createSpan({cls:"mdbase-status-value",text:t})}function aC(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}var Oc=class extends Ae.ItemView{constructor(t,n){super(t);this.host=n;this.destination="types";this.editorMode="design";this.schema=null;this.query="";this.selectedPath=null;this.model=null;this.originalModel=null;this.yamlDraft="";this.dirty=!1;this.busy=!1;this.migrationPlan=null;this.allowLossy=!1;this.mirrorStatus=null;this.mirrorPreview=null;this.mirrorProgress=null;this.transientMessage="";this.issueQuery="";this.issueSeverity="all";this.issueLimit=250;this.enrollmentVerification="";this.enrollmentAbort=null}getViewType(){return Mn}getDisplayText(){return"mdbase"}getIcon(){return Ci}async onOpen(){this.containerEl.addClass("mdbase-workspace"),await this.refresh(!0)}async onClose(){var t;(t=this.enrollmentAbort)==null||t.abort(),this.enrollmentAbort=null}async refresh(t=!1){try{this.schema=await this.host.loadWorkspaceSchema(t),this.selectedPath&&!this.typeEntries().some(n=>n.filePath===this.selectedPath)&&(this.selectedPath=null,this.model=null,this.originalModel=null),!this.selectedPath&&this.typeEntries().length&&!Ae.Platform.isMobile&&(this.selectedPath=this.typeEntries()[0].filePath),this.selectedPath&&(!this.model||t)&&await this.selectType(this.selectedPath,!1),this.destination==="sync"&&await this.refreshMirrorStatus(),this.render()}catch(n){this.transientMessage=n instanceof Error?n.message:String(n),this.render()}}showDestination(t){this.destination=t,t==="sync"?this.refreshMirrorStatus().then(()=>this.render()):this.render()}typeEntries(){return this.schema?[...this.schema.types.values()].sort((t,n)=>t.name.localeCompare(n.name)):[]}render(){let t=this.containerEl;t.empty(),t.addClass("mdbase-workspace");let n=t.createDiv({cls:"mdbase-shell"});this.renderTopbar(n),this.transientMessage&&n.createDiv({cls:"mdbase-inline-message",text:this.transientMessage}).setAttr("role","status");let i=n.createDiv({cls:"mdbase-workspace-content"});this.destination==="types"?this.renderTypes(i):this.destination==="sync"?this.renderSync(i):this.renderIssues(i)}renderTopbar(t){let n=t.createDiv({cls:"mdbase-topbar"}),i=n.createDiv({cls:"mdbase-identity"}),s=i.createSpan({cls:"mdbase-mark"});s.setAttr("aria-hidden","true"),(0,Ae.setIcon)(s,Ci),i.createSpan({cls:"mdbase-title",text:"mdbase"});let o=n.createDiv({cls:"mdbase-nav"});o.setAttr("role","tablist");for(let[a,c]of[["types","Types"],["sync","Sync"],["issues","Issues"]]){let l=o.createEl("button",{text:c});if(l.addClass("mdbase-nav-button"),l.setAttr("role","tab"),l.setAttr("aria-selected",String(this.destination===a)),this.destination===a&&l.addClass("is-active"),a==="issues"&&this.host.getIssues().length){let u=this.host.getIssues().length;l.createSpan({cls:"mdbase-count",text:aC(u)}).setAttr("title",`${u} issues`)}l.onclick=()=>this.showDestination(a)}}renderTypes(t){if(!this.schema){let i=t.createDiv({cls:"mdbase-empty-state"});i.createEl("h2",{text:"Start an mdbase collection"}),i.createEl("p",{text:"Initialize this vault as a local v0.3 collection, or use Sync to connect an empty vault to a collection authority."});let s=i.createDiv({cls:"mdbase-actions"}),o=s.createEl("button",{text:"Initialize local collection"});o.addClass("mod-cta"),o.disabled=this.busy||this.host.getMirrorProfile()!==null,o.onclick=()=>void this.perform(async()=>{await this.host.initializeCollection(),await this.refresh(!0)});let a=s.createEl("button",{text:"Connect collection authority"});a.onclick=()=>this.showDestination("sync");return}this.schema.config.spec_version.startsWith("0.2.")&&this.renderLegacyBanner(t);let n=t.createDiv({cls:"mdbase-types-layout"});this.model&&n.addClass("has-selection"),this.renderTypeList(n),this.renderTypeEditor(n)}renderLegacyBanner(t){var o;let n=t.createDiv({cls:"mdbase-legacy-banner"}),i=n.createDiv();i.createEl("strong",{text:`mdbase ${(o=this.schema)==null?void 0:o.config.spec_version} compatibility mode`}),i.createEl("p",{text:"Types are readable and validation remains available, but authoring is disabled until a reviewed v0.3 migration."});let s=n.createEl("button",{text:this.migrationPlan?"Review migration":"Analyze migration"});s.disabled=this.busy||this.host.getMirrorProfile()!==null,s.onclick=()=>void this.perform(async()=>{this.migrationPlan=await this.host.analyzeMigration(),this.render()}),this.host.getMirrorProfile()&&n.createDiv({cls:"mdbase-form-description",text:"Hosted resources must be migrated at the collection authority."}),this.migrationPlan&&this.renderMigrationReview(t,this.migrationPlan)}renderMigrationReview(t,n){let i=t.createDiv({cls:"mdbase-migration-review"}),s=i.createDiv({cls:"mdbase-section-header"});s.createEl("h3",{text:"Migration review"}),s.createSpan({cls:"mdbase-spec-badge",text:`${n.sourceVersion} \u2192 ${n.targetVersion}`});let o=i.createDiv({cls:"mdbase-status-list"});je(o,"Files replaced",String(n.operations.length)),je(o,"Type definitions",String(n.typeSummaries.length)),je(o,"Record reads verified",String(n.recordsVerified)),n.recordsSkipped&&je(o,"Records skipped",String(n.recordsSkipped)),je(o,"Record files rewritten","0"),je(o,"Recovery backup",n.backupLocation);let a=i.createDiv({cls:"mdbase-review-list"});n.diagnostics.length||a.createDiv({cls:"mdbase-review-ok",text:"No migration diagnostics."});for(let d of n.diagnostics.slice(0,250)){let f=a.createDiv({cls:"mdbase-review-item"});f.setAttr("data-severity",d.severity),f.createDiv({cls:"mdbase-review-code",text:`${d.severity} \xB7 ${d.path}`}),f.createDiv({text:d.message})}if(n.diagnostics.length>250&&a.createDiv({cls:"mdbase-form-description",text:`Showing 250 of ${n.diagnostics.length} diagnostics.`}),!n.applicable){let d=i.createEl("label",{cls:"mdbase-consent"}),f=d.createEl("input",{type:"checkbox"});f.checked=this.allowLossy,f.onchange=()=>{this.allowLossy=f.checked,this.render()},d.createSpan({text:"I reviewed the lossy diagnostics and want to apply this migration."})}let c=i.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Apply migration"});l.addClass("mod-warning"),l.disabled=this.busy||!n.applicable&&!this.allowLossy,l.onclick=()=>void this.perform(async()=>{await this.host.applyMigration(n,this.allowLossy),this.migrationPlan=null,this.allowLossy=!1,this.model=null,this.originalModel=null,await this.refresh(!0)});let u=c.createEl("button",{text:"Close review"});u.onclick=()=>{this.migrationPlan=null,this.render()}}renderTypeList(t){var u,d,f,p;let n=t.createDiv({cls:"mdbase-type-list-pane"}),i=n.createDiv({cls:"mdbase-pane-header"});i.createEl("h2",{text:"Types"});let s=i.createEl("button");s.setAttr("aria-label","Create type"),(0,Ae.setIcon)(s,"plus"),s.disabled=((d=(u=this.schema)==null?void 0:u.config.spec_version.startsWith("0.2."))!=null?d:!0)||((f=this.host.getMirrorProfile())==null?void 0:f.mode)==="read_only",s.onclick=()=>this.createType();let o=n.createEl("input",{type:"search"});o.addClass("mdbase-type-search"),o.placeholder="Search types",o.setAttr("aria-label","Search types"),o.value=this.query,o.oninput=()=>{this.query=o.value,this.render();let m=this.containerEl.querySelector(".mdbase-type-search");m==null||m.focus(),m==null||m.setSelectionRange(m.value.length,m.value.length)};let a=n.createDiv({cls:"mdbase-type-list"}),c=this.query.trim().toLowerCase(),l=this.typeEntries().filter(m=>{var h;return`${m.name} ${(h=m.description)!=null?h:""} ${m.filePath}`.toLowerCase().includes(c)});if(!l.length){a.createDiv({cls:"mdbase-empty-list",text:c?"No matching types.":"No type definitions."});return}for(let m of l){let h=a.createEl("button",{cls:"mdbase-type-row"});m.filePath===this.selectedPath&&h.addClass("is-active"),h.setAttr("aria-current",m.filePath===this.selectedPath?"true":"false"),h.createSpan({cls:"mdbase-type-name",text:m.name}),h.createSpan({cls:"mdbase-type-meta",text:`${Object.keys(m.fields).length} fields \xB7 ${(p=m.specProfile)!=null?p:"v0.2"}`}),h.onclick=()=>void this.selectType(m.filePath)}}renderTypeEditor(t){var h,y,b,g;let n=t.createDiv({cls:"mdbase-type-editor-pane"});if(!this.model){let _=n.createDiv({cls:"mdbase-empty-state"});_.createEl("h2",{text:"Choose a type"}),_.createEl("p",{text:"Select a type definition from the list to inspect or edit it."});return}let i=((h=this.host.getMirrorProfile())==null?void 0:h.mode)==="read_only",s=this.model.specProfile==="v0.2"||i||!!this.model.readOnlyReason,o=(y=this.model.readOnlyReason)!=null?y:i?"This mirror has read-only access. Re-enroll it with write access before editing types.":"This v0.2 type is read-only. Review and apply a collection migration before editing.",a=n.createDiv({cls:"mdbase-editor-header"}),c=a.createEl("button",{cls:"mdbase-mobile-back"});c.setAttr("aria-label","Back to type list"),(0,Ae.setIcon)(c,"arrow-left"),c.onclick=()=>{if(this.dirty){new Ae.Notice("Save or discard the current type changes before going back.");return}this.selectedPath=null,this.model=null,this.originalModel=null,this.render()};let l=a.createDiv(),u=l.createDiv({cls:"mdbase-editor-title-line"});u.createEl("h2",{text:this.model.name||"Untitled type"}),u.createSpan({cls:"mdbase-spec-badge",text:(b=this.model.specProfile)!=null?b:"v0.2"}),this.dirty&&u.createSpan({cls:"mdbase-dirty",text:"Unsaved"}),l.createDiv({cls:"mdbase-editor-path",text:(g=this.selectedPath)!=null?g:"New type"});let d=a.createDiv({cls:"mdbase-editor-actions"});if(this.selectedPath){let _=d.createEl("button",{text:"Open source"});_.onclick=()=>void this.host.openFileByPath(this.selectedPath)}let f=d.createEl("button",{text:"Save"});f.addClass("mod-cta"),f.disabled=s||!this.dirty||this.busy,f.onclick=()=>void this.saveCurrentType(),s&&n.createDiv({cls:"mdbase-readonly-note",text:o});let p=n.createDiv({cls:"mdbase-mode-switch"});p.setAttr("role","tablist");for(let[_,k]of[["design","Design"],["yaml","YAML"]]){let v=p.createEl("button",{text:k});v.setAttr("role","tab"),v.setAttr("aria-selected",String(this.editorMode===_)),this.editorMode===_&&v.addClass("is-active"),v.onclick=()=>this.switchEditorMode(_)}let m=n.createDiv({cls:"mdbase-editor-document"});this.editorMode==="design"?this.renderDesignEditor(m,this.model,s):this.renderYamlEditor(m,s)}renderDesignEditor(t,n,i){let s=t.createEl("section",{cls:"mdbase-editor-section"});s.createEl("h3",{text:"Identity"});let o=Nt(s,"Name",n.name,E=>{n.name=E,this.markDirty()},{description:"Stable type name used by collection records."});o.disabled=i;let a=Nt(s,"Description",n.description,E=>{n.description=E,this.markDirty()},{multiline:!0});a.disabled=i;let c=Nt(s,"Display field",n.displayNameKey,E=>{n.displayNameKey=E,this.markDirty()},{placeholder:"title"});c.disabled=i;let l=s.createEl("label",{cls:"mdbase-checkbox-row"}),u=l.createEl("input",{type:"checkbox"});u.checked=n.strictMode===!0,u.disabled=i,u.onchange=()=>{n.strictMode=u.checked,this.markDirty()},l.createSpan({text:"Reject undeclared fields"});let d=t.createEl("section",{cls:"mdbase-editor-section"});d.createEl("h3",{text:"Membership"});let f=Nt(d,"Path glob",n.matchPathGlob,E=>{n.matchPathGlob=E,this.markDirty()},{placeholder:"Projects/**/*.md"});f.disabled=i;let p=Nt(d,"Fields present",n.matchFieldsPresent,E=>{n.matchFieldsPresent=E,this.markDirty()},{description:"Comma-separated frontmatter keys."});p.disabled=i;let m=Nt(d,"Where",n.matchWhere,E=>{n.matchWhere=E,this.markDirty()},{multiline:!0,description:"YAML predicate, including contains and nested equality conditions.",placeholder:`tags: + contains: task`});m.disabled=i;let h=t.createEl("section",{cls:"mdbase-editor-section"}),y=h.createDiv({cls:"mdbase-section-header"});y.createEl("h3",{text:"Fields"});let b=y.createEl("button",{text:"Add field"});b.disabled=i,b.onclick=()=>{n.fields.push({name:"",definition:{type:"string"}}),this.markDirty(!0)};let g=h.createDiv({cls:"mdbase-fields"});for(let[E,O]of n.fields.entries())this.renderFieldRow(g,O,E,i);n.fields.length||g.createDiv({cls:"mdbase-empty-list",text:"No fields declared."});let _=t.createEl("section",{cls:"mdbase-editor-section"});_.createEl("h3",{text:"Placement"});let k=Nt(_,"Path pattern",n.pathPattern,E=>{n.pathPattern=E,this.markDirty()},{placeholder:"Notes/{title}.md"});k.disabled=i;let v=t.createEl("section",{cls:"mdbase-editor-section mdbase-change-review"});if(v.createEl("h3",{text:"Change review"}),!this.dirty)v.createEl("p",{text:"No pending changes."});else{let E=v.createEl("ul");for(let O of oC(this.originalModel,n))E.createEl("li",{text:O})}}renderFieldRow(t,n,i,s){this.renderFieldDefinition(t,n.definition,{name:n.name,nameLabel:`Field ${i+1} name`,onNameInput:o=>{n.name=o,this.markDirty()},required:n.definition.required===!0,onRequiredChange:o=>{n.definition.required=o,this.markDirty()},onRemove:()=>{var o;(o=this.model)==null||o.fields.splice(i,1),this.markDirty(!0)},readOnly:s,depth:0})}renderFieldDefinition(t,n,i){var u;let s=t.createDiv({cls:"mdbase-field-node"});s.setAttr("data-depth",String(i.depth));let o=s.createDiv({cls:"mdbase-field-row"});if(i.staticLabel)o.createDiv({cls:"mdbase-field-role",text:i.staticLabel});else{let d=o.createEl("input",{type:"text",cls:"mdbase-field-name-control"});d.setAttr("aria-label",i.nameLabel),d.placeholder="fieldName",d.value=(u=i.name)!=null?u:"",d.disabled=i.readOnly,i.onNameInput&&(d.oninput=()=>{var f;return(f=i.onNameInput)==null?void 0:f.call(i,d.value)}),i.onNameCommit&&(d.onchange=()=>{var f;return(f=i.onNameCommit)==null?void 0:f.call(i,d.value,d)})}let a=o.createEl("select",{cls:"mdbase-field-type-control"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} type`);for(let d of iC){let f=d==="any"?"Any value":d[0].toUpperCase()+d.slice(1);a.createEl("option",{value:d,text:f})}a.value=Jw(n),a.disabled=i.readOnly,a.onchange=()=>{n.type=a.value,a.value==="list"&&!Cn(n.items)&&(n.items={type:"string"}),a.value==="object"&&!Cn(n.fields)&&(n.fields={}),a.value==="enum"&&!Array.isArray(n.values)&&(n.values=[]),this.markDirty(!0)};let c=o.createEl("input",{type:"text",cls:"mdbase-field-description-control"});if(c.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} description`),c.placeholder="Description",c.value=typeof n.description=="string"?n.description:"",c.disabled=i.readOnly,c.oninput=()=>{c.value?n.description=c.value:delete n.description,this.markDirty()},i.onRequiredChange){let d=o.createEl("label",{cls:"mdbase-field-required"}),f=d.createEl("input",{type:"checkbox"});f.checked=i.required===!0,f.disabled=i.readOnly,f.onchange=()=>{var p;return(p=i.onRequiredChange)==null?void 0:p.call(i,f.checked)},d.createSpan({text:"Required"})}if(i.onRemove){let d=o.createEl("button",{cls:"mdbase-field-remove"});d.setAttr("aria-label",`Remove ${i.name||i.staticLabel||"field"}`),(0,Ae.setIcon)(d,"trash-2"),d.disabled=i.readOnly,d.onclick=i.onRemove}let l=Jw(n);l==="enum"&&this.renderEnumFieldDetails(s,n,i),l==="link"&&this.renderLinkFieldDetails(s,n,i),l==="list"&&this.renderListFieldDetails(s,n,i),l==="object"&&this.renderObjectFieldDetails(s,n,i)}renderEnumFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=s.createEl("label",{text:"Allowed values"}),a=s.createEl("input",{type:"text"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Enum"} allowed values`),a.placeholder="draft, published, archived",a.value=Array.isArray(n.values)?n.values.map(String).join(", "):"",a.disabled=i.readOnly,a.oninput=()=>{n.values=a.value.split(",").map(c=>c.trim()).filter(Boolean),this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`}renderLinkFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-details mdbase-field-options"}),o=s.createEl("label",{text:"Target type"}),a=s.createEl("input",{type:"text"});a.setAttr("aria-label",`${i.name||i.staticLabel||"Link"} target type`),a.placeholder="Any type",a.value=typeof n.target=="string"?n.target:"",a.disabled=i.readOnly,a.oninput=()=>{a.value.trim()?n.target=a.value.trim():delete n.target,this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`;let c=s.createEl("label",{cls:"mdbase-field-required"}),l=c.createEl("input",{type:"checkbox"});l.checked=n.validate_exists===!0,l.disabled=i.readOnly,l.onchange=()=>{n.validate_exists=l.checked,this.markDirty()},c.createSpan({text:"Validate target exists"})}renderListFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-children"});s.createDiv({cls:"mdbase-field-children-label",text:"List items"});let o=Cn(n.items)?n.items:{type:"any"};!Cn(n.items)&&!i.readOnly&&(n.items=o),this.renderFieldDefinition(s,o,{staticLabel:"Item",nameLabel:"List item",readOnly:i.readOnly,depth:i.depth+1})}renderObjectFieldDetails(t,n,i){let s=t.createDiv({cls:"mdbase-field-children"}),o=s.createDiv({cls:"mdbase-field-children-header"});o.createDiv({cls:"mdbase-field-children-label",text:"Object fields"});let a=o.createEl("button",{text:"Add nested field"});a.disabled=i.readOnly;let c=Cn(n.fields)?n.fields:{};!Cn(n.fields)&&!i.readOnly&&(n.fields=c),a.onclick=()=>{let d=sC(c);Yw(c,d,{type:"string"}),this.markDirty(!0)};let l=s.createDiv({cls:"mdbase-nested-fields"}),u=Object.entries(c).filter(d=>Cn(d[1]));if(!u.length){l.createDiv({cls:"mdbase-empty-list",text:"No nested fields."});return}for(let[d,f]of u){let p=d;this.renderFieldDefinition(l,f,{name:p,nameLabel:`${p} nested field name`,onNameCommit:(m,h)=>{let y=m.trim();if(!y){new Ae.Notice("Nested field name is required."),h.value=p;return}if(y!==p&&Object.prototype.hasOwnProperty.call(c,y)){new Ae.Notice(`Nested field already exists: ${y}`),h.value=p;return}y!==p&&(delete c[p],Yw(c,y,f),p=y,this.markDirty())},required:f.required===!0,onRequiredChange:m=>{f.required=m,this.markDirty()},onRemove:()=>{delete c[p],this.markDirty(!0)},readOnly:i.readOnly,depth:i.depth+1})}}renderYamlEditor(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section mdbase-yaml-section"});i.createEl("h3",{text:"Canonical type document"}),i.createEl("p",{cls:"mdbase-form-description",text:"Unknown v0.3 extensions are preserved. Invalid YAML is never normalized or saved."});let s=i.createEl("textarea",{cls:"mdbase-yaml-editor"});s.setAttr("aria-label","Type definition YAML"),s.value=this.yamlDraft,s.disabled=n,s.spellcheck=!1,s.oninput=()=>{this.yamlDraft=s.value,this.markDirty(!1)}}renderSync(t){var f,p,m,h,y,b;let n=t.createDiv({cls:"mdbase-sync-document"}),i=n.createDiv({cls:"mdbase-document-header"});i.createEl("h2",{text:"Sync"}),i.createEl("p",{text:"Connect this vault to a collection authority and keep ordinary Markdown mirrored locally."});let s=this.host.getMirrorProfile();if(!s){this.renderEnrollment(n);return}let o=n.createEl("section",{cls:"mdbase-editor-section"});o.createEl("h3",{text:"Collection authority"});let a=o.createDiv({cls:"mdbase-status-list"});if(je(a,"Name",s.name),je(a,"Collection",s.collectionId),je(a,"Access",s.mode==="read_write"?"Read and write":"Read only"),je(a,"Provider",s.syncUrl),je(a,"State",(p=(f=this.mirrorStatus)==null?void 0:f.state.replace(/_/g," "))!=null?p:"Checking"),je(a,"Last synced",(h=(m=this.mirrorStatus)==null?void 0:m.last_synced_at)!=null?h:"Never"),this.mirrorProgress){let g=this.mirrorProgress.total,_=o.createEl("progress");_.max=g!=null?g:1,_.value=g==null?0:this.mirrorProgress.completed,g==null&&_.removeAttribute("value"),o.createDiv({cls:"mdbase-progress-label",text:`${this.mirrorProgress.phase}: ${this.mirrorProgress.completed}${g==null?"":` of ${g}`}`})}let c=o.createDiv({cls:"mdbase-actions"}),l=c.createEl("button",{text:"Preview"});l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{this.mirrorPreview=await this.host.connectSync.preview(),this.render()});let u=c.createEl("button",{text:"Sync now"});u.addClass("mod-cta"),u.disabled=this.busy,u.onclick=()=>void this.perform(async()=>{this.mirrorStatus=await this.host.connectSync.sync(g=>{this.mirrorProgress=g,this.render()}),this.mirrorProgress=null,this.transientMessage="Sync completed and the local checkpoint was verified.",await this.refresh(!0)}),this.mirrorPreview&&this.renderMirrorPreview(n,this.mirrorPreview),(y=this.mirrorStatus)!=null&&y.conflicts.length&&this.renderConflicts(n,this.mirrorStatus),(b=this.mirrorStatus)!=null&&b.local_issues.length&&this.renderLocalMirrorIssues(n,this.mirrorStatus);let d=n.createEl("section",{cls:"mdbase-editor-section"});d.createEl("h3",{text:"Mirror ownership"}),d.createEl("p",{text:"Use this plugin as the only sync owner for this vault. Obsidian protects concurrent operations inside the app; a separate desktop mirror process cannot share that mobile-safe lease."})}renderEnrollment(t){if(this.schema||this.host.connectSync.getAdoptionMarker()){this.renderLocalAdoption(t);return}let n=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});if(n.createEl("h3",{text:"Connect collection authority"}),n.createEl("p",{text:"Connect will open an approval page. Credentials are stored in Obsidian's secret store and never written into this vault."}),this.enrollmentVerification){let d=n.createDiv({cls:"mdbase-approval-link"});d.createSpan({text:"Approval page: "});let f=d.createEl("a",{text:"Open Connect",href:this.enrollmentVerification});f.setAttr("target","_blank"),f.setAttr("rel","noopener noreferrer")}let i="https://connect.mdbase.dev",s="Obsidian",o="",a="read_write";Nt(n,"Connect URL",i,d=>{i=d},{placeholder:"https://connect.mdbase.dev"}),Nt(n,"Mirror name",s,d=>{s=d}),Nt(n,"Collection ID",o,d=>{o=d},{description:"Optional. Leave blank to choose during approval."});let c=n.createDiv({cls:"mdbase-form-row"});c.createEl("label",{text:"Access"});let l=c.createEl("select");l.createEl("option",{value:"read_write",text:"Read and write"}),l.createEl("option",{value:"read_only",text:"Read only"}),l.value=a,l.onchange=()=>{a=l.value==="read_only"?"read_only":"read_write"};let u=n.createEl("button",{text:"Open Connect approval"});u.addClass("mod-cta"),u.disabled=this.busy,u.onclick=()=>void this.perform(async()=>{var f;(f=this.enrollmentAbort)==null||f.abort();let d=new AbortController;this.enrollmentAbort=d;try{await this.host.connectSync.enroll({controlUrl:i,mirrorName:s,mode:a,...o.trim()?{collectionId:o.trim()}:{}},{signal:d.signal,onVerification:p=>{this.enrollmentVerification=p.verificationUri,this.transientMessage="Approve the mirror in the Connect page. This view will keep waiting securely.",window.open(p.verificationUri,"_blank","noopener,noreferrer"),this.render()},onStatus:p=>{this.transientMessage=p.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying enrollment (attempt ${p.attempt}).`,this.render()}}),this.enrollmentVerification="",this.transientMessage="Mirror enrolled. Preview before the first sync.",await this.refreshMirrorStatus(),this.render()}finally{this.enrollmentAbort===d&&(this.enrollmentAbort=null)}})}renderLocalAdoption(t){var u,d;let n=this.host.connectSync.getAdoptionMarker(),i=t.createEl("section",{cls:"mdbase-editor-section mdbase-enrollment"});i.createEl("h3",{text:"Host this local collection"}),i.createEl("p",{text:n?"This vault has a durable adoption checkpoint. Resume it without creating another hosted collection.":"Hosted mdbase will adopt an exact snapshot and become the collection authority. This vault will then continue as a read-write mirror."});let s=this.enrollmentVerification||(n==null?void 0:n.session.verificationUri);if(s){let f=i.createDiv({cls:"mdbase-approval-link"});f.createSpan({text:"Approval page: "});let p=f.createEl("a",{text:"Open Connect",href:s});p.setAttr("target","_blank"),p.setAttr("rel","noopener noreferrer")}let o=(u=n==null?void 0:n.session.controlUrl)!=null?u:"https://connect.mdbase.dev",a=(d=n==null?void 0:n.session.requested.mirrorName)!=null?d:"Obsidian";if(!n)Nt(i,"Connect URL",o,f=>{o=f},{placeholder:"https://connect.mdbase.dev"}),Nt(i,"Mirror name",a,f=>{a=f});else{let f=i.createDiv({cls:"mdbase-status-list"});je(f,"Collection",n.session.requested.collectionId),je(f,"Phase",n.phase.replace(/_/g," ")),je(f,"Connect",n.session.controlUrl)}let c=i.createDiv({cls:"mdbase-inline-message"});c.createEl("strong",{text:"Authority cut-over: "}),c.appendText("once final staging begins, plugin-managed local edits pause until hosted activation is confirmed. The checkpoint survives app restarts and uncertain network responses.");let l=i.createEl("button",{text:n?"Resume adoption":"Approve and host collection"});if(l.addClass("mod-cta"),l.disabled=this.busy,l.onclick=()=>void this.perform(async()=>{var h;(h=this.enrollmentAbort)==null||h.abort();let f=new AbortController;this.enrollmentAbort=f;let p=y=>{this.enrollmentVerification=y.verificationUri,this.transientMessage="Approve the authority move in Connect, then return here. This checkpoint is safe to resume.",this.render()},m=y=>{this.transientMessage=y.state==="waiting_for_approval"?"Waiting for authority-move approval in Connect\u2026":`Connect is retrying (attempt ${y.attempt}).`,this.render()};try{n?await this.host.connectSync.resumeAdoption({signal:f.signal,onVerification:p,onStatus:m}):await this.host.connectSync.adoptLocalCollection({controlUrl:o,mirrorName:a},{signal:f.signal,onVerification:p,onStatus:m}),this.enrollmentVerification="",this.transientMessage="Hosted mdbase is authoritative and this vault is now its read-write mirror.",await this.refresh(!0)}finally{this.enrollmentAbort===f&&(this.enrollmentAbort=null)}}),n&&!["activating","adopted"].includes(n.phase)){let f=i.createEl("button",{text:"Cancel adoption"});f.disabled=this.busy,f.onclick=()=>void this.perform(async()=>{await this.host.connectSync.cancelAdoption(),this.enrollmentVerification="",this.transientMessage="Collection adoption cancelled. This vault remains the local authority.",await this.refresh(!0)})}}renderMirrorPreview(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Sync preview"});let s=i.createDiv({cls:"mdbase-status-list"});if(je(s,"Download documents",String(n.download_documents)),je(s,"Upload documents",String(n.upload_documents)),je(s,"Unchanged documents",String(n.unchanged_documents)),n.collisions.length){i.createDiv({cls:"mdbase-inline-error",text:`${n.collisions.length} path collision${n.collisions.length===1?"":"s"} must be resolved before sync.`});let o=i.createEl("ul");for(let a of n.collisions.slice(0,100))o.createEl("li",{text:a})}if(n.local_issues.length){i.createDiv({cls:"mdbase-inline-error",text:`${n.local_issues.length} local file${n.local_issues.length===1?"":"s"} cannot be uploaded until its frontmatter is fixed.`});let o=i.createEl("ul");for(let a of n.local_issues.slice(0,100))o.createEl("li",{text:`${a.path}: ${a.message}`})}}renderConflicts(t,n){var s;let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Conflicts"});for(let o of n.conflicts){let a=i.createDiv({cls:"mdbase-conflict-row"}),c=a.createDiv();c.createEl("strong",{text:(s=o.path)!=null?s:o.record_id}),c.createDiv({text:o.message});let l=a.createDiv({cls:"mdbase-actions"});for(let u of["local","remote"]){let d=l.createEl("button",{text:u==="local"?"Keep local":"Use remote"});d.disabled=this.busy,d.onclick=()=>void this.perform(async()=>{this.mirrorStatus=await this.host.connectSync.resolveConflict(o.record_id,u),this.render()})}}}renderLocalMirrorIssues(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Local files needing attention"}),i.createEl("p",{text:"These files remain untouched and unsynced. Other valid Markdown continues to synchronize."});for(let s of n.local_issues){let o=i.createDiv({cls:"mdbase-conflict-row"}),a=o.createDiv();a.createEl("strong",{text:s.path}),a.createDiv({text:s.message});let l=o.createDiv({cls:"mdbase-actions"}).createEl("button",{text:"Open file"});l.disabled=this.busy,l.onclick=()=>void this.host.openFileByPath(s.path)}}renderIssues(t){var b;let n=t.createDiv({cls:"mdbase-issues-document"}),i=this.host.getIssues(),s=new Set(i.map(g=>g.path)).size,o=n.createDiv({cls:"mdbase-document-header"}),a=o.createDiv();a.createEl("h2",{text:"Issues"}),a.createEl("p",{text:i.length?`${i.length.toLocaleString()} validation issues in ${s.toLocaleString()} files.`:"The collection has no current validation issues."});let c=o.createEl("button",{text:"Validate collection"});c.disabled=this.busy,c.onclick=()=>void this.perform(async()=>{await this.host.validateCollection(),this.render()});let l=n.createDiv({cls:"mdbase-issue-controls"}),u=l.createEl("select");u.setAttr("aria-label","Issue severity"),u.createEl("option",{value:"all",text:"All severities"}),u.createEl("option",{value:"error",text:"Errors"}),u.createEl("option",{value:"warn",text:"Warnings"}),u.value=this.issueSeverity,u.onchange=()=>{this.issueSeverity=u.value==="error"||u.value==="warn"?u.value:"all",this.issueLimit=250,this.render()};let d=l.createEl("input",{type:"search"});d.setAttr("aria-label","Filter issues"),d.placeholder="Filter by path, code, field, or message",d.value=this.issueQuery,d.oninput=()=>{this.issueQuery=d.value,this.issueLimit=250,this.render();let g=this.containerEl.querySelector(".mdbase-issue-controls input[type='search']");g==null||g.focus(),g==null||g.setSelectionRange(g.value.length,g.value.length)};let f=this.issueQuery.trim().toLowerCase(),p=i.filter(g=>{var _;return this.issueSeverity!=="all"&&g.severity!==this.issueSeverity?!1:f?`${g.path} ${g.code} ${(_=g.field)!=null?_:""} ${g.message}`.toLowerCase().includes(f):!0}),m=new Set(p.map(g=>g.path)).size;if(n.createDiv({cls:"mdbase-issues-summary",text:p.length===i.length?`Showing ${Math.min(p.length,this.issueLimit).toLocaleString()} of ${p.length.toLocaleString()} issues`:`${p.length.toLocaleString()} matching issues in ${m.toLocaleString()} files`}),!p.length){n.createDiv({cls:"mdbase-empty-state",text:"No validation issues."});return}let h=p.slice(0,this.issueLimit),y=new Map;for(let g of h)y.set(g.path,[...(b=y.get(g.path))!=null?b:[],g]);for(let[g,_]of y){let k=n.createEl("section",{cls:"mdbase-issue-group"}),v=k.createDiv({cls:"mdbase-issue-group-header"}),E=v.createEl("button",{cls:"mdbase-issue-file-button"});(0,Ae.setIcon)(E.createSpan({cls:"mdbase-issue-file-icon"}),"file-text"),E.createSpan({cls:"mdbase-issue-file-path",text:g}),E.onclick=()=>void this.host.openFileByPath(g),v.createSpan({cls:"mdbase-issue-file-count",text:`${_.length} ${_.length===1?"issue":"issues"}`});for(let O of _){let w=k.createEl("button",{cls:"mdbase-issue-row"});w.setAttr("data-severity",O.severity),w.setAttr("aria-label",`${O.severity==="warn"?"Warning":"Error"}: ${O.message}`),w.createSpan({cls:"mdbase-issue-indicator"}).setAttr("aria-hidden","true");let x=w.createDiv({cls:"mdbase-issue-metadata"});x.createEl("code",{text:O.code}),x.createDiv({cls:"mdbase-issue-context",text:`${O.severity==="warn"?"Warning":"Error"}${O.field?` \xB7 ${O.field}`:""}`}),w.createDiv({cls:"mdbase-issue-row-message",text:O.message}),w.onclick=()=>void this.host.openFileByPath(O.path,O.field)}}if(p.length>h.length){let g=n.createEl("button",{cls:"mdbase-load-more",text:`Load ${Math.min(250,p.length-h.length)} more`});g.onclick=()=>{this.issueLimit+=250,this.render()}}}async selectType(t,n=!0){if(n&&this.dirty&&t!==this.selectedPath){new Ae.Notice("Save or discard the current type changes before switching.");return}let i=await this.host.loadTypeModel(t);this.selectedPath=t,this.model=i,this.originalModel=Xf(i),this.yamlDraft=`${wt(Xw(i),i.body)} +`,this.dirty=!1,this.editorMode="design",this.render()}createType(){if(this.dirty){new Ae.Notice("Save or discard the current type changes before creating another type.");return}let t=Yf();this.selectedPath=null,this.model=t,this.originalModel=null,this.yamlDraft=`${wt(lo(t),t.body)} +`,this.dirty=!0,this.editorMode="design",this.render()}switchEditorMode(t){if(!(!this.model||t===this.editorMode)){if(t==="yaml")try{this.yamlDraft=`${wt(Xw(this.model),this.model.body)} +`}catch(n){new Ae.Notice(n instanceof Error?n.message:String(n));return}else if(!this.readYamlDraftIntoModel())return;this.editorMode=t,this.render()}}readYamlDraftIntoModel(){var n,i;let t=Ct(this.yamlDraft);if(!t.hasFrontmatter||t.error)return new Ae.Notice(`Invalid type YAML: ${(n=t.error)!=null?n:"frontmatter is missing"}`),!1;if(t.frontmatter.kind!=="mdbase.type")return new Ae.Notice("Canonical v0.3 type YAML requires kind: mdbase.type."),!1;try{return this.model=Ic(t.frontmatter,t.body,((i=this.model)==null?void 0:i.name)||"type"),!0}catch(s){return new Ae.Notice(s instanceof Error?s.message:String(s)),!1}}async saveCurrentType(){if(!(!this.model||this.model.specProfile!=="v0.3"||this.model.readOnlyReason)&&!(this.editorMode==="yaml"&&!this.readYamlDraftIntoModel())){if(!this.model.name.trim()){new Ae.Notice("Type name is required.");return}await this.perform(async()=>{let t=await this.host.saveTypeModel(this.model,this.selectedPath);this.selectedPath=t.path,this.originalModel=Xf(this.model),this.dirty=!1,this.transientMessage=`Saved ${t.path}.`,await this.refresh(!0)})}}markDirty(t=!1){var o,a;if(this.dirty=!0,t){this.render();return}let n=this.containerEl.querySelector(".mdbase-editor-title-line");n&&!n.querySelector(".mdbase-dirty")&&n.createSpan({cls:"mdbase-dirty",text:"Unsaved"});let i=this.containerEl.querySelector(".mdbase-editor-actions .mod-cta");i&&((o=this.model)==null?void 0:o.specProfile)==="v0.3"&&!this.model.readOnlyReason&&((a=this.host.getMirrorProfile())==null?void 0:a.mode)!=="read_only"&&(i.disabled=!1);let s=this.containerEl.querySelector(".mdbase-change-review");if(s){let c=s.querySelector("p");c&&c.setText("Pending changes. Review details after leaving the current field.")}}async refreshMirrorStatus(){try{this.mirrorStatus=await this.host.connectSync.status()}catch(t){this.mirrorStatus=null,this.transientMessage=t instanceof Error?t.message:String(t)}}async perform(t){if(!this.busy){this.busy=!0,this.transientMessage="",this.render();try{await t()}catch(n){let i=n instanceof Error?n.message:String(n);this.transientMessage=i,new Ae.Notice(i)}finally{this.busy=!1,this.render()}}}};function Xw(r){var e;return r.specProfile==="v0.3"&&!r.readOnlyReason?lo(r):Xf((e=r.originalFrontmatter)!=null?e:{name:r.name,fields:Object.fromEntries(r.fields.map(t=>[t.name,t.definition]))})}var Mi="mdbase-issues-view",cC={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null};function lC(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return e.version===1&&typeof e.syncUrl=="string"&&typeof e.controlUrl=="string"&&typeof e.collectionId=="string"&&typeof e.replicaId=="string"&&(e.mode==="read_only"||e.mode==="read_write")&&typeof e.name=="string"&&typeof e.enrollmentId=="string"&&typeof e.accessTokenExpiresAt=="string"}function dC(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var uo=class extends D.Modal{constructor(t,n,i="",s=""){super(t);this.resolvePromise=null;this.settled=!1;this.title=n,this.placeholder=i,this.defaultValue=s}openAndGetValue(){return new Promise(t=>{this.settled=!1,this.resolvePromise=t,this.open()})}onOpen(){let{contentEl:t}=this;t.empty(),t.createEl("h3",{text:this.title});let n=t.createEl("input",{type:"text"});n.placeholder=this.placeholder,n.value=this.defaultValue,n.addClass("prompt-input");let i=t.createDiv({cls:"modal-button-container"}),s=i.createEl("button",{text:"Cancel"}),o=i.createEl("button",{text:"OK"});o.addClass("mod-cta"),s.onclick=()=>{this.finish(null),this.close()},o.onclick=()=>{this.finish(n.value.trim()),this.close()},n.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),this.finish(n.value.trim()),this.close()),a.key==="Escape"&&(a.preventDefault(),this.finish(null),this.close())}),window.setTimeout(()=>n.focus(),0)}onClose(){this.settled||this.finish(null),this.contentEl.empty()}finish(t){var n;this.settled||(this.settled=!0,(n=this.resolvePromise)==null||n.call(this,t),this.resolvePromise=null)}},Qf=class extends D.SuggestModal{constructor(t,n,i){super(t);this.resultHandled=!1;this.typeDefs=[...n].sort((s,o)=>s.name.localeCompare(o.name)),this.onResult=i,this.setPlaceholder("Type to search..."),this.setInstructions([{command:"\u2191\u2193",purpose:"navigate"},{command:"\u21B5",purpose:"select"},{command:"esc",purpose:"cancel"}]),this.containerEl.addClass("mdbase-type-picker-modal"),this.titleEl.setText("Select type definition")}getSuggestions(t){let n=t.trim().toLowerCase();return n?this.typeDefs.filter(i=>{var a,c,l;let s=(c=(a=i.match)==null?void 0:a.path_glob)!=null?c:"";return`${i.name} ${(l=i.display_name_key)!=null?l:""} ${i.filePath} ${s}`.toLowerCase().includes(n)}).slice(0,100):this.typeDefs.slice(0,100)}renderSuggestion(t,n){var o,a;let i=n.createDiv({cls:"mdbase-type-picker-suggestion"});i.createDiv({cls:"mdbase-type-picker-name",text:t.name});let s=i.createDiv({cls:"mdbase-type-picker-meta"});s.createSpan({cls:"mdbase-type-picker-path",text:t.filePath}),s.createSpan({cls:"mdbase-type-picker-count",text:`${Object.keys((o=t.fields)!=null?o:{}).length} fields`}),(a=t.match)!=null&&a.path_glob&&i.createDiv({cls:"mdbase-type-picker-match",text:`match: ${t.match.path_glob}`})}onChooseSuggestion(t){this.resultHandled=!0,this.onResult({type:"selected",typeDef:t})}onClose(){window.setTimeout(()=>{this.resultHandled||this.onResult({type:"cancelled"})},0),super.onClose()}};function uC(r,e){return new Promise(t=>{new Qf(r,e,i=>{if(i.type==="selected"){t(i.typeDef);return}t(null)}).open()})}var Zf=class extends D.ItemView{constructor(t,n){super(t);this.severityFilter="all";this.query="";this.plugin=n}getViewType(){return Mi}getDisplayText(){return"mdbase issues"}getIcon(){return"shield-alert"}async onOpen(){this.containerEl.empty(),this.containerEl.addClass("mdbase-issues-view"),this.render()}render(){var m;let t=this.containerEl;t.empty(),t.addClass("mdbase-issues-view");let n=t.createDiv({cls:"mdbase-issues-header"});n.createEl("h3",{text:"mdbase Issues"});let s=n.createDiv({cls:"mdbase-issues-header-actions"}).createEl("button",{text:"Refresh"});s.addClass("mod-cta"),s.onclick=()=>{this.plugin.runCollectionValidation(!1)};let o=t.createDiv({cls:"mdbase-issues-controls"}),a=o.createEl("select");a.addClass("mdbase-issues-severity"),a.createEl("option",{value:"all",text:"All severities"}),a.createEl("option",{value:"error",text:"Errors only"}),a.createEl("option",{value:"warn",text:"Warnings only"}),a.value=this.severityFilter,a.onchange=()=>{let h=a.value;(h==="error"||h==="warn"||h==="all")&&(this.severityFilter=h),this.render()};let c=o.createEl("input",{type:"search"});c.addClass("mdbase-issues-query"),c.placeholder="Filter by path, code, message, field",c.value=this.query,c.oninput=()=>{this.query=c.value,this.render()};let l=this.plugin.getIssues(),u=this.query.trim().toLowerCase(),d=l.filter(h=>{var b;return this.severityFilter!=="all"&&h.severity!==this.severityFilter?!1:u?`${h.path} ${h.code} ${h.message} ${(b=h.field)!=null?b:""}`.toLowerCase().includes(u):!0}),f=d.slice(0,500);if(t.createDiv({cls:"mdbase-issues-count",text:d.length>f.length?`Showing ${f.length} of ${d.length} matching issues`:d.length===l.length?`${d.length} issue${d.length===1?"":"s"}`:`${d.length} of ${l.length} issue${l.length===1?"":"s"}`}),d.length===0){t.createDiv({cls:"mdbase-empty",text:l.length===0?"No validation issues.":"No issues match current filters."});return}let p=new Map;for(let h of f){let y=(m=p.get(h.path))!=null?m:[];y.push(h),p.set(h.path,y)}for(let[h,y]of p.entries()){t.createDiv({cls:"mdbase-issue-file",text:h});for(let b of y){let g=t.createDiv({cls:"mdbase-issue-item"});g.setAttr("data-severity",b.severity),g.createDiv({cls:"mdbase-issue-code",text:`${b.severity.toUpperCase()} \xB7 ${b.code}${b.field?` \xB7 ${b.field}`:""}`}),g.createDiv({cls:"mdbase-issue-message",text:b.message});let _=g.createDiv({cls:"mdbase-issue-actions"}),k=_.createEl("button",{text:b.field?"Open field":"Open file"});k.onclick=E=>{E.stopPropagation(),this.plugin.openIssue(b)};let v=this.plugin.getQuickFixLabel(b);if(v){let E=_.createEl("button",{text:v});E.onclick=O=>{O.stopPropagation(),this.plugin.applyQuickFix(b)}}g.onclick=()=>{this.plugin.openIssue(b)}}}}},ep=class extends D.PluginSettingTab{constructor(e,t){super(e,t),this.plugin=t}display(){let{containerEl:e}=this;e.empty(),e.createEl("h2",{text:"mdbase settings"}),new D.Setting(e).setName("Validate on save").setDesc("Run mdbase validation when a markdown file is modified.").addToggle(t=>t.setValue(this.plugin.settings.validateOnSave).onChange(async n=>{this.plugin.settings.validateOnSave=n,await this.plugin.saveSettings()})),new D.Setting(e).setName("Validate on file open").setDesc("Validate the active note when opened.").addToggle(t=>t.setValue(this.plugin.settings.validateOnOpen).onChange(async n=>{this.plugin.settings.validateOnOpen=n,await this.plugin.saveSettings()})),new D.Setting(e).setName("Show notices on save").setDesc("Display a notice when save-time validation finds issues.").addToggle(t=>t.setValue(this.plugin.settings.showNoticeOnSave).onChange(async n=>{this.plugin.settings.showNoticeOnSave=n,await this.plugin.saveSettings()})),new D.Setting(e).setName("Allow local application interoperability").setDesc("Allow installed Obsidian plugins to exchange validated mdbase events and actions in this vault. Contracts establish compatibility; this switch is the separate user grant.").addToggle(t=>t.setValue(this.plugin.settings.interopEnabled).onChange(async n=>{this.plugin.settings.interopEnabled=n,await this.plugin.saveSettings()}))}},Tc=class extends D.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.sortedIssuesCache=null;this.schemaCache=null;this.schemaLoadPromise=null;this.pendingSaveValidations=new Map;this.saveValidationDebounceMs=250;this.connectSync=new kc(t,{getMirrorProfile:()=>this.getMirrorProfile(),saveMirrorProfile:async i=>{this.settings.mirrorProfile=i,await this.saveSettings()}}),this.interopBridge=new ua(t,()=>{var i;return((i=this.settings)==null?void 0:i.interopEnabled)===!0}),this.api={apiVersion:1,interop:this.interopBridge,getInteropStatus:()=>{var i;return{enabled:((i=this.settings)==null?void 0:i.interopEnabled)===!0,profileVersion:"0.1"}}}}async onload(){await this.loadSettings(),await this.connectSync.initialize(),(0,D.addIcon)(Ci,Gw),this.statusBarEl=this.addStatusBarItem(),this.updateStatusBar(),this.registerView(Mn,n=>new Oc(n,this)),this.registerView(Mi,n=>new Zf(n,this)),this.addSettingTab(new ep(this.app,this)),this.addRibbonIcon(Ci,"Open mdbase",()=>void this.openWorkspace()),this.addCommand({id:"mdbase-open",name:"mdbase: Open workspace",callback:()=>void this.openWorkspace()}),this.addCommand({id:"mdbase-initialize-collection",name:"mdbase: Initialize collection",callback:()=>void this.initializeCollectionCommand()}),this.addCommand({id:"mdbase-create-type",name:"mdbase: Create type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-type",name:"mdbase: Edit type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-edit-current-type",name:"mdbase: Edit current type definition",callback:()=>void this.openWorkspace("types")}),this.addCommand({id:"mdbase-create-note-from-type",name:"mdbase: Create note from type",callback:()=>void this.createNoteFromTypeCommand()}),this.addCommand({id:"mdbase-validate-current-note",name:"mdbase: Validate current note",callback:()=>void this.validateCurrentNoteCommand()}),this.addCommand({id:"mdbase-validate-collection",name:"mdbase: Validate collection",callback:()=>void this.runCollectionValidation(!0)}),this.addCommand({id:"mdbase-open-issues-view",name:"mdbase: Open issues view",callback:()=>void this.openWorkspace("issues")}),this.addCommand({id:"mdbase-sync",name:"mdbase: Sync collection authority",callback:()=>void this.syncHostedCollectionCommand()}),this.addCommand({id:"mdbase-open-sync",name:"mdbase: Open sync",callback:()=>void this.openWorkspace("sync")}),this.registerEvent(this.app.vault.on("modify",n=>{n instanceof D.TFile&&this.onVaultModify(n)})),this.registerEvent(this.app.vault.on("rename",(n,i)=>{n instanceof D.TFile&&this.onVaultRename(n,i)})),this.registerEvent(this.app.vault.on("delete",n=>{n instanceof D.TFile&&this.onVaultDelete(n)})),this.registerEvent(this.app.vault.on("create",n=>{n instanceof D.TFile&&this.onVaultCreate(n)})),this.registerEvent(this.app.workspace.on("file-open",n=>{this.settings.validateOnOpen&&(!(n instanceof D.TFile)||n.extension!=="md"||this.validateFileAndStore(n,"open"))}));let t=this.app.workspace.getActiveFile();t&&this.settings.validateOnOpen&&this.validateFileAndStore(t,"open")}async onunload(){await this.interopBridge.dispose(),this.app.workspace.getLeavesOfType(Mn).forEach(t=>t.detach()),this.app.workspace.getLeavesOfType(Mi).forEach(t=>t.detach()),this.clearAllPendingSaveValidations()}async loadSettings(){this.settings=Object.assign({},cC,await this.loadData()),lC(this.settings.mirrorProfile)||(this.settings.mirrorProfile=null)}async saveSettings(){await this.saveData(this.settings)}getIssues(){var t;return(t=this.sortedIssuesCache)!=null||(this.sortedIssuesCache=Array.from(this.issueMap.values()).flat().sort((n,i)=>n.path.localeCompare(i.path)||n.severity.localeCompare(i.severity)||n.code.localeCompare(i.code))),this.sortedIssuesCache}getMirrorProfile(){return this.settings.mirrorProfile?{...this.settings.mirrorProfile}:null}async loadWorkspaceSchema(t=!1){return this.getConfigAndTypes(t)}async loadTypeModel(t){var s;let n=this.app.vault.getAbstractFileByPath((0,D.normalizePath)(t));if(!(n instanceof D.TFile))throw new Error(`Type file not found: ${t}`);let i=Ct(await this.app.vault.cachedRead(n));if(!i.hasFrontmatter||i.error)throw new Error(`Invalid type frontmatter: ${(s=i.error)!=null?s:"frontmatter is missing"}`);return Ic(i.frontmatter,i.body,n.basename)}async saveTypeModel(t,n){var a;if(this.connectSync.assertLocalAuthorityWritable(),((a=this.getMirrorProfile())==null?void 0:a.mode)==="read_only")throw new Error("This mirror has read-only access. Re-enroll it with write access before editing types.");let i=await ci(this.app.vault);if(!i)throw new Error("No mdbase.yaml found.");if(!i.spec_version.startsWith("0.3."))throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let s=n?this.app.vault.getAbstractFileByPath((0,D.normalizePath)(n)):null;if(s!=null&&!(s instanceof D.TFile))throw new Error(`Type file not found: ${n}`);let o=await this.writeTypeDefinition(i,t,s);return this.refreshWorkspaceViews(!0),o}async initializeCollection(){this.connectSync.assertLocalAuthorityWritable(),await this.initializeCollectionCommand(),this.refreshWorkspaceViews(!0)}async validateCollection(){await this.runCollectionValidation(!1)}analyzeMigration(){if(this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");return Hw(this.app.vault)}async applyMigration(t,n){var s,o;if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");let i=await Kw(this.app.vault,t,{allowLossy:n});if(!i.applied)throw new Error(i.restored?`Migration failed and all writes were rolled back. ${(s=i.error)!=null?s:""}`.trim():`Migration needs manual recovery. See ${i.manifestPath}. ${(o=i.error)!=null?o:""}`.trim());this.invalidateSchemaCache(),new D.Notice(`Migrated to mdbase v0.3. Recovery manifest: ${i.manifestPath}`),this.refreshWorkspaceViews(!0)}async openIssue(t){await this.openFileByPath(t.path,t.field)}getQuickFixLabel(t){return["unknown_field","schema_additional_properties"].includes(t.code)&&t.field?"Remove field":["missing_required","schema_required"].includes(t.code)&&t.field?"Add placeholder":null}async applyQuickFix(t){this.connectSync.assertLocalAuthorityWritable();let n=this.app.vault.getAbstractFileByPath(t.path);if(!(n instanceof D.TFile)){new D.Notice(`File not found: ${t.path}`);return}let i=await this.app.vault.cachedRead(n),s=Ct(i);if(s.error){new D.Notice(`Cannot apply quick fix: invalid frontmatter (${s.error})`);return}if(["unknown_field","schema_additional_properties"].includes(t.code)&&t.field){let o=ya(t.field);if(!(o in s.frontmatter)){new D.Notice(`Field '${o}' not found in frontmatter.`);return}delete s.frontmatter[o],await this.app.vault.modify(n,`${wt(s.frontmatter,s.body)} +`),new D.Notice(`Removed '${o}' from ${n.basename}`),await this.validateFileAndStore(n,"manual");return}if(["missing_required","schema_required"].includes(t.code)&&t.field){let o=ya(t.field);s.frontmatter[o]===void 0&&(s.frontmatter[o]="TODO");let a=s.hasFrontmatter?s.body:i;await this.app.vault.modify(n,`${wt(s.frontmatter,a)} +`),new D.Notice(`Added placeholder '${o}' to ${n.basename}`),await this.validateFileAndStore(n,"manual");return}new D.Notice("No quick fix available for this issue.")}async openFileByPath(t,n){let i=this.app.vault.getAbstractFileByPath(t);if(!(i instanceof D.TFile)){new D.Notice(`File not found: ${t}`);return}await this.app.workspace.getLeaf(!0).openFile(i),n&&this.revealFrontmatterField(i,n)}revealFrontmatterField(t,n){let i=this.app.workspace.getMostRecentLeaf();if(!i||!(i.view instanceof D.MarkdownView))return;let s=i.view;if(!(s.file instanceof D.TFile)||s.file.path!==t.path)return;let o=s.editor,a=o.lineCount();if(a<3)return;let c=ya(n),l=new RegExp(`^\\s*${dC(c)}\\s*:`);if(o.getLine(0).trim()==="---")for(let u=1;us.severity==="error").length,i=t.length-n;if(t.length===0){this.statusBarEl.setText("mdbase: no issues");return}this.statusBarEl.setText(`mdbase: ${n} error${n===1?"":"s"}, ${i} warning${i===1?"":"s"}`)}async openIssuesView(){var i;let t=this.app.workspace.getLeavesOfType(Mi)[0];if(t){this.app.workspace.revealLeaf(t),t.view.render();return}let n=(i=this.app.workspace.getRightLeaf(!1))!=null?i:this.app.workspace.getLeaf(!0);await n.setViewState({type:Mi,active:!0}),this.app.workspace.revealLeaf(n)}async openWorkspace(t="types"){let n=this.app.workspace.getLeavesOfType(Mn)[0];if(n){this.app.workspace.revealLeaf(n);let o=n.view;o.showDestination(t),await o.refresh();return}let i=this.app.workspace.getLeaf(!0);await i.setViewState({type:Mn,active:!0}),this.app.workspace.revealLeaf(i),i.view.showDestination(t)}refreshWorkspaceViews(t=!1){for(let n of this.app.workspace.getLeavesOfType(Mn))n.view.refresh(t)}refreshIssueViews(){this.updateStatusBar();for(let t of this.app.workspace.getLeavesOfType(Mi))t.view.render();this.refreshWorkspaceViews()}setFileIssues(t,n){n.length===0?this.issueMap.delete(t):this.issueMap.set(t,n),this.sortedIssuesCache=null,this.refreshIssueViews()}clearFileIssues(t){this.issueMap.has(t)&&(this.issueMap.delete(t),this.sortedIssuesCache=null,this.refreshIssueViews())}moveFileIssues(t,n){let i=this.issueMap.get(t);i&&(this.issueMap.delete(t),this.issueMap.set(n,i.map(s=>({...s,path:n}))),this.sortedIssuesCache=null,this.refreshIssueViews())}clearAllPendingSaveValidations(){for(let t of this.pendingSaveValidations.values())window.clearTimeout(t);this.pendingSaveValidations.clear()}clearPendingSaveValidation(t){let n=this.pendingSaveValidations.get(t);n!=null&&(window.clearTimeout(n),this.pendingSaveValidations.delete(t))}scheduleSaveValidation(t){this.clearPendingSaveValidation(t.path);let n=window.setTimeout(()=>{this.pendingSaveValidations.delete(t.path),this.validateFileAndStore(t,"save")},this.saveValidationDebounceMs);this.pendingSaveValidations.set(t.path,n)}isSchemaRelevantPath(t){let n=(0,D.normalizePath)(t);if(n==="mdbase.yaml")return!0;let i=new Set(["_types"]);this.schemaCache&&i.add((0,D.normalizePath)(this.schemaCache.config.settings.types_folder));for(let s of i)if(n===s||n.startsWith(`${s}/`))return!0;return!1}invalidateSchemaCache(){this.schemaCache=null,this.schemaLoadPromise=null}async getConfigAndTypes(t=!1){if(t&&this.invalidateSchemaCache(),this.schemaCache)return this.schemaCache;if(this.schemaLoadPromise)return this.schemaLoadPromise;this.schemaLoadPromise=(async()=>{let n=await ci(this.app.vault);if(!n)return null;let i=await Kb(this.app.vault,n);return{config:n,types:i}})();try{let n=await this.schemaLoadPromise;return n&&(this.schemaCache=n),n}finally{this.schemaLoadPromise=null}}async requireConfigAndTypes(t={}){var s,o;let n=(s=t.background)!=null?s:!1,i=await this.getConfigAndTypes((o=t.forceReload)!=null?o:!1);return i?(i.types.size===0&&!n&&new D.Notice(`No types found in ${i.config.settings.types_folder}`),i):(n||new D.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}onVaultModify(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),this.settings.validateOnSave&&t.extension==="md"&&this.scheduleSaveValidation(t)}onVaultRename(t,n){(this.isSchemaRelevantPath(n)||this.isSchemaRelevantPath(t.path))&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(n),this.moveFileIssues(n,t.path),this.settings.validateOnSave&&this.scheduleSaveValidation(t))}onVaultDelete(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews()),t.extension==="md"&&(this.clearPendingSaveValidation(t.path),this.clearFileIssues(t.path))}onVaultCreate(t){this.isSchemaRelevantPath(t.path)&&(this.invalidateSchemaCache(),this.refreshWorkspaceViews())}async validateFileAndStore(t,n){let i=await this.requireConfigAndTypes({background:n!=="manual"});if(!i)return n!=="manual"&&this.clearFileIssues(t.path),[];let s=await Vu(this.app.vault,t,i.config,i.types);return this.setFileIssues(t.path,s),n==="save"&&this.settings.showNoticeOnSave&&s.length>0&&new D.Notice(`mdbase: ${s.length} issue${s.length===1?"":"s"} in ${t.basename}`),s}async initializeCollectionCommand(){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()){new D.Notice("This vault is configured as a mirror. Sync it instead of initializing a local collection.");return}let{created:t}=await Bb(this.app.vault);if(this.invalidateSchemaCache(),t.length===0){new D.Notice("mdbase collection already initialized.");return}new D.Notice(`Initialized mdbase collection: ${t.join(", ")}`)}async syncHostedCollectionCommand(){if(!this.getMirrorProfile()){await this.openWorkspace("sync");return}try{let t=await this.connectSync.sync();this.invalidateSchemaCache(),this.refreshWorkspaceViews(!0);let n=t.conflicts.length+t.local_issues.length;new D.Notice(n?`Sync completed with ${n} item${n===1?"":"s"} needing attention.`:"mdbase sync completed.")}catch(t){new D.Notice(`mdbase sync failed: ${t instanceof Error?t.message:String(t)}`),await this.openWorkspace("sync")}}async createNoteFromTypeCommand(){var u,d;this.connectSync.assertLocalAuthorityWritable();let t=await this.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new D.Notice("No type definitions found.");return}let n=await uC(this.app,Array.from(t.types.values()));if(!n)return;let i=Jb(n,t.config),s=Yb(n,i);for(let[f,p]of s){let m=`Required field: ${f}`,h=await new uo(this.app,m,(u=p.type)!=null?u:"string").openAndGetValue();if(h==null)return;if(h.trim().length===0){new D.Notice(`Field '${f}' is required.`);return}try{i[f]=Uu(h,p)}catch(y){new D.Notice(`Invalid value for ${f}: ${y instanceof Error?y.message:String(y)}`);return}}let o=(d=n.display_name_key)!=null?d:"title";if(i[o]==null){let f=await new uo(this.app,`Optional ${o} (used for filename)`,"").openAndGetValue();f&&f.trim().length>0&&(i[o]=f.trim())}let a=await Qb(this.app.vault,n,i),c=await new uo(this.app,"Note path","Relative path in vault",a).openAndGetValue();if(c==null)return;let l=(0,D.normalizePath)(c.trim().length>0?c.trim():a);l.endsWith(".md")||(l=`${l}.md`);try{let f=await Zb(this.app.vault,l,i);await this.app.workspace.getLeaf(!0).openFile(f),new D.Notice(`Created note: ${f.path}`),await this.validateFileAndStore(f,"manual")}catch(f){new D.Notice(f instanceof Error?f.message:String(f))}}async validateCurrentNoteCommand(){let t=this.app.workspace.getActiveFile();if(!(t instanceof D.TFile)||t.extension!=="md"){new D.Notice("Open a markdown note first.");return}let n=await this.validateFileAndStore(t,"manual");n.length===0?new D.Notice("No issues in current note."):(new D.Notice(`Found ${n.length} issue${n.length===1?"":"s"} in current note.`),await this.openIssuesView())}async runCollectionValidation(t){var o;let n=await this.requireConfigAndTypes({background:!1});if(!n)return;let i=await Gb(this.app.vault,n.config,n.types),s=new Map;for(let a of i){let c=(o=s.get(a.path))!=null?o:[];c.push(a),s.set(a.path,c)}if(this.issueMap=s,this.sortedIssuesCache=null,this.refreshIssueViews(),t)if(i.length===0)new D.Notice("Collection validation passed with no issues.");else{let a=i.filter(l=>l.severity==="error").length,c=i.length-a;new D.Notice(`Collection validation: ${a} error(s), ${c} warning(s)`),await this.openIssuesView()}}async ensureFolderExists(t){let n=(0,D.normalizePath)(t).replace(/\/+$/,"");if(!n)return;let i=n.split("/"),s="";for(let o of i)s=s?`${s}/${o}`:o,await this.app.vault.adapter.exists(s)||await this.app.vault.createFolder(s)}async writeTypeDefinition(t,n,i){let s=n.name.trim();if(!s)throw new Error("Type name is required.");if(!t.spec_version.startsWith("0.3.")||n.specProfile!=="v0.3")throw new Error("mdbase v0.2 type definitions are read-only. Migrate the collection first.");let o=lo(n),a=n.body.trim()||`# ${s} -Type definition for ${i}.`,c=`${at(o,a)} -`,l=(0,L.normalizePath)(t.settings.types_folder),u=(0,L.normalizePath)(`${l}/${i}.md`);if(!s){if(await this.ensureFolderExists(l),await this.app.vault.adapter.exists(u))throw new Error(`Type already exists: ${u}`);let y=await this.app.vault.create(u,c);return this.invalidateSchemaCache(),y}let d=s.path.lastIndexOf("/"),f=d>=0?s.path.slice(0,d):"",m=(0,L.normalizePath)(`${f?`${f}/`:""}${i}.md`)||u;if(m!==s.path&&await this.app.vault.adapter.exists(m))throw new Error(`Cannot rename type file to ${m}; file already exists.`);m!==s.path&&await this.app.fileManager.renameFile(s,m);let h=this.app.vault.getAbstractFileByPath(m);if(!(h instanceof L.TFile))throw new Error(`Unable to access updated type file: ${m}`);return await this.app.vault.modify(h,c),this.invalidateSchemaCache(),h}}; +Type definition for ${s}.`,c=`${wt(o,a)} +`,l=(0,D.normalizePath)(t.settings.types_folder),u=(0,D.normalizePath)(`${l}/${s}.md`);if(!i){if(await this.ensureFolderExists(l),await this.app.vault.adapter.exists(u))throw new Error(`Type already exists: ${u}`);let y=await this.app.vault.create(u,c);return this.invalidateSchemaCache(),y}let d=i.path.lastIndexOf("/"),f=d>=0?i.path.slice(0,d):"",m=(0,D.normalizePath)(`${f?`${f}/`:""}${s}.md`)||u;if(m!==i.path&&await this.app.vault.adapter.exists(m))throw new Error(`Cannot rename type file to ${m}; file already exists.`);m!==i.path&&await this.app.fileManager.renameFile(i,m);let h=this.app.vault.getAbstractFileByPath(m);if(!(h instanceof D.TFile))throw new Error(`Unable to access updated type file: ${m}`);return await this.app.vault.modify(h,c),this.invalidateSchemaCache(),h}}; diff --git a/package-lock.json b/package-lock.json index a935688..2b29dfb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,9 +9,9 @@ "version": "0.3.1", "license": "MIT", "dependencies": { - "@callumalpass/mdbase-interop": "file:vendor/callumalpass-mdbase-interop-0.1.0-rc.2.tgz", - "@mdbase/connect-protocol": "file:vendor/mdbase-connect-protocol-0.1.0-beta.21-35c137579861.tgz", - "@mdbase/connect-sync": "file:vendor/mdbase-connect-sync-0.1.0-beta.21-35c137579861.tgz", + "@callumalpass/mdbase-interop": "0.1.0-rc.2", + "@mdbase-dev/connect-protocol": "0.1.0-beta.23", + "@mdbase-dev/connect-sync": "0.1.0-beta.23", "ajv": "^8.20.0", "ajv-formats": "^3.0.1", "picomatch": "^4.0.5" @@ -28,7 +28,7 @@ }, "node_modules/@callumalpass/mdbase-interop": { "version": "0.1.0-rc.2", - "resolved": "file:vendor/callumalpass-mdbase-interop-0.1.0-rc.2.tgz", + "resolved": "https://registry.npmjs.org/@callumalpass/mdbase-interop/-/mdbase-interop-0.1.0-rc.2.tgz", "integrity": "sha512-Le3wYZpuUS17HOVNT8eu/SJ8rCVsRGSJ9fMw79M9DcaeekO+Kavj1pnp9nOtP7HM5alP/raAzOi/T1ELci68GQ==", "license": "MIT", "dependencies": { @@ -505,26 +505,26 @@ } }, "node_modules/@marijn/find-cluster-break": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.2.tgz", - "integrity": "sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==", + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.3.tgz", + "integrity": "sha512-FY+MKLBoTsLNJF/eLWaOsXGdz6uh3Iu1axjPf6TUq92IYumcTcXWHoS747JARLkcdlJ/Waiaxc5wQfFO8jC6NA==", "dev": true, "license": "MIT", "peer": true }, - "node_modules/@mdbase/connect-protocol": { - "version": "0.1.0-beta.21", - "resolved": "file:vendor/mdbase-connect-protocol-0.1.0-beta.21-35c137579861.tgz", - "integrity": "sha512-sFIQ/QH4KLkzlBTqfObjnQgpsbvArYqMSApCX98U2BqeBHG02PdQz6vkIH5iS4Cf0SnD4b5eA1ONe+An2h1xWw==", + "node_modules/@mdbase-dev/connect-protocol": { + "version": "0.1.0-beta.23", + "resolved": "https://registry.npmjs.org/@mdbase-dev/connect-protocol/-/connect-protocol-0.1.0-beta.23.tgz", + "integrity": "sha512-IHbuwIBSh1d+Xys7KVnKctqz2c4SuE7g78A1K7ZGgUjWpqo+li99k4cNYcpgjPNOTlGr9hs19HPLqLFhVxZ9UA==", "license": "MIT" }, - "node_modules/@mdbase/connect-sync": { - "version": "0.1.0-beta.21", - "resolved": "file:vendor/mdbase-connect-sync-0.1.0-beta.21-35c137579861.tgz", - "integrity": "sha512-XFswT6qADLJlLwip27PN8khBBH46APpjnXM3qWfhZE1ZLdOJ9oRGSvgnupMRMwyuhSCf0Jy/aUvgbkQcNOesRg==", + "node_modules/@mdbase-dev/connect-sync": { + "version": "0.1.0-beta.23", + "resolved": "https://registry.npmjs.org/@mdbase-dev/connect-sync/-/connect-sync-0.1.0-beta.23.tgz", + "integrity": "sha512-hEfXJwJkaSNRLljNayF13pOLDDQTnHx1uf3elCJuARP/8kjHFBgQAzB7uDjM0j/W8YFrTca8yF9XJAHw4vk+CQ==", "license": "MIT", "dependencies": { - "@mdbase/connect-protocol": "0.1.0-beta.21", + "@mdbase-dev/connect-protocol": "0.1.0-beta.23", "@noble/hashes": "^2.2.0", "yaml": "^2.9.0" }, @@ -555,16 +555,16 @@ } }, "node_modules/@types/estree": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", - "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", "dev": true, "license": "MIT" }, "node_modules/@types/node": { - "version": "22.19.11", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.11.tgz", - "integrity": "sha512-BH7YwL6rA93ReqeQS1c4bsPpcfOmJasG+Fkr6Y59q83f9M1WcBRHR2vM+P9eOisYRcN3ujQoiZY8uk5W+1WL8w==", + "version": "22.20.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.1.tgz", + "integrity": "sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==", "dev": true, "license": "MIT", "dependencies": { @@ -572,9 +572,9 @@ } }, "node_modules/@types/picomatch": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@types/picomatch/-/picomatch-4.0.2.tgz", - "integrity": "sha512-qHHxQ+P9PysNEGbALT8f8YOSHW0KJu6l2xU8DYY0fu/EmGxXdVnuTLvFUvBgPJMSqXq29SYHveejeAha+4AYgA==", + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/@types/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-iG0T6+nYJ9FAPmx9SsUlnwcq1ZVRuCXcVEvWnntoPlrOpwtSTKNDC9uVAxTsC3PUvJ+99n4RpAcNgBbHX3JSnQ==", "dev": true, "license": "MIT" }, @@ -622,9 +622,9 @@ } }, "node_modules/builtin-modules": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-5.0.0.tgz", - "integrity": "sha512-bkXY9WsVpY7CvMhKSR6pZilZu9Ln5WDrKVBUXf2S443etkmEO4V58heTecXcUIsNsi4Rx8JUO4NfX1IcQl4deg==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/builtin-modules/-/builtin-modules-5.3.0.tgz", + "integrity": "sha512-hMQUl2bUFG339QygPM97E+mc8OY1IAchORZxm4a/frcYwKzozMzRVDBwHW0NjOqGElLm2O37AVQE8ikxlZHrMQ==", "dev": true, "license": "MIT", "engines": { @@ -635,9 +635,9 @@ } }, "node_modules/crelt": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz", - "integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==", + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz", + "integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==", "dev": true, "license": "MIT", "peer": true @@ -691,9 +691,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.4", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.4.tgz", - "integrity": "sha512-8JnbkQ4juDyvYs4mgFGQqg4yCYtFDtUtmp2QIQq11ZZe5CFQ5wcqm1rqDgAh/QdMySuBnPzMUiJUNZG5N/AiQw==", + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz", + "integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==", "funding": [ { "type": "github", @@ -723,9 +723,9 @@ } }, "node_modules/obsidian": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/obsidian/-/obsidian-1.12.2.tgz", - "integrity": "sha512-DGAzpt6vo+sMDET/o8Zj26Bj2hbHrFsNUU8TtnzCyerO/OHksMFQnU9QEnPHVsOMstt/WnHXfC56j2r1syObWg==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/obsidian/-/obsidian-1.13.1.tgz", + "integrity": "sha512-qtTEA2pmhJzhuhJqzbBFRYhpIOqvW+krDYjtFynv66KbxBbumHBlsJfWw3I4jtnK/6fZwbQhCrmmDdRwXmX56w==", "dev": true, "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index 6439022..db76f28 100644 --- a/package.json +++ b/package.json @@ -32,9 +32,9 @@ "typescript": "^5.7.2" }, "dependencies": { - "@callumalpass/mdbase-interop": "file:vendor/callumalpass-mdbase-interop-0.1.0-rc.2.tgz", - "@mdbase/connect-protocol": "file:vendor/mdbase-connect-protocol-0.1.0-beta.21-35c137579861.tgz", - "@mdbase/connect-sync": "file:vendor/mdbase-connect-sync-0.1.0-beta.21-35c137579861.tgz", + "@callumalpass/mdbase-interop": "0.1.0-rc.2", + "@mdbase-dev/connect-protocol": "0.1.0-beta.23", + "@mdbase-dev/connect-sync": "0.1.0-beta.23", "ajv": "^8.20.0", "ajv-formats": "^3.0.1", "picomatch": "^4.0.5" diff --git a/scripts/check-mobile.mjs b/scripts/check-mobile.mjs index 533ceba..8675f67 100644 --- a/scripts/check-mobile.mjs +++ b/scripts/check-mobile.mjs @@ -4,7 +4,7 @@ import { readFile } from "node:fs/promises"; const bundle = await readFile(new URL("../main.js", import.meta.url)); const source = bundle.toString("utf8"); const gzipBytes = gzipSync(bundle).byteLength; -const rawBudget = 550 * 1024; +const rawBudget = 575 * 1024; const gzipBudget = 170 * 1024; const forbidden = [ /require\((["'])node:(?:fs|path|crypto|os|worker_threads|child_process)\1\)/, @@ -30,4 +30,3 @@ console.log(JSON.stringify({ raw_budget: rawBudget, gzip_budget: gzipBudget, })); - diff --git a/src/connectSync.ts b/src/connectSync.ts index 314c9a4..3fd8df1 100644 --- a/src/connectSync.ts +++ b/src/connectSync.ts @@ -11,17 +11,19 @@ import { import picomatch from "picomatch"; import type { AuthorityImportSnapshot, + CollectionFileDescriptor, JsonObject, SyncChangesPage, + SyncFileSnapshotPage, SyncMutation, SyncMutationReceipt, SyncSession, SyncSnapshotPage, -} from "@mdbase/connect-protocol"; +} from "@mdbase-dev/connect-protocol"; import { SyncError, type SyncTransport, -} from "@mdbase/connect-sync"; +} from "@mdbase-dev/connect-sync"; import { AuthorityAdoptionClient, AuthorityAdoptionError, @@ -32,7 +34,7 @@ import { type AuthorityAdoptionStatus, type AuthorityAdoptionVerification, type CompletedAuthorityAdoption, -} from "@mdbase/connect-sync/adoption"; +} from "@mdbase-dev/connect-sync/adoption"; import { DirectoryMirror, type DirectoryMirrorOptions, @@ -44,7 +46,7 @@ import { type MirrorStateStore, type MirrorStatus, WritableDirectoryMirror, -} from "@mdbase/connect-sync/mirror"; +} from "@mdbase-dev/connect-sync/mirror"; import { MirrorEnrollmentClient, type MirrorEnrollment, @@ -52,7 +54,7 @@ import { type MirrorEnrollmentRequester, type MirrorEnrollmentStatus, type MirrorEnrollmentVerification, -} from "@mdbase/connect-sync/enrollment"; +} from "@mdbase-dev/connect-sync/enrollment"; import { isExcluded, loadMdbaseConfig, @@ -201,6 +203,7 @@ export function createObsidianAdoptionRequester(): AuthorityAdoptionRequester { export class ObsidianSyncTransport implements SyncTransport { private readonly syncUrl: string; + private readonly filesUrl: string; constructor( syncUrl: string, @@ -229,6 +232,7 @@ implements SyncTransport { throw new SyncError("invalid_sync_url", "Sync URL must identify one authority sync endpoint."); } this.syncUrl = endpoint.href.replace(/\/$/, ""); + this.filesUrl = this.syncUrl.replace(/\/sync$/, "/files"); } openSession(): Promise { @@ -241,6 +245,74 @@ implements SyncTransport { return this.request("GET", `snapshot?${query.toString()}`); } + fileSnapshot(snapshotId: string, page?: string): Promise { + const query = new URLSearchParams({ snapshot_id: snapshotId }); + if (page) query.set("page", page); + return this.request("GET", `files/snapshot?${query.toString()}`); + } + + async *downloadFile(file: CollectionFileDescriptor): AsyncGenerator { + const transferId = crypto.randomUUID(); + try { + const session = await this.fileRequest>("POST", "downloads", { + protocol_version: 1, + type: "open_file_download", + transfer_id: transferId, + file_id: file.file_id, + revision: file.revision, + }); + const strategy = isRecord(session.strategy) ? session.strategy : {}; + const partSize = strategy.part_size; + if ( + session.protocol_version !== 1 + || session.type !== "file_transfer" + || session.transfer_id !== transferId + || session.direction !== "download" + || session.protection !== "transport_tls" + || session.total_size !== file.size + || strategy.kind !== "object_ranges" + || !Number.isSafeInteger(partSize) + || (partSize as number) <= 0 + ) { + throw new SyncError( + "invalid_sync_response", + "The authority returned an incompatible file download session.", + ); + } + + const partCount = Math.ceil(file.size / (partSize as number)); + for (let partIndex = 0; partIndex < partCount; partIndex += 1) { + const expectedLength = Math.min(partSize as number, file.size - partIndex * (partSize as number)); + const response = await requestUrl({ + url: `${this.filesUrl}/downloads/${encodeURIComponent(transferId)}/parts/${partIndex}`, + method: "GET", + headers: { authorization: `Bearer ${this.accessToken}` }, + throw: false, + }); + if (response.status < 200 || response.status >= 300) { + const value = parseJsonResponse(response.text, response.json); + const error = isRecord(value) && isRecord(value.error) ? value.error : {}; + throw new SyncError( + typeof error.code === "string" ? error.code : "file_download_failed", + typeof error.message === "string" + ? error.message + : `File download failed (${response.status}).`, + ); + } + if (response.arrayBuffer.byteLength !== expectedLength) { + throw new SyncError( + "file_integrity_failed", + "The authority returned a file part with the wrong length.", + ); + } + yield new Uint8Array(response.arrayBuffer); + } + } finally { + await this.fileRequest("DELETE", `transfers/${encodeURIComponent(transferId)}`) + .catch(() => undefined); + } + } + changes(after: number, limit = 200): Promise> { const query = new URLSearchParams({ after: String(after), limit: String(limit) }); return this.request("GET", `changes?${query.toString()}`); @@ -250,9 +322,26 @@ implements SyncTransport { return this.request("POST", "mutations", mutation); } - private async request(method: "GET" | "POST", path: string, body?: unknown): Promise { + private request(method: "GET" | "POST", path: string, body?: unknown): Promise { + return this.requestAt(this.syncUrl, method, path, body); + } + + private fileRequest( + method: "GET" | "POST" | "DELETE", + path: string, + body?: unknown, + ): Promise { + return this.requestAt(this.filesUrl, method, path, body); + } + + private async requestAt( + baseUrl: string, + method: "GET" | "POST" | "DELETE", + path: string, + body?: unknown, + ): Promise { const response = await requestUrl({ - url: `${this.syncUrl}/${path}`, + url: `${baseUrl}/${path}`, method, headers: { authorization: `Bearer ${this.accessToken}`, @@ -341,6 +430,73 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { .filter((path) => !RESERVED_WRITE_PREFIXES.some((prefix) => path.startsWith(prefix))) .sort(); } + + async inspectBinary(input: string): Promise<{ size: number; content_digest: `sha256:${string}` } | null> { + const path = safeMirrorPath(input); + const file = this.vault.getAbstractFileByPath(path); + if (file == null) return null; + if (!(file instanceof TFile)) { + throw new SyncError("mirror_path_collision", `Expected a file at ${path}.`); + } + const bytes = await this.vault.readBinary(file); + const digest = await crypto.subtle.digest("SHA-256", bytes); + const hex = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""); + return { size: bytes.byteLength, content_digest: `sha256:${hex}` }; + } + + async writeBinary(input: string, source: AsyncIterable): Promise { + const path = safeMirrorPath(input); + const chunks: Uint8Array[] = []; + let size = 0; + for await (const chunk of source) { + if (!(chunk instanceof Uint8Array) || !Number.isSafeInteger(size + chunk.byteLength)) { + throw new SyncError("invalid_file_materialization", "The binary file stream is invalid or too large."); + } + chunks.push(chunk); + size += chunk.byteLength; + } + const bytes = new Uint8Array(size); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + + const slash = path.lastIndexOf("/"); + if (slash >= 0) await ensureFolder(this.vault, path.slice(0, slash)); + const existing = this.vault.getAbstractFileByPath(path); + if (existing instanceof TFolder) { + throw new SyncError("mirror_path_collision", `A folder blocks the mirror file ${path}.`); + } + if (existing instanceof TFile) { + await this.vault.modifyBinary(existing, bytes.buffer); + } else { + await this.vault.createBinary(path, bytes.buffer); + } + } + + async listBinary(excluded: ReadonlySet): Promise { + return this.vault + .getFiles() + .map((file) => normalizePath(file.path)) + .filter((path) => !path.toLowerCase().endsWith(".md")) + .filter((path) => !excluded.has(path)) + .filter((path) => !RESERVED_WRITE_PREFIXES.some((prefix) => path.startsWith(prefix))) + .sort(); + } + + async readBinary(input: string): Promise | null> { + const path = safeMirrorPath(input); + const file = this.vault.getAbstractFileByPath(path); + if (file == null) return null; + if (!(file instanceof TFile)) { + throw new SyncError("mirror_path_collision", `Expected a file at ${path}.`); + } + const bytes = new Uint8Array(await this.vault.readBinary(file)); + return (async function* (): AsyncGenerator { + yield bytes; + })(); + } } export class IndexedDbMirrorStateStore implements MirrorStateStore { diff --git a/src/migration.ts b/src/migration.ts index f95e2ee..3eaef1e 100644 --- a/src/migration.ts +++ b/src/migration.ts @@ -6,7 +6,7 @@ import { TFolder, Vault, } from "obsidian"; -import { portableMirrorRuntime } from "@mdbase/connect-sync/mirror"; +import { portableMirrorRuntime } from "@mdbase-dev/connect-sync/mirror"; import { fieldsFromV03Schema, formatMarkdown, diff --git a/src/workspaceView.ts b/src/workspaceView.ts index 848cd3c..8206436 100644 --- a/src/workspaceView.ts +++ b/src/workspaceView.ts @@ -6,8 +6,8 @@ import { TFile, WorkspaceLeaf, } from "obsidian"; -import type { MirrorInitializationPreview, MirrorProgress, MirrorStatus } from "@mdbase/connect-sync/mirror"; -import type { AuthorityAdoptionStatus } from "@mdbase/connect-sync/adoption"; +import type { MirrorInitializationPreview, MirrorProgress, MirrorStatus } from "@mdbase-dev/connect-sync/mirror"; +import type { AuthorityAdoptionStatus } from "@mdbase-dev/connect-sync/adoption"; import type { ConnectSyncController, MirrorProfile, diff --git a/test/connectSync.adoption.test.ts b/test/connectSync.adoption.test.ts index 3c6ef2c..cd613cf 100644 --- a/test/connectSync.adoption.test.ts +++ b/test/connectSync.adoption.test.ts @@ -2,7 +2,7 @@ import * as assert from "node:assert/strict"; import { randomUUID } from "node:crypto"; import { test } from "node:test"; import { normalizePath, TFile, TFolder } from "obsidian"; -import type { AuthorityImportSnapshot } from "@mdbase/connect-protocol"; +import type { AuthorityImportSnapshot } from "@mdbase-dev/connect-protocol"; import { AuthorityAdoptionError, AuthorityAdoptionOutcomeUnknownError, @@ -10,11 +10,11 @@ import { type AuthorityAdoptionSession, type CompletedAuthorityAdoption, type PreparedAuthorityAdoption, -} from "@mdbase/connect-sync/adoption"; +} from "@mdbase-dev/connect-sync/adoption"; import type { MirrorEnrollment, MirrorEnrollmentClient, -} from "@mdbase/connect-sync/enrollment"; +} from "@mdbase-dev/connect-sync/enrollment"; import { ConnectSyncController, type ConnectSyncSettingsHost, @@ -202,8 +202,10 @@ class FakeAdoption { status: "ready", adoption: this.adoptionView("prepared"), import: { + import_id: this.adoptionId, manifest_url: `https://provider.example/v1/authority-imports/${this.adoptionId}/manifest`, records_url: `https://provider.example/v1/authority-imports/${this.adoptionId}/records`, + files_url: `https://provider.example/v1/authority-imports/${this.adoptionId}/files`, finalize_url: `https://provider.example/v1/authority-imports/${this.adoptionId}/finalize`, access_token: "ati_test_secret_abcdefghijklmnopqrstuvwxyz", }, diff --git a/test/mdbaseCore.test.ts b/test/mdbaseCore.test.ts index bd9c731..f3dd2dc 100644 --- a/test/mdbaseCore.test.ts +++ b/test/mdbaseCore.test.ts @@ -446,6 +446,49 @@ test("v0.3 view query scope stays nested and the view validates as an ordinary r assert.deepEqual(await validateFile(vault as unknown as any, file, config, types), []); }); +test("v0.3 view query scope stays nested and the view validates as an ordinary record", async () => { + const vault = new MockVault(); + await vault.writeNote("_types/view.md", { + kind: "mdbase.type", + name: "view", + version: 1, + schema: { + dialect: "json-schema-2020-12", + value: { + type: "object", + required: ["type", "id", "version", "name", "views"], + additionalProperties: false, + properties: { + type: { const: "view" }, + id: { type: "string" }, + version: { type: "integer", minimum: 1 }, + name: { type: "string" }, + query: { + type: "object", + properties: { types: { type: "array", items: { type: "string" } } }, + additionalProperties: false, + }, + views: { type: "array", minItems: 1, items: { type: "object" } }, + }, + }, + }, + }); + const file = await vault.writeNote("views/tasks.md", { + type: "view", + id: "tasks.views", + version: 1, + name: "Task views", + query: { types: ["task"] }, + views: [{ id: "all", name: "All tasks" }], + }); + const config = createV03Config(); + const types = await loadTypeDefinitions(vault as unknown as any, config); + const parsed = parseFrontmatter(await vault.cachedRead(file)); + + assert.deepEqual(getTypesForFile(file.path, parsed.frontmatter, config, types), ["view"]); + assert.deepEqual(await validateFile(vault as unknown as any, file, config, types), []); +}); + test("v0.3 collection validation enforces links and unique rules", async () => { const vault = new MockVault(); await vault.writeNote("_types/task.md", v03TaskType()); diff --git a/test/v3-foundations.test.ts b/test/v3-foundations.test.ts index 885e439..751200d 100644 --- a/test/v3-foundations.test.ts +++ b/test/v3-foundations.test.ts @@ -3,19 +3,19 @@ import { createHash } from "node:crypto"; import { performance } from "node:perf_hooks"; import { test } from "node:test"; import { normalizePath, TFile, TFolder } from "obsidian"; -import { MemoryAuthority } from "@mdbase/connect-sync"; +import { MemoryAuthority } from "@mdbase-dev/connect-sync"; import { DirectoryMirror, MemoryMirrorLease, MemoryMirrorStateStore, WritableDirectoryMirror, -} from "@mdbase/connect-sync/mirror"; +} from "@mdbase-dev/connect-sync/mirror"; import { ConnectSyncController, DeviceMirrorLease, ObsidianMirrorFileSystem, } from "../src/connectSync"; -import { MirrorEnrollmentClient } from "@mdbase/connect-sync/enrollment"; +import { MirrorEnrollmentClient } from "@mdbase-dev/connect-sync/enrollment"; import { analyzeV02Migration, applyV02Migration, @@ -36,6 +36,7 @@ import { interface StoredFile { file: TFile; content: string; + binary?: ArrayBuffer; } const TestFile = TFile as unknown as { new (path: string): TFile }; @@ -82,6 +83,10 @@ class MemoryVault { return [...this.files.values()].map((entry) => entry.file).filter((file) => file.extension === "md"); } + getFiles(): TFile[] { + return [...this.files.values()].map((entry) => entry.file); + } + async cachedRead(file: TFile): Promise { const entry = this.files.get(file.path); if (!entry) throw new Error(`missing ${file.path}`); @@ -115,6 +120,24 @@ class MemoryVault { this.files.set(file.path, { file, content }); } + async readBinary(file: TFile): Promise { + const entry = this.files.get(file.path); + if (!entry) throw new Error(`missing ${file.path}`); + return entry.binary?.slice(0) ?? new TextEncoder().encode(entry.content).buffer; + } + + async createBinary(path: string, value: ArrayBuffer): Promise { + const normalized = normalizePath(path); + if (this.files.has(normalized) || this.folders.has(normalized)) throw new Error(`exists ${normalized}`); + const file = new TestFile(normalized); + this.files.set(normalized, { file, content: "", binary: value.slice(0) }); + return file; + } + + async modifyBinary(file: TFile, value: ArrayBuffer): Promise { + this.files.set(file.path, { file, content: "", binary: value.slice(0) }); + } + async createFolder(path: string): Promise { const normalized = normalizePath(path); if (!this.folders.has(normalized)) this.folders.set(normalized, new TestFolder(normalized)); @@ -515,6 +538,37 @@ test("Obsidian mirror adapter rejects traversal and reserved paths", async () => assert.equal(await fs.read("notes/ok.md"), null); }); +test("Obsidian mirror adapter round-trips and verifies binary files", async () => { + const vault = new MemoryVault(); + const fs = new ObsidianMirrorFileSystem(vault as never); + const bytes = new Uint8Array([137, 80, 78, 71, 1, 2, 3, 4]); + await fs.writeBinary("attachments/tasks/task-1/photo.png", (async function* () { + yield bytes.slice(0, 3); + yield bytes.slice(3); + })()); + + assert.deepEqual(await fs.inspectBinary("attachments/tasks/task-1/photo.png"), { + size: bytes.byteLength, + content_digest: `sha256:${createHash("sha256").update(bytes).digest("hex")}`, + }); + assert.deepEqual(await fs.listBinary(new Set()), ["attachments/tasks/task-1/photo.png"]); + const source = await fs.readBinary("attachments/tasks/task-1/photo.png"); + assert.ok(source); + const chunks: Uint8Array[] = []; + for await (const chunk of source) chunks.push(chunk); + assert.deepEqual(chunks, [bytes]); + + const replacement = new Uint8Array([9, 8, 7]); + await fs.writeBinary("attachments/tasks/task-1/photo.png", (async function* () { + yield replacement; + })()); + assert.equal((await fs.inspectBinary("attachments/tasks/task-1/photo.png"))?.size, 3); + await assert.rejects( + fs.writeBinary(".obsidian/photo.png", (async function* () { yield bytes; })()), + /reserved path/, + ); +}); + test("Connect enrollment keeps credentials out of plugin data and refuses local-authority vaults", async () => { const pairingId = "11111111-1111-4111-8111-111111111111"; const collectionId = "22222222-2222-4222-8222-222222222222"; diff --git a/vendor/README.md b/vendor/README.md deleted file mode 100644 index a48d549..0000000 --- a/vendor/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# Vendored mdbase Connect SDK - -The tarballs in this directory are exact consumer artifacts generated from -`mdbase-dev/mdbase-connect` by: - -```sh -pnpm package:consumer -- --destination /home/calluma/projects/mdbase-obsidian/vendor -``` - -`mdbase-connect-sdk.json` records the source revision, sizes, and integrity -digests. The plugin consumes the portable mirror and enrollment entry points; -it must not import `@mdbase/connect-sync/node`. - diff --git a/vendor/callumalpass-mdbase-interop-0.1.0-rc.2.tgz b/vendor/callumalpass-mdbase-interop-0.1.0-rc.2.tgz deleted file mode 100644 index 5cb25c0..0000000 Binary files a/vendor/callumalpass-mdbase-interop-0.1.0-rc.2.tgz and /dev/null differ diff --git a/vendor/mdbase-connect-protocol-0.1.0-beta.11.tgz b/vendor/mdbase-connect-protocol-0.1.0-beta.11.tgz deleted file mode 100644 index 9c3a2d7..0000000 Binary files a/vendor/mdbase-connect-protocol-0.1.0-beta.11.tgz and /dev/null differ diff --git a/vendor/mdbase-connect-protocol-0.1.0-beta.21-35c137579861.tgz b/vendor/mdbase-connect-protocol-0.1.0-beta.21-35c137579861.tgz deleted file mode 100644 index 53b6fa5..0000000 Binary files a/vendor/mdbase-connect-protocol-0.1.0-beta.21-35c137579861.tgz and /dev/null differ diff --git a/vendor/mdbase-connect-protocol-0.1.0-beta.8-c3a44aa7063a.tgz b/vendor/mdbase-connect-protocol-0.1.0-beta.8-c3a44aa7063a.tgz deleted file mode 100644 index 6a93db2..0000000 Binary files a/vendor/mdbase-connect-protocol-0.1.0-beta.8-c3a44aa7063a.tgz and /dev/null differ diff --git a/vendor/mdbase-connect-sdk.json b/vendor/mdbase-connect-sdk.json deleted file mode 100644 index 67ef07f..0000000 --- a/vendor/mdbase-connect-sdk.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "schema_version": 1, - "repository": "https://github.com/mdbase-dev/mdbase-connect", - "revision": "35c137579861e49baaec4029eaa9d18a43442e5e", - "artifacts": [ - { - "package": "protocol", - "file": "mdbase-connect-protocol-0.1.0-beta.21-35c137579861.tgz", - "bytes": 15956, - "sha512": "sFIQ/QH4KLkzlBTqfObjnQgpsbvArYqMSApCX98U2BqeBHG02PdQz6vkIH5iS4Cf0SnD4b5eA1ONe+An2h1xWw==" - }, - { - "package": "sync", - "file": "mdbase-connect-sync-0.1.0-beta.21-35c137579861.tgz", - "bytes": 61361, - "sha512": "XFswT6qADLJlLwip27PN8khBBH46APpjnXM3qWfhZE1ZLdOJ9oRGSvgnupMRMwyuhSCf0Jy/aUvgbkQcNOesRg==" - } - ] -} diff --git a/vendor/mdbase-connect-sync-0.1.0-beta.11.tgz b/vendor/mdbase-connect-sync-0.1.0-beta.11.tgz deleted file mode 100644 index 49e9a8b..0000000 Binary files a/vendor/mdbase-connect-sync-0.1.0-beta.11.tgz and /dev/null differ diff --git a/vendor/mdbase-connect-sync-0.1.0-beta.21-35c137579861.tgz b/vendor/mdbase-connect-sync-0.1.0-beta.21-35c137579861.tgz deleted file mode 100644 index 4e5b6d8..0000000 Binary files a/vendor/mdbase-connect-sync-0.1.0-beta.21-35c137579861.tgz and /dev/null differ diff --git a/vendor/mdbase-connect-sync-0.1.0-beta.8-c3a44aa7063a.tgz b/vendor/mdbase-connect-sync-0.1.0-beta.8-c3a44aa7063a.tgz deleted file mode 100644 index 8eb4006..0000000 Binary files a/vendor/mdbase-connect-sync-0.1.0-beta.8-c3a44aa7063a.tgz and /dev/null differ