diff --git a/README.md b/README.md index 18d0918..39dcc1e 100644 --- a/README.md +++ b/README.md @@ -44,14 +44,20 @@ Before every sync, the workspace presents an exact transfer ledger grouped by downloads, uploads, and items needing attention. If the hosted head or local changes move after review, the plugin stops and asks for a fresh review. Sync can be stopped safely after the current request without losing its durable -checkpoint, and path collisions never overwrite local files silently. +checkpoint, and path collisions never overwrite local files silently. Disabling +the plugin cancels sync/enrollment/adoption and fences subsequent mirror content +writes; an already-issued Vault write or HTTP request may still finish. Markdown always syncs. Binary files are an explicit per-device choice, grouped as images, audio, video, PDFs, and other files, with collection-relative folder exclusions. Hidden, reserved, Markdown, and non-portable file paths are never materialized. Downloads and uploads are digest-verified; writable uploads are staged in a chunked, content-addressed IndexedDB cache so an interrupted sync -can resume safely. Binary creates, updates, moves, deletes, and conflicts appear +can resume safely. Binary sync and adoption currently enforce a **32 MiB per-file +limit** on desktop and mobile: Obsidian's Vault APIs require whole-file buffers, +so chunked network transfer does not imply bounded-memory streaming. Oversized +files fail explicitly; exclude their folder from file sync before retrying. +Binary creates, updates, moves, deletes, and conflicts appear as files—not Markdown—in the preflight ledger. Local collection adoption uses the same policy and stages exact bytes for both warm and fenced snapshots. @@ -87,6 +93,9 @@ Open **mdbase: Open workspace** and choose **Types**. - Drafts survive plugin reloads and Obsidian restarts; stale source revisions are blocked, and high-impact schema changes require an explicit review. - Dirty changes and validation failures are shown before save. +- Validation quick fixes target exact nested properties, preserve sibling data, + and use Obsidian's atomic file processing API. Ambiguous legacy nested paths + are not offered automatic fixes. - v0.2 definitions are browsable but read-only until migration. On mobile, the type list and editor use separate navigation states with @@ -143,6 +152,12 @@ npm test npm run build ``` +Stability regression tests cover interrupted adoption cleanup, unload during +binary materialization, nested quick fixes, binary size limits, and production +IndexedDB adapters using `fake-indexeddb` (including aborted transactions and +mirror restart recovery). These are not a substitute for real Obsidian/mobile +suspension, quota, and restart acceptance testing. + Additional gates: ```bash @@ -160,7 +175,7 @@ writing it and enforces checked-in schema, migration-analysis, validation, and issue-render budgets. Set `OBSIDIAN_TEST_VAULT` to profile another registered disposable vault with the exact installed bundle. -The Connect protocol and sync SDKs are pinned to `0.1.0-beta.69`, and mdbase +The Connect protocol and sync SDKs are pinned to `0.1.0-beta.91`, and mdbase interop is pinned to `0.1.0-rc.2`. Update `package.json`, regenerate `package-lock.json`, and rerun the binary round-trip and mobile gates when advancing them. diff --git a/docs/stability-acceptance.md b/docs/stability-acceptance.md new file mode 100644 index 0000000..ae10ff4 --- /dev/null +++ b/docs/stability-acceptance.md @@ -0,0 +1,80 @@ +# Desktop stability acceptance — 2026-09-13 + +Environment: Obsidian **1.13.7**, installer 1.12.7, Linux desktop. Driven through +`obsidian vault=test ...` using CLI commands, renderer `eval`, DOM button/input +interaction, and a screenshot. The exact production bundle from the stability +worktree was temporarily installed in `/home/calluma/testvault/test`. + +Full live-run bundle SHA-256: +`8afaeeb6f45e720fc71d8edea7e0924e92382b8be4b0231bd9b8259910b71f4d` + +A subsequent lint-only rename of the quick-fix result property (`document` to +`content`) produced final bundle SHA-256 +`a0d37e38823145663cef5e272e10b41f89f3a98aa21f651d96a90b1b99058617`. +That exact final bundle was reinstalled and the live nested-field, escaped-pointer, +stale-fix, body-preservation, and validation assertions rerun successfully. +Final automated gates: **92 tests pass**, lint passes, production build and mobile +bundle checks pass. + +## Live checks passed + +- Plugin enable, workspace command, and type-workbench rendering. +- Validation of a temporary nested-schema type and its records using the real + Obsidian YAML parser and Vault APIs. +- Nested additional-property removal preserves the parent and valid siblings. +- Required-property placeholders reach nested objects and objects inside lists; + JSON Pointer escaping and literal dotted property names are preserved. +- A repeated/stale quick fix does not rewrite the file. +- The actual Issues workspace **Remove field** button updates only the intended + field; the resulting note validates successfully. +- Actual workbench description input and **Save** button persist a type edit. +- An external edit after opening a type causes a stale-revision save to fail. +- Binary bytes round-trip through the production adapter and real Vault APIs. +- A 33 MiB local binary and an oversized incoming stream are refused; the latter + never creates a vault file. +- Production IndexedDB adapters persist a checkpoint and binary snapshot in + Obsidian's real Chromium IndexedDB. An interrupted replacement source preserves + the previous snapshot. Both checkpoint and bytes survive plugin disable/enable + and a subsequent full **test-vault reload**. +- Disabling the actual installed plugin while a production binary-adapter write + is paused in its input stream causes the resumed write to reject with + `AbortError: Plugin unloaded.` No destination file is materialized. +- Adoption reconciliation removes an injected completed-adoption checkpoint and + snapshot while retaining its matching mirror role. This uses the installed + controller class and real Vault adapter, with metadata paths redirected into + the disposable fixture and a test-only settings/secret host. It is **not** a + hosted enrollment/adoption round trip. +- `obsidian vault=test dev:errors` reported no captured errors. + +## Defect found live and fixed + +Repeated quick fixes appended trailing blank lines because they used a generic +Markdown formatter followed by an extra newline. Quick fixes now replace only +frontmatter, preserving every byte after the closing delimiter. Added a unit +regression for repeated fixes, leading/trailing whitespace, CRLF body content, +and a missing final newline. The live assertions were rerun successfully on the +rebuilt bundle after this fix. + +## Isolation and cleanup + +No hosted service or production Connect account was contacted. Only the existing +test vault was modified, using uniquely named temporary records/type metadata +and random IndexedDB replica keys. The original installed plugin directory was +backed up before testing. Temporary records and IndexedDB entries were removed; +the original plugin files/settings were restored and re-enabled, with a directory +comparison confirming restoration. + +Local harness scripts, screenshot, results, and original-plugin backup are under +`/home/calluma/testvault/.mdbase-stability-backup-20260905/` (the suffix is the +fixture identifier, not the execution date). + +## Not established by this run + +- End-to-end hosted sync/enrollment/adoption against Connect LAB. +- Real Android/iOS operation, suspension, or memory-pressure behavior. +- OS process termination or power loss during a transaction. +- Real quota exhaustion or IndexedDB corruption. +- Full visual/accessibility or cross-plugin compatibility coverage. + +These checks improve desktop integration confidence; they are not a claim that +all sync or mobile stability risks have been eliminated. diff --git a/main.js b/main.js index ba511d7..f1f6c1b 100644 --- a/main.js +++ b/main.js @@ -3,96 +3,99 @@ THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ -var B0=Object.create;var Oo=Object.defineProperty;var V0=Object.getOwnPropertyDescriptor;var z0=Object.getOwnPropertyNames;var H0=Object.getPrototypeOf,K0=Object.prototype.hasOwnProperty;var E=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),W0=(r,e)=>{for(var t in e)Oo(r,t,{get:e[t],enumerable:!0})},rh=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of z0(e))!K0.call(r,i)&&i!==t&&Oo(r,i,{get:()=>e[i],enumerable:!(n=V0(e,i))||n.enumerable});return r};var vn=(r,e,t)=>(t=r!=null?B0(H0(r)):{},rh(e||!r||!r.__esModule?Oo(t,"default",{value:r,enumerable:!0}):t,r)),G0=r=>rh(Oo({},"__esModule",{value:!0}),r);var rs=E(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.regexpCode=ae.getEsmExportName=ae.getProperty=ae.safeStringify=ae.stringify=ae.strConcat=ae.addCodeArg=ae.str=ae._=ae.nil=ae._Code=ae.Name=ae.IDENTIFIER=ae._CodeOrName=void 0;var es=class{};ae._CodeOrName=es;ae.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var wn=class extends es{constructor(e){if(super(),!ae.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}}};ae.Name=wn;var At=class extends es{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 wn&&(t[n.str]=(t[n.str]||0)+1),t),{})}};ae._Code=At;ae.nil=new At("");function nh(r,...e){let t=[r[0]],n=0;for(;n{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.ValueScope=ot.ValueScopeName=ot.Scope=ot.varKinds=ot.UsedValueState=void 0;var st=rs(),yl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},No;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(No||(ot.UsedValueState=No={}));ot.varKinds={const:new st.Name("const"),let:new st.Name("let"),var:new st.Name("var")};var Do=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof st.Name?e:this.name(e)}name(e){return new st.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}}};ot.Scope=Do;var Lo=class extends st.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,st._)`.${new st.Name(t)}[${n}]`}};ot.ValueScopeName=Lo;var nS=(0,st._)`\n`,gl=class extends Do{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?nS:st.nil}}get(){return this._scope}name(e){return new Lo(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,st._)`${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=st.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,No.Started);let u=t(l);if(u){let d=this.opts.es5?ot.varKinds.var:ot.varKinds.const;s=(0,st._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=i?.(l))s=(0,st._)`${s}${u}${this.opts._n}`;else throw new yl(l);c.set(l,No.Completed)})}return s}};ot.ValueScope=gl});var B=E(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.or=J.and=J.not=J.CodeGen=J.operators=J.varKinds=J.ValueScopeName=J.ValueScope=J.Scope=J.Name=J.regexpCode=J.stringify=J.getProperty=J.nil=J.strConcat=J.str=J._=void 0;var ne=rs(),Dt=bl(),zr=rs();Object.defineProperty(J,"_",{enumerable:!0,get:function(){return zr._}});Object.defineProperty(J,"str",{enumerable:!0,get:function(){return zr.str}});Object.defineProperty(J,"strConcat",{enumerable:!0,get:function(){return zr.strConcat}});Object.defineProperty(J,"nil",{enumerable:!0,get:function(){return zr.nil}});Object.defineProperty(J,"getProperty",{enumerable:!0,get:function(){return zr.getProperty}});Object.defineProperty(J,"stringify",{enumerable:!0,get:function(){return zr.stringify}});Object.defineProperty(J,"regexpCode",{enumerable:!0,get:function(){return zr.regexpCode}});Object.defineProperty(J,"Name",{enumerable:!0,get:function(){return zr.Name}});var Uo=bl();Object.defineProperty(J,"Scope",{enumerable:!0,get:function(){return Uo.Scope}});Object.defineProperty(J,"ValueScope",{enumerable:!0,get:function(){return Uo.ValueScope}});Object.defineProperty(J,"ValueScopeName",{enumerable:!0,get:function(){return Uo.ValueScopeName}});Object.defineProperty(J,"varKinds",{enumerable:!0,get:function(){return Uo.varKinds}});J.operators={GT:new ne._Code(">"),GTE:new ne._Code(">="),LT:new ne._Code("<"),LTE:new ne._Code("<="),EQ:new ne._Code("==="),NEQ:new ne._Code("!=="),NOT:new ne._Code("!"),OR:new ne._Code("||"),AND:new ne._Code("&&"),ADD:new ne._Code("+")};var vr=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},_l=class extends vr{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=Qn(this.rhs,e,t)),this}get names(){return this.rhs instanceof ne._CodeOrName?this.rhs.names:{}}},jo=class extends vr{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 ne.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Qn(this.rhs,e,t),this}get names(){let e=this.lhs instanceof ne.Name?{}:{...this.lhs.names};return Fo(e,this.rhs)}},vl=class extends jo{constructor(e,t,n,i){super(e,n,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},wl=class extends vr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Sl=class extends vr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},$l=class extends vr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},El=class extends vr{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=Qn(this.code,e,t),this}get names(){return this.code instanceof ne._CodeOrName?this.code.names:{}}},ns=class extends vr{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)||(iS(e,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>En(e,t.names),{})}},wr=class extends ns{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Al=class extends ns{},Xn=class extends wr{};Xn.kind="else";var Sn=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 Xn(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(sh(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=Qn(this.condition,e,t),this}get names(){let e=super.names;return Fo(e,this.condition),this.else&&En(e,this.else.names),e}};Sn.kind="if";var $n=class extends wr{};$n.kind="for";var xl=class extends $n{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=Qn(this.iteration,e,t),this}get names(){return En(super.names,this.iteration.names)}},kl=class extends $n{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=Fo(super.names,this.from);return Fo(e,this.to)}},qo=class extends $n{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=Qn(this.iterable,e,t),this}get names(){return En(super.names,this.iterable.names)}},is=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)}};is.kind="func";var ss=class extends ns{render(e){return"return "+super.render(e)}};ss.kind="return";var Pl=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&&En(e,this.catch.names),this.finally&&En(e,this.finally.names),e}},os=class extends wr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};os.kind="catch";var as=class extends wr{render(e){return"finally"+super.render(e)}};as.kind="finally";var Cl=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 Al]}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 _l(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 jo(e,t,n))}add(e,t){return this._leafNode(new vl(e,J.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==ne.nil&&this._leafNode(new El(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,ne.addCodeArg)(t,i));return t.push("}"),new ne._Code(t)}if(e,t,n){if(this._blockNode(new Sn(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 Sn(e))}else(){return this._elseNode(new Xn)}endIf(){return this._endBlockNode(Sn,Xn)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new xl(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 kl(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 ne.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,ne._)`${o}.length`,a=>{this.var(s,(0,ne._)`${o}[${a}]`),n(s)})}return this._for(new qo("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,ne._)`Object.keys(${t})`,n);let s=this._scope.toName(e);return this._for(new qo("in",i,s,t),()=>n(s))}endFor(){return this._endBlockNode($n)}label(e){return this._leafNode(new wl(e))}break(e){return this._leafNode(new Sl(e))}return(e){let t=new ss;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ss)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new Pl;if(this._blockNode(i),this.code(e),t){let s=this.name("e");this._currNode=i.catch=new os(s),t(s)}return n&&(this._currNode=i.finally=new as,this.code(n)),this._endBlockNode(os,as)}throw(e){return this._leafNode(new $l(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=ne.nil,n,i){return this._blockNode(new is(e,t,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(is)}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 Sn))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}};J.CodeGen=Cl;function En(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function Fo(r,e){return e instanceof ne._CodeOrName?En(r,e.names):r}function Qn(r,e,t){if(r instanceof ne.Name)return n(r);if(!i(r))return r;return new ne._Code(r._items.reduce((s,o)=>(o instanceof ne.Name&&(o=n(o)),o instanceof ne._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 ne._Code&&s._items.some(o=>o instanceof ne.Name&&e[o.str]===1&&t[o.str]!==void 0)}}function iS(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function sh(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,ne._)`!${Ml(r)}`}J.not=sh;var sS=oh(J.operators.AND);function oS(...r){return r.reduce(sS)}J.and=oS;var aS=oh(J.operators.OR);function cS(...r){return r.reduce(aS)}J.or=cS;function oh(r){return(e,t)=>e===ne.nil?t:t===ne.nil?e:(0,ne._)`${Ml(e)} ${r} ${Ml(t)}`}function Ml(r){return r instanceof ne.Name?r:(0,ne._)`(${r})`}});var X=E(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.checkStrictMode=Y.getErrorPath=Y.Type=Y.useFunc=Y.setEvaluated=Y.evaluatedPropsToName=Y.mergeEvaluated=Y.eachItem=Y.unescapeJsonPointer=Y.escapeJsonPointer=Y.escapeFragment=Y.unescapeFragment=Y.schemaRefOrVal=Y.schemaHasRulesButRef=Y.schemaHasRules=Y.checkUnknownRules=Y.alwaysValidSchema=Y.toHash=void 0;var pe=B(),lS=rs();function dS(r){let e={};for(let t of r)e[t]=!0;return e}Y.toHash=dS;function uS(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(lh(r,e),!dh(e,r.self.RULES.all))}Y.alwaysValidSchema=uS;function lh(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]||ph(r,`unknown keyword: "${s}"`)}Y.checkUnknownRules=lh;function dh(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}Y.schemaHasRules=dh;function fS(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(t!=="$ref"&&e.all[t])return!0;return!1}Y.schemaHasRulesButRef=fS;function pS({topSchemaRef:r,schemaPath:e},t,n,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,pe._)`${t}`}return(0,pe._)`${r}${e}${(0,pe.getProperty)(n)}`}Y.schemaRefOrVal=pS;function hS(r){return uh(decodeURIComponent(r))}Y.unescapeFragment=hS;function mS(r){return encodeURIComponent(Il(r))}Y.escapeFragment=mS;function Il(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}Y.escapeJsonPointer=Il;function uh(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}Y.unescapeJsonPointer=uh;function yS(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}Y.eachItem=yS;function ah({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(i,s,o,a)=>{let c=o===void 0?s:o instanceof pe.Name?(s instanceof pe.Name?r(i,s,o):e(i,s,o),o):s instanceof pe.Name?(e(i,o,s),s):t(s,o);return a===pe.Name&&!(c instanceof pe.Name)?n(i,c):c}}Y.mergeEvaluated={props:ah({mergeNames:(r,e,t)=>r.if((0,pe._)`${t} !== true && ${e} !== undefined`,()=>{r.if((0,pe._)`${e} === true`,()=>r.assign(t,!0),()=>r.assign(t,(0,pe._)`${t} || {}`).code((0,pe._)`Object.assign(${t}, ${e})`))}),mergeToName:(r,e,t)=>r.if((0,pe._)`${t} !== true`,()=>{e===!0?r.assign(t,!0):(r.assign(t,(0,pe._)`${t} || {}`),Rl(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:fh}),items:ah({mergeNames:(r,e,t)=>r.if((0,pe._)`${t} !== true && ${e} !== undefined`,()=>r.assign(t,(0,pe._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(r,e,t)=>r.if((0,pe._)`${t} !== true`,()=>r.assign(t,e===!0?!0:(0,pe._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(r,e)=>r===!0?!0:Math.max(r,e),resultToName:(r,e)=>r.var("items",e)})};function fh(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,pe._)`{}`);return e!==void 0&&Rl(r,t,e),t}Y.evaluatedPropsToName=fh;function Rl(r,e,t){Object.keys(t).forEach(n=>r.assign((0,pe._)`${e}${(0,pe.getProperty)(n)}`,!0))}Y.setEvaluated=Rl;var ch={};function gS(r,e){return r.scopeValue("func",{ref:e,code:ch[e.code]||(ch[e.code]=new lS._Code(e.code))})}Y.useFunc=gS;var Tl;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(Tl||(Y.Type=Tl={}));function bS(r,e,t){if(r instanceof pe.Name){let n=e===Tl.Num;return t?n?(0,pe._)`"[" + ${r} + "]"`:(0,pe._)`"['" + ${r} + "']"`:n?(0,pe._)`"/" + ${r}`:(0,pe._)`"/" + ${r}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,pe.getProperty)(r).toString():"/"+Il(r)}Y.getErrorPath=bS;function ph(r,e,t=r.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===!0)throw new Error(e);r.self.logger.warn(e)}}Y.checkStrictMode=ph});var xt=E(Ol=>{"use strict";Object.defineProperty(Ol,"__esModule",{value:!0});var Ue=B(),_S={data:new Ue.Name("data"),valCxt:new Ue.Name("valCxt"),instancePath:new Ue.Name("instancePath"),parentData:new Ue.Name("parentData"),parentDataProperty:new Ue.Name("parentDataProperty"),rootData:new Ue.Name("rootData"),dynamicAnchors:new Ue.Name("dynamicAnchors"),vErrors:new Ue.Name("vErrors"),errors:new Ue.Name("errors"),this:new Ue.Name("this"),self:new Ue.Name("self"),scope:new Ue.Name("scope"),json:new Ue.Name("json"),jsonPos:new Ue.Name("jsonPos"),jsonLen:new Ue.Name("jsonLen"),jsonPart:new Ue.Name("jsonPart")};Ol.default=_S});var cs=E(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.extendErrors=Be.resetErrorsCount=Be.reportExtraError=Be.reportError=Be.keyword$DataError=Be.keywordError=void 0;var se=B(),Bo=X(),Ye=xt();Be.keywordError={message:({keyword:r})=>(0,se.str)`must pass "${r}" keyword validation`};Be.keyword$DataError={message:({keyword:r,schemaType:e})=>e?(0,se.str)`"${r}" keyword must be ${e} ($data)`:(0,se.str)`"${r}" keyword is invalid ($data)`};function vS(r,e=Be.keywordError,t,n){let{it:i}=r,{gen:s,compositeRule:o,allErrors:a}=i,c=yh(r,e,t);n??(o||a)?hh(s,c):mh(i,(0,se._)`[${c}]`)}Be.reportError=vS;function wS(r,e=Be.keywordError,t){let{it:n}=r,{gen:i,compositeRule:s,allErrors:o}=n,a=yh(r,e,t);hh(i,a),s||o||mh(n,Ye.default.vErrors)}Be.reportExtraError=wS;function SS(r,e){r.assign(Ye.default.errors,e),r.if((0,se._)`${Ye.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,se._)`${Ye.default.vErrors}.length`,e),()=>r.assign(Ye.default.vErrors,null)))}Be.resetErrorsCount=SS;function $S({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,Ye.default.errors,a=>{r.const(o,(0,se._)`${Ye.default.vErrors}[${a}]`),r.if((0,se._)`${o}.instancePath === undefined`,()=>r.assign((0,se._)`${o}.instancePath`,(0,se.strConcat)(Ye.default.instancePath,s.errorPath))),r.assign((0,se._)`${o}.schemaPath`,(0,se.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(r.assign((0,se._)`${o}.schema`,t),r.assign((0,se._)`${o}.data`,n))})}Be.extendErrors=$S;function hh(r,e){let t=r.const("err",e);r.if((0,se._)`${Ye.default.vErrors} === null`,()=>r.assign(Ye.default.vErrors,(0,se._)`[${t}]`),(0,se._)`${Ye.default.vErrors}.push(${t})`),r.code((0,se._)`${Ye.default.errors}++`)}function mh(r,e){let{gen:t,validateName:n,schemaEnv:i}=r;i.$async?t.throw((0,se._)`new ${r.ValidationError}(${e})`):(t.assign((0,se._)`${n}.errors`,e),t.return(!1))}var An={keyword:new se.Name("keyword"),schemaPath:new se.Name("schemaPath"),params:new se.Name("params"),propertyName:new se.Name("propertyName"),message:new se.Name("message"),schema:new se.Name("schema"),parentSchema:new se.Name("parentSchema")};function yh(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,se._)`{}`:ES(r,e,t)}function ES(r,e,t={}){let{gen:n,it:i}=r,s=[AS(i,t),xS(r,t)];return kS(r,e,s),n.object(...s)}function AS({errorPath:r},{instancePath:e}){let t=e?(0,se.str)`${r}${(0,Bo.getErrorPath)(e,Bo.Type.Str)}`:r;return[Ye.default.instancePath,(0,se.strConcat)(Ye.default.instancePath,t)]}function xS({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let i=n?e:(0,se.str)`${e}/${r}`;return t&&(i=(0,se.str)`${i}${(0,Bo.getErrorPath)(t,Bo.Type.Str)}`),[An.schemaPath,i]}function kS(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([An.keyword,i],[An.params,typeof e=="function"?e(r):e||(0,se._)`{}`]),c.messages&&n.push([An.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([An.schema,o],[An.parentSchema,(0,se._)`${u}${d}`],[Ye.default.data,s]),l&&n.push([An.propertyName,l])}});var bh=E(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.boolOrEmptySchema=Zn.topBoolOrEmptySchema=void 0;var PS=cs(),CS=B(),MS=xt(),TS={message:"boolean schema is false"};function IS(r){let{gen:e,schema:t,validateName:n}=r;t===!1?gh(r,!1):typeof t=="object"&&t.$async===!0?e.return(MS.default.data):(e.assign((0,CS._)`${n}.errors`,null),e.return(!0))}Zn.topBoolOrEmptySchema=IS;function RS(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),gh(r)):t.var(e,!0)}Zn.boolOrEmptySchema=RS;function gh(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,PS.reportError)(i,TS,void 0,e)}});var Nl=E(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.getRules=ei.isJSONType=void 0;var OS=["string","number","integer","boolean","null","object","array"],NS=new Set(OS);function DS(r){return typeof r=="string"&&NS.has(r)}ei.isJSONType=DS;function LS(){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:{}}}ei.getRules=LS});var Dl=E(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.shouldUseRule=Hr.shouldUseGroup=Hr.schemaHasRulesForType=void 0;function jS({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&_h(r,n)}Hr.schemaHasRulesForType=jS;function _h(r,e){return e.rules.some(t=>vh(r,t))}Hr.shouldUseGroup=_h;function vh(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))}Hr.shouldUseRule=vh});var ls=E(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.reportTypeError=Ve.checkDataTypes=Ve.checkDataType=Ve.coerceAndCheckDataType=Ve.getJSONTypes=Ve.getSchemaTypes=Ve.DataType=void 0;var qS=Nl(),FS=Dl(),US=cs(),H=B(),wh=X(),ti;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(ti||(Ve.DataType=ti={}));function BS(r){let e=Sh(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}Ve.getSchemaTypes=BS;function Sh(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(qS.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ve.getJSONTypes=Sh;function VS(r,e){let{gen:t,data:n,opts:i}=r,s=zS(e,i.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,FS.schemaHasRulesForType)(r,e[0]));if(o){let a=jl(e,n,i.strictNumbers,ti.Wrong);t.if(a,()=>{s.length?HS(r,e,s):ql(r)})}return o}Ve.coerceAndCheckDataType=VS;var $h=new Set(["string","number","integer","boolean","null"]);function zS(r,e){return e?r.filter(t=>$h.has(t)||e==="array"&&t==="array"):[]}function HS(r,e,t){let{gen:n,data:i,opts:s}=r,o=n.let("dataType",(0,H._)`typeof ${i}`),a=n.let("coerced",(0,H._)`undefined`);s.coerceTypes==="array"&&n.if((0,H._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,H._)`${i}[0]`).assign(o,(0,H._)`typeof ${i}`).if(jl(e,i,s.strictNumbers),()=>n.assign(a,i))),n.if((0,H._)`${a} !== undefined`);for(let l of t)($h.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),ql(r),n.endIf(),n.if((0,H._)`${a} !== undefined`,()=>{n.assign(i,a),KS(r,a)});function c(l){switch(l){case"string":n.elseIf((0,H._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,H._)`"" + ${i}`).elseIf((0,H._)`${i} === null`).assign(a,(0,H._)`""`);return;case"number":n.elseIf((0,H._)`${o} == "boolean" || ${i} === null - || (${o} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,H._)`+${i}`);return;case"integer":n.elseIf((0,H._)`${o} === "boolean" || ${i} === null - || (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,H._)`+${i}`);return;case"boolean":n.elseIf((0,H._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,H._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,H._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,H._)`${o} === "string" || ${o} === "number" - || ${o} === "boolean" || ${i} === null`).assign(a,(0,H._)`[${i}]`)}}}function KS({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,H._)`${e} !== undefined`,()=>r.assign((0,H._)`${e}[${t}]`,n))}function Ll(r,e,t,n=ti.Correct){let i=n===ti.Correct?H.operators.EQ:H.operators.NEQ,s;switch(r){case"null":return(0,H._)`${e} ${i} null`;case"array":s=(0,H._)`Array.isArray(${e})`;break;case"object":s=(0,H._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,H._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,H._)`typeof ${e} ${i} ${r}`}return n===ti.Correct?s:(0,H.not)(s);function o(a=H.nil){return(0,H.and)((0,H._)`typeof ${e} == "number"`,a,t?(0,H._)`isFinite(${e})`:H.nil)}}Ve.checkDataType=Ll;function jl(r,e,t,n){if(r.length===1)return Ll(r[0],e,t,n);let i,s=(0,wh.toHash)(r);if(s.array&&s.object){let o=(0,H._)`typeof ${e} != "object"`;i=s.null?o:(0,H._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=H.nil;s.number&&delete s.integer;for(let o in s)i=(0,H.and)(i,Ll(o,e,t,n));return i}Ve.checkDataTypes=jl;var WS={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,H._)`{type: ${r}}`:(0,H._)`{type: ${e}}`};function ql(r){let e=GS(r);(0,US.reportError)(e,WS)}Ve.reportTypeError=ql;function GS(r){let{gen:e,data:t,schema:n}=r,i=(0,wh.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var Ah=E(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});Vo.assignDefaults=void 0;var ri=B(),JS=X();function YS(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)Eh(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>Eh(r,s,i.default))}Vo.assignDefaults=YS;function Eh(r,e,t){let{gen:n,compositeRule:i,data:s,opts:o}=r;if(t===void 0)return;let a=(0,ri._)`${s}${(0,ri.getProperty)(e)}`;if(i){(0,JS.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,ri._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,ri._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,ri._)`${a} = ${(0,ri.stringify)(t)}`)}});var kt=E(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.validateUnion=ue.validateArray=ue.usePattern=ue.callValidateCode=ue.schemaProperties=ue.allSchemaProperties=ue.noPropertyInData=ue.propertyInData=ue.isOwnProperty=ue.hasPropFunc=ue.reportMissingProp=ue.checkMissingProp=ue.checkReportMissingProp=void 0;var ye=B(),Fl=X(),Kr=xt(),XS=X();function QS(r,e){let{gen:t,data:n,it:i}=r;t.if(Bl(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,ye._)`${e}`},!0),r.error()})}ue.checkReportMissingProp=QS;function ZS({gen:r,data:e,it:{opts:t}},n,i){return(0,ye.or)(...n.map(s=>(0,ye.and)(Bl(r,e,s,t.ownProperties),(0,ye._)`${i} = ${s}`)))}ue.checkMissingProp=ZS;function e$(r,e){r.setParams({missingProperty:e},!0),r.error()}ue.reportMissingProp=e$;function xh(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ye._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=xh;function Ul(r,e,t){return(0,ye._)`${xh(r)}.call(${e}, ${t})`}ue.isOwnProperty=Ul;function t$(r,e,t,n){let i=(0,ye._)`${e}${(0,ye.getProperty)(t)} !== undefined`;return n?(0,ye._)`${i} && ${Ul(r,e,t)}`:i}ue.propertyInData=t$;function Bl(r,e,t,n){let i=(0,ye._)`${e}${(0,ye.getProperty)(t)} === undefined`;return n?(0,ye.or)(i,(0,ye.not)(Ul(r,e,t))):i}ue.noPropertyInData=Bl;function kh(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=kh;function r$(r,e){return kh(e).filter(t=>!(0,Fl.alwaysValidSchema)(r,e[t]))}ue.schemaProperties=r$;function n$({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,c,l){let u=l?(0,ye._)`${r}, ${e}, ${n}${i}`:e,d=[[Kr.default.instancePath,(0,ye.strConcat)(Kr.default.instancePath,s)],[Kr.default.parentData,o.parentData],[Kr.default.parentDataProperty,o.parentDataProperty],[Kr.default.rootData,Kr.default.rootData]];o.opts.dynamicRef&&d.push([Kr.default.dynamicAnchors,Kr.default.dynamicAnchors]);let f=(0,ye._)`${u}, ${t.object(...d)}`;return c!==ye.nil?(0,ye._)`${a}.call(${c}, ${f})`:(0,ye._)`${a}(${f})`}ue.callValidateCode=n$;var i$=(0,ye._)`new RegExp`;function s$({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,ye._)`${i.code==="new RegExp"?i$:(0,XS.useFunc)(r,i)}(${t}, ${n})`})}ue.usePattern=s$;function o$(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,ye._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:Fl.Type.Num},s),e.if((0,ye.not)(s),a)})}}ue.validateArray=o$;function a$(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,Fl.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,ye._)`${o} || ${a}`),r.mergeValidEvaluated(u,a)||e.if((0,ye.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}ue.validateUnion=a$});var Mh=E(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.validateKeywordUsage=rr.validSchemaType=rr.funcKeywordCode=rr.macroKeywordCode=void 0;var Xe=B(),xn=xt(),c$=kt(),l$=cs();function d$(r,e){let{gen:t,keyword:n,schema:i,parentSchema:s,it:o}=r,a=e.macro.call(o.self,i,s,o),c=Ch(t,n,a);o.opts.validateSchema!==!1&&o.self.validateSchema(a,!0);let l=t.name("valid");r.subschema({schema:a,schemaPath:Xe.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),r.pass(l,()=>r.error(!0))}rr.macroKeywordCode=d$;function u$(r,e){var t;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=r;p$(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,u=Ch(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&&Ph(r),y(()=>r.error());else{let g=e.async?p():m();e.modifying&&Ph(r),y(()=>f$(r,g))}}function p(){let g=n.let("ruleErrs",null);return n.try(()=>h((0,Xe._)`await `),v=>n.assign(d,!1).if((0,Xe._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(g,(0,Xe._)`${v}.errors`),()=>n.throw(v))),g}function m(){let g=(0,Xe._)`${u}.errors`;return n.assign(g,null),h(Xe.nil),g}function h(g=e.async?(0,Xe._)`await `:Xe.nil){let v=c.opts.passContext?xn.default.this:xn.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Xe._)`${g}${(0,c$.callValidateCode)(r,u,v,_)}`,e.modifying)}function y(g){var v;n.if((0,Xe.not)((v=e.valid)!==null&&v!==void 0?v:d),g)}}rr.funcKeywordCode=u$;function Ph(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,Xe._)`${n.parentData}[${n.parentDataProperty}]`))}function f$(r,e){let{gen:t}=r;t.if((0,Xe._)`Array.isArray(${e})`,()=>{t.assign(xn.default.vErrors,(0,Xe._)`${xn.default.vErrors} === null ? ${e} : ${xn.default.vErrors}.concat(${e})`).assign(xn.default.errors,(0,Xe._)`${xn.default.vErrors}.length`),(0,l$.extendErrors)(r)},()=>r.error())}function p$({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function Ch(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,Xe.stringify)(t)})}function h$(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>"u")}rr.validSchemaType=h$;function m$({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?.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)}}rr.validateKeywordUsage=m$});var Ih=E(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.extendSubschemaMode=Wr.extendSubschemaData=Wr.getSubschema=void 0;var nr=B(),Th=X();function y$(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,nr._)`${r.schemaPath}${(0,nr.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,nr._)`${r.schemaPath}${(0,nr.getProperty)(e)}${(0,nr.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,Th.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')}Wr.getSubschema=y$;function g$(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,nr._)`${e.data}${(0,nr.getProperty)(t)}`,!0);c(f),r.errorPath=(0,nr.str)`${l}${(0,Th.getErrorPath)(t,n,d.jsPropertySyntax)}`,r.parentDataProperty=(0,nr._)`${t}`,r.dataPathArr=[...u,r.parentDataProperty]}if(i!==void 0){let l=i instanceof nr.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]}}Wr.extendSubschemaData=g$;function b$(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}Wr.extendSubschemaMode=b$});var Vl=E((dD,Rh)=>{"use strict";Rh.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 Nh=E((uD,Oh)=>{"use strict";var Gr=Oh.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(){};zo(e,n,i,r,"",r)};Gr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Gr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Gr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Gr.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 zo(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 Gr.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.getSchemaRefs=at.resolveUrl=at.normalizeId=at._getFullPath=at.getFullPath=at.inlineRef=void 0;var v$=X(),w$=Vl(),S$=Nh(),$$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function E$(r,e=!0){return typeof r=="boolean"?!0:e===!0?!zl(r):e?Dh(r)<=e:!1}at.inlineRef=E$;var A$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function zl(r){for(let e in r){if(A$.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(zl)||typeof t=="object"&&zl(t))return!0}return!1}function Dh(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!$$.has(t)&&(typeof r[t]=="object"&&(0,v$.eachItem)(r[t],n=>e+=Dh(n)),e===1/0))return 1/0}return e}function Lh(r,e="",t){t!==!1&&(e=ni(e));let n=r.parse(e);return jh(r,n)}at.getFullPath=Lh;function jh(r,e){return r.serialize(e).split("#")[0]+"#"}at._getFullPath=jh;var x$=/#\/?$/;function ni(r){return r?r.replace(x$,""):""}at.normalizeId=ni;function k$(r,e,t){return t=ni(t),r.resolve(e,t)}at.resolveUrl=k$;var P$=/^[a-z_][-a-z0-9._]*$/i;function C$(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=ni(r[t]||e),s={"":i},o=Lh(n,i,!1),a={},c=new Set;return S$(r,{allKeys:!0},(d,f,p,m)=>{if(m===void 0)return;let h=o+f,y=s[m];typeof d[t]=="string"&&(y=g.call(this,d[t])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[f]=y;function g(_){let w=this.opts.uriResolver.resolve;if(_=ni(y?w(y,_):_),c.has(_))throw u(_);c.add(_);let A=this.refs[_];return typeof A=="string"&&(A=this.refs[A]),typeof A=="object"?l(d,A.schema,_):_!==ni(h)&&(_[0]==="#"?(l(d,a[_],_),a[_]=d):this.refs[_]=h),_}function v(_){if(typeof _=="string"){if(!P$.test(_))throw new Error(`invalid anchor "${_}"`);g.call(this,`#${_}`)}}}),a;function l(d,f,p){if(f!==void 0&&!w$(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}at.getSchemaRefs=C$});var ii=E(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.getData=Jr.KeywordCxt=Jr.validateFunctionCode=void 0;var Vh=bh(),qh=ls(),Kl=Dl(),Ho=ls(),M$=Ah(),fs=Mh(),Hl=Ih(),j=B(),U=xt(),T$=ds(),Sr=X(),us=cs();function I$(r){if(Kh(r)&&(Wh(r),Hh(r))){N$(r);return}zh(r,()=>(0,Vh.topBoolOrEmptySchema)(r))}Jr.validateFunctionCode=I$;function zh({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},s){i.code.es5?r.func(e,(0,j._)`${U.default.data}, ${U.default.valCxt}`,n.$async,()=>{r.code((0,j._)`"use strict"; ${Fh(t,i)}`),O$(r,i),r.code(s)}):r.func(e,(0,j._)`${U.default.data}, ${R$(i)}`,n.$async,()=>r.code(Fh(t,i)).code(s))}function R$(r){return(0,j._)`{${U.default.instancePath}="", ${U.default.parentData}, ${U.default.parentDataProperty}, ${U.default.rootData}=${U.default.data}${r.dynamicRef?(0,j._)`, ${U.default.dynamicAnchors}={}`:j.nil}}={}`}function O$(r,e){r.if(U.default.valCxt,()=>{r.var(U.default.instancePath,(0,j._)`${U.default.valCxt}.${U.default.instancePath}`),r.var(U.default.parentData,(0,j._)`${U.default.valCxt}.${U.default.parentData}`),r.var(U.default.parentDataProperty,(0,j._)`${U.default.valCxt}.${U.default.parentDataProperty}`),r.var(U.default.rootData,(0,j._)`${U.default.valCxt}.${U.default.rootData}`),e.dynamicRef&&r.var(U.default.dynamicAnchors,(0,j._)`${U.default.valCxt}.${U.default.dynamicAnchors}`)},()=>{r.var(U.default.instancePath,(0,j._)`""`),r.var(U.default.parentData,(0,j._)`undefined`),r.var(U.default.parentDataProperty,(0,j._)`undefined`),r.var(U.default.rootData,U.default.data),e.dynamicRef&&r.var(U.default.dynamicAnchors,(0,j._)`{}`)})}function N$(r){let{schema:e,opts:t,gen:n}=r;zh(r,()=>{t.$comment&&e.$comment&&Jh(r),F$(r),n.let(U.default.vErrors,null),n.let(U.default.errors,0),t.unevaluated&&D$(r),Gh(r),V$(r)})}function D$(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,j._)`${t}.evaluated`),e.if((0,j._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,j._)`${r.evaluated}.props`,(0,j._)`undefined`)),e.if((0,j._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,j._)`${r.evaluated}.items`,(0,j._)`undefined`))}function Fh(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,j._)`/*# sourceURL=${t} */`:j.nil}function L$(r,e){if(Kh(r)&&(Wh(r),Hh(r))){j$(r,e);return}(0,Vh.boolOrEmptySchema)(r,e)}function Hh({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 Kh(r){return typeof r.schema!="boolean"}function j$(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&Jh(r),U$(r),B$(r);let s=n.const("_errs",U.default.errors);Gh(r,s),n.var(e,(0,j._)`${s} === ${U.default.errors}`)}function Wh(r){(0,Sr.checkUnknownRules)(r),q$(r)}function Gh(r,e){if(r.opts.jtd)return Uh(r,[],!1,e);let t=(0,qh.getSchemaTypes)(r.schema),n=(0,qh.coerceAndCheckDataType)(r,t);Uh(r,t,!n,e)}function q$(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,Sr.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function F$(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,Sr.checkStrictMode)(r,"default is ignored in the schema root")}function U$(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,T$.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function B$(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function Jh({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let s=t.$comment;if(i.$comment===!0)r.code((0,j._)`${U.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,j.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,j._)`${U.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function V$(r){let{gen:e,schemaEnv:t,validateName:n,ValidationError:i,opts:s}=r;t.$async?e.if((0,j._)`${U.default.errors} === 0`,()=>e.return(U.default.data),()=>e.throw((0,j._)`new ${i}(${U.default.vErrors})`)):(e.assign((0,j._)`${n}.errors`,U.default.vErrors),s.unevaluated&&z$(r),e.return((0,j._)`${U.default.errors} === 0`))}function z$({gen:r,evaluated:e,props:t,items:n}){t instanceof j.Name&&r.assign((0,j._)`${e}.props`,t),n instanceof j.Name&&r.assign((0,j._)`${e}.items`,n)}function Uh(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,Sr.schemaHasRulesButRef)(s,u))){i.block(()=>Xh(r,"$ref",u.all.$ref.definition));return}c.jtd||H$(r,e),i.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,Kl.shouldUseGroup)(s,f)&&(f.type?(i.if((0,Ho.checkDataType)(f.type,o,c.strictNumbers)),Bh(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,Ho.reportTypeError)(r)),i.endIf()):Bh(r,f),a||i.if((0,j._)`${U.default.errors} === ${n||0}`))}}function Bh(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,M$.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,Kl.shouldUseRule)(n,s)&&Xh(r,s.keyword,s.definition,e.type)})}function H$(r,e){r.schemaEnv.meta||!r.opts.strictTypes||(K$(r,e),r.opts.allowUnionTypes||W$(r,e),G$(r,r.dataTypes))}function K$(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{Yh(r.dataTypes,t)||Wl(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),Y$(r,e)}}function W$(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Wl(r,"use allowUnionTypes to allow union type keyword")}function G$(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,Kl.shouldUseRule)(r.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>J$(e,o))&&Wl(r,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function J$(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function Yh(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function Y$(r,e){let t=[];for(let n of r.dataTypes)Yh(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function Wl(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,Sr.checkStrictMode)(r,e,r.opts.strictTypes)}var Ko=class{constructor(e,t,n){if((0,fs.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,Sr.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",Qh(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,fs.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,j.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,j.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,j._)`${t} !== undefined && (${(0,j.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?us.reportExtraError:us.reportError)(this,this.def.error,t)}$dataError(){(0,us.reportError)(this,this.def.$dataError||us.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,us.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=j.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=j.nil,t=j.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:s,def:o}=this;n.if((0,j.or)((0,j._)`${i} === undefined`,t)),e!==j.nil&&n.assign(e,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==j.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:i,it:s}=this;return(0,j.or)(o(),a());function o(){if(n.length){if(!(t instanceof j.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,j._)`${(0,Ho.checkDataTypes)(c,t,s.opts.strictNumbers,Ho.DataType.Wrong)}`}return j.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,j._)`!${c}(${t})`}return j.nil}}subschema(e,t){let n=(0,Hl.getSubschema)(this.it,e);(0,Hl.extendSubschemaData)(n,this.it,e),(0,Hl.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return L$(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Sr.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=Sr.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,j.Name)),!0}};Jr.KeywordCxt=Ko;function Xh(r,e,t,n){let i=new Ko(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,fs.funcKeywordCode)(i,t):"macro"in t?(0,fs.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,fs.funcKeywordCode)(i,t)}var X$=/^\/(?:[^~]|~0|~1)*$/,Q$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Qh(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,s;if(r==="")return U.default.rootData;if(r[0]==="/"){if(!X$.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,s=U.default.rootData}else{let l=Q$.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,j._)`${s}${(0,j.getProperty)((0,Sr.unescapeJsonPointer)(l))}`,o=(0,j._)`${o} && ${s}`);return o;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Jr.getData=Qh});var ps=E(Jl=>{"use strict";Object.defineProperty(Jl,"__esModule",{value:!0});var Gl=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Jl.default=Gl});var si=E(Ql=>{"use strict";Object.defineProperty(Ql,"__esModule",{value:!0});var Yl=ds(),Xl=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,Yl.resolveUrl)(e,t,n),this.missingSchema=(0,Yl.normalizeId)((0,Yl.getFullPath)(e,this.missingRef))}};Ql.default=Xl});var hs=E(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.resolveSchema=Pt.getCompilingSchema=Pt.resolveRef=Pt.compileSchema=Pt.SchemaEnv=void 0;var Lt=B(),Z$=ps(),kn=xt(),jt=ds(),Zh=X(),eE=ii(),oi=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?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Pt.SchemaEnv=oi;function ed(r){let e=em.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 Lt.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;r.$async&&(a=o.scopeValue("Error",{ref:Z$.default,code:(0,Lt._)`require("ajv/dist/runtime/validation_error").default`}));let c=o.scopeName("validate");r.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:kn.default.data,parentData:kn.default.parentData,parentDataProperty:kn.default.parentDataProperty,dataNames:[kn.default.data],dataPathArr:[Lt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:r.schema,code:(0,Lt.stringify)(r.schema)}:{ref:r.schema}),validateName:c,ValidationError:a,schema:r.schema,schemaEnv:r,rootId:t,baseId:r.baseId||t,schemaPath:Lt.nil,errSchemaPath:r.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Lt._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(r),(0,eE.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let d=o.toString();u=`${o.scopeRefs(kn.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,r));let p=new Function(`${kn.default.self}`,`${kn.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 Lt.Name?void 0:m,items:h instanceof Lt.Name?void 0:h,dynamicProps:m instanceof Lt.Name,dynamicItems:h instanceof Lt.Name},p.source&&(p.source.evaluated=(0,Lt.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=ed;function tE(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=iE.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 oi({schema:o,schemaId:a,root:r,baseId:e}))}if(s!==void 0)return r.refs[t]=rE.call(this,s)}Pt.resolveRef=tE;function rE(r){return(0,jt.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:ed.call(this,r)}function em(r){for(let e of this._compilations)if(nE(e,r))return e}Pt.getCompilingSchema=em;function nE(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function iE(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||Wo.call(this,r,e)}function Wo(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 Zl.call(this,t,r);let s=(0,jt.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=Wo.call(this,r,o);return typeof a?.schema!="object"?void 0:Zl.call(this,t,a)}if(typeof o?.schema=="object"){if(o.validate||ed.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 oi({schema:a,schemaId:c,root:r,baseId:i})}return Zl.call(this,t,o)}}Pt.resolveSchema=Wo;var sE=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Zl(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,Zh.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!sE.has(a)&&l&&(e=(0,jt.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,Zh.schemaHasRulesButRef)(t,this.RULES)){let a=(0,jt.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=Wo.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new oi({schema:t,schemaId:o,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var tm=E((gD,oE)=>{oE.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 nd=E((bD,am)=>{"use strict";var aE=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),nm=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),td=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),im=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),cE=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function rd(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 lE=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function rm(r){return r.length=0,!0}function dE(r,e,t){if(r.length){let n=rd(r);if(n!=="")e.push(n);else return t.error=!0,!1;r.length=0}return!0}function uE(r){let e=0,t={error:!1,address:"",zone:""},n=[],i=[],s=!1,o=!1,a=dE;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=rm}else{i.push(l);continue}}return i.length&&(a===rm?t.zone=i.join(""):o?n.push(i.join("")):n.push(rd(i))),t.address=n.join(""),t}function sm(r){if(fE(r,":")<2)return{host:r,isIPV6:!1};let e=uE(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 fE(r,e){let t=0;for(let n=0;nhE[n])}function gE(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n{"use strict";var{isUUID:wE}=nd(),SE=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,$E=["http","https","ws","wss","urn","urn:uuid"];function EE(r){return $E.indexOf(r)!==-1}function id(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 cm(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function lm(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 AE(r){return r.secure=id(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function xE(r){if((r.port===(id(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 kE(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(SE);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=sd(i);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function PE(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=sd(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 CE(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!wE(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function ME(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var dm={scheme:"http",domainHost:!0,parse:cm,serialize:lm},TE={scheme:"https",domainHost:dm.domainHost,parse:cm,serialize:lm},Go={scheme:"ws",domainHost:!0,parse:AE,serialize:xE},IE={scheme:"wss",domainHost:Go.domainHost,parse:Go.parse,serialize:Go.serialize},RE={scheme:"urn",parse:kE,serialize:PE,skipNormalize:!0},OE={scheme:"urn:uuid",parse:CE,serialize:ME,skipNormalize:!0},Jo={http:dm,https:TE,ws:Go,wss:IE,urn:RE,"urn:uuid":OE};Object.setPrototypeOf(Jo,null);function sd(r){return r&&(Jo[r]||Jo[r.toLowerCase()])||void 0}um.exports={wsIsSecure:id,SCHEMES:Jo,isValidSchemeName:EE,getSchemeHandler:sd}});var gm=E((vD,Qo)=>{"use strict";var{normalizeIPv6:NE,removeDotSegments:ms,recomposeAuthority:DE,normalizePercentEncoding:LE,normalizePathEncoding:jE,escapePreservingEscapes:qE,reescapeHostDelimiters:FE,isIPv4:UE,nonSimpleDomain:BE}=nd(),{SCHEMES:VE,getSchemeHandler:hm}=fm();function zE(r,e){return typeof r=="string"?r=XE(r,e):typeof r=="object"&&(r=Xo(Pn(r,e),e)),r}function HE(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:s}=Yo(r,n),{parsed:o,malformedAuthorityOrPort:a}=Yo(e,n);if(s||a)throw new Error(i.error||o.error||"URI is malformed.");let c=mm(i,o,n,!0);return n.skipEscape=!0,Pn(c,n)}function mm(r,e,t,n){let i={};return n||(r=Xo(Pn(r,t),t),e=Xo(Pn(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=ms(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=ms(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=ms(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=ms(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 KE(r,e,t){let n=pm(r,t),i=pm(e,t);return n!==void 0&&i!==void 0&&n.toLowerCase()===i.toLowerCase()}function Pn(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=hm(n.scheme||t.scheme);s&&s.serialize&&s.serialize(t,n),t.path!==void 0&&(n.skipEscape?t.path=LE(t.path):(t.path=qE(t.path),t.scheme!==void 0&&(t.path=t.path.split("%3A").join(":")))),n.reference!=="suffix"&&t.scheme&&i.push(t.scheme,":");let o=DE(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=ms(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 WE=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,GE=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,JE=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function YE(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 Yo(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(GE);o!==null&&o[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let a=r.match(JE);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(WE);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=YE(n,c);if(l!==void 0&&(n.error=n.error||l,i=!0),n.host)if(UE(n.host)===!1){let f=NE(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=hm(t.scheme||n.scheme);if(!t.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(t.domainHost||u&&u.domainHost)&&s===!1&&BE(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=FE(unescape(n.host),s))),n.path&&(n.path=jE(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{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 Xo(r,e){return Yo(r,e).parsed}function XE(r,e){return ym(r,e).normalized}function ym(r,e){let{parsed:t,malformedAuthorityOrPort:n}=Yo(r,e);return{normalized:n?r:Pn(t,e),malformedAuthorityOrPort:n}}function pm(r,e){if(typeof r=="string"){let{normalized:t,malformedAuthorityOrPort:n}=ym(r,e);return n?void 0:t}if(typeof r=="object")return Pn(r,e)}var od={SCHEMES:VE,normalize:zE,resolve:HE,resolveComponent:mm,equal:KE,serialize:Pn,parse:Xo};Qo.exports=od;Qo.exports.default=od;Qo.exports.fastUri=od});var _m=E(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var bm=gm();bm.code='require("ajv/dist/runtime/uri").default';ad.default=bm});var dd=E(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.CodeGen=Oe.Name=Oe.nil=Oe.stringify=Oe.str=Oe._=Oe.KeywordCxt=void 0;var QE=ii();Object.defineProperty(Oe,"KeywordCxt",{enumerable:!0,get:function(){return QE.KeywordCxt}});var ai=B();Object.defineProperty(Oe,"_",{enumerable:!0,get:function(){return ai._}});Object.defineProperty(Oe,"str",{enumerable:!0,get:function(){return ai.str}});Object.defineProperty(Oe,"stringify",{enumerable:!0,get:function(){return ai.stringify}});Object.defineProperty(Oe,"nil",{enumerable:!0,get:function(){return ai.nil}});Object.defineProperty(Oe,"Name",{enumerable:!0,get:function(){return ai.Name}});Object.defineProperty(Oe,"CodeGen",{enumerable:!0,get:function(){return ai.CodeGen}});var ZE=ps(),Em=si(),eA=Nl(),ys=hs(),tA=B(),gs=ds(),Zo=ls(),ld=X(),vm=tm(),rA=_m(),Am=(r,e)=>new RegExp(r,e);Am.code="new RegExp";var nA=["removeAdditional","useDefaults","coerceTypes"],iA=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),sA={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."},oA={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},wm=200;function aA(r){var e,t,n,i,s,o,a,c,l,u,d,f,p,m,h,y,g,v,_,w,A,x,M,S,C;let $=r.strict,V=(e=r.code)===null||e===void 0?void 0:e.optimize,q=V===!0||V===void 0?1:V||0,oe=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:Am,P=(i=r.uriResolver)!==null&&i!==void 0?i:rA.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:q,regExp:oe}:{optimize:q,regExp:oe},loopRequired:(h=r.loopRequired)!==null&&h!==void 0?h:wm,loopEnum:(y=r.loopEnum)!==null&&y!==void 0?y:wm,meta:(g=r.meta)!==null&&g!==void 0?g:!0,messages:(v=r.messages)!==null&&v!==void 0?v:!0,inlineRefs:(_=r.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(w=r.schemaId)!==null&&w!==void 0?w:"$id",addUsedSchema:(A=r.addUsedSchema)!==null&&A!==void 0?A:!0,validateSchema:(x=r.validateSchema)!==null&&x!==void 0?x:!0,validateFormats:(M=r.validateFormats)!==null&&M!==void 0?M:!0,unicodeRegExp:(S=r.unicodeRegExp)!==null&&S!==void 0?S:!0,int32range:(C=r.int32range)!==null&&C!==void 0?C:!0,uriResolver:P}}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,...aA(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new tA.ValueScope({scope:{},prefixes:iA,es5:t,lines:n}),this.logger=pA(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,eA.getRules)(),Sm.call(this,sA,e,"NOT SUPPORTED"),Sm.call(this,oA,e,"DEPRECATED","warn"),this._metaOpts=uA.call(this),e.formats&&lA.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&dA.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),cA.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=vm;n==="id"&&(i={...vm},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 Em.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,gs.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=$m.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new ys.SchemaEnv({schema:{},schemaId:n});if(t=ys.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=$m.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,gs.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(mA.call(this,n,t),!t)return(0,ld.eachItem)(n,s=>cd.call(this,s)),this;gA.call(this,t);let i={...t,type:(0,Zo.getJSONTypes)(t.type),schemaType:(0,Zo.getJSONTypes)(t.schemaType)};return(0,ld.eachItem)(n,i.type.length===0?s=>cd.call(this,s,i):s=>i.type.forEach(o=>cd.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]=xm(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,gs.normalizeId)(o||n);let l=gs.getSchemaRefs.call(this,e,n);return c=new ys.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):ys.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{ys.compileSchema.call(this,e)}finally{this.opts=t}}};bs.ValidationError=ZE.default;bs.MissingRefError=Em.default;Oe.default=bs;function Sm(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 $m(r){return r=(0,gs.normalizeId)(r),this.schemas[r]||this.refs[r]}function cA(){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 lA(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function dA(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 uA(){let r={...this.opts};for(let e of nA)delete r[e];return r}var fA={log(){},warn(){},error(){}};function pA(r){if(r===!1)return fA;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 hA=/^[a-z_$][a-z0-9_$:-]*$/i;function mA(r,e){let{RULES:t}=this;if((0,ld.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!hA.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 cd(r,e,t){var n;let i=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,Zo.getJSONTypes)(e.type),schemaType:(0,Zo.getJSONTypes)(e.schemaType)}};e.before?yA.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 yA(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 gA(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=xm(e)),r.validateSchema=this.compile(e,!0))}var bA={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function xm(r){return{anyOf:[r,bA]}}});var km=E(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var _A={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ud.default=_A});var ra=E(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.callRef=Cn.getValidate=void 0;var vA=si(),Pm=kt(),ct=B(),ci=xt(),Cm=hs(),ea=X(),wA={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=Cm.resolveRef.call(c,l,i,t);if(u===void 0)throw new vA.default(n.opts.uriResolver,i,t);if(u instanceof Cm.SchemaEnv)return f(u);return p(u);function d(){if(s===l)return ta(r,o,s,s.$async);let m=e.scopeValue("root",{ref:l});return ta(r,(0,ct._)`${m}.validate`,l,l.$async)}function f(m){let h=Mm(r,m);ta(r,h,m,m.$async)}function p(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,ct.stringify)(m)}:{ref:m}),y=e.name("valid"),g=r.subschema({schema:m,dataTypes:[],schemaPath:ct.nil,topSchemaRef:h,errSchemaPath:t},y);r.mergeEvaluated(g),r.ok(y)}}};function Mm(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,ct._)`${t.scopeValue("wrapper",{ref:e})}.validate`}Cn.getValidate=Mm;function ta(r,e,t,n){let{gen:i,it:s}=r,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?ci.default.this:ct.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,ct._)`await ${(0,Pm.callValidateCode)(r,e,l)}`),p(e),o||i.assign(m,!0)},h=>{i.if((0,ct._)`!(${h} instanceof ${s.ValidationError})`,()=>i.throw(h)),f(h),o||i.assign(m,!1)}),r.ok(m)}function d(){r.result((0,Pm.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(m){let h=(0,ct._)`${m}.errors`;i.assign(ci.default.vErrors,(0,ct._)`${ci.default.vErrors} === null ? ${h} : ${ci.default.vErrors}.concat(${h})`),i.assign(ci.default.errors,(0,ct._)`${ci.default.vErrors}.length`)}function p(m){var h;if(!s.opts.unevaluated)return;let y=(h=t?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=ea.mergeEvaluated.props(i,y.props,s.props));else{let g=i.var("props",(0,ct._)`${m}.evaluated.props`);s.props=ea.mergeEvaluated.props(i,g,s.props,ct.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=ea.mergeEvaluated.items(i,y.items,s.items));else{let g=i.var("items",(0,ct._)`${m}.evaluated.items`);s.items=ea.mergeEvaluated.items(i,g,s.items,ct.Name)}}}Cn.callRef=ta;Cn.default=wA});var pd=E(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var SA=km(),$A=ra(),EA=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",SA.default,$A.default];fd.default=EA});var Tm=E(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var na=B(),Yr=na.operators,ia={maximum:{okStr:"<=",ok:Yr.LTE,fail:Yr.GT},minimum:{okStr:">=",ok:Yr.GTE,fail:Yr.LT},exclusiveMaximum:{okStr:"<",ok:Yr.LT,fail:Yr.GTE},exclusiveMinimum:{okStr:">",ok:Yr.GT,fail:Yr.LTE}},AA={message:({keyword:r,schemaCode:e})=>(0,na.str)`must be ${ia[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,na._)`{comparison: ${ia[r].okStr}, limit: ${e}}`},xA={keyword:Object.keys(ia),type:"number",schemaType:"number",$data:!0,error:AA,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,na._)`${t} ${ia[e].fail} ${n} || isNaN(${t})`)}};hd.default=xA});var Im=E(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var _s=B(),kA={message:({schemaCode:r})=>(0,_s.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,_s._)`{multipleOf: ${r}}`},PA={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:kA,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,s=i.opts.multipleOfPrecision,o=e.let("res"),a=s?(0,_s._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,_s._)`${o} !== parseInt(${o})`;r.fail$data((0,_s._)`(${n} === 0 || (${o} = ${t}/${n}, ${a}))`)}};md.default=PA});var Om=E(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});function Rm(r){let e=r.length,t=0,n=0,i;for(;n=55296&&i<=56319&&n{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var Mn=B(),CA=X(),MA=Om(),TA={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,Mn.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,Mn._)`{limit: ${r}}`},IA={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:TA,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,s=e==="maxLength"?Mn.operators.GT:Mn.operators.LT,o=i.opts.unicode===!1?(0,Mn._)`${t}.length`:(0,Mn._)`${(0,CA.useFunc)(r.gen,MA.default)}(${t})`;r.fail$data((0,Mn._)`${o} ${s} ${n}`)}};gd.default=IA});var Dm=E(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var RA=kt(),OA=X(),li=B(),NA={message:({schemaCode:r})=>(0,li.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,li._)`{pattern: ${r}}`},DA={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:NA,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,li._)`new RegExp`:(0,OA.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,li._)`${l}(${s}, ${a}).test(${t})`),()=>e.assign(u,!1)),r.fail$data((0,li._)`!${u}`)}else{let c=(0,RA.usePattern)(r,i);r.fail$data((0,li._)`!${c}.test(${t})`)}}};bd.default=DA});var Lm=E(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var vs=B(),LA={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,vs.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,vs._)`{limit: ${r}}`},jA={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:LA,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?vs.operators.GT:vs.operators.LT;r.fail$data((0,vs._)`Object.keys(${t}).length ${i} ${n}`)}};_d.default=jA});var jm=E(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var ws=kt(),Ss=B(),qA=X(),FA={message:({params:{missingProperty:r}})=>(0,Ss.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,Ss._)`{missingProperty: ${r}}`},UA={keyword:"required",type:"object",schemaType:"array",$data:!0,error:FA,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?.[h]===void 0&&!m.has(h)){let y=o.schemaEnv.baseId+o.errSchemaPath,g=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,qA.checkStrictMode)(o,g,o.opts.strictRequired)}}function l(){if(c||s)r.block$data(Ss.nil,d);else for(let p of t)(0,ws.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,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,i,p,a.ownProperties),()=>r.error())})}function f(p,m){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(m,(0,ws.propertyInData)(e,i,p,a.ownProperties)),e.if((0,Ss.not)(m),()=>{r.error(),e.break()})},Ss.nil)}}};vd.default=UA});var qm=E(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var $s=B(),BA={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,$s.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,$s._)`{limit: ${r}}`},VA={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:BA,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?$s.operators.GT:$s.operators.LT;r.fail$data((0,$s._)`${t}.length ${i} ${n}`)}};wd.default=VA});var sa=E(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var Fm=Vl();Fm.code='require("ajv/dist/runtime/equal").default';Sd.default=Fm});var Um=E(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var $d=ls(),Ne=B(),zA=X(),HA=sa(),KA={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}}`},WA={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:KA,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,$d.getSchemaTypes)(s.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"),g=(0,$d.checkDataTypes)(l,y,a.opts.strictNumbers,$d.DataType.Wrong),v=e.const("indices",(0,Ne._)`{}`);e.for((0,Ne._)`;${m}--;`,()=>{e.let(y,(0,Ne._)`${t}[${m}]`),e.if(g,(0,Ne._)`continue`),l.length>1&&e.if((0,Ne._)`typeof ${y} == "string"`,(0,Ne._)`${y} += "_"`),e.if((0,Ne._)`typeof ${v}[${y}] == "number"`,()=>{e.assign(h,(0,Ne._)`${v}[${y}]`),r.error(),e.assign(c,!1).break()}).code((0,Ne._)`${v}[${y}] = ${m}`)})}function p(m,h){let y=(0,zA.useFunc)(e,HA.default),g=e.name("outer");e.label(g).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(g)})))}}};Ed.default=WA});var Bm=E(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var Ad=B(),GA=X(),JA=sa(),YA={message:"must be equal to constant",params:({schemaCode:r})=>(0,Ad._)`{allowedValue: ${r}}`},XA={keyword:"const",$data:!0,error:YA,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:s}=r;n||s&&typeof s=="object"?r.fail$data((0,Ad._)`!${(0,GA.useFunc)(e,JA.default)}(${t}, ${i})`):r.fail((0,Ad._)`${s} !== ${t}`)}};xd.default=XA});var Vm=E(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var Es=B(),QA=X(),ZA=sa(),ex={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,Es._)`{allowedValues: ${r}}`},tx={keyword:"enum",schemaType:"array",$data:!0,error:ex,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??(c=(0,QA.useFunc)(e,ZA.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,Es.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,Es._)`${l()}(${t}, ${p})`,()=>e.assign(u,!0).break()))}function f(p,m){let h=i[m];return typeof h=="object"&&h!==null?(0,Es._)`${l()}(${t}, ${p}[${m}])`:(0,Es._)`${t} === ${h}`}}};kd.default=tx});var Cd=E(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var rx=Tm(),nx=Im(),ix=Nm(),sx=Dm(),ox=Lm(),ax=jm(),cx=qm(),lx=Um(),dx=Bm(),ux=Vm(),fx=[rx.default,nx.default,ix.default,sx.default,ox.default,ax.default,cx.default,lx.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},dx.default,ux.default];Pd.default=fx});var Td=E(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.validateAdditionalItems=void 0;var Tn=B(),Md=X(),px={message:({params:{len:r}})=>(0,Tn.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,Tn._)`{limit: ${r}}`},hx={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:px,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,Md.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}zm(r,n)}};function zm(r,e){let{gen:t,schema:n,data:i,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,Tn._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,Tn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Md.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,Tn._)`${a} <= ${e.length}`);t.if((0,Tn.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,u=>{r.subschema({keyword:s,dataProp:u,dataPropType:Md.Type.Num},l),o.allErrors||t.if((0,Tn.not)(l),()=>t.break())})}}As.validateAdditionalItems=zm;As.default=hx});var Id=E(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});xs.validateTuple=void 0;var Hm=B(),oa=X(),mx=kt(),yx={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return Km(r,"additionalItems",e);t.items=!0,!(0,oa.alwaysValidSchema)(t,e)&&r.ok((0,mx.validateArray)(r))}};function Km(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=oa.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,Hm._)`${s}.length`);t.forEach((d,f)=>{(0,oa.alwaysValidSchema)(a,d)||(n.if((0,Hm._)`${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,oa.checkStrictMode)(a,y,f.strictTuples)}}}xs.validateTuple=Km;xs.default=yx});var Wm=E(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var gx=Id(),bx={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,gx.validateTuple)(r,"items")};Rd.default=bx});var Jm=E(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});var Gm=B(),_x=X(),vx=kt(),wx=Td(),Sx={message:({params:{len:r}})=>(0,Gm.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,Gm._)`{limit: ${r}}`},$x={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Sx,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,_x.alwaysValidSchema)(n,e)&&(i?(0,wx.validateAdditionalItems)(r,i):r.ok((0,vx.validateArray)(r)))}};Od.default=$x});var Ym=E(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var Ct=B(),aa=X(),Ex={message:({params:{min:r,max:e}})=>e===void 0?(0,Ct.str)`must contain at least ${r} valid item(s)`:(0,Ct.str)`must contain at least ${r} and no more than ${e} valid item(s)`,params:({params:{min:r,max:e}})=>e===void 0?(0,Ct._)`{minContains: ${r}}`:(0,Ct._)`{minContains: ${r}, maxContains: ${e}}`},Ax={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Ex,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,Ct._)`${i}.length`);if(r.setParams({min:o,max:a}),a===void 0&&o===0){(0,aa.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,aa.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,aa.alwaysValidSchema)(s,t)){let h=(0,Ct._)`${u} >= ${o}`;a!==void 0&&(h=(0,Ct._)`${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,Ct._)`${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,g=>{r.subschema({keyword:"contains",dataProp:g,dataPropType:aa.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,Ct._)`${h}++`),a===void 0?e.if((0,Ct._)`${h} >= ${o}`,()=>e.assign(d,!0).break()):(e.if((0,Ct._)`${h} > ${a}`,()=>e.assign(d,!1).break()),o===1?e.assign(d,!0):e.if((0,Ct._)`${h} >= ${o}`,()=>e.assign(d,!0)))}}};Nd.default=Ax});var ca=E(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.validateSchemaDeps=ir.validatePropertyDeps=ir.error=void 0;var Dd=B(),xx=X(),ks=kt();ir.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,Dd.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,Dd._)`{property: ${r}, +var vS=Object.create;var zo=Object.defineProperty;var _S=Object.getOwnPropertyDescriptor;var wS=Object.getOwnPropertyNames;var SS=Object.getPrototypeOf,$S=Object.prototype.hasOwnProperty;var E=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),ES=(r,e)=>{for(var t in e)zo(r,t,{get:e[t],enumerable:!0})},bh=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of wS(e))!$S.call(r,i)&&i!==t&&zo(r,i,{get:()=>e[i],enumerable:!(n=_S(e,i))||n.enumerable});return r};var An=(r,e,t)=>(t=r!=null?vS(SS(r)):{},bh(e||!r||!r.__esModule?zo(t,"default",{value:r,enumerable:!0}):t,r)),xS=r=>bh(zo({},"__esModule",{value:!0}),r);var ds=E(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.regexpCode=ae.getEsmExportName=ae.getProperty=ae.safeStringify=ae.stringify=ae.strConcat=ae.addCodeArg=ae.str=ae._=ae.nil=ae._Code=ae.Name=ae.IDENTIFIER=ae._CodeOrName=void 0;var cs=class{};ae._CodeOrName=cs;ae.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var kn=class extends cs{constructor(e){if(super(),!ae.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}}};ae.Name=kn;var kt=class extends cs{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 kn&&(t[n.str]=(t[n.str]||0)+1),t),{})}};ae._Code=kt;ae.nil=new kt("");function vh(r,...e){let t=[r[0]],n=0;for(;n{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.ValueScope=lt.ValueScopeName=lt.Scope=lt.varKinds=lt.UsedValueState=void 0;var ct=ds(),El=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ho;(function(r){r[r.Started=0]="Started",r[r.Completed=1]="Completed"})(Ho||(lt.UsedValueState=Ho={}));lt.varKinds={const:new ct.Name("const"),let:new ct.Name("let"),var:new ct.Name("var")};var Ko=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof ct.Name?e:this.name(e)}name(e){return new ct.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}}};lt.Scope=Ko;var Wo=class extends ct.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=(0,ct._)`.${new ct.Name(t)}[${n}]`}};lt.ValueScopeName=Wo;var OS=(0,ct._)`\n`,xl=class extends Ko{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?OS:ct.nil}}get(){return this._scope}name(e){return new Wo(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,ct._)`${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=ct.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,Ho.Started);let u=t(l);if(u){let d=this.opts.es5?lt.varKinds.var:lt.varKinds.const;s=(0,ct._)`${s}${d} ${l} = ${u};${this.opts._n}`}else if(u=i?.(l))s=(0,ct._)`${s}${u}${this.opts._n}`;else throw new El(l);c.set(l,Ho.Completed)})}return s}};lt.ValueScope=xl});var B=E(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.or=J.and=J.not=J.CodeGen=J.operators=J.varKinds=J.ValueScopeName=J.ValueScope=J.Scope=J.Name=J.regexpCode=J.stringify=J.getProperty=J.nil=J.strConcat=J.str=J._=void 0;var ne=ds(),jt=Al(),Jr=ds();Object.defineProperty(J,"_",{enumerable:!0,get:function(){return Jr._}});Object.defineProperty(J,"str",{enumerable:!0,get:function(){return Jr.str}});Object.defineProperty(J,"strConcat",{enumerable:!0,get:function(){return Jr.strConcat}});Object.defineProperty(J,"nil",{enumerable:!0,get:function(){return Jr.nil}});Object.defineProperty(J,"getProperty",{enumerable:!0,get:function(){return Jr.getProperty}});Object.defineProperty(J,"stringify",{enumerable:!0,get:function(){return Jr.stringify}});Object.defineProperty(J,"regexpCode",{enumerable:!0,get:function(){return Jr.regexpCode}});Object.defineProperty(J,"Name",{enumerable:!0,get:function(){return Jr.Name}});var Xo=Al();Object.defineProperty(J,"Scope",{enumerable:!0,get:function(){return Xo.Scope}});Object.defineProperty(J,"ValueScope",{enumerable:!0,get:function(){return Xo.ValueScope}});Object.defineProperty(J,"ValueScopeName",{enumerable:!0,get:function(){return Xo.ValueScopeName}});Object.defineProperty(J,"varKinds",{enumerable:!0,get:function(){return Xo.varKinds}});J.operators={GT:new ne._Code(">"),GTE:new ne._Code(">="),LT:new ne._Code("<"),LTE:new ne._Code("<="),EQ:new ne._Code("==="),NEQ:new ne._Code("!=="),NOT:new ne._Code("!"),OR:new ne._Code("||"),AND:new ne._Code("&&"),ADD:new ne._Code("+")};var Ar=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},kl=class extends Ar{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?jt.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=li(this.rhs,e,t)),this}get names(){return this.rhs instanceof ne._CodeOrName?this.rhs.names:{}}},Go=class extends Ar{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 ne.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=li(this.rhs,e,t),this}get names(){let e=this.lhs instanceof ne.Name?{}:{...this.lhs.names};return Yo(e,this.rhs)}},Pl=class extends Go{constructor(e,t,n,i){super(e,n,i),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Cl=class extends Ar{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Ml=class extends Ar{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Il=class extends Ar{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Tl=class extends Ar{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=li(this.code,e,t),this}get names(){return this.code instanceof ne._CodeOrName?this.code.names:{}}},us=class extends Ar{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)||(NS(e,s.names),n.splice(i,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>Mn(e,t.names),{})}},kr=class extends us{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Rl=class extends us{},ci=class extends kr{};ci.kind="else";var Pn=class r extends kr{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 ci(n):n}if(t)return e===!1?t instanceof r?t:t.nodes:this.nodes.length?this:new r(wh(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=li(this.condition,e,t),this}get names(){let e=super.names;return Yo(e,this.condition),this.else&&Mn(e,this.else.names),e}};Pn.kind="if";var Cn=class extends kr{};Cn.kind="for";var Ol=class extends Cn{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=li(this.iteration,e,t),this}get names(){return Mn(super.names,this.iteration.names)}},Nl=class extends Cn{constructor(e,t,n,i){super(),this.varKind=e,this.name=t,this.from=n,this.to=i}render(e){let t=e.es5?jt.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=Yo(super.names,this.from);return Yo(e,this.to)}},Jo=class extends Cn{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=li(this.iterable,e,t),this}get names(){return Mn(super.names,this.iterable.names)}},fs=class extends kr{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)}};fs.kind="func";var ps=class extends us{render(e){return"return "+super.render(e)}};ps.kind="return";var Dl=class extends kr{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&&Mn(e,this.catch.names),this.finally&&Mn(e,this.finally.names),e}},hs=class extends kr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};hs.kind="catch";var ms=class extends kr{render(e){return"finally"+super.render(e)}};ms.kind="finally";var Ll=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?` +`:""},this._extScope=e,this._scope=new jt.Scope({parent:e}),this._nodes=[new Rl]}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 kl(e,s,n)),s}const(e,t,n){return this._def(jt.varKinds.const,e,t,n)}let(e,t,n){return this._def(jt.varKinds.let,e,t,n)}var(e,t,n){return this._def(jt.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new Go(e,t,n))}add(e,t){return this._leafNode(new Pl(e,J.operators.ADD,t))}code(e){return typeof e=="function"?e():e!==ne.nil&&this._leafNode(new Tl(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,ne.addCodeArg)(t,i));return t.push("}"),new ne._Code(t)}if(e,t,n){if(this._blockNode(new Pn(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 Pn(e))}else(){return this._elseNode(new ci)}endIf(){return this._endBlockNode(Pn,ci)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new Ol(e),t)}forRange(e,t,n,i,s=this.opts.es5?jt.varKinds.var:jt.varKinds.let){let o=this._scope.toName(e);return this._for(new Nl(s,o,t,n),()=>i(o))}forOf(e,t,n,i=jt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let o=t instanceof ne.Name?t:this.var("_arr",t);return this.forRange("_i",0,(0,ne._)`${o}.length`,a=>{this.var(s,(0,ne._)`${o}[${a}]`),n(s)})}return this._for(new Jo("of",i,s,t),()=>n(s))}forIn(e,t,n,i=this.opts.es5?jt.varKinds.var:jt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ne._)`Object.keys(${t})`,n);let s=this._scope.toName(e);return this._for(new Jo("in",i,s,t),()=>n(s))}endFor(){return this._endBlockNode(Cn)}label(e){return this._leafNode(new Cl(e))}break(e){return this._leafNode(new Ml(e))}return(e){let t=new ps;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ps)}try(e,t,n){if(!t&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let i=new Dl;if(this._blockNode(i),this.code(e),t){let s=this.name("e");this._currNode=i.catch=new hs(s),t(s)}return n&&(this._currNode=i.finally=new ms,this.code(n)),this._endBlockNode(hs,ms)}throw(e){return this._leafNode(new Il(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=ne.nil,n,i){return this._blockNode(new fs(e,t,n)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(fs)}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 Pn))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}};J.CodeGen=Ll;function Mn(r,e){for(let t in e)r[t]=(r[t]||0)+(e[t]||0);return r}function Yo(r,e){return e instanceof ne._CodeOrName?Mn(r,e.names):r}function li(r,e,t){if(r instanceof ne.Name)return n(r);if(!i(r))return r;return new ne._Code(r._items.reduce((s,o)=>(o instanceof ne.Name&&(o=n(o)),o instanceof ne._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 ne._Code&&s._items.some(o=>o instanceof ne.Name&&e[o.str]===1&&t[o.str]!==void 0)}}function NS(r,e){for(let t in e)r[t]=(r[t]||0)-(e[t]||0)}function wh(r){return typeof r=="boolean"||typeof r=="number"||r===null?!r:(0,ne._)`!${jl(r)}`}J.not=wh;var DS=Sh(J.operators.AND);function LS(...r){return r.reduce(DS)}J.and=LS;var jS=Sh(J.operators.OR);function qS(...r){return r.reduce(jS)}J.or=qS;function Sh(r){return(e,t)=>e===ne.nil?t:t===ne.nil?e:(0,ne._)`${jl(e)} ${r} ${jl(t)}`}function jl(r){return r instanceof ne.Name?r:(0,ne._)`(${r})`}});var X=E(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.checkStrictMode=Y.getErrorPath=Y.Type=Y.useFunc=Y.setEvaluated=Y.evaluatedPropsToName=Y.mergeEvaluated=Y.eachItem=Y.unescapeJsonPointer=Y.escapeJsonPointer=Y.escapeFragment=Y.unescapeFragment=Y.schemaRefOrVal=Y.schemaHasRulesButRef=Y.schemaHasRules=Y.checkUnknownRules=Y.alwaysValidSchema=Y.toHash=void 0;var pe=B(),FS=ds();function US(r){let e={};for(let t of r)e[t]=!0;return e}Y.toHash=US;function BS(r,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(xh(r,e),!Ah(e,r.self.RULES.all))}Y.alwaysValidSchema=BS;function xh(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]||Ch(r,`unknown keyword: "${s}"`)}Y.checkUnknownRules=xh;function Ah(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(e[t])return!0;return!1}Y.schemaHasRules=Ah;function VS(r,e){if(typeof r=="boolean")return!r;for(let t in r)if(t!=="$ref"&&e.all[t])return!0;return!1}Y.schemaHasRulesButRef=VS;function zS({topSchemaRef:r,schemaPath:e},t,n,i){if(!i){if(typeof t=="number"||typeof t=="boolean")return t;if(typeof t=="string")return(0,pe._)`${t}`}return(0,pe._)`${r}${e}${(0,pe.getProperty)(n)}`}Y.schemaRefOrVal=zS;function HS(r){return kh(decodeURIComponent(r))}Y.unescapeFragment=HS;function KS(r){return encodeURIComponent(Fl(r))}Y.escapeFragment=KS;function Fl(r){return typeof r=="number"?`${r}`:r.replace(/~/g,"~0").replace(/\//g,"~1")}Y.escapeJsonPointer=Fl;function kh(r){return r.replace(/~1/g,"/").replace(/~0/g,"~")}Y.unescapeJsonPointer=kh;function WS(r,e){if(Array.isArray(r))for(let t of r)e(t);else e(r)}Y.eachItem=WS;function $h({mergeNames:r,mergeToName:e,mergeValues:t,resultToName:n}){return(i,s,o,a)=>{let c=o===void 0?s:o instanceof pe.Name?(s instanceof pe.Name?r(i,s,o):e(i,s,o),o):s instanceof pe.Name?(e(i,o,s),s):t(s,o);return a===pe.Name&&!(c instanceof pe.Name)?n(i,c):c}}Y.mergeEvaluated={props:$h({mergeNames:(r,e,t)=>r.if((0,pe._)`${t} !== true && ${e} !== undefined`,()=>{r.if((0,pe._)`${e} === true`,()=>r.assign(t,!0),()=>r.assign(t,(0,pe._)`${t} || {}`).code((0,pe._)`Object.assign(${t}, ${e})`))}),mergeToName:(r,e,t)=>r.if((0,pe._)`${t} !== true`,()=>{e===!0?r.assign(t,!0):(r.assign(t,(0,pe._)`${t} || {}`),Ul(r,t,e))}),mergeValues:(r,e)=>r===!0?!0:{...r,...e},resultToName:Ph}),items:$h({mergeNames:(r,e,t)=>r.if((0,pe._)`${t} !== true && ${e} !== undefined`,()=>r.assign(t,(0,pe._)`${e} === true ? true : ${t} > ${e} ? ${t} : ${e}`)),mergeToName:(r,e,t)=>r.if((0,pe._)`${t} !== true`,()=>r.assign(t,e===!0?!0:(0,pe._)`${t} > ${e} ? ${t} : ${e}`)),mergeValues:(r,e)=>r===!0?!0:Math.max(r,e),resultToName:(r,e)=>r.var("items",e)})};function Ph(r,e){if(e===!0)return r.var("props",!0);let t=r.var("props",(0,pe._)`{}`);return e!==void 0&&Ul(r,t,e),t}Y.evaluatedPropsToName=Ph;function Ul(r,e,t){Object.keys(t).forEach(n=>r.assign((0,pe._)`${e}${(0,pe.getProperty)(n)}`,!0))}Y.setEvaluated=Ul;var Eh={};function GS(r,e){return r.scopeValue("func",{ref:e,code:Eh[e.code]||(Eh[e.code]=new FS._Code(e.code))})}Y.useFunc=GS;var ql;(function(r){r[r.Num=0]="Num",r[r.Str=1]="Str"})(ql||(Y.Type=ql={}));function JS(r,e,t){if(r instanceof pe.Name){let n=e===ql.Num;return t?n?(0,pe._)`"[" + ${r} + "]"`:(0,pe._)`"['" + ${r} + "']"`:n?(0,pe._)`"/" + ${r}`:(0,pe._)`"/" + ${r}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return t?(0,pe.getProperty)(r).toString():"/"+Fl(r)}Y.getErrorPath=JS;function Ch(r,e,t=r.opts.strictSchema){if(t){if(e=`strict mode: ${e}`,t===!0)throw new Error(e);r.self.logger.warn(e)}}Y.checkStrictMode=Ch});var Pt=E(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var Be=B(),YS={data:new Be.Name("data"),valCxt:new Be.Name("valCxt"),instancePath:new Be.Name("instancePath"),parentData:new Be.Name("parentData"),parentDataProperty:new Be.Name("parentDataProperty"),rootData:new Be.Name("rootData"),dynamicAnchors:new Be.Name("dynamicAnchors"),vErrors:new Be.Name("vErrors"),errors:new Be.Name("errors"),this:new Be.Name("this"),self:new Be.Name("self"),scope:new Be.Name("scope"),json:new Be.Name("json"),jsonPos:new Be.Name("jsonPos"),jsonLen:new Be.Name("jsonLen"),jsonPart:new Be.Name("jsonPart")};Bl.default=YS});var ys=E(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.extendErrors=Ve.resetErrorsCount=Ve.reportExtraError=Ve.reportError=Ve.keyword$DataError=Ve.keywordError=void 0;var se=B(),Qo=X(),Qe=Pt();Ve.keywordError={message:({keyword:r})=>(0,se.str)`must pass "${r}" keyword validation`};Ve.keyword$DataError={message:({keyword:r,schemaType:e})=>e?(0,se.str)`"${r}" keyword must be ${e} ($data)`:(0,se.str)`"${r}" keyword is invalid ($data)`};function XS(r,e=Ve.keywordError,t,n){let{it:i}=r,{gen:s,compositeRule:o,allErrors:a}=i,c=Th(r,e,t);n??(o||a)?Mh(s,c):Ih(i,(0,se._)`[${c}]`)}Ve.reportError=XS;function QS(r,e=Ve.keywordError,t){let{it:n}=r,{gen:i,compositeRule:s,allErrors:o}=n,a=Th(r,e,t);Mh(i,a),s||o||Ih(n,Qe.default.vErrors)}Ve.reportExtraError=QS;function ZS(r,e){r.assign(Qe.default.errors,e),r.if((0,se._)`${Qe.default.vErrors} !== null`,()=>r.if(e,()=>r.assign((0,se._)`${Qe.default.vErrors}.length`,e),()=>r.assign(Qe.default.vErrors,null)))}Ve.resetErrorsCount=ZS;function e$({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,Qe.default.errors,a=>{r.const(o,(0,se._)`${Qe.default.vErrors}[${a}]`),r.if((0,se._)`${o}.instancePath === undefined`,()=>r.assign((0,se._)`${o}.instancePath`,(0,se.strConcat)(Qe.default.instancePath,s.errorPath))),r.assign((0,se._)`${o}.schemaPath`,(0,se.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(r.assign((0,se._)`${o}.schema`,t),r.assign((0,se._)`${o}.data`,n))})}Ve.extendErrors=e$;function Mh(r,e){let t=r.const("err",e);r.if((0,se._)`${Qe.default.vErrors} === null`,()=>r.assign(Qe.default.vErrors,(0,se._)`[${t}]`),(0,se._)`${Qe.default.vErrors}.push(${t})`),r.code((0,se._)`${Qe.default.errors}++`)}function Ih(r,e){let{gen:t,validateName:n,schemaEnv:i}=r;i.$async?t.throw((0,se._)`new ${r.ValidationError}(${e})`):(t.assign((0,se._)`${n}.errors`,e),t.return(!1))}var In={keyword:new se.Name("keyword"),schemaPath:new se.Name("schemaPath"),params:new se.Name("params"),propertyName:new se.Name("propertyName"),message:new se.Name("message"),schema:new se.Name("schema"),parentSchema:new se.Name("parentSchema")};function Th(r,e,t){let{createErrors:n}=r.it;return n===!1?(0,se._)`{}`:t$(r,e,t)}function t$(r,e,t={}){let{gen:n,it:i}=r,s=[r$(i,t),n$(r,t)];return i$(r,e,s),n.object(...s)}function r$({errorPath:r},{instancePath:e}){let t=e?(0,se.str)`${r}${(0,Qo.getErrorPath)(e,Qo.Type.Str)}`:r;return[Qe.default.instancePath,(0,se.strConcat)(Qe.default.instancePath,t)]}function n$({keyword:r,it:{errSchemaPath:e}},{schemaPath:t,parentSchema:n}){let i=n?e:(0,se.str)`${e}/${r}`;return t&&(i=(0,se.str)`${i}${(0,Qo.getErrorPath)(t,Qo.Type.Str)}`),[In.schemaPath,i]}function i$(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([In.keyword,i],[In.params,typeof e=="function"?e(r):e||(0,se._)`{}`]),c.messages&&n.push([In.message,typeof t=="function"?t(r):t]),c.verbose&&n.push([In.schema,o],[In.parentSchema,(0,se._)`${u}${d}`],[Qe.default.data,s]),l&&n.push([In.propertyName,l])}});var Oh=E(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.boolOrEmptySchema=di.topBoolOrEmptySchema=void 0;var s$=ys(),o$=B(),a$=Pt(),c$={message:"boolean schema is false"};function l$(r){let{gen:e,schema:t,validateName:n}=r;t===!1?Rh(r,!1):typeof t=="object"&&t.$async===!0?e.return(a$.default.data):(e.assign((0,o$._)`${n}.errors`,null),e.return(!0))}di.topBoolOrEmptySchema=l$;function d$(r,e){let{gen:t,schema:n}=r;n===!1?(t.var(e,!1),Rh(r)):t.var(e,!0)}di.boolOrEmptySchema=d$;function Rh(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,s$.reportError)(i,c$,void 0,e)}});var Vl=E(ui=>{"use strict";Object.defineProperty(ui,"__esModule",{value:!0});ui.getRules=ui.isJSONType=void 0;var u$=["string","number","integer","boolean","null","object","array"],f$=new Set(u$);function p$(r){return typeof r=="string"&&f$.has(r)}ui.isJSONType=p$;function h$(){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:{}}}ui.getRules=h$});var zl=E(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.shouldUseRule=Yr.shouldUseGroup=Yr.schemaHasRulesForType=void 0;function m$({schema:r,self:e},t){let n=e.RULES.types[t];return n&&n!==!0&&Nh(r,n)}Yr.schemaHasRulesForType=m$;function Nh(r,e){return e.rules.some(t=>Dh(r,t))}Yr.shouldUseGroup=Nh;function Dh(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))}Yr.shouldUseRule=Dh});var gs=E(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.reportTypeError=ze.checkDataTypes=ze.checkDataType=ze.coerceAndCheckDataType=ze.getJSONTypes=ze.getSchemaTypes=ze.DataType=void 0;var y$=Vl(),g$=zl(),b$=ys(),z=B(),Lh=X(),fi;(function(r){r[r.Correct=0]="Correct",r[r.Wrong=1]="Wrong"})(fi||(ze.DataType=fi={}));function v$(r){let e=jh(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}ze.getSchemaTypes=v$;function jh(r){let e=Array.isArray(r)?r:r?[r]:[];if(e.every(y$.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ze.getJSONTypes=jh;function _$(r,e){let{gen:t,data:n,opts:i}=r,s=w$(e,i.coerceTypes),o=e.length>0&&!(s.length===0&&e.length===1&&(0,g$.schemaHasRulesForType)(r,e[0]));if(o){let a=Kl(e,n,i.strictNumbers,fi.Wrong);t.if(a,()=>{s.length?S$(r,e,s):Wl(r)})}return o}ze.coerceAndCheckDataType=_$;var qh=new Set(["string","number","integer","boolean","null"]);function w$(r,e){return e?r.filter(t=>qh.has(t)||e==="array"&&t==="array"):[]}function S$(r,e,t){let{gen:n,data:i,opts:s}=r,o=n.let("dataType",(0,z._)`typeof ${i}`),a=n.let("coerced",(0,z._)`undefined`);s.coerceTypes==="array"&&n.if((0,z._)`${o} == 'object' && Array.isArray(${i}) && ${i}.length == 1`,()=>n.assign(i,(0,z._)`${i}[0]`).assign(o,(0,z._)`typeof ${i}`).if(Kl(e,i,s.strictNumbers),()=>n.assign(a,i))),n.if((0,z._)`${a} !== undefined`);for(let l of t)(qh.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),Wl(r),n.endIf(),n.if((0,z._)`${a} !== undefined`,()=>{n.assign(i,a),$$(r,a)});function c(l){switch(l){case"string":n.elseIf((0,z._)`${o} == "number" || ${o} == "boolean"`).assign(a,(0,z._)`"" + ${i}`).elseIf((0,z._)`${i} === null`).assign(a,(0,z._)`""`);return;case"number":n.elseIf((0,z._)`${o} == "boolean" || ${i} === null + || (${o} == "string" && ${i} && ${i} == +${i})`).assign(a,(0,z._)`+${i}`);return;case"integer":n.elseIf((0,z._)`${o} === "boolean" || ${i} === null + || (${o} === "string" && ${i} && ${i} == +${i} && !(${i} % 1))`).assign(a,(0,z._)`+${i}`);return;case"boolean":n.elseIf((0,z._)`${i} === "false" || ${i} === 0 || ${i} === null`).assign(a,!1).elseIf((0,z._)`${i} === "true" || ${i} === 1`).assign(a,!0);return;case"null":n.elseIf((0,z._)`${i} === "" || ${i} === 0 || ${i} === false`),n.assign(a,null);return;case"array":n.elseIf((0,z._)`${o} === "string" || ${o} === "number" + || ${o} === "boolean" || ${i} === null`).assign(a,(0,z._)`[${i}]`)}}}function $$({gen:r,parentData:e,parentDataProperty:t},n){r.if((0,z._)`${e} !== undefined`,()=>r.assign((0,z._)`${e}[${t}]`,n))}function Hl(r,e,t,n=fi.Correct){let i=n===fi.Correct?z.operators.EQ:z.operators.NEQ,s;switch(r){case"null":return(0,z._)`${e} ${i} null`;case"array":s=(0,z._)`Array.isArray(${e})`;break;case"object":s=(0,z._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=o((0,z._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=o();break;default:return(0,z._)`typeof ${e} ${i} ${r}`}return n===fi.Correct?s:(0,z.not)(s);function o(a=z.nil){return(0,z.and)((0,z._)`typeof ${e} == "number"`,a,t?(0,z._)`isFinite(${e})`:z.nil)}}ze.checkDataType=Hl;function Kl(r,e,t,n){if(r.length===1)return Hl(r[0],e,t,n);let i,s=(0,Lh.toHash)(r);if(s.array&&s.object){let o=(0,z._)`typeof ${e} != "object"`;i=s.null?o:(0,z._)`!${e} || ${o}`,delete s.null,delete s.array,delete s.object}else i=z.nil;s.number&&delete s.integer;for(let o in s)i=(0,z.and)(i,Hl(o,e,t,n));return i}ze.checkDataTypes=Kl;var E$={message:({schema:r})=>`must be ${r}`,params:({schema:r,schemaValue:e})=>typeof r=="string"?(0,z._)`{type: ${r}}`:(0,z._)`{type: ${e}}`};function Wl(r){let e=x$(r);(0,b$.reportError)(e,E$)}ze.reportTypeError=Wl;function x$(r){let{gen:e,data:t,schema:n}=r,i=(0,Lh.schemaRefOrVal)(r,n,"type");return{gen:e,keyword:"type",data:t,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:r}}});var Uh=E(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.assignDefaults=void 0;var pi=B(),A$=X();function k$(r,e){let{properties:t,items:n}=r.schema;if(e==="object"&&t)for(let i in t)Fh(r,i,t[i].default);else e==="array"&&Array.isArray(n)&&n.forEach((i,s)=>Fh(r,s,i.default))}Zo.assignDefaults=k$;function Fh(r,e,t){let{gen:n,compositeRule:i,data:s,opts:o}=r;if(t===void 0)return;let a=(0,pi._)`${s}${(0,pi.getProperty)(e)}`;if(i){(0,A$.checkStrictMode)(r,`default is ignored for: ${a}`);return}let c=(0,pi._)`${a} === undefined`;o.useDefaults==="empty"&&(c=(0,pi._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,pi._)`${a} = ${(0,pi.stringify)(t)}`)}});var Ct=E(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.validateUnion=ue.validateArray=ue.usePattern=ue.callValidateCode=ue.schemaProperties=ue.allSchemaProperties=ue.noPropertyInData=ue.propertyInData=ue.isOwnProperty=ue.hasPropFunc=ue.reportMissingProp=ue.checkMissingProp=ue.checkReportMissingProp=void 0;var ye=B(),Gl=X(),Xr=Pt(),P$=X();function C$(r,e){let{gen:t,data:n,it:i}=r;t.if(Yl(t,n,e,i.opts.ownProperties),()=>{r.setParams({missingProperty:(0,ye._)`${e}`},!0),r.error()})}ue.checkReportMissingProp=C$;function M$({gen:r,data:e,it:{opts:t}},n,i){return(0,ye.or)(...n.map(s=>(0,ye.and)(Yl(r,e,s,t.ownProperties),(0,ye._)`${i} = ${s}`)))}ue.checkMissingProp=M$;function I$(r,e){r.setParams({missingProperty:e},!0),r.error()}ue.reportMissingProp=I$;function Bh(r){return r.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ye._)`Object.prototype.hasOwnProperty`})}ue.hasPropFunc=Bh;function Jl(r,e,t){return(0,ye._)`${Bh(r)}.call(${e}, ${t})`}ue.isOwnProperty=Jl;function T$(r,e,t,n){let i=(0,ye._)`${e}${(0,ye.getProperty)(t)} !== undefined`;return n?(0,ye._)`${i} && ${Jl(r,e,t)}`:i}ue.propertyInData=T$;function Yl(r,e,t,n){let i=(0,ye._)`${e}${(0,ye.getProperty)(t)} === undefined`;return n?(0,ye.or)(i,(0,ye.not)(Jl(r,e,t))):i}ue.noPropertyInData=Yl;function Vh(r){return r?Object.keys(r).filter(e=>e!=="__proto__"):[]}ue.allSchemaProperties=Vh;function R$(r,e){return Vh(e).filter(t=>!(0,Gl.alwaysValidSchema)(r,e[t]))}ue.schemaProperties=R$;function O$({schemaCode:r,data:e,it:{gen:t,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,c,l){let u=l?(0,ye._)`${r}, ${e}, ${n}${i}`:e,d=[[Xr.default.instancePath,(0,ye.strConcat)(Xr.default.instancePath,s)],[Xr.default.parentData,o.parentData],[Xr.default.parentDataProperty,o.parentDataProperty],[Xr.default.rootData,Xr.default.rootData]];o.opts.dynamicRef&&d.push([Xr.default.dynamicAnchors,Xr.default.dynamicAnchors]);let f=(0,ye._)`${u}, ${t.object(...d)}`;return c!==ye.nil?(0,ye._)`${a}.call(${c}, ${f})`:(0,ye._)`${a}(${f})`}ue.callValidateCode=O$;var N$=(0,ye._)`new RegExp`;function D$({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,ye._)`${i.code==="new RegExp"?N$:(0,P$.useFunc)(r,i)}(${t}, ${n})`})}ue.usePattern=D$;function L$(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,ye._)`${t}.length`);e.forRange("i",0,c,l=>{r.subschema({keyword:n,dataProp:l,dataPropType:Gl.Type.Num},s),e.if((0,ye.not)(s),a)})}}ue.validateArray=L$;function j$(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,Gl.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,ye._)`${o} || ${a}`),r.mergeValidEvaluated(u,a)||e.if((0,ye.not)(o))})),r.result(o,()=>r.reset(),()=>r.error(!0))}ue.validateUnion=j$});var Kh=E(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.validateKeywordUsage=or.validSchemaType=or.funcKeywordCode=or.macroKeywordCode=void 0;var Ze=B(),Tn=Pt(),q$=Ct(),F$=ys();function U$(r,e){let{gen:t,keyword:n,schema:i,parentSchema:s,it:o}=r,a=e.macro.call(o.self,i,s,o),c=Hh(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))}or.macroKeywordCode=U$;function B$(r,e){var t;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=r;z$(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,o,c):e.validate,u=Hh(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&&zh(r),y(()=>r.error());else{let g=e.async?p():m();e.modifying&&zh(r),y(()=>V$(r,g))}}function p(){let g=n.let("ruleErrs",null);return n.try(()=>h((0,Ze._)`await `),_=>n.assign(d,!1).if((0,Ze._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(g,(0,Ze._)`${_}.errors`),()=>n.throw(_))),g}function m(){let g=(0,Ze._)`${u}.errors`;return n.assign(g,null),h(Ze.nil),g}function h(g=e.async?(0,Ze._)`await `:Ze.nil){let _=c.opts.passContext?Tn.default.this:Tn.default.self,v=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,Ze._)`${g}${(0,q$.callValidateCode)(r,u,_,v)}`,e.modifying)}function y(g){var _;n.if((0,Ze.not)((_=e.valid)!==null&&_!==void 0?_:d),g)}}or.funcKeywordCode=B$;function zh(r){let{gen:e,data:t,it:n}=r;e.if(n.parentData,()=>e.assign(t,(0,Ze._)`${n.parentData}[${n.parentDataProperty}]`))}function V$(r,e){let{gen:t}=r;t.if((0,Ze._)`Array.isArray(${e})`,()=>{t.assign(Tn.default.vErrors,(0,Ze._)`${Tn.default.vErrors} === null ? ${e} : ${Tn.default.vErrors}.concat(${e})`).assign(Tn.default.errors,(0,Ze._)`${Tn.default.vErrors}.length`),(0,F$.extendErrors)(r)},()=>r.error())}function z$({schemaEnv:r},e){if(e.async&&!r.$async)throw new Error("async keyword in sync schema")}function Hh(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 H$(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>"u")}or.validSchemaType=H$;function K$({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?.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)}}or.validateKeywordUsage=K$});var Gh=E(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.extendSubschemaMode=Qr.extendSubschemaData=Qr.getSubschema=void 0;var ar=B(),Wh=X();function W$(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,ar._)`${r.schemaPath}${(0,ar.getProperty)(e)}`,errSchemaPath:`${r.errSchemaPath}/${e}`}:{schema:a[t],schemaPath:(0,ar._)`${r.schemaPath}${(0,ar.getProperty)(e)}${(0,ar.getProperty)(t)}`,errSchemaPath:`${r.errSchemaPath}/${e}/${(0,Wh.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')}Qr.getSubschema=W$;function G$(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,ar._)`${e.data}${(0,ar.getProperty)(t)}`,!0);c(f),r.errorPath=(0,ar.str)`${l}${(0,Wh.getErrorPath)(t,n,d.jsPropertySyntax)}`,r.parentDataProperty=(0,ar._)`${t}`,r.dataPathArr=[...u,r.parentDataProperty]}if(i!==void 0){let l=i instanceof ar.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]}}Qr.extendSubschemaData=G$;function J$(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}Qr.extendSubschemaMode=J$});var Xl=E((YD,Jh)=>{"use strict";Jh.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 Xh=E((XD,Yh)=>{"use strict";var Zr=Yh.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(){};ea(e,n,i,r,"",r)};Zr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Zr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Zr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Zr.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 ea(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 Zr.arrayKeywords)for(var f=0;f{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.getSchemaRefs=dt.resolveUrl=dt.normalizeId=dt._getFullPath=dt.getFullPath=dt.inlineRef=void 0;var X$=X(),Q$=Xl(),Z$=Xh(),eE=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function tE(r,e=!0){return typeof r=="boolean"?!0:e===!0?!Ql(r):e?Qh(r)<=e:!1}dt.inlineRef=tE;var rE=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ql(r){for(let e in r){if(rE.has(e))return!0;let t=r[e];if(Array.isArray(t)&&t.some(Ql)||typeof t=="object"&&Ql(t))return!0}return!1}function Qh(r){let e=0;for(let t in r){if(t==="$ref")return 1/0;if(e++,!eE.has(t)&&(typeof r[t]=="object"&&(0,X$.eachItem)(r[t],n=>e+=Qh(n)),e===1/0))return 1/0}return e}function Zh(r,e="",t){t!==!1&&(e=hi(e));let n=r.parse(e);return em(r,n)}dt.getFullPath=Zh;function em(r,e){return r.serialize(e).split("#")[0]+"#"}dt._getFullPath=em;var nE=/#\/?$/;function hi(r){return r?r.replace(nE,""):""}dt.normalizeId=hi;function iE(r,e,t){return t=hi(t),r.resolve(e,t)}dt.resolveUrl=iE;var sE=/^[a-z_][-a-z0-9._]*$/i;function oE(r,e){if(typeof r=="boolean")return{};let{schemaId:t,uriResolver:n}=this.opts,i=hi(r[t]||e),s={"":i},o=Zh(n,i,!1),a={},c=new Set;return Z$(r,{allKeys:!0},(d,f,p,m)=>{if(m===void 0)return;let h=o+f,y=s[m];typeof d[t]=="string"&&(y=g.call(this,d[t])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[f]=y;function g(v){let w=this.opts.uriResolver.resolve;if(v=hi(y?w(y,v):v),c.has(v))throw u(v);c.add(v);let S=this.refs[v];return typeof S=="string"&&(S=this.refs[S]),typeof S=="object"?l(d,S.schema,v):v!==hi(h)&&(v[0]==="#"?(l(d,a[v],v),a[v]=d):this.refs[v]=h),v}function _(v){if(typeof v=="string"){if(!sE.test(v))throw new Error(`invalid anchor "${v}"`);g.call(this,`#${v}`)}}}),a;function l(d,f,p){if(f!==void 0&&!Q$(d,f))throw u(p)}function u(d){return new Error(`reference "${d}" resolves to more than one schema`)}}dt.getSchemaRefs=oE});var mi=E(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.getData=en.KeywordCxt=en.validateFunctionCode=void 0;var sm=Oh(),tm=gs(),ed=zl(),ta=gs(),aE=Uh(),_s=Kh(),Zl=Gh(),j=B(),U=Pt(),cE=bs(),Pr=X(),vs=ys();function lE(r){if(cm(r)&&(lm(r),am(r))){fE(r);return}om(r,()=>(0,sm.topBoolOrEmptySchema)(r))}en.validateFunctionCode=lE;function om({gen:r,validateName:e,schema:t,schemaEnv:n,opts:i},s){i.code.es5?r.func(e,(0,j._)`${U.default.data}, ${U.default.valCxt}`,n.$async,()=>{r.code((0,j._)`"use strict"; ${rm(t,i)}`),uE(r,i),r.code(s)}):r.func(e,(0,j._)`${U.default.data}, ${dE(i)}`,n.$async,()=>r.code(rm(t,i)).code(s))}function dE(r){return(0,j._)`{${U.default.instancePath}="", ${U.default.parentData}, ${U.default.parentDataProperty}, ${U.default.rootData}=${U.default.data}${r.dynamicRef?(0,j._)`, ${U.default.dynamicAnchors}={}`:j.nil}}={}`}function uE(r,e){r.if(U.default.valCxt,()=>{r.var(U.default.instancePath,(0,j._)`${U.default.valCxt}.${U.default.instancePath}`),r.var(U.default.parentData,(0,j._)`${U.default.valCxt}.${U.default.parentData}`),r.var(U.default.parentDataProperty,(0,j._)`${U.default.valCxt}.${U.default.parentDataProperty}`),r.var(U.default.rootData,(0,j._)`${U.default.valCxt}.${U.default.rootData}`),e.dynamicRef&&r.var(U.default.dynamicAnchors,(0,j._)`${U.default.valCxt}.${U.default.dynamicAnchors}`)},()=>{r.var(U.default.instancePath,(0,j._)`""`),r.var(U.default.parentData,(0,j._)`undefined`),r.var(U.default.parentDataProperty,(0,j._)`undefined`),r.var(U.default.rootData,U.default.data),e.dynamicRef&&r.var(U.default.dynamicAnchors,(0,j._)`{}`)})}function fE(r){let{schema:e,opts:t,gen:n}=r;om(r,()=>{t.$comment&&e.$comment&&um(r),gE(r),n.let(U.default.vErrors,null),n.let(U.default.errors,0),t.unevaluated&&pE(r),dm(r),_E(r)})}function pE(r){let{gen:e,validateName:t}=r;r.evaluated=e.const("evaluated",(0,j._)`${t}.evaluated`),e.if((0,j._)`${r.evaluated}.dynamicProps`,()=>e.assign((0,j._)`${r.evaluated}.props`,(0,j._)`undefined`)),e.if((0,j._)`${r.evaluated}.dynamicItems`,()=>e.assign((0,j._)`${r.evaluated}.items`,(0,j._)`undefined`))}function rm(r,e){let t=typeof r=="object"&&r[e.schemaId];return t&&(e.code.source||e.code.process)?(0,j._)`/*# sourceURL=${t} */`:j.nil}function hE(r,e){if(cm(r)&&(lm(r),am(r))){mE(r,e);return}(0,sm.boolOrEmptySchema)(r,e)}function am({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 cm(r){return typeof r.schema!="boolean"}function mE(r,e){let{schema:t,gen:n,opts:i}=r;i.$comment&&t.$comment&&um(r),bE(r),vE(r);let s=n.const("_errs",U.default.errors);dm(r,s),n.var(e,(0,j._)`${s} === ${U.default.errors}`)}function lm(r){(0,Pr.checkUnknownRules)(r),yE(r)}function dm(r,e){if(r.opts.jtd)return nm(r,[],!1,e);let t=(0,tm.getSchemaTypes)(r.schema),n=(0,tm.coerceAndCheckDataType)(r,t);nm(r,t,!n,e)}function yE(r){let{schema:e,errSchemaPath:t,opts:n,self:i}=r;e.$ref&&n.ignoreKeywordsWithRef&&(0,Pr.schemaHasRulesButRef)(e,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${t}"`)}function gE(r){let{schema:e,opts:t}=r;e.default!==void 0&&t.useDefaults&&t.strictSchema&&(0,Pr.checkStrictMode)(r,"default is ignored in the schema root")}function bE(r){let e=r.schema[r.opts.schemaId];e&&(r.baseId=(0,cE.resolveUrl)(r.opts.uriResolver,r.baseId,e))}function vE(r){if(r.schema.$async&&!r.schemaEnv.$async)throw new Error("async schema in sync schema")}function um({gen:r,schemaEnv:e,schema:t,errSchemaPath:n,opts:i}){let s=t.$comment;if(i.$comment===!0)r.code((0,j._)`${U.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=(0,j.str)`${n}/$comment`,a=r.scopeValue("root",{ref:e.root});r.code((0,j._)`${U.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,j._)`${U.default.errors} === 0`,()=>e.return(U.default.data),()=>e.throw((0,j._)`new ${i}(${U.default.vErrors})`)):(e.assign((0,j._)`${n}.errors`,U.default.vErrors),s.unevaluated&&wE(r),e.return((0,j._)`${U.default.errors} === 0`))}function wE({gen:r,evaluated:e,props:t,items:n}){t instanceof j.Name&&r.assign((0,j._)`${e}.props`,t),n instanceof j.Name&&r.assign((0,j._)`${e}.items`,n)}function nm(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,Pr.schemaHasRulesButRef)(s,u))){i.block(()=>pm(r,"$ref",u.all.$ref.definition));return}c.jtd||SE(r,e),i.block(()=>{for(let f of u.rules)d(f);d(u.post)});function d(f){(0,ed.shouldUseGroup)(s,f)&&(f.type?(i.if((0,ta.checkDataType)(f.type,o,c.strictNumbers)),im(r,f),e.length===1&&e[0]===f.type&&t&&(i.else(),(0,ta.reportTypeError)(r)),i.endIf()):im(r,f),a||i.if((0,j._)`${U.default.errors} === ${n||0}`))}}function im(r,e){let{gen:t,schema:n,opts:{useDefaults:i}}=r;i&&(0,aE.assignDefaults)(r,e.type),t.block(()=>{for(let s of e.rules)(0,ed.shouldUseRule)(n,s)&&pm(r,s.keyword,s.definition,e.type)})}function SE(r,e){r.schemaEnv.meta||!r.opts.strictTypes||($E(r,e),r.opts.allowUnionTypes||EE(r,e),xE(r,r.dataTypes))}function $E(r,e){if(e.length){if(!r.dataTypes.length){r.dataTypes=e;return}e.forEach(t=>{fm(r.dataTypes,t)||td(r,`type "${t}" not allowed by context "${r.dataTypes.join(",")}"`)}),kE(r,e)}}function EE(r,e){e.length>1&&!(e.length===2&&e.includes("null"))&&td(r,"use allowUnionTypes to allow union type keyword")}function xE(r,e){let t=r.self.RULES.all;for(let n in t){let i=t[n];if(typeof i=="object"&&(0,ed.shouldUseRule)(r.schema,i)){let{type:s}=i.definition;s.length&&!s.some(o=>AE(e,o))&&td(r,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function AE(r,e){return r.includes(e)||e==="number"&&r.includes("integer")}function fm(r,e){return r.includes(e)||e==="integer"&&r.includes("number")}function kE(r,e){let t=[];for(let n of r.dataTypes)fm(e,n)?t.push(n):e.includes("integer")&&n==="number"&&t.push("integer");r.dataTypes=t}function td(r,e){let t=r.schemaEnv.baseId+r.errSchemaPath;e+=` at "${t}" (strictTypes)`,(0,Pr.checkStrictMode)(r,e,r.opts.strictTypes)}var ra=class{constructor(e,t,n){if((0,_s.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,Pr.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",hm(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,_s.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,j.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,j.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,j._)`${t} !== undefined && (${(0,j.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?vs.reportExtraError:vs.reportError)(this,this.def.error,t)}$dataError(){(0,vs.reportError)(this,this.def.$dataError||vs.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,vs.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=j.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=j.nil,t=j.nil){if(!this.$data)return;let{gen:n,schemaCode:i,schemaType:s,def:o}=this;n.if((0,j.or)((0,j._)`${i} === undefined`,t)),e!==j.nil&&n.assign(e,!0),(s.length||o.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==j.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:i,it:s}=this;return(0,j.or)(o(),a());function o(){if(n.length){if(!(t instanceof j.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,j._)`${(0,ta.checkDataTypes)(c,t,s.opts.strictNumbers,ta.DataType.Wrong)}`}return j.nil}function a(){if(i.validateSchema){let c=e.scopeValue("validate$data",{ref:i.validateSchema});return(0,j._)`!${c}(${t})`}return j.nil}}subschema(e,t){let n=(0,Zl.getSubschema)(this.it,e);(0,Zl.extendSubschemaData)(n,this.it,e),(0,Zl.extendSubschemaMode)(n,e);let i={...this.it,...n,items:void 0,props:void 0};return hE(i,t),i}mergeEvaluated(e,t){let{it:n,gen:i}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Pr.mergeEvaluated.props(i,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=Pr.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,j.Name)),!0}};en.KeywordCxt=ra;function pm(r,e,t,n){let i=new ra(r,t,e);"code"in t?t.code(i,n):i.$data&&t.validate?(0,_s.funcKeywordCode)(i,t):"macro"in t?(0,_s.macroKeywordCode)(i,t):(t.compile||t.validate)&&(0,_s.funcKeywordCode)(i,t)}var PE=/^\/(?:[^~]|~0|~1)*$/,CE=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function hm(r,{dataLevel:e,dataNames:t,dataPathArr:n}){let i,s;if(r==="")return U.default.rootData;if(r[0]==="/"){if(!PE.test(r))throw new Error(`Invalid JSON-pointer: ${r}`);i=r,s=U.default.rootData}else{let l=CE.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,j._)`${s}${(0,j.getProperty)((0,Pr.unescapeJsonPointer)(l))}`,o=(0,j._)`${o} && ${s}`);return o;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}en.getData=hm});var ws=E(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});var rd=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};nd.default=rd});var yi=E(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var id=bs(),sd=class extends Error{constructor(e,t,n,i){super(i||`can't resolve reference ${n} from id ${t}`),this.missingRef=(0,id.resolveUrl)(e,t,n),this.missingSchema=(0,id.normalizeId)((0,id.getFullPath)(e,this.missingRef))}};od.default=sd});var Ss=E(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.resolveSchema=Mt.getCompilingSchema=Mt.resolveRef=Mt.compileSchema=Mt.SchemaEnv=void 0;var qt=B(),ME=ws(),Rn=Pt(),Ft=bs(),mm=X(),IE=mi(),gi=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,Ft.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Mt.SchemaEnv=gi;function cd(r){let e=ym.call(this,r);if(e)return e;let t=(0,Ft.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:ME.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:Rn.default.data,parentData:Rn.default.parentData,parentDataProperty:Rn.default.parentDataProperty,dataNames:[Rn.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,IE.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let d=o.toString();u=`${o.scopeRefs(Rn.default.scope)}return ${d}`,this.opts.code.process&&(u=this.opts.code.process(u,r));let p=new Function(`${Rn.default.self}`,`${Rn.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)}}Mt.compileSchema=cd;function TE(r,e,t){var n;t=(0,Ft.resolveUrl)(this.opts.uriResolver,e,t);let i=r.refs[t];if(i)return i;let s=NE.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 gi({schema:o,schemaId:a,root:r,baseId:e}))}if(s!==void 0)return r.refs[t]=RE.call(this,s)}Mt.resolveRef=TE;function RE(r){return(0,Ft.inlineRef)(r.schema,this.opts.inlineRefs)?r.schema:r.validate?r:cd.call(this,r)}function ym(r){for(let e of this._compilations)if(OE(e,r))return e}Mt.getCompilingSchema=ym;function OE(r,e){return r.schema===e.schema&&r.root===e.root&&r.baseId===e.baseId}function NE(r,e){let t;for(;typeof(t=this.refs[e])=="string";)e=t;return t||this.schemas[e]||na.call(this,r,e)}function na(r,e){let t=this.opts.uriResolver.parse(e),n=(0,Ft._getFullPath)(this.opts.uriResolver,t),i=(0,Ft.getFullPath)(this.opts.uriResolver,r.baseId,void 0);if(Object.keys(r.schema).length>0&&n===i)return ad.call(this,t,r);let s=(0,Ft.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=na.call(this,r,o);return typeof a?.schema!="object"?void 0:ad.call(this,t,a)}if(typeof o?.schema=="object"){if(o.validate||cd.call(this,o),s===(0,Ft.normalizeId)(e)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];return l&&(i=(0,Ft.resolveUrl)(this.opts.uriResolver,i,l)),new gi({schema:a,schemaId:c,root:r,baseId:i})}return ad.call(this,t,o)}}Mt.resolveSchema=na;var DE=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ad(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,mm.unescapeFragment)(a)];if(c===void 0)return;t=c;let l=typeof t=="object"&&t[this.opts.schemaId];!DE.has(a)&&l&&(e=(0,Ft.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof t!="boolean"&&t.$ref&&!(0,mm.schemaHasRulesButRef)(t,this.RULES)){let a=(0,Ft.resolveUrl)(this.opts.uriResolver,e,t.$ref);s=na.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new gi({schema:t,schemaId:o,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var gm=E((nL,LE)=>{LE.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 hd=E((iL,Em)=>{"use strict";var jE=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),dd=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u),qE=RegExp.prototype.test.bind(/^\d*$/u),On=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),ud=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),vm=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),fd=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),FE=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),ut=new Array(256);{let r="0123456789ABCDEF";for(let e=0;e<256;e++)ut[e]="%"+r[e>>4]+r[e&15]}function He(r){return r<2048?ut[192|r>>6]+ut[128|r&63]:r<65536?ut[224|r>>12]+ut[128|r>>6&63]+ut[128|r&63]:ut[240|r>>18]+ut[128|r>>12&63]+ut[128|r>>6&63]+ut[128|r&63]}function UE(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 BE=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),VE=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),zE=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),HE=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function KE(r){if(r.length===0)return!1;for(let e=0;et&&(t=i,e=n)):(n=-1,i=0);if(t<2)return r.join(":");let s=r.slice(0,e).join(":"),o=r.slice(e+t).join(":");return s+"::"+o}function WE(r){let e=r.indexOf("::");if(e!==-1&&r.indexOf("::",e+1)!==-1)return;let t=e===-1?r.split(":"):r.slice(0,e).split(":"),n=e===-1?[]:r.slice(e+2).split(":");e!==-1&&(t.length===1&&t[0]===""&&(t.length=0),n.length===1&&n[0]===""&&(n.length=0));let i=t.concat(n),s=0;for(let a=0;a=8)return;let o=i.slice(0,t.length);for(let a=s;a<8;a++)o.push("0");for(let a=t.length;aYE[n])}function wm(r,e=!1){if(r.indexOf("%")===-1)return r;let t="";for(let n=0;n57343)e+=He(i);else if(i<=56319&&t+1=56320&&s<=57343?(e+=He(65536+(i-55296<<10)+(s-56320)),t++):e+=He(65533)}else e+=He(65533)}}return e}function ex(r,e=!1){let t="",n=e&&r[0]!=="/";for(let i=0;i57343)t+=He(o);else if(o<=56319&&i+1=56320&&a<=57343?(t+=He(65536+(o-55296<<10)+(a-56320)),i++):t+=He(65533)}else t+=He(65533)}}return t}function pd(r,e){let t="";for(let n=0;n57343)t+=He(s);else if(s<=56319&&n+1=56320&&o<=57343?(t+=He(65536+(s-55296<<10)+(o-56320)),n++):t+=He(65533)}else t+=He(65533)}}return t}function Sm(r){return pd(r,FE)}function tx(r){return pd(r,fd)}function rx(r){return pd(r,fd)}function $m(r){return r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||r===42||r===43||r===45||r===46||r===47||r===64||r===95}function nx(r){let e="";for(let t=0;t57343)e+=He(i);else if(i<=56319&&t+1=56320&&s<=57343?(e+=He(65536+(i-55296<<10)+(s-56320)),t++):e+=He(65533)}else e+=He(65533)}}return e}function ix(r){let e="";for(let t=0;t{"use strict";var{isUUID:ox}=hd(),ax=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,cx=["http","https","ws","wss","urn","urn:uuid"];function lx(r){return cx.indexOf(r)!==-1}function md(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 xm(r){return r.host||(r.error=r.error||"HTTP URIs must have a host."),r}function Am(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 dx(r){return r.secure=md(r),r.resourceName=(r.path||"/")+(r.query?"?"+r.query:""),r.path=void 0,r.query=void 0,r}function ux(r){if((r.port===(md(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=r.resourceName.indexOf("?"),t=e===-1?r.resourceName:r.resourceName.slice(0,e);r.path=t&&t!=="/"?t:void 0,r.query=e===-1?void 0:r.resourceName.slice(e+1),r.resourceName=void 0}return r.fragment=void 0,r}function fx(r,e){if(!r.path)return r.error="URN can not be parsed",r;let t=r.path.match(ax);if(t&&t[0]===r.path){let n=e.scheme||r.scheme||"urn";r.nid=t[1].toLowerCase(),r.nss=t[2];let i=`${n}:${e.nid||r.nid}`,s=yd(i);r.path=void 0,s&&(r=s.parse(r,e))}else r.error=r.error||"URN can not be parsed.";return r}function px(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=yd(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 hx(r,e){let t=r;return t.uuid=t.nss,t.nss=void 0,!e.tolerant&&(!t.uuid||!ox(t.uuid))&&(t.error=t.error||"UUID is not valid."),t}function mx(r){let e=r;return e.nss=(r.uuid||"").toLowerCase(),e}var km={scheme:"http",domainHost:!0,parse:xm,serialize:Am},yx={scheme:"https",domainHost:km.domainHost,parse:xm,serialize:Am},ia={scheme:"ws",domainHost:!0,parse:dx,serialize:ux},gx={scheme:"wss",domainHost:ia.domainHost,parse:ia.parse,serialize:ia.serialize},bx={scheme:"urn",parse:fx,serialize:px,skipNormalize:!0},vx={scheme:"urn:uuid",parse:hx,serialize:mx,skipNormalize:!0},sa={http:km,https:yx,ws:ia,wss:gx,urn:bx,"urn:uuid":vx};Object.setPrototypeOf(sa,null);function yd(r){return r&&(sa[r]||sa[r.toLowerCase()])||void 0}Pm.exports={wsIsSecure:md,SCHEMES:sa,isValidSchemeName:lx,getSchemeHandler:yd}});var Vm=E((oL,ca)=>{"use strict";var{normalizeIPv6:Om,removeDotSegments:Es,recomposeAuthority:_x,normalizePercentEncoding:Nm,normalizePathEncoding:wx,serializePathEncoding:Mm,normalizeQueryFragmentEncoding:Im,encodeQuery:Sx,encodeFragment:$x,reescapeHostDelimiters:Ex,isIPv4:Dm,nonSimpleDomain:xx}=hd(),{SCHEMES:Lm,getSchemeHandler:gd}=Cm(),jm=/^[A-Za-z][A-Za-z0-9+.-]*$/u,qm="URI scheme is malformed.";function Tm(r){let e=unescape(String(r));if(!jm.test(e))throw new TypeError(qm);return e}function Ax(r,e){return typeof r=="string"?r=Ox(r,e):typeof r=="object"&&(r=aa(Nn(r,e),e)),r}function kx(r,e,t){let n=t?Object.assign({scheme:"null"},t):{scheme:"null"},{parsed:i,malformedAuthorityOrPort:s,malformedPercentEncoding:o,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:l}=oa(r,n),{parsed:u,malformedAuthorityOrPort:d,malformedPercentEncoding:f,malformedSchemeSpecific:p,malformedHost:m,malformedScheme:h}=oa(e,n);if(s||d||o||f||a||p||c||m||l||h)throw new Error(i.error||u.error||"URI is malformed.");let y=Fm(i,u,n,!0),g=gd(t&&t.scheme||y.scheme),_=y.host,v=_!==void 0&&_!==""&&(Dm(_)||Om(_).isIPV6);Um(y,t||{},g,v);let w=_&&_.indexOf("%")!==-1&&!/\P{ASCII}/u.test(_);if(y.error&&!w)throw new Error(y.error);return n.skipEscape=!0,Nn(y,n)}function Fm(r,e,t,n){let i={};return n||(r=aa(Nn(r,t),t),e=aa(Nn(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=Es(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=Es(e.path||""),i.query=e.query):(e.path?(e.path[0]==="/"?i.path=Es(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=Es(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 Px(r,e,t){let n=Rm(r,t),i=Rm(e,t);return n!==void 0&&i!==void 0&&n===i}function Nn(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=[];t.scheme&&(t.scheme=Tm(t.scheme));let s=gd(n.scheme||t.scheme);s&&s.serialize&&s.serialize(t,n);let o=t.userinfo!==void 0||t.host!==void 0||t.port!==void 0,a=!n.skipEscape&&t.scheme===void 0&&!o;t.path!==void 0&&(n.skipEscape?t.path=Nm(t.path):t.path=Mm(t.path,a)),n.reference!=="suffix"&&t.scheme&&(t.scheme=Tm(t.scheme),i.push(t.scheme,":"));let c=_x(t);if(c!==void 0&&(n.reference!=="suffix"&&i.push("//"),i.push(c),t.path&&t.path[0]!=="/"&&i.push("/")),t.path!==void 0){let l=t.path;!n.absolutePath&&(!s||!s.absolutePath)&&(l=Es(l)),a&&(l=Mm(l,!0)),c===void 0&&l[0]==="/"&&l[1]==="/"&&(l="/%2F"+l.slice(2)),i.push(l)}return t.query!==void 0&&i.push("?",Sx(t.query)),t.fragment!==void 0&&i.push("#",$x(t.fragment)),i.join("")}var Cx=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,Mx=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,Ix=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function Tx(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 $s(r){if(r===void 0)return!1;let e=r.indexOf("%");for(;e!==-1;){if(e+2>=r.length||!/^[\da-f]{2}$/iu.test(r.slice(e+1,e+3)))return!0;e=r.indexOf("%",e+3)}return!1}function bd(r){return r[0]==="["&&r[r.length-1]==="]"}function Rx(r){let e=r[4];return $s(r[3])||e!==void 0&&!bd(e)&&$s(e)||$s(r[6])||$s(r[7])||$s(r[8])}function Um(r,e,t,n){if(!e.unicodeSupport&&(!t||!t.unicodeSupport)&&r.host&&!bd(r.host)&&(e.domainHost||t&&t.domainHost)&&n===!1&&xx(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(i){return r.error=r.error||"Host's domain name can not be converted to ASCII: "+i,!0}return!1}function oa(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,o=!1,a=!1,c=!1,l=!1,u=!1;t.reference==="suffix"&&(t.scheme?r=t.scheme+":"+r:r="//"+r);let d=r.match(Mx);d!==null&&d[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",i=!0);let f=r.match(Ix);if(f!==null){let m=f[1],h=m.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",i=!0):m.length!==h.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",i=!0))}let p=r.match(Cx);if(p){if(n.scheme=p[1],n.userinfo=p[3],n.host=p[4],n.port=parseInt(p[5],10),n.path=p[6]||"",n.query=p[7],n.fragment=p[8],n.scheme!==void 0){let y=unescape(n.scheme);jm.test(y)?n.scheme=y.toLowerCase():(n.error=n.error||qm,l=!0)}s=Rx(p),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=p[5]);let m=Tx(n,p);if(m!==void 0&&(n.error=n.error||m,i=!0),n.host)if(Dm(n.host)===!1){let g=bd(n.host),_=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,v=Om(n.host);u=v.isIPV6||v.isIPVFuture===!0,c=_&&(!g||v.error===!0),n.host=u?v.host:v.host.toLowerCase(),c&&(n.error=n.error||"URI host is malformed.",i=!0)}else u=!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 h=gd(t.scheme||n.scheme);if(c||(a=Um(n,t,h,u)),!h||h&&!h.skipNormalize){if(r.indexOf("%")!==-1&&n.host!==void 0&&!c){let y=u?n.host:Nm(n.host,!0);n.host=Ex(y,u)}n.path&&(n.path=wx(n.path)),n.query&&(n.query=Im(n.query)),n.fragment&&(n.fragment=Im(n.fragment))}h&&h.parse&&(h.parse(n,t),h===Lm.urn&&n.nid===void 0&&(o=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:l}}function aa(r,e){return oa(r,e).parsed}function Ox(r,e){return Bm(r,e).normalized}function Bm(r,e){let{parsed:t,malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:a}=oa(r,e);return{normalized:n||i||s||o||a?r:Nn(t,e),malformedAuthorityOrPort:n,malformedPercentEncoding:i,malformedSchemeSpecific:s,malformedHost:o,malformedScheme:a}}function Rm(r,e){if(typeof r!="string"&&typeof r!="object")return;let t;try{t=typeof r=="string"?r:Nn(r,e)}catch{return}let{normalized:n,malformedAuthorityOrPort:i,malformedPercentEncoding:s,malformedSchemeSpecific:o,malformedHost:a,malformedScheme:c}=Bm(t,e);return i||s||o||a||c?void 0:n}var vd={SCHEMES:Lm,normalize:Ax,resolve:kx,resolveComponent:Fm,equal:Px,serialize:Nn,parse:aa};ca.exports=vd;ca.exports.default=vd;ca.exports.fastUri=vd});var Hm=E(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var zm=Vm();zm.code='require("ajv/dist/runtime/uri").default';_d.default=zm});var $d=E(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.CodeGen=Ne.Name=Ne.nil=Ne.stringify=Ne.str=Ne._=Ne.KeywordCxt=void 0;var Nx=mi();Object.defineProperty(Ne,"KeywordCxt",{enumerable:!0,get:function(){return Nx.KeywordCxt}});var bi=B();Object.defineProperty(Ne,"_",{enumerable:!0,get:function(){return bi._}});Object.defineProperty(Ne,"str",{enumerable:!0,get:function(){return bi.str}});Object.defineProperty(Ne,"stringify",{enumerable:!0,get:function(){return bi.stringify}});Object.defineProperty(Ne,"nil",{enumerable:!0,get:function(){return bi.nil}});Object.defineProperty(Ne,"Name",{enumerable:!0,get:function(){return bi.Name}});Object.defineProperty(Ne,"CodeGen",{enumerable:!0,get:function(){return bi.CodeGen}});var Dx=ws(),Ym=yi(),Lx=Vl(),xs=Ss(),jx=B(),As=bs(),la=gs(),Sd=X(),Km=gm(),qx=Hm(),Xm=(r,e)=>new RegExp(r,e);Xm.code="new RegExp";var Fx=["removeAdditional","useDefaults","coerceTypes"],Ux=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Bx={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."},Vx={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Wm=200;function zx(r){var e,t,n,i,s,o,a,c,l,u,d,f,p,m,h,y,g,_,v,w,S,x,C,$,M;let A=r.strict,W=(e=r.code)===null||e===void 0?void 0:e.optimize,q=W===!0||W===void 0?1:W||0,oe=(n=(t=r.code)===null||t===void 0?void 0:t.regExp)!==null&&n!==void 0?n:Xm,P=(i=r.uriResolver)!==null&&i!==void 0?i:qx.default;return{strictSchema:(o=(s=r.strictSchema)!==null&&s!==void 0?s:A)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=r.strictNumbers)!==null&&a!==void 0?a:A)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=r.strictTypes)!==null&&l!==void 0?l:A)!==null&&u!==void 0?u:"log",strictTuples:(f=(d=r.strictTuples)!==null&&d!==void 0?d:A)!==null&&f!==void 0?f:"log",strictRequired:(m=(p=r.strictRequired)!==null&&p!==void 0?p:A)!==null&&m!==void 0?m:!1,code:r.code?{...r.code,optimize:q,regExp:oe}:{optimize:q,regExp:oe},loopRequired:(h=r.loopRequired)!==null&&h!==void 0?h:Wm,loopEnum:(y=r.loopEnum)!==null&&y!==void 0?y:Wm,meta:(g=r.meta)!==null&&g!==void 0?g:!0,messages:(_=r.messages)!==null&&_!==void 0?_:!0,inlineRefs:(v=r.inlineRefs)!==null&&v!==void 0?v:!0,schemaId:(w=r.schemaId)!==null&&w!==void 0?w:"$id",addUsedSchema:(S=r.addUsedSchema)!==null&&S!==void 0?S:!0,validateSchema:(x=r.validateSchema)!==null&&x!==void 0?x:!0,validateFormats:(C=r.validateFormats)!==null&&C!==void 0?C:!0,unicodeRegExp:($=r.unicodeRegExp)!==null&&$!==void 0?$:!0,int32range:(M=r.int32range)!==null&&M!==void 0?M:!0,uriResolver:P}}var ks=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,...zx(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new jx.ValueScope({scope:{},prefixes:Ux,es5:t,lines:n}),this.logger=Yx(e.logger);let i=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Lx.getRules)(),Gm.call(this,Bx,e,"NOT SUPPORTED"),Gm.call(this,Vx,e,"DEPRECATED","warn"),this._metaOpts=Gx.call(this),e.formats&&Kx.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Wx.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Hx.call(this),e.validateFormats=i}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,i=Km;n==="id"&&(i={...Km},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 Ym.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,As.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=Jm.call(this,e))=="string";)e=t;if(t===void 0){let{schemaId:n}=this.opts,i=new xs.SchemaEnv({schema:{},schemaId:n});if(t=xs.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=Jm.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,As.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(Qx.call(this,n,t),!t)return(0,Sd.eachItem)(n,s=>wd.call(this,s)),this;eA.call(this,t);let i={...t,type:(0,la.getJSONTypes)(t.type),schemaType:(0,la.getJSONTypes)(t.schemaType)};return(0,Sd.eachItem)(n,i.type.length===0?s=>wd.call(this,s,i):s=>i.type.forEach(o=>wd.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]=Qm(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,As.normalizeId)(o||n);let l=As.getSchemaRefs.call(this,e,n);return c=new xs.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):xs.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{xs.compileSchema.call(this,e)}finally{this.opts=t}}};ks.ValidationError=Dx.default;ks.MissingRefError=Ym.default;Ne.default=ks;function Gm(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 Jm(r){return r=(0,As.normalizeId)(r),this.schemas[r]||this.refs[r]}function Hx(){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 Kx(){for(let r in this.opts.formats){let e=this.opts.formats[r];e&&this.addFormat(r,e)}}function Wx(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 Gx(){let r={...this.opts};for(let e of Fx)delete r[e];return r}var Jx={log(){},warn(){},error(){}};function Yx(r){if(r===!1)return Jx;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 Xx=/^[a-z_$][a-z0-9_$:-]*$/i;function Qx(r,e){let{RULES:t}=this;if((0,Sd.eachItem)(r,n=>{if(t.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Xx.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 wd(r,e,t){var n;let i=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,la.getJSONTypes)(e.type),schemaType:(0,la.getJSONTypes)(e.schemaType)}};e.before?Zx.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 Zx(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 eA(r){let{metaSchema:e}=r;e!==void 0&&(r.$data&&this.opts.$data&&(e=Qm(e)),r.validateSchema=this.compile(e,!0))}var tA={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Qm(r){return{anyOf:[r,tA]}}});var Zm=E(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var rA={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Ed.default=rA});var fa=E(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.callRef=Dn.getValidate=void 0;var nA=yi(),ey=Ct(),ft=B(),vi=Pt(),ty=Ss(),da=X(),iA={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=ty.resolveRef.call(c,l,i,t);if(u===void 0)throw new nA.default(n.opts.uriResolver,i,t);if(u instanceof ty.SchemaEnv)return f(u);return p(u);function d(){if(s===l)return ua(r,o,s,s.$async);let m=e.scopeValue("root",{ref:l});return ua(r,(0,ft._)`${m}.validate`,l,l.$async)}function f(m){let h=ry(r,m);ua(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"),g=r.subschema({schema:m,dataTypes:[],schemaPath:ft.nil,topSchemaRef:h,errSchemaPath:t},y);r.mergeEvaluated(g),r.ok(y)}}};function ry(r,e){let{gen:t}=r;return e.validate?t.scopeValue("validate",{ref:e.validate}):(0,ft._)`${t.scopeValue("wrapper",{ref:e})}.validate`}Dn.getValidate=ry;function ua(r,e,t,n){let{gen:i,it:s}=r,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?vi.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,ey.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,ey.callValidateCode)(r,e,l),()=>p(e),()=>f(e))}function f(m){let h=(0,ft._)`${m}.errors`;i.assign(vi.default.vErrors,(0,ft._)`${vi.default.vErrors} === null ? ${h} : ${vi.default.vErrors}.concat(${h})`),i.assign(vi.default.errors,(0,ft._)`${vi.default.vErrors}.length`)}function p(m){var h;if(!s.opts.unevaluated)return;let y=(h=t?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=da.mergeEvaluated.props(i,y.props,s.props));else{let g=i.var("props",(0,ft._)`${m}.evaluated.props`);s.props=da.mergeEvaluated.props(i,g,s.props,ft.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=da.mergeEvaluated.items(i,y.items,s.items));else{let g=i.var("items",(0,ft._)`${m}.evaluated.items`);s.items=da.mergeEvaluated.items(i,g,s.items,ft.Name)}}}Dn.callRef=ua;Dn.default=iA});var Ad=E(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var sA=Zm(),oA=fa(),aA=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",sA.default,oA.default];xd.default=aA});var ny=E(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var pa=B(),tn=pa.operators,ha={maximum:{okStr:"<=",ok:tn.LTE,fail:tn.GT},minimum:{okStr:">=",ok:tn.GTE,fail:tn.LT},exclusiveMaximum:{okStr:"<",ok:tn.LT,fail:tn.GTE},exclusiveMinimum:{okStr:">",ok:tn.GT,fail:tn.LTE}},cA={message:({keyword:r,schemaCode:e})=>(0,pa.str)`must be ${ha[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,pa._)`{comparison: ${ha[r].okStr}, limit: ${e}}`},lA={keyword:Object.keys(ha),type:"number",schemaType:"number",$data:!0,error:cA,code(r){let{keyword:e,data:t,schemaCode:n}=r;r.fail$data((0,pa._)`${t} ${ha[e].fail} ${n} || isNaN(${t})`)}};kd.default=lA});var iy=E(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var Ps=B(),dA={message:({schemaCode:r})=>(0,Ps.str)`must be multiple of ${r}`,params:({schemaCode:r})=>(0,Ps._)`{multipleOf: ${r}}`},uA={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:dA,code(r){let{gen:e,data:t,schemaCode:n,it:i}=r,s=i.opts.multipleOfPrecision,o=e.let("res"),a=s?(0,Ps._)`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:(0,Ps._)`${o} !== parseInt(${o})`;r.fail$data((0,Ps._)`(${n} === 0 || (${o} = ${t}/${n}, ${a}))`)}};Pd.default=uA});var oy=E(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});function sy(r){let e=r.length,t=0,n=0,i;for(;n=55296&&i<=56319&&n{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var Ln=B(),fA=X(),pA=oy(),hA={message({keyword:r,schemaCode:e}){let t=r==="maxLength"?"more":"fewer";return(0,Ln.str)`must NOT have ${t} than ${e} characters`},params:({schemaCode:r})=>(0,Ln._)`{limit: ${r}}`},mA={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:hA,code(r){let{keyword:e,data:t,schemaCode:n,it:i}=r,s=e==="maxLength"?Ln.operators.GT:Ln.operators.LT,o=i.opts.unicode===!1?(0,Ln._)`${t}.length`:(0,Ln._)`${(0,fA.useFunc)(r.gen,pA.default)}(${t})`;r.fail$data((0,Ln._)`${o} ${s} ${n}`)}};Md.default=mA});var cy=E(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var yA=Ct(),gA=X(),_i=B(),bA={message:({schemaCode:r})=>(0,_i.str)`must match pattern "${r}"`,params:({schemaCode:r})=>(0,_i._)`{pattern: ${r}}`},vA={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:bA,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,_i._)`new RegExp`:(0,gA.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,_i._)`${l}(${s}, ${a}).test(${t})`),()=>e.assign(u,!1)),r.fail$data((0,_i._)`!${u}`)}else{let c=(0,yA.usePattern)(r,i);r.fail$data((0,_i._)`!${c}.test(${t})`)}}};Id.default=vA});var ly=E(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var Cs=B(),_A={message({keyword:r,schemaCode:e}){let t=r==="maxProperties"?"more":"fewer";return(0,Cs.str)`must NOT have ${t} than ${e} properties`},params:({schemaCode:r})=>(0,Cs._)`{limit: ${r}}`},wA={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:_A,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxProperties"?Cs.operators.GT:Cs.operators.LT;r.fail$data((0,Cs._)`Object.keys(${t}).length ${i} ${n}`)}};Td.default=wA});var dy=E(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var Ms=Ct(),Is=B(),SA=X(),$A={message:({params:{missingProperty:r}})=>(0,Is.str)`must have required property '${r}'`,params:({params:{missingProperty:r}})=>(0,Is._)`{missingProperty: ${r}}`},EA={keyword:"required",type:"object",schemaType:"array",$data:!0,error:$A,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?.[h]===void 0&&!m.has(h)){let y=o.schemaEnv.baseId+o.errSchemaPath,g=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,SA.checkStrictMode)(o,g,o.opts.strictRequired)}}function l(){if(c||s)r.block$data(Is.nil,d);else for(let p of t)(0,Ms.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,Ms.checkMissingProp)(r,t,p)),(0,Ms.reportMissingProp)(r,p),e.else()}function d(){e.forOf("prop",n,p=>{r.setParams({missingProperty:p}),e.if((0,Ms.noPropertyInData)(e,i,p,a.ownProperties),()=>r.error())})}function f(p,m){r.setParams({missingProperty:p}),e.forOf(p,n,()=>{e.assign(m,(0,Ms.propertyInData)(e,i,p,a.ownProperties)),e.if((0,Is.not)(m),()=>{r.error(),e.break()})},Is.nil)}}};Rd.default=EA});var uy=E(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});var Ts=B(),xA={message({keyword:r,schemaCode:e}){let t=r==="maxItems"?"more":"fewer";return(0,Ts.str)`must NOT have ${t} than ${e} items`},params:({schemaCode:r})=>(0,Ts._)`{limit: ${r}}`},AA={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:xA,code(r){let{keyword:e,data:t,schemaCode:n}=r,i=e==="maxItems"?Ts.operators.GT:Ts.operators.LT;r.fail$data((0,Ts._)`${t}.length ${i} ${n}`)}};Od.default=AA});var ma=E(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var fy=Xl();fy.code='require("ajv/dist/runtime/equal").default';Nd.default=fy});var py=E(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var Dd=gs(),De=B(),kA=X(),PA=ma(),CA={message:({params:{i:r,j:e}})=>(0,De.str)`must NOT have duplicate items (items ## ${e} and ${r} are identical)`,params:({params:{i:r,j:e}})=>(0,De._)`{i: ${r}, j: ${e}}`},MA={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:CA,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,Dd.getSchemaTypes)(s.items):[];r.block$data(c,u,(0,De._)`${o} === false`),r.ok(c);function u(){let m=e.let("i",(0,De._)`${t}.length`),h=e.let("j");r.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,De._)`${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"),g=(0,Dd.checkDataTypes)(l,y,a.opts.strictNumbers,Dd.DataType.Wrong),_=e.const("indices",(0,De._)`{}`);e.for((0,De._)`;${m}--;`,()=>{e.let(y,(0,De._)`${t}[${m}]`),e.if(g,(0,De._)`continue`),l.length>1&&e.if((0,De._)`typeof ${y} == "string"`,(0,De._)`${y} += "_"`),e.if((0,De._)`typeof ${_}[${y}] == "number"`,()=>{e.assign(h,(0,De._)`${_}[${y}]`),r.error(),e.assign(c,!1).break()}).code((0,De._)`${_}[${y}] = ${m}`)})}function p(m,h){let y=(0,kA.useFunc)(e,PA.default),g=e.name("outer");e.label(g).for((0,De._)`;${m}--;`,()=>e.for((0,De._)`${h} = ${m}; ${h}--;`,()=>e.if((0,De._)`${y}(${t}[${m}], ${t}[${h}])`,()=>{r.error(),e.assign(c,!1).break(g)})))}}};Ld.default=MA});var hy=E(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var jd=B(),IA=X(),TA=ma(),RA={message:"must be equal to constant",params:({schemaCode:r})=>(0,jd._)`{allowedValue: ${r}}`},OA={keyword:"const",$data:!0,error:RA,code(r){let{gen:e,data:t,$data:n,schemaCode:i,schema:s}=r;n||s&&typeof s=="object"?r.fail$data((0,jd._)`!${(0,IA.useFunc)(e,TA.default)}(${t}, ${i})`):r.fail((0,jd._)`${s} !== ${t}`)}};qd.default=OA});var my=E(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var Rs=B(),NA=X(),DA=ma(),LA={message:"must be equal to one of the allowed values",params:({schemaCode:r})=>(0,Rs._)`{allowedValues: ${r}}`},jA={keyword:"enum",schemaType:"array",$data:!0,error:LA,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??(c=(0,NA.useFunc)(e,DA.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,Rs.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,Rs._)`${l()}(${t}, ${p})`,()=>e.assign(u,!0).break()))}function f(p,m){let h=i[m];return typeof h=="object"&&h!==null?(0,Rs._)`${l()}(${t}, ${p}[${m}])`:(0,Rs._)`${t} === ${h}`}}};Fd.default=jA});var Bd=E(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var qA=ny(),FA=iy(),UA=ay(),BA=cy(),VA=ly(),zA=dy(),HA=uy(),KA=py(),WA=hy(),GA=my(),JA=[qA.default,FA.default,UA.default,BA.default,VA.default,zA.default,HA.default,KA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},WA.default,GA.default];Ud.default=JA});var zd=E(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.validateAdditionalItems=void 0;var jn=B(),Vd=X(),YA={message:({params:{len:r}})=>(0,jn.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,jn._)`{limit: ${r}}`},XA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:YA,code(r){let{parentSchema:e,it:t}=r,{items:n}=e;if(!Array.isArray(n)){(0,Vd.checkStrictMode)(t,'"additionalItems" is ignored when "items" is not an array of schemas');return}yy(r,n)}};function yy(r,e){let{gen:t,schema:n,data:i,keyword:s,it:o}=r;o.items=!0;let a=t.const("len",(0,jn._)`${i}.length`);if(n===!1)r.setParams({len:e.length}),r.pass((0,jn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Vd.alwaysValidSchema)(o,n)){let l=t.var("valid",(0,jn._)`${a} <= ${e.length}`);t.if((0,jn.not)(l),()=>c(l)),r.ok(l)}function c(l){t.forRange("i",e.length,a,u=>{r.subschema({keyword:s,dataProp:u,dataPropType:Vd.Type.Num},l),o.allErrors||t.if((0,jn.not)(l),()=>t.break())})}}Os.validateAdditionalItems=yy;Os.default=XA});var Hd=E(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});Ns.validateTuple=void 0;var gy=B(),ya=X(),QA=Ct(),ZA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(r){let{schema:e,it:t}=r;if(Array.isArray(e))return by(r,"additionalItems",e);t.items=!0,!(0,ya.alwaysValidSchema)(t,e)&&r.ok((0,QA.validateArray)(r))}};function by(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=ya.mergeEvaluated.items(n,t.length,a.items));let c=n.name("valid"),l=n.const("len",(0,gy._)`${s}.length`);t.forEach((d,f)=>{(0,ya.alwaysValidSchema)(a,d)||(n.if((0,gy._)`${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,ya.checkStrictMode)(a,y,f.strictTuples)}}}Ns.validateTuple=by;Ns.default=ZA});var vy=E(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});var ek=Hd(),tk={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:r=>(0,ek.validateTuple)(r,"items")};Kd.default=tk});var wy=E(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var _y=B(),rk=X(),nk=Ct(),ik=zd(),sk={message:({params:{len:r}})=>(0,_y.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,_y._)`{limit: ${r}}`},ok={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:sk,code(r){let{schema:e,parentSchema:t,it:n}=r,{prefixItems:i}=t;n.items=!0,!(0,rk.alwaysValidSchema)(n,e)&&(i?(0,ik.validateAdditionalItems)(r,i):r.ok((0,nk.validateArray)(r)))}};Wd.default=ok});var Sy=E(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var It=B(),ga=X(),ak={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}}`},ck={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:ak,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,ga.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,ga.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),r.fail();return}if((0,ga.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,g=>{r.subschema({keyword:"contains",dataProp:g,dataPropType:ga.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)))}}};Gd.default=ck});var ba=E(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.validateSchemaDeps=cr.validatePropertyDeps=cr.error=void 0;var Jd=B(),lk=X(),Ds=Ct();cr.error={message:({params:{property:r,depsCount:e,deps:t}})=>{let n=e===1?"property":"properties";return(0,Jd.str)`must have ${n} ${t} when property ${r} is present`},params:({params:{property:r,depsCount:e,deps:t,missingProperty:n}})=>(0,Jd._)`{property: ${r}, missingProperty: ${n}, depsCount: ${e}, - deps: ${t}}`};var kx={keyword:"dependencies",type:"object",schemaType:"object",error:ir.error,code(r){let[e,t]=Px(r);Xm(r,e),Qm(r,t)}};function Px({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 Xm(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,ks.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,ks.checkReportMissingProp)(r,l)}):(t.if((0,Dd._)`${c} && (${(0,ks.checkMissingProp)(r,a,s)})`),(0,ks.reportMissingProp)(r,s),t.else())}}ir.validatePropertyDeps=Xm;function Qm(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,xx.alwaysValidSchema)(s,e[a])||(t.if((0,ks.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))}ir.validateSchemaDeps=Qm;ir.default=kx});var ey=E(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var Zm=B(),Cx=X(),Mx={message:"property name must be valid",params:({params:r})=>(0,Zm._)`{propertyName: ${r.propertyName}}`},Tx={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Mx,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,Cx.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,Zm.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};Ld.default=Tx});var qd=E(jd=>{"use strict";Object.defineProperty(jd,"__esModule",{value:!0});var la=kt(),qt=B(),Ix=xt(),da=X(),Rx={message:"must NOT have additional properties",params:({params:r})=>(0,qt._)`{additionalProperty: ${r.additionalProperty}}`},Ox={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Rx,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,da.alwaysValidSchema)(o,t))return;let l=(0,la.allSchemaProperties)(n.properties),u=(0,la.allSchemaProperties)(n.patternProperties);d(),r.ok((0,qt._)`${s} === ${Ix.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 g;if(l.length>8){let v=(0,da.schemaRefOrVal)(o,n.properties,"properties");g=(0,la.isOwnProperty)(e,v,y)}else l.length?g=(0,qt.or)(...l.map(v=>(0,qt._)`${y} === ${v}`)):g=qt.nil;return u.length&&(g=(0,qt.or)(g,...u.map(v=>(0,qt._)`${(0,la.usePattern)(r,v)}.test(${y})`))),(0,qt.not)(g)}function p(y){e.code((0,qt._)`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,da.alwaysValidSchema)(o,t)){let g=e.name("valid");c.removeAdditional==="failing"?(h(y,g,!1),e.if((0,qt.not)(g),()=>{r.reset(),p(y)})):(h(y,g),a||e.if((0,qt.not)(g),()=>e.break()))}}function h(y,g,v){let _={keyword:"additionalProperties",dataProp:y,dataPropType:da.Type.Str};v===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(_,g)}}};jd.default=Ox});var ny=E(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var Nx=ii(),ty=kt(),Fd=X(),ry=qd(),Dx={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&&ry.default.code(new Nx.KeywordCxt(s,ry.default,"additionalProperties"));let o=(0,ty.allSchemaProperties)(t);for(let d of o)s.definedProperties.add(d);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=Fd.mergeEvaluated.props(e,(0,Fd.toHash)(o),s.props));let a=o.filter(d=>!(0,Fd.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,ty.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)}}};Ud.default=Dx});var ay=E(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});var iy=kt(),ua=B(),sy=X(),oy=X(),Lx={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,iy.allSchemaProperties)(t),c=a.filter(h=>(0,sy.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 ua.Name)&&(s.props=(0,oy.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,sy.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,ua._)`${(0,iy.usePattern)(r,h)}.test(${y})`,()=>{let g=c.includes(h);g||r.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:oy.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,ua._)`${d}[${y}]`,!0):!g&&!s.allErrors&&e.if((0,ua.not)(u),()=>e.break())})})}}};Bd.default=Lx});var cy=E(Vd=>{"use strict";Object.defineProperty(Vd,"__esModule",{value:!0});var jx=X(),qx={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,jx.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"}};Vd.default=qx});var ly=E(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});var Fx=kt(),Ux={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Fx.validateUnion,error:{message:"must match a schema in anyOf"}};zd.default=Ux});var dy=E(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var fa=B(),Bx=X(),Vx={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,fa._)`{passingSchemas: ${r.passing}}`},zx={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Vx,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,Bx.alwaysValidSchema)(i,u)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,fa._)`${c} && ${o}`).assign(o,!1).assign(a,(0,fa._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,d),f&&r.mergeEvaluated(f,fa.Name)})})}}};Hd.default=zx});var uy=E(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});var Hx=X(),Kx={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,Hx.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};Kd.default=Kx});var hy=E(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var pa=B(),py=X(),Wx={message:({params:r})=>(0,pa.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,pa._)`{failingKeyword: ${r.ifClause}}`},Gx={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Wx,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,py.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=fy(n,"then"),s=fy(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,pa.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,pa._)`${u}`):r.setParams({ifClause:u})}}}};function fy(r,e){let t=r.schema[e];return t!==void 0&&!(0,py.alwaysValidSchema)(r,t)}Wd.default=Gx});var my=E(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var Jx=X(),Yx={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,Jx.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};Gd.default=Yx});var Yd=E(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var Xx=Td(),Qx=Wm(),Zx=Id(),ek=Jm(),tk=Ym(),rk=ca(),nk=ey(),ik=qd(),sk=ny(),ok=ay(),ak=cy(),ck=ly(),lk=dy(),dk=uy(),uk=hy(),fk=my();function pk(r=!1){let e=[ak.default,ck.default,lk.default,dk.default,uk.default,fk.default,nk.default,ik.default,rk.default,sk.default,ok.default];return r?e.push(Qx.default,ek.default):e.push(Xx.default,Zx.default),e.push(tk.default),e}Jd.default=pk});var Qd=E(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});Ps.dynamicAnchor=void 0;var Xd=B(),hk=xt(),yy=hs(),mk=ra(),yk={keyword:"$dynamicAnchor",schemaType:"string",code:r=>gy(r,r.schema)};function gy(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,Xd._)`${hk.default.dynamicAnchors}${(0,Xd.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:gk(r);t.if((0,Xd._)`!${i}`,()=>t.assign(i,s))}Ps.dynamicAnchor=gy;function gk(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 yy.SchemaEnv({schema:t,schemaId:c,root:i,baseId:s,localRefs:o,meta:a});return yy.compileSchema.call(n,l),(0,mk.getValidate)(r,l)}Ps.default=yk});var Zd=E(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});Cs.dynamicRef=void 0;var by=B(),bk=xt(),_y=ra(),_k={keyword:"$dynamicRef",schemaType:"string",code:r=>vy(r,r.schema)};function vy(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,by._)`${bk.default.dynamicAnchors}${(0,by.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,_y.callRef)(r,c),t.let(l,!0)}):()=>(0,_y.callRef)(r,c)}}Cs.dynamicRef=vy;Cs.default=_k});var wy=E(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});var vk=Qd(),wk=X(),Sk={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,vk.dynamicAnchor)(r,""):(0,wk.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};eu.default=Sk});var Sy=E(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});var $k=Zd(),Ek={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,$k.dynamicRef)(r,r.schema)};tu.default=Ek});var $y=E(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});var Ak=Qd(),xk=Zd(),kk=wy(),Pk=Sy(),Ck=[Ak.default,xk.default,kk.default,Pk.default];ru.default=Ck});var Ay=E(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});var Ey=ca(),Mk={keyword:"dependentRequired",type:"object",schemaType:"object",error:Ey.error,code:r=>(0,Ey.validatePropertyDeps)(r)};nu.default=Mk});var xy=E(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});var Tk=ca(),Ik={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,Tk.validateSchemaDeps)(r)};iu.default=Ik});var ky=E(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0});var Rk=X(),Ok={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,Rk.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};su.default=Ok});var Py=E(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});var Nk=Ay(),Dk=xy(),Lk=ky(),jk=[Nk.default,Dk.default,Lk.default];ou.default=jk});var My=E(au=>{"use strict";Object.defineProperty(au,"__esModule",{value:!0});var Xr=B(),Cy=X(),qk=xt(),Fk={message:"must NOT have unevaluated properties",params:({params:r})=>(0,Xr._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},Uk={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:Fk,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 Xr.Name?e.if((0,Xr._)`${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,Xr._)`${i} === ${qk.default.errors}`);function c(d){if(t===!1){r.setParams({unevaluatedProperty:d}),r.error(),o||e.break();return}if(!(0,Cy.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:Cy.Type.Str},f),o||e.if((0,Xr.not)(f),()=>e.break())}}function l(d,f){return(0,Xr._)`!${d} || !${d}[${f}]`}function u(d,f){let p=[];for(let m in d)d[m]===!0&&p.push((0,Xr._)`${f} !== ${m}`);return(0,Xr.and)(...p)}}};au.default=Uk});var Iy=E(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});var In=B(),Ty=X(),Bk={message:({params:{len:r}})=>(0,In.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,In._)`{limit: ${r}}`},Vk={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:Bk,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,In._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,In._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,Ty.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,In._)`${o} <= ${s}`);e.if((0,In.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:Ty.Type.Num},c),i.allErrors||e.if((0,In.not)(c),()=>e.break())})}}};cu.default=Vk});var Ry=E(lu=>{"use strict";Object.defineProperty(lu,"__esModule",{value:!0});var zk=My(),Hk=Iy(),Kk=[zk.default,Hk.default];lu.default=Kk});var Oy=E(du=>{"use strict";Object.defineProperty(du,"__esModule",{value:!0});var Ae=B(),Wk={message:({schemaCode:r})=>(0,Ae.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,Ae._)`{format: ${r}}`},Gk={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Wk,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,Ae._)`${m}[${o}]`),y=t.let("fType"),g=t.let("format");t.if((0,Ae._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>t.assign(y,(0,Ae._)`${h}.type || "string"`).assign(g,(0,Ae._)`${h}.validate`),()=>t.assign(y,(0,Ae._)`"string"`).assign(g,h)),r.fail$data((0,Ae.or)(v(),_()));function v(){return c.strictSchema===!1?Ae.nil:(0,Ae._)`${o} && !${g}`}function _(){let w=u.$async?(0,Ae._)`(${h}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,Ae._)`${g}(${n})`,A=(0,Ae._)`(typeof ${g} == "function" ? ${w} : ${g}.test(${n}))`;return(0,Ae._)`${g} && ${g} !== true && ${y} === ${e} && !${A}`}}function p(){let m=d.formats[s];if(!m){v();return}if(m===!0)return;let[h,y,g]=_(m);h===e&&r.pass(w());function v(){if(c.strictSchema===!1){d.logger.warn(A());return}throw new Error(A());function A(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function _(A){let x=A instanceof RegExp?(0,Ae.regexpCode)(A):c.code.formats?(0,Ae._)`${c.code.formats}${(0,Ae.getProperty)(s)}`:void 0,M=t.scopeValue("formats",{key:s,ref:A,code:x});return typeof A=="object"&&!(A instanceof RegExp)?[A.type||"string",A.validate,(0,Ae._)`${M}.validate`]:["string",A,M]}function w(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Ae._)`await ${g}(${n})`}return typeof y=="function"?(0,Ae._)`${g}(${n})`:(0,Ae._)`${g}.test(${n})`}}}};du.default=Gk});var fu=E(uu=>{"use strict";Object.defineProperty(uu,"__esModule",{value:!0});var Jk=Oy(),Yk=[Jk.default];uu.default=Yk});var pu=E(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.contentVocabulary=di.metadataVocabulary=void 0;di.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];di.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Dy=E(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});var Xk=pd(),Qk=Cd(),Zk=Yd(),eP=$y(),tP=Py(),rP=Ry(),nP=fu(),Ny=pu(),iP=[eP.default,Xk.default,Qk.default,(0,Zk.default)(!0),nP.default,Ny.metadataVocabulary,Ny.contentVocabulary,tP.default,rP.default];hu.default=iP});var jy=E(ha=>{"use strict";Object.defineProperty(ha,"__esModule",{value:!0});ha.DiscrError=void 0;var Ly;(function(r){r.Tag="tag",r.Mapping="mapping"})(Ly||(ha.DiscrError=Ly={}))});var gu=E(yu=>{"use strict";Object.defineProperty(yu,"__esModule",{value:!0});var ui=B(),mu=jy(),qy=hs(),sP=si(),oP=X(),aP={message:({params:{discrError:r,tagName:e}})=>r===mu.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,ui._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},cP={keyword:"discriminator",type:"object",schemaType:"object",error:aP,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,ui._)`${t}${(0,ui.getProperty)(a)}`);e.if((0,ui._)`typeof ${l} == "string"`,()=>u(),()=>r.error(!1,{discrError:mu.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,ui._)`${l} === ${m}`),e.assign(c,d(p[m]));e.else(),r.error(!1,{discrError:mu.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,ui.Name),m}function f(){var p;let m={},h=g(i),y=!0;for(let w=0;w{lP.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 Uy=E((wL,dP)=>{dP.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 By=E((SL,uP)=>{uP.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 Vy=E(($L,fP)=>{fP.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 zy=E((EL,pP)=>{pP.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 Hy=E((AL,hP)=>{hP.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 Ky=E((xL,mP)=>{mP.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 Wy=E((kL,yP)=>{yP.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 Gy=E(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});var gP=Fy(),bP=Uy(),_P=By(),vP=Vy(),wP=zy(),SP=Hy(),$P=Ky(),EP=Wy(),AP=["/properties"];function xP(r){return[gP,bP,_P,vP,wP,e(this,SP),$P,e(this,EP)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,AP):n}}bu.default=xP});var wu=E((ge,vu)=>{"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.Ajv2020=void 0;var kP=dd(),PP=Dy(),CP=gu(),MP=Gy(),_u="https://json-schema.org/draft/2020-12/schema",fi=class extends kP.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),PP.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(CP.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(MP.default.call(this,e),this.refs["http://json-schema.org/schema"]=_u)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(_u)?_u:void 0)}};ge.Ajv2020=fi;vu.exports=ge=fi;vu.exports.Ajv2020=fi;Object.defineProperty(ge,"__esModule",{value:!0});ge.default=fi;var TP=ii();Object.defineProperty(ge,"KeywordCxt",{enumerable:!0,get:function(){return TP.KeywordCxt}});var pi=B();Object.defineProperty(ge,"_",{enumerable:!0,get:function(){return pi._}});Object.defineProperty(ge,"str",{enumerable:!0,get:function(){return pi.str}});Object.defineProperty(ge,"stringify",{enumerable:!0,get:function(){return pi.stringify}});Object.defineProperty(ge,"nil",{enumerable:!0,get:function(){return pi.nil}});Object.defineProperty(ge,"Name",{enumerable:!0,get:function(){return pi.Name}});Object.defineProperty(ge,"CodeGen",{enumerable:!0,get:function(){return pi.CodeGen}});var IP=ps();Object.defineProperty(ge,"ValidationError",{enumerable:!0,get:function(){return IP.default}});var RP=si();Object.defineProperty(ge,"MissingRefError",{enumerable:!0,get:function(){return RP.default}})});var rg=E(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.formatNames=or.fastFormats=or.fullFormats=void 0;function sr(r,e){return{validate:r,compare:e}}or.fullFormats={date:sr(Qy,Au),time:sr($u(!0),xu),"date-time":sr(Jy(!0),eg),"iso-time":sr($u(),Zy),"iso-date-time":sr(Jy(),tg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:qP,"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:KP,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:FP,int32:{type:"number",validate:VP},int64:{type:"number",validate:zP},float:{type:"number",validate:Xy},double:{type:"number",validate:Xy},password:!0,binary:!0};or.fastFormats={...or.fullFormats,date:sr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Au),time:sr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,xu),"date-time":sr(/^\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,eg),"iso-time":sr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Zy),"iso-date-time":sr(/^\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,tg),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};or.formatNames=Object.keys(or.fullFormats);function OP(r){return r%4===0&&(r%100!==0||r%400===0)}var NP=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,DP=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Qy(r){let e=NP.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&&OP(t)?29:DP[n])}function Au(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 xu(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 Zy(r,e){if(!(r&&e))return;let t=Su.exec(r),n=Su.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=UP}function zP(r){return Number.isInteger(r)}function Xy(){return!0}var HP=/[^\\]\\Z/;function KP(r){if(HP.test(r))return!1;try{return new RegExp(r),!0}catch{return!1}}});var ig=E(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});var WP=pd(),GP=Cd(),JP=Yd(),YP=fu(),ng=pu(),XP=[WP.default,GP.default,(0,JP.default)(),YP.default,ng.metadataVocabulary,ng.contentVocabulary];ku.default=XP});var sg=E((TL,QP)=>{QP.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 ag=E((be,Pu)=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.MissingRefError=be.ValidationError=be.CodeGen=be.Name=be.nil=be.stringify=be.str=be._=be.KeywordCxt=be.Ajv=void 0;var ZP=dd(),e1=ig(),t1=gu(),og=sg(),r1=["/properties"],ma="http://json-schema.org/draft-07/schema",hi=class extends ZP.default{_addVocabularies(){super._addVocabularies(),e1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(t1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(og,r1):og;this.addMetaSchema(e,ma,!1),this.refs["http://json-schema.org/schema"]=ma}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ma)?ma:void 0)}};be.Ajv=hi;Pu.exports=be=hi;Pu.exports.Ajv=hi;Object.defineProperty(be,"__esModule",{value:!0});be.default=hi;var n1=ii();Object.defineProperty(be,"KeywordCxt",{enumerable:!0,get:function(){return n1.KeywordCxt}});var mi=B();Object.defineProperty(be,"_",{enumerable:!0,get:function(){return mi._}});Object.defineProperty(be,"str",{enumerable:!0,get:function(){return mi.str}});Object.defineProperty(be,"stringify",{enumerable:!0,get:function(){return mi.stringify}});Object.defineProperty(be,"nil",{enumerable:!0,get:function(){return mi.nil}});Object.defineProperty(be,"Name",{enumerable:!0,get:function(){return mi.Name}});Object.defineProperty(be,"CodeGen",{enumerable:!0,get:function(){return mi.CodeGen}});var i1=ps();Object.defineProperty(be,"ValidationError",{enumerable:!0,get:function(){return i1.default}});var s1=si();Object.defineProperty(be,"MissingRefError",{enumerable:!0,get:function(){return s1.default}})});var cg=E(yi=>{"use strict";Object.defineProperty(yi,"__esModule",{value:!0});yi.formatLimitDefinition=void 0;var o1=ag(),Ft=B(),Qr=Ft.operators,ya={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}},a1={message:({keyword:r,schemaCode:e})=>(0,Ft.str)`should be ${ya[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Ft._)`{comparison: ${ya[r].okStr}, limit: ${e}}`};yi.formatLimitDefinition={keyword:Object.keys(ya),type:"string",schemaType:"string",$data:!0,error:a1,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 o1.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,Ft._)`${f}[${c.schemaCode}]`);r.fail$data((0,Ft.or)((0,Ft._)`typeof ${p} != "object"`,(0,Ft._)`${p} instanceof RegExp`,(0,Ft._)`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,Ft._)`${o.code.formats}${(0,Ft.getProperty)(f)}`:void 0});r.fail$data(d(m))}function d(f){return(0,Ft._)`${f}.compare(${t}, ${n}) ${ya[i].fail} 0`}},dependencies:["format"]};var c1=r=>(r.addKeyword(yi.formatLimitDefinition),r);yi.default=c1});var Tu=E((Ms,ug)=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});var gi=rg(),l1=cg(),Cu=B(),lg=new Cu.Name("fullFormats"),d1=new Cu.Name("fastFormats"),Mu=(r,e={keywords:!0})=>{if(Array.isArray(e))return dg(r,e,gi.fullFormats,lg),r;let[t,n]=e.mode==="fast"?[gi.fastFormats,d1]:[gi.fullFormats,lg],i=e.formats||gi.formatNames;return dg(r,i,t,n),e.keywords&&(0,l1.default)(r),r};Mu.get=(r,e="full")=>{let n=(e==="fast"?gi.fastFormats:gi.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function dg(r,e,t,n){var i,s;(i=(s=r.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,Cu._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}ug.exports=Ms=Mu;Object.defineProperty(Ms,"__esModule",{value:!0});Ms.default=Mu});var vi=E((qL,bg)=>{"use strict";var p1="2.0.0",h1=Number.MAX_SAFE_INTEGER||9007199254740991,m1=16,y1=250,g1=["major","premajor","minor","preminor","patch","prepatch","prerelease"];bg.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:m1,MAX_SAFE_BUILD_LENGTH:y1,MAX_SAFE_INTEGER:h1,RELEASE_TYPES:g1,SEMVER_SPEC_VERSION:p1,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Ts=E((FL,_g)=>{"use strict";var b1=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};_g.exports=b1});var wi=E((cr,vg)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:Nu,MAX_SAFE_BUILD_LENGTH:_1,MAX_LENGTH:v1}=vi(),w1=Ts();cr=vg.exports={};var S1=cr.re=[],$1=cr.safeRe=[],N=cr.src=[],E1=cr.safeSrc=[],D=cr.t={},A1=0,Du="[a-zA-Z0-9-]",x1=[["\\s",1],["\\d",v1],[Du,_1]],k1=r=>{for(let[e,t]of x1)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},z=(r,e,t)=>{let n=k1(e),i=A1++;w1(r,i,e),D[r]=i,N[i]=e,E1[i]=n,S1[i]=new RegExp(e,t?"g":void 0),$1[i]=new RegExp(n,t?"g":void 0)};z("NUMERICIDENTIFIER","0|[1-9]\\d*");z("NUMERICIDENTIFIERLOOSE","\\d+");z("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Du}*`);z("MAINVERSION",`(${N[D.NUMERICIDENTIFIER]})\\.(${N[D.NUMERICIDENTIFIER]})\\.(${N[D.NUMERICIDENTIFIER]})`);z("MAINVERSIONLOOSE",`(${N[D.NUMERICIDENTIFIERLOOSE]})\\.(${N[D.NUMERICIDENTIFIERLOOSE]})\\.(${N[D.NUMERICIDENTIFIERLOOSE]})`);z("PRERELEASEIDENTIFIER",`(?:${N[D.NONNUMERICIDENTIFIER]}|${N[D.NUMERICIDENTIFIER]})`);z("PRERELEASEIDENTIFIERLOOSE",`(?:${N[D.NONNUMERICIDENTIFIER]}|${N[D.NUMERICIDENTIFIERLOOSE]})`);z("PRERELEASE",`(?:-(${N[D.PRERELEASEIDENTIFIER]}(?:\\.${N[D.PRERELEASEIDENTIFIER]})*))`);z("PRERELEASELOOSE",`(?:-?(${N[D.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${N[D.PRERELEASEIDENTIFIERLOOSE]})*))`);z("BUILDIDENTIFIER",`${Du}+`);z("BUILD",`(?:\\+(${N[D.BUILDIDENTIFIER]}(?:\\.${N[D.BUILDIDENTIFIER]})*))`);z("FULLPLAIN",`v?${N[D.MAINVERSION]}${N[D.PRERELEASE]}?${N[D.BUILD]}?`);z("FULL",`^${N[D.FULLPLAIN]}$`);z("LOOSEPLAIN",`[v=\\s]*${N[D.MAINVERSIONLOOSE]}${N[D.PRERELEASELOOSE]}?${N[D.BUILD]}?`);z("LOOSE",`^${N[D.LOOSEPLAIN]}$`);z("GTLT","((?:<|>)?=?)");z("XRANGEIDENTIFIERLOOSE",`${N[D.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);z("XRANGEIDENTIFIER",`${N[D.NUMERICIDENTIFIER]}|x|X|\\*`);z("XRANGEPLAIN",`[v=\\s]*(${N[D.XRANGEIDENTIFIER]})(?:\\.(${N[D.XRANGEIDENTIFIER]})(?:\\.(${N[D.XRANGEIDENTIFIER]})(?:${N[D.PRERELEASE]})?${N[D.BUILD]}?)?)?`);z("XRANGEPLAINLOOSE",`[v=\\s]*(${N[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${N[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${N[D.XRANGEIDENTIFIERLOOSE]})(?:${N[D.PRERELEASELOOSE]})?${N[D.BUILD]}?)?)?`);z("XRANGE",`^${N[D.GTLT]}\\s*${N[D.XRANGEPLAIN]}$`);z("XRANGELOOSE",`^${N[D.GTLT]}\\s*${N[D.XRANGEPLAINLOOSE]}$`);z("COERCEPLAIN",`(^|[^\\d])(\\d{1,${Nu}})(?:\\.(\\d{1,${Nu}}))?(?:\\.(\\d{1,${Nu}}))?`);z("COERCE",`${N[D.COERCEPLAIN]}(?:$|[^\\d])`);z("COERCEFULL",N[D.COERCEPLAIN]+`(?:${N[D.PRERELEASE]})?(?:${N[D.BUILD]})?(?:$|[^\\d])`);z("COERCERTL",N[D.COERCE],!0);z("COERCERTLFULL",N[D.COERCEFULL],!0);z("LONETILDE","(?:~>?)");z("TILDETRIM",`(\\s*)${N[D.LONETILDE]}\\s+`,!0);cr.tildeTrimReplace="$1~";z("TILDE",`^${N[D.LONETILDE]}${N[D.XRANGEPLAIN]}$`);z("TILDELOOSE",`^${N[D.LONETILDE]}${N[D.XRANGEPLAINLOOSE]}$`);z("LONECARET","(?:\\^)");z("CARETTRIM",`(\\s*)${N[D.LONECARET]}\\s+`,!0);cr.caretTrimReplace="$1^";z("CARET",`^${N[D.LONECARET]}${N[D.XRANGEPLAIN]}$`);z("CARETLOOSE",`^${N[D.LONECARET]}${N[D.XRANGEPLAINLOOSE]}$`);z("COMPARATORLOOSE",`^${N[D.GTLT]}\\s*(${N[D.LOOSEPLAIN]})$|^$`);z("COMPARATOR",`^${N[D.GTLT]}\\s*(${N[D.FULLPLAIN]})$|^$`);z("COMPARATORTRIM",`(\\s*)${N[D.GTLT]}\\s*(${N[D.LOOSEPLAIN]}|${N[D.XRANGEPLAIN]})`,!0);cr.comparatorTrimReplace="$1$2$3";z("HYPHENRANGE",`^\\s*(${N[D.XRANGEPLAIN]})\\s+-\\s+(${N[D.XRANGEPLAIN]})\\s*$`);z("HYPHENRANGELOOSE",`^\\s*(${N[D.XRANGEPLAINLOOSE]})\\s+-\\s+(${N[D.XRANGEPLAINLOOSE]})\\s*$`);z("STAR","(<|>)?=?\\s*\\*");z("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");z("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var _a=E((UL,wg)=>{"use strict";var P1=Object.freeze({loose:!0}),C1=Object.freeze({}),M1=r=>r?typeof r!="object"?P1:r:C1;wg.exports=M1});var Lu=E((BL,Eg)=>{"use strict";var Sg=/^[0-9]+$/,$g=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:r$g(e,r);Eg.exports={compareIdentifiers:$g,rcompareIdentifiers:T1}});var De=E((VL,xg)=>{"use strict";var va=Ts(),{MAX_LENGTH:Ag,MAX_SAFE_INTEGER:wa}=vi(),{safeRe:Sa,t:$a}=wi(),I1=_a(),{compareIdentifiers:ju}=Lu(),R1=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nAg)throw new TypeError(`version is longer than ${Ag} characters`);va("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Sa[$a.LOOSE]:Sa[$a.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>wa||this.major<0)throw new TypeError("Invalid major version");if(this.minor>wa||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>wa||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(va("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 ju(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(va("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 ju(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?Sa[$a.PRERELEASELOOSE]:Sa[$a.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]),R1(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}};xg.exports=qu});var en=E((zL,Pg)=>{"use strict";var kg=De(),O1=(r,e,t=!1)=>{if(r instanceof kg)return r;try{return new kg(r,e)}catch(n){if(!t)return null;throw n}};Pg.exports=O1});var Mg=E((HL,Cg)=>{"use strict";var N1=en(),D1=(r,e)=>{let t=N1(r,e);return t?t.version:null};Cg.exports=D1});var Ig=E((KL,Tg)=>{"use strict";var L1=en(),j1=(r,e)=>{let t=L1(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Tg.exports=j1});var Ng=E((WL,Og)=>{"use strict";var Rg=De(),q1=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new Rg(r instanceof Rg?r.version:r,t).inc(e,n,i).version}catch{return null}};Og.exports=q1});var jg=E((GL,Lg)=>{"use strict";var Dg=en(),F1=(r,e)=>{let t=Dg(r,null,!0),n=Dg(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"};Lg.exports=F1});var Fg=E((JL,qg)=>{"use strict";var U1=De(),B1=(r,e)=>new U1(r,e).major;qg.exports=B1});var Bg=E((YL,Ug)=>{"use strict";var V1=De(),z1=(r,e)=>new V1(r,e).minor;Ug.exports=z1});var zg=E((XL,Vg)=>{"use strict";var H1=De(),K1=(r,e)=>new H1(r,e).patch;Vg.exports=K1});var Kg=E((QL,Hg)=>{"use strict";var W1=en(),G1=(r,e)=>{let t=W1(r,e);return t&&t.prerelease.length?t.prerelease:null};Hg.exports=G1});var Mt=E((ZL,Gg)=>{"use strict";var Wg=De(),J1=(r,e,t)=>new Wg(r,t).compare(new Wg(e,t));Gg.exports=J1});var Yg=E((e2,Jg)=>{"use strict";var Y1=Mt(),X1=(r,e,t)=>Y1(e,r,t);Jg.exports=X1});var Qg=E((t2,Xg)=>{"use strict";var Q1=Mt(),Z1=(r,e)=>Q1(r,e,!0);Xg.exports=Z1});var Ea=E((r2,eb)=>{"use strict";var Zg=De(),eC=(r,e,t)=>{let n=new Zg(r,t),i=new Zg(e,t);return n.compare(i)||n.compareBuild(i)};eb.exports=eC});var rb=E((n2,tb)=>{"use strict";var tC=Ea(),rC=(r,e)=>r.sort((t,n)=>tC(t,n,e));tb.exports=rC});var ib=E((i2,nb)=>{"use strict";var nC=Ea(),iC=(r,e)=>r.sort((t,n)=>nC(n,t,e));nb.exports=iC});var Is=E((s2,sb)=>{"use strict";var sC=Mt(),oC=(r,e,t)=>sC(r,e,t)>0;sb.exports=oC});var Aa=E((o2,ob)=>{"use strict";var aC=Mt(),cC=(r,e,t)=>aC(r,e,t)<0;ob.exports=cC});var Fu=E((a2,ab)=>{"use strict";var lC=Mt(),dC=(r,e,t)=>lC(r,e,t)===0;ab.exports=dC});var Uu=E((c2,cb)=>{"use strict";var uC=Mt(),fC=(r,e,t)=>uC(r,e,t)!==0;cb.exports=fC});var xa=E((l2,lb)=>{"use strict";var pC=Mt(),hC=(r,e,t)=>pC(r,e,t)>=0;lb.exports=hC});var ka=E((d2,db)=>{"use strict";var mC=Mt(),yC=(r,e,t)=>mC(r,e,t)<=0;db.exports=yC});var Bu=E((u2,ub)=>{"use strict";var gC=Fu(),bC=Uu(),_C=Is(),vC=xa(),wC=Aa(),SC=ka(),$C=(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 gC(r,t,n);case"!=":return bC(r,t,n);case">":return _C(r,t,n);case">=":return vC(r,t,n);case"<":return wC(r,t,n);case"<=":return SC(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};ub.exports=$C});var pb=E((f2,fb)=>{"use strict";var EC=De(),AC=en(),{safeRe:Pa,t:Ca}=wi(),xC=(r,e)=>{if(r instanceof EC)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?Pa[Ca.COERCEFULL]:Pa[Ca.COERCE]);else{let c=e.includePrerelease?Pa[Ca.COERCERTLFULL]:Pa[Ca.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 AC(`${n}.${i}.${s}${o}${a}`,e)};fb.exports=xC});var mb=E((p2,hb)=>{"use strict";var kC=en(),PC=vi(),CC=De(),MC=(r,e,t)=>{if(!PC.RELEASE_TYPES.includes(e))return null;let n=TC(r,t);return n&&IC(n,e)},TC=(r,e)=>{let t=r instanceof CC?r.version:r;return kC(t,e)},IC=(r,e)=>{if(RC(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()},RC=r=>r.startsWith("pre");hb.exports=MC});var gb=E((h2,yb)=>{"use strict";var Vu=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}};yb.exports=Vu});var Tt=E((m2,wb)=>{"use strict";var OC=/\s+/g,zu=class r{constructor(e,t){if(t=DC(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof Hu)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(OC," "),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=>!_b(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&&HC(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(zC,"");let n=((this.options.includePrerelease&&BC)|(this.options.loose&&VC))+":"+e,i=bb.get(n);if(i)return i;let s=this.options.loose,o=s?Qe[Le.HYPHENRANGELOOSE]:Qe[Le.HYPHENRANGE];e=e.replace(o,rM(this.options.includePrerelease)),_e("hyphen replace",e),e=e.replace(Qe[Le.COMPARATORTRIM],qC),_e("comparator trim",e),e=e.replace(Qe[Le.TILDETRIM],FC),_e("tilde trim",e),e=e.replace(Qe[Le.CARETTRIM],UC),_e("caret trim",e);let a=e.split(" ").map(d=>KC(d,this.options)).join(" ").split(/\s+/).map(d=>tM(d,this.options));s&&(a=a.filter(d=>(_e("loose invalid filter",d,this.options),!!d.match(Qe[Le.COMPARATORLOOSE])))),_e("range list",a);let c=new Map,l=a.map(d=>new Hu(d,this.options));for(let d of l){if(_b(d))return[d];c.set(d.value,d)}c.size>1&&c.has("")&&c.delete("");let u=[...c.values()];return bb.set(n,u),u}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>vb(n,t)&&e.set.some(i=>vb(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 LC(e,this.options)}catch{return!1}for(let t=0;tr.value==="<0.0.0-0",HC=r=>r.value==="",vb=(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},KC=(r,e)=>(r=r.replace(Qe[Le.BUILD],""),_e("comp",r,e),r=YC(r,e),_e("caret",r),r=GC(r,e),_e("tildes",r),r=QC(r,e),_e("xrange",r),r=eM(r,e),_e("stars",r),r),Me=r=>!r||r.toLowerCase()==="x"||r==="*",WC=(r,e,t)=>Me(r)&&!Me(e)||Me(e)&&t&&!Me(t),GC=(r,e)=>r.trim().split(/\s+/).map(t=>JC(t,e)).join(" "),JC=(r,e)=>{let t=e.loose?Qe[Le.TILDELOOSE]:Qe[Le.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 Me(s)?l="":Me(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Me(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})},YC=(r,e)=>r.trim().split(/\s+/).map(t=>XC(t,e)).join(" "),XC=(r,e)=>{_e("caret",r,e);let t=e.loose?Qe[Le.CARETLOOSE]:Qe[Le.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 Me(s)?l="":Me(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Me(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})},QC=(r,e)=>(_e("replaceXRanges",r,e),r.split(/\s+/).map(t=>ZC(t,e)).join(" ")),ZC=(r,e)=>{r=r.trim();let t=e.loose?Qe[Le.XRANGELOOSE]:Qe[Le.XRANGE];return r.replace(t,(n,i,s,o,a,c)=>{if(_e("xRange",r,n,i,s,o,a,c),WC(s,o,a))return r;let l=Me(s),u=l||Me(o),d=u||Me(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})},eM=(r,e)=>(_e("replaceStars",r,e),r.trim().replace(Qe[Le.STAR],"")),tM=(r,e)=>(_e("replaceGTE0",r,e),r.trim().replace(Qe[e.includePrerelease?Le.GTE0PRE:Le.GTE0],"")),rM=r=>(e,t,n,i,s,o,a,c,l,u,d,f)=>(Me(n)?t="":Me(i)?t=`>=${n}.0.0${r?"-0":""}`:Me(s)?t=`>=${n}.${i}.0${r?"-0":""}`:o?t=`>=${t}`:t=`>=${t}${r?"-0":""}`,Me(l)?c="":Me(u)?c=`<${+l+1}.0.0-0`:Me(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()),nM=(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 Rs=E((y2,kb)=>{"use strict";var Os=Symbol("SemVer ANY"),Gu=class r{static get ANY(){return Os}constructor(e,t){if(t=Sb(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Wu("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Os?this.value="":this.value=this.operator+this.semver.version,Wu("comp",this)}parse(e){let t=this.options.loose?$b[Eb.COMPARATORLOOSE]:$b[Eb.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 Ab(n[2],this.options.loose):this.semver=Os}toString(){return this.value}test(e){if(Wu("Comparator.test",e,this.options.loose),this.semver===Os||e===Os)return!0;if(typeof e=="string")try{e=new Ab(e,this.options)}catch{return!1}return Ku(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 xb(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new xb(this.value,t).test(e.semver):(t=Sb(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("=")||Ku(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Ku(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};kb.exports=Gu;var Sb=_a(),{safeRe:$b,t:Eb}=wi(),Ku=Bu(),Wu=Ts(),Ab=De(),xb=Tt()});var Ns=E((g2,Pb)=>{"use strict";var iM=Tt(),sM=(r,e,t)=>{try{e=new iM(e,t)}catch{return!1}return e.test(r)};Pb.exports=sM});var Mb=E((b2,Cb)=>{"use strict";var oM=Tt(),aM=(r,e)=>new oM(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));Cb.exports=aM});var Ib=E((_2,Tb)=>{"use strict";var cM=De(),lM=Tt(),dM=(r,e,t)=>{let n=null,i=null,s=null;try{s=new lM(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new cM(n,t))}),n};Tb.exports=dM});var Ob=E((v2,Rb)=>{"use strict";var uM=De(),fM=Tt(),pM=(r,e,t)=>{let n=null,i=null,s=null;try{s=new fM(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new uM(n,t))}),n};Rb.exports=pM});var Lb=E((w2,Db)=>{"use strict";var Ju=De(),hM=Tt(),Nb=Is(),mM=(r,e)=>{r=new hM(r,e);let t=new Ju("0.0.0");if(r.test(t)||(t=new Ju("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new Ju(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||Nb(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||Nb(t,s))&&(t=s)}return t&&r.test(t)?t:null};Db.exports=mM});var qb=E((S2,jb)=>{"use strict";var yM=Tt(),gM=(r,e)=>{try{return new yM(r,e).range||"*"}catch{return null}};jb.exports=gM});var Ma=E(($2,Vb)=>{"use strict";var bM=De(),Bb=Rs(),{ANY:_M}=Bb,vM=Tt(),wM=Ns(),Fb=Is(),Ub=Aa(),SM=ka(),$M=xa(),EM=(r,e,t,n)=>{r=new bM(r,n),e=new vM(e,n);let i,s,o,a,c;switch(t){case">":i=Fb,s=SM,o=Ub,a=">",c=">=";break;case"<":i=Ub,s=$M,o=Fb,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(wM(r,e,n))return!1;for(let l=0;l{p.semver===_M&&(p=new Bb(">=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};Vb.exports=EM});var Hb=E((E2,zb)=>{"use strict";var AM=Ma(),xM=(r,e,t)=>AM(r,e,">",t);zb.exports=xM});var Wb=E((A2,Kb)=>{"use strict";var kM=Ma(),PM=(r,e,t)=>kM(r,e,"<",t);Kb.exports=PM});var Yb=E((x2,Jb)=>{"use strict";var Gb=Tt(),CM=(r,e,t)=>(r=new Gb(r,t),e=new Gb(e,t),r.intersects(e,t));Jb.exports=CM});var Qb=E((k2,Xb)=>{"use strict";var MM=Ns(),TM=Mt();Xb.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((u,d)=>TM(u,d,t));for(let u of o)MM(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 Zb=Tt(),Qu=Rs(),{ANY:Yu}=Qu,Xu=Ns(),Zu=Mt(),IM=(r,e,t={})=>{if(r===e)return!0;r=new Zb(r,t),e=new Zb(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=OM(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},RM=[new Qu(">=0.0.0-0")],e_=[new Qu(">=0.0.0")],OM=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===Yu){if(e.length===1&&e[0].semver===Yu)return!0;t.includePrerelease?r=RM:r=e_}if(e.length===1&&e[0].semver===Yu){if(t.includePrerelease)return!0;e=e_}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=t_(i,p,t):p.operator==="<"||p.operator==="<="?s=r_(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=Zu(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&&!Xu(p,String(i),t)||s&&!Xu(p,String(s),t))return null;for(let m of e)if(!Xu(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=t_(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=r_(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)},t_=(r,e,t)=>{if(!r)return e;let n=Zu(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},r_=(r,e,t)=>{if(!r)return e;let n=Zu(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};n_.exports=IM});var c_=E((C2,a_)=>{"use strict";var ef=wi(),s_=vi(),NM=De(),o_=Lu(),DM=en(),LM=Mg(),jM=Ig(),qM=Ng(),FM=jg(),UM=Fg(),BM=Bg(),VM=zg(),zM=Kg(),HM=Mt(),KM=Yg(),WM=Qg(),GM=Ea(),JM=rb(),YM=ib(),XM=Is(),QM=Aa(),ZM=Fu(),eT=Uu(),tT=xa(),rT=ka(),nT=Bu(),iT=pb(),sT=mb(),oT=Rs(),aT=Tt(),cT=Ns(),lT=Mb(),dT=Ib(),uT=Ob(),fT=Lb(),pT=qb(),hT=Ma(),mT=Hb(),yT=Wb(),gT=Yb(),bT=Qb(),_T=i_();a_.exports={parse:DM,valid:LM,clean:jM,inc:qM,diff:FM,major:UM,minor:BM,patch:VM,prerelease:zM,compare:HM,rcompare:KM,compareLoose:WM,compareBuild:GM,sort:JM,rsort:YM,gt:XM,lt:QM,eq:ZM,neq:eT,gte:tT,lte:rT,cmp:nT,coerce:iT,truncate:sT,Comparator:oT,Range:aT,satisfies:cT,toComparators:lT,maxSatisfying:dT,minSatisfying:uT,minVersion:fT,validRange:pT,outside:hT,gtr:mT,ltr:yT,intersects:gT,simplifyRange:bT,subset:_T,SemVer:NM,re:ef.re,src:ef.src,tokens:ef.t,SEMVER_SPEC_VERSION:s_.SEMVER_SPEC_VERSION,RELEASE_TYPES:s_.RELEASE_TYPES,compareIdentifiers:o_.compareIdentifiers,rcompareIdentifiers:o_.rcompareIdentifiers}});var Ls=E((K2,b_)=>{"use strict";var h_="[^\\\\/]",PT="(?=.)",m_="[^/]",of="(?:\\/|$)",y_="(?:^|\\/)",af=`\\.{1,2}${of}`,CT="(?!\\.)",MT=`(?!${y_}${af})`,TT=`(?!\\.{0,1}${of})`,IT=`(?!${af})`,RT="[^.\\/]",OT=`${m_}*?`,NT="/",g_={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:PT,QMARK:m_,END_ANCHOR:of,DOTS_SLASH:af,NO_DOT:CT,NO_DOTS:MT,NO_DOT_SLASH:TT,NO_DOTS_SLASH:IT,QMARK_NO_DOT:RT,STAR:OT,START_ANCHOR:y_,SEP:NT},DT={...g_,SLASH_LITERAL:"[\\\\/]",QMARK:h_,STAR:`${h_}*?`,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:"\\"},LT={__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"};b_.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:LT,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?DT:g_}}});var js=E(lt=>{"use strict";var{REGEX_BACKSLASH:jT,REGEX_REMOVE_BACKSLASH:qT,REGEX_SPECIAL_CHARS:FT,REGEX_SPECIAL_CHARS_GLOBAL:UT}=Ls();lt.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);lt.hasRegexChars=r=>FT.test(r);lt.isRegexChar=r=>r.length===1&<.hasRegexChars(r);lt.escapeRegex=r=>r.replace(UT,"\\$1");lt.toPosixSlashes=r=>r.replace(jT,"/");lt.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let r=navigator.platform.toLowerCase();return r==="win32"||r==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":!1};lt.removeBackslashes=r=>r.replace(qT,e=>e==="\\"?"":e);lt.escapeLast=(r,e,t)=>{let n=r.lastIndexOf(e,t);return n===-1?r:r[n-1]==="\\"?lt.escapeLast(r,e,n-1):`${r.slice(0,n)}\\${r.slice(n)}`};lt.removePrefix=(r,e={})=>{let t=r;return t.startsWith("./")&&(t=t.slice(2),e.prefix="./"),t};lt.wrapOutput=(r,e={},t={})=>{let n=t.contains?"":"^",i=t.contains?"":"$",s=`${n}(?:${r})${i}`;return e.negated===!0&&(s=`(?:^(?!${s}).*$)`),s};lt.basename=(r,{windows:e}={})=>{let t=r.split(e?/[\\/]/:"/"),n=t[t.length-1];return n===""?t[t.length-2]:n}});var x_=E((G2,A_)=>{"use strict";var __=js(),{CHAR_ASTERISK:cf,CHAR_AT:BT,CHAR_BACKWARD_SLASH:qs,CHAR_COMMA:VT,CHAR_DOT:lf,CHAR_EXCLAMATION_MARK:df,CHAR_FORWARD_SLASH:E_,CHAR_LEFT_CURLY_BRACE:uf,CHAR_LEFT_PARENTHESES:ff,CHAR_LEFT_SQUARE_BRACKET:zT,CHAR_PLUS:HT,CHAR_QUESTION_MARK:v_,CHAR_RIGHT_CURLY_BRACE:KT,CHAR_RIGHT_PARENTHESES:w_,CHAR_RIGHT_SQUARE_BRACKET:WT}=Ls(),S_=r=>r===E_||r===qs,$_=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},GT=(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,g=!1,v=!1,_=!1,w=!1,A=!1,x=0,M,S,C={value:"",depth:0,isGlob:!1},$=()=>l>=n,V=()=>c.charCodeAt(l+1),q=()=>(M=S,c.charCodeAt(++l));for(;l0&&(P=c.slice(0,u),c=c.slice(u),d-=u),oe&&m===!0&&d>0?(oe=c.slice(0,d),k=c.slice(d)):m===!0?(oe="",k=c):oe=c,oe&&oe!==""&&oe!=="/"&&oe!==c&&S_(oe.charCodeAt(oe.length-1))&&(oe=oe.slice(0,-1)),t.unescape===!0&&(k&&(k=__.removeBackslashes(k)),oe&&v===!0&&(oe=__.removeBackslashes(oe)));let F={prefix:P,input:r,start:u,base:oe,glob:k,isBrace:f,isBracket:p,isGlob:m,isExtglob:h,isGlobstar:y,negated:_,negatedExtglob:w};if(t.tokens===!0&&(F.maxDepth=0,S_(S)||o.push(C),F.tokens=o),t.parts===!0||t.tokens===!0){let Q;for(let fe=0;fe{"use strict";var Fs=Ls(),gt=js(),{MAX_LENGTH:Oa,POSIX_REGEX_SOURCE:JT,REGEX_NON_SPECIAL_CHARS:YT,REGEX_SPECIAL_CHARS_BACKREF:XT,REPLACEMENTS:k_}=Fs,QT=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch{return r.map(i=>gt.escapeRegex(i)).join("..")}return t},Si=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,P_=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},ZT=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},hf=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(ZT(e))return e.replace(/\\(.)/g,"$1")},eI=r=>{let e=r.map(hf).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}}}}},tI=r=>`${r.length===1?gt.escapeRegex(r[0]):`[${r.map(t=>gt.escapeRegex(t)).join("")}]`}*`,rI=r=>{let e=0,t=[];for(;eo.trim());if(i.length!==1)return;let s=hf(i[0]);if(!s||s.length!==1)return;t.push(s),e+=n.end+1}if(!(t.length<1))return t},nI=r=>{let e=0,t=r.trim(),n=pf(t);for(;n;)e++,t=n.body.trim(),n=pf(t);return e},iI=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Fs.DEFAULT_MAX_EXTGLOB_RECURSION,n=P_(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||eI(n)))return{risky:!0};let i=[],s=!1,o=!0;for(let a of n){let c=rI(a);if(c){s=!0,i.push(...c);continue}let l=hf(a);if(l&&l.length===1){i.push(l);continue}if(o=!1,nI(a)>t)return{risky:!0}}return s?o?{risky:!0,safeOutput:tI([...new Set(i)])}:{risky:!0}:{risky:!1}},mf=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=k_[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(Oa,t.maxLength):Oa,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=Fs.globChars(t.windows),l=Fs.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:g,QMARK:v,QMARK_NO_DOT:_,STAR:w,START_ANCHOR:A}=c,x=I=>`(${a}(?:(?!${A}${I.dot?m:u}).)*?)`,M=t.dot?"":h,S=t.dot?v:_,C=t.bash===!0?x(t):w;t.capture&&(C=`(${C})`),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=gt.removePrefix(r,$),i=r.length;let V=[],q=[],oe=[],P=s,k,F=()=>$.index===i-1,Q=$.peek=(I=1)=>r[$.index+I],fe=$.advance=()=>r[++$.index]||"",Je=()=>r.slice($.index+1),Fe=(I="",we=0)=>{$.consumed+=I,$.index+=we},Br=I=>{$.output+=I.output!=null?I.output:I.value,Fe(I.value)},F0=()=>{let I=1;for(;Q()==="!"&&(Q(2)!=="("||Q(3)==="?");)fe(),$.start++,I++;return I%2===0?!1:($.negated=!0,$.start++,!0)},Io=I=>{$[I]++,oe.push(I)},Vr=I=>{$[I]--,oe.pop()},Z=I=>{if(P.type==="globstar"){let we=$.braces>0&&(I.type==="comma"||I.type==="brace"),T=I.extglob===!0||V.length&&(I.type==="pipe"||I.type==="paren");I.type!=="slash"&&I.type!=="paren"&&!we&&!T&&($.output=$.output.slice(0,-P.output.length),P.type="star",P.value="*",P.output=C,$.output+=P.output)}if(V.length&&I.type!=="paren"&&(V[V.length-1].inner+=I.value),(I.value||I.output)&&Br(I),P&&P.type==="text"&&I.type==="text"){P.output=(P.output||P.value)+I.value,P.value+=I.value;return}I.prev=P,o.push(I),P=I},Ro=(I,we)=>{let T={...l[we],conditions:1,inner:""};T.prev=P,T.parens=$.parens,T.output=$.output,T.startIndex=$.index,T.tokensIndex=o.length;let ee=(t.capture?"(":"")+T.open;Io("parens"),Z({type:I,value:we,output:$.output?"":p}),Z({type:"paren",extglob:!0,value:fe(),output:ee}),V.push(T)},U0=I=>{let we=r.slice(I.startIndex,$.index+1),T=r.slice(I.startIndex+2,$.index),ee=iI(T,t);if((I.type==="plus"||I.type==="star")&&ee.risky){let he=ee.safeOutput?(I.output?"":p)+(t.capture?`(${ee.safeOutput})`:ee.safeOutput):void 0,er=o[I.tokensIndex];er.type="text",er.value=we,er.output=he||gt.escapeRegex(we);for(let tr=I.tokensIndex+1;tr1&&I.inner.includes("/")&&(he=x(t)),(he!==C||F()||/^\)+$/.test(Je()))&&(me=I.close=`)$))${he}`),I.inner.includes("*")&&(Ce=Je())&&/^\.[^\\/.]+$/.test(Ce)){let er=mf(Ce,{...e,fastpaths:!1}).output;me=I.close=`)${er})${he})`}I.prev.type==="bos"&&($.negatedExtglob=!0)}Z({type:"paren",extglob:!0,value:k,output:me}),Vr("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let I=!1,we=r.replace(XT,(T,ee,me,Ce,he,er)=>Ce==="\\"?(I=!0,T):Ce==="?"?ee?ee+Ce+(he?v.repeat(he.length):""):er===0?S+(he?v.repeat(he.length):""):v.repeat(me.length):Ce==="."?u.repeat(me.length):Ce==="*"?ee?ee+Ce+(he?C:""):C:ee?T:`\\${T}`);return I===!0&&(t.unescape===!0?we=we.replace(/\\/g,""):we=we.replace(/\\+/g,T=>T.length%2===0?"\\\\":T?"\\":"")),we===r&&t.contains===!0?($.output=r,$):($.output=gt.wrapOutput(we,$,e),$)}for(;!F();){if(k=fe(),k==="\0")continue;if(k==="\\"){let T=Q();if(T==="/"&&t.bash!==!0||T==="."||T===";")continue;if(!T){k+="\\",Z({type:"text",value:k});continue}let ee=/^\\+/.exec(Je()),me=0;if(ee&&ee[0].length>2&&(me=ee[0].length,$.index+=me,me%2!==0&&(k+="\\")),t.unescape===!0?k=fe():k+=fe(),$.brackets===0){Z({type:"text",value:k});continue}}if($.brackets>0&&(k!=="]"||P.value==="["||P.value==="[^")){if(t.posix!==!1&&k===":"){let T=P.value.slice(1);if(T.includes("[")&&(P.posix=!0,T.includes(":"))){let ee=P.value.lastIndexOf("["),me=P.value.slice(0,ee),Ce=P.value.slice(ee+2),he=JT[Ce];if(he){P.value=me+he,$.backtrack=!0,fe(),!s.output&&o.indexOf(P)===1&&(s.output=p);continue}}}(k==="["&&Q()!==":"||k==="-"&&Q()==="]")&&(k=`\\${k}`),k==="]"&&(P.value==="["||P.value==="[^")&&(k=`\\${k}`),t.posix===!0&&k==="!"&&P.value==="["&&(k="^"),P.value+=k,Br({value:k});continue}if($.quotes===1&&k!=='"'){k=gt.escapeRegex(k),P.value+=k,Br({value:k});continue}if(k==='"'){$.quotes=$.quotes===1?0:1,t.keepQuotes===!0&&Z({type:"text",value:k});continue}if(k==="("){Io("parens"),Z({type:"paren",value:k});continue}if(k===")"){if($.parens===0&&t.strictBrackets===!0)throw new SyntaxError(Si("opening","("));let T=V[V.length-1];if(T&&$.parens===T.parens+1){U0(V.pop());continue}Z({type:"paren",value:k,output:$.parens?")":"\\)"}),Vr("parens");continue}if(k==="["){if(t.nobracket===!0||!Je().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(Si("closing","]"));k=`\\${k}`}else Io("brackets");Z({type:"bracket",value:k});continue}if(k==="]"){if(t.nobracket===!0||P&&P.type==="bracket"&&P.value.length===1){Z({type:"text",value:k,output:`\\${k}`});continue}if($.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(Si("opening","["));Z({type:"text",value:k,output:`\\${k}`});continue}Vr("brackets");let T=P.value.slice(1);if(P.posix!==!0&&T[0]==="^"&&!T.includes("/")&&(k=`/${k}`),P.value+=k,Br({value:k}),t.literalBrackets===!1||gt.hasRegexChars(T))continue;let ee=gt.escapeRegex(P.value);if($.output=$.output.slice(0,-P.value.length),t.literalBrackets===!0){$.output+=ee,P.value=ee;continue}P.value=`(${a}${ee}|${P.value})`,$.output+=P.value;continue}if(k==="{"&&t.nobrace!==!0){Io("braces");let T={type:"brace",value:k,output:"(",outputIndex:$.output.length,tokensIndex:$.tokens.length};q.push(T),Z(T);continue}if(k==="}"){let T=q[q.length-1];if(t.nobrace===!0||!T){Z({type:"text",value:k,output:k});continue}let ee=")";if(T.dots===!0){let me=o.slice(),Ce=[];for(let he=me.length-1;he>=0&&(o.pop(),me[he].type!=="brace");he--)me[he].type!=="dots"&&Ce.unshift(me[he].value);ee=QT(Ce,t),$.backtrack=!0}if(T.comma!==!0&&T.dots!==!0){let me=$.output.slice(0,T.outputIndex),Ce=$.tokens.slice(T.tokensIndex);T.value=T.output="\\{",k=ee="\\}",$.output=me;for(let he of Ce)$.output+=he.output||he.value}Z({type:"brace",value:k,output:ee}),Vr("braces"),q.pop();continue}if(k==="|"){V.length>0&&V[V.length-1].conditions++,Z({type:"text",value:k});continue}if(k===","){let T=k,ee=q[q.length-1];ee&&oe[oe.length-1]==="braces"&&(ee.comma=!0,T="|"),Z({type:"comma",value:k,output:T});continue}if(k==="/"){if(P.type==="dot"&&$.index===$.start+1){$.start=$.index+1,$.consumed="",$.output="",o.pop(),P=s;continue}Z({type:"slash",value:k,output:f});continue}if(k==="."){if($.braces>0&&P.type==="dot"){P.value==="."&&(P.output=u);let T=q[q.length-1];P.type="dots",P.output+=k,P.value+=k,T.dots=!0;continue}if($.braces+$.parens===0&&P.type!=="bos"&&P.type!=="slash"){Z({type:"text",value:k,output:u});continue}Z({type:"dot",value:k,output:u});continue}if(k==="?"){if(!(P&&P.value==="(")&&t.noextglob!==!0&&Q()==="("&&Q(2)!=="?"){Ro("qmark",k);continue}if(P&&P.type==="paren"){let ee=Q(),me=k;(P.value==="("&&!/[!=<:]/.test(ee)||ee==="<"&&!/<([!=]|\w+>)/.test(Je()))&&(me=`\\${k}`),Z({type:"text",value:k,output:me});continue}if(t.dot!==!0&&(P.type==="slash"||P.type==="bos")){Z({type:"qmark",value:k,output:_});continue}Z({type:"qmark",value:k,output:v});continue}if(k==="!"){if(t.noextglob!==!0&&Q()==="("&&(Q(2)!=="?"||!/[!=<:]/.test(Q(3)))){Ro("negate",k);continue}if(t.nonegate!==!0&&$.index===0){F0();continue}}if(k==="+"){if(t.noextglob!==!0&&Q()==="("&&Q(2)!=="?"){Ro("plus",k);continue}if(P&&P.value==="("||t.regex===!1){Z({type:"plus",value:k,output:d});continue}if(P&&(P.type==="bracket"||P.type==="paren"||P.type==="brace")||$.parens>0){Z({type:"plus",value:k});continue}Z({type:"plus",value:d});continue}if(k==="@"){if(t.noextglob!==!0&&Q()==="("&&Q(2)!=="?"){Z({type:"at",extglob:!0,value:k,output:""});continue}Z({type:"text",value:k});continue}if(k!=="*"){(k==="$"||k==="^")&&(k=`\\${k}`);let T=YT.exec(Je());T&&(k+=T[0],$.index+=T[0].length),Z({type:"text",value:k});continue}if(P&&(P.type==="globstar"||P.star===!0)){P.type="star",P.star=!0,P.value+=k,P.output=C,$.backtrack=!0,$.globstar=!0,Fe(k);continue}let I=Je();if(t.noextglob!==!0&&/^\([^?]/.test(I)){Ro("star",k);continue}if(P.type==="star"){if(t.noglobstar===!0){Fe(k);continue}let T=P.prev,ee=T.prev,me=T.type==="slash"||T.type==="bos",Ce=ee&&(ee.type==="star"||ee.type==="globstar");if(t.bash===!0&&(!me||I[0]&&I[0]!=="/")){Z({type:"star",value:k,output:""});continue}let he=$.braces>0&&(T.type==="comma"||T.type==="brace"),er=V.length&&(T.type==="pipe"||T.type==="paren");if(!me&&T.type!=="paren"&&!he&&!er){Z({type:"star",value:k,output:""});continue}for(;I.slice(0,3)==="/**";){let tr=r[$.index+4];if(tr&&tr!=="/")break;I=I.slice(3),Fe("/**",3)}if(T.type==="bos"&&F()){P.type="globstar",P.value+=k,P.output=x(t),$.output=P.output,$.globstar=!0,Fe(k);continue}if(T.type==="slash"&&T.prev.type!=="bos"&&!Ce&&F()){$.output=$.output.slice(0,-(T.output+P.output).length),T.output=`(?:${T.output}`,P.type="globstar",P.output=x(t)+(t.strictSlashes?")":"|$)"),P.value+=k,$.globstar=!0,$.output+=T.output+P.output,Fe(k);continue}if(T.type==="slash"&&T.prev.type!=="bos"&&I[0]==="/"){let tr=I[1]!==void 0?"|$":"";$.output=$.output.slice(0,-(T.output+P.output).length),T.output=`(?:${T.output}`,P.type="globstar",P.output=`${x(t)}${f}|${f}${tr})`,P.value+=k,$.output+=T.output+P.output,$.globstar=!0,Fe(k+fe()),Z({type:"slash",value:"/",output:""});continue}if(T.type==="bos"&&I[0]==="/"){P.type="globstar",P.value+=k,P.output=`(?:^|${f}|${x(t)}${f})`,$.output=P.output,$.globstar=!0,Fe(k+fe()),Z({type:"slash",value:"/",output:""});continue}$.output=$.output.slice(0,-P.output.length),P.type="globstar",P.output=x(t),P.value+=k,$.output+=P.output,$.globstar=!0,Fe(k);continue}let we={type:"star",value:k,output:C};if(t.bash===!0){we.output=".*?",(P.type==="bos"||P.type==="slash")&&(we.output=M+we.output),Z(we);continue}if(P&&(P.type==="bracket"||P.type==="paren")&&t.regex===!0){we.output=k,Z(we);continue}($.index===$.start||P.type==="slash"||P.type==="dot")&&(P.type==="dot"?($.output+=y,P.output+=y):t.dot===!0?($.output+=g,P.output+=g):($.output+=M,P.output+=M),Q()!=="*"&&($.output+=p,P.output+=p)),Z(we)}for(;$.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(Si("closing","]"));$.output=gt.escapeLast($.output,"["),Vr("brackets")}for(;$.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(Si("closing",")"));$.output=gt.escapeLast($.output,"("),Vr("parens")}for(;$.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(Si("closing","}"));$.output=gt.escapeLast($.output,"{"),Vr("braces")}if(t.strictSlashes!==!0&&(P.type==="star"||P.type==="bracket")&&Z({type:"maybe_slash",value:"",output:`${f}?`}),$.backtrack===!0){$.output="";for(let I of $.tokens)$.output+=I.output!=null?I.output:I.value,I.suffix&&($.output+=I.suffix)}return $};mf.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(Oa,t.maxLength):Oa,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=k_[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}=Fs.globChars(t.windows),m=t.dot?u:l,h=t.dot?d:l,y=t.capture?"":"?:",g={negated:!1,prefix:""},v=t.bash===!0?".*?":f;t.capture&&(v=`(${v})`);let _=M=>M.noglobstar===!0?v:`(${y}(?:(?!${p}${M.dot?c:s}).)*?)`,w=M=>{switch(M){case"*":return`${m}${a}${v}`;case".*":return`${s}${a}${v}`;case"*.*":return`${m}${v}${s}${a}${v}`;case"*/*":return`${m}${v}${o}${a}${h}${v}`;case"**":return m+_(t);case"**/*":return`(?:${m}${_(t)}${o})?${h}${a}${v}`;case"**/*.*":return`(?:${m}${_(t)}${o})?${h}${v}${s}${a}${v}`;case"**/.*":return`(?:${m}${_(t)}${o})?${s}${a}${v}`;default:{let S=/^(.*?)\.(\w+)$/.exec(M);if(!S)return;let C=w(S[1]);return C?C+s+S[2]:void 0}}},A=gt.removePrefix(r,g),x=w(A);return x&&t.strictSlashes!==!0&&(x+=`${o}?`),x};C_.exports=mf});var R_=E((Y2,I_)=>{"use strict";var sI=x_(),yf=M_(),T_=js(),oI=Ls(),aI=r=>r&&typeof r=="object"&&!Array.isArray(r),xe=(r,e,t=!1)=>{if(Array.isArray(r)){let u=r.map(f=>xe(f,e,t));return f=>{for(let p of u){let m=p(f);if(m)return m}return!1}}let n=aI(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?xe.compileRe(r,e):xe.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=xe(i.ignore,u,t)}let l=(u,d=!1)=>{let{isMatch:f,match:p,output:m}=xe.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};xe.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?T_.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=xe.matchBase(r,e,t,i):a=e.exec(c)),{isMatch:!!a,match:a,output:c}};xe.matchBase=(r,e,t,n=t&&t.windows)=>(e instanceof RegExp?e:xe.makeRe(e,t)).test(T_.basename(r,{windows:n}));xe.isMatch=(r,e,t)=>xe(e,t)(r);xe.parse=(r,e)=>Array.isArray(r)?r.map(t=>xe.parse(t,e)):yf(r,{...e,fastpaths:!1});xe.scan=(r,e)=>sI(r,e);xe.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=xe.toRegex(a,e);return n===!0&&(c.state=r),c};xe.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=yf.fastpaths(r,e)),i.output||(i=yf(r,e)),xe.compileRe(i,e,t,n)};xe.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/$^/}};xe.constants=oI;I_.exports=xe});var gf=E((X2,D_)=>{"use strict";var O_=R_(),cI=js();function N_(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:cI.isWindows()}),O_(r,e,t)}Object.assign(N_,O_);D_.exports=N_});var WN={};W0(WN,{default:()=>pl});module.exports=G0(WN);var O=require("obsidian");var R=class extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="InteropError"}toPortableError(e){return{code:this.code,message:this.message,...this.details===void 0?{}:{details:this.details},...e===void 0?{}:{retryable:e}}}},Zi=class extends Error{status;error;constructor(e,t){super(t.message),this.status=e,this.error=t,this.name="ActionHandlerError"}};var fg=vn(wu(),1),pg=vn(Tu(),1);var Iu={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 u1=pg.default;function hg(){return Object.fromEntries(Object.entries(Iu).map(([r,e])=>[r,structuredClone(e)]))}function Ru(){let r=new fg.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});u1(r);let e=hg();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(Iu[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function Zr(r){return(r??[]).map(e=>`${e.instancePath||"/"} ${e.message??e.keyword}`).join("; ")}function ar(r,e){if(!("value"in r))throw new R("contract_digest_conflict",`${e} must be resolved to an inline JSON Schema before runtime registration.`);return structuredClone(r.value)}function mg(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=ar(r.record_schema,"record_schema"),r.binding_schema&&(e.binding_schema=ar(r.binding_schema,"binding_schema"));break;case"event":e.data_schema=ar(r.data_schema,"data_schema"),r.source_schema&&(e.source_schema=ar(r.source_schema,"source_schema"));break;case"action":e.input_schema=ar(r.input_schema,"input_schema"),r.output_schema&&(e.output_schema=ar(r.output_schema,"output_schema")),r.error_schema&&(e.error_schema=ar(r.error_schema,"error_schema")),r.provider_schema&&(e.provider_schema=ar(r.provider_schema,"provider_schema")),r.behavior&&(e.behavior=structuredClone(r.behavior));break}return e}async function ga(r){return _i(mg(r))}async function _i(r){return`sha256:${await f1(Ou(r))}`}function yg(r,e){return{data:bi(r,e.data_schema,`${e.id} data_schema`),...e.source_schema?{source:bi(r,e.source_schema,`${e.id} source_schema`)}:{}}}function gg(r,e){return{input:bi(r,e.input_schema,`${e.id} input_schema`),...e.output_schema?{output:bi(r,e.output_schema,`${e.id} output_schema`)}:{},...e.error_schema?{error:bi(r,e.error_schema,`${e.id} error_schema`)}:{},...e.provider_schema?{provider:bi(r,e.provider_schema,`${e.id} provider_schema`)}:{}}}function ba(r,e,t,n){if(!(!r||r(e)))throw new R(t,`${n} failed JSON Schema validation: ${Zr(r.errors)}`)}function bi(r,e,t){try{return r.compile(ar(e,t))}catch(n){throw new R("contract_digest_conflict",`${t} could not be compiled: ${n instanceof Error?n.message:String(n)}`)}}function Ou(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(Ou).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${Ou(n)}`).join(",")}}`}async function f1(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 Ar=vn(c_(),1);var tf={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},vT=new Set(["specversion","id","source","type","time","subject","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion","mdbaseinstanceid","correlationid","causationid"]),Ds=class{options;profileVersion="0.1";transport;ajv=Ru();contractValidator=$r(this.ajv,"contract");eventValidator=$r(this.ajv,"event");actionRequestValidator=$r(this.ajv,"actionRequest");actionInvocationValidator=$r(this.ajv,"actionInvocation");actionOutcomeValidator=$r(this.ajv,"actionOutcome");eventSourceDeclarationValidator=$r(this.ajv,"eventSourceDeclaration");actionProviderDeclarationValidator=$r(this.ajv,"actionProviderDeclaration");contracts=new Map;clients=new Map;eventSources=new Map;actionProviders=new Map;subscriptions=new Map;activeActions=new Map;completedActions=new Map;admissionLocks=new Map;recentEvents=new Map;authorize;now;idFactory;recentEventLimit;completedRequestLimit;nextSequence=0;disposed=!1;constructor(e={}){this.options=e,this.authorize=e.authorize??(()=>!1),this.now=e.now??(()=>new Date),this.idFactory=e.idFactory??(t=>{this.nextSequence+=1;let n=typeof globalThis.crypto?.randomUUID=="function"?globalThis.crypto.randomUUID():`${this.now().getTime().toString(36)}-${this.nextSequence.toString(36)}`;return`${t}_${n}`}),this.recentEventLimit=Math.max(1,e.recentEventLimit??1e3),this.completedRequestLimit=Math.max(1,e.completedRequestLimit??1e3),this.transport={...tf,...structuredClone(e.transport??{}),delivery:[...e.transport?.delivery??tf.delivery],ordering:[...e.transport?.ordering??tf.ordering]}}connect(e){this.assertActive(),wT(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){let n=this.requireClient(e);if(t.contracts.length===0)throw new R("request_rejected","An event-source declaration must include a contract.");let i=`${e}:${t.declaration_id}`;if(this.eventSources.has(i))throw new R("request_rejected",`Event-source declaration ${t.declaration_id} is already registered.`);let s=new Map;for(let l of t.contracts){let u=await this.prepareEventContract(l.contract),d=l_(l.requirement,u.reference);if(d_(d,u.reference),await this.assertAuthorized({operation:"register_event_source",principal:n.identity,contract:u.reference}),u.sourceValidator&&!u.sourceValidator(l.binding??{}))throw new R("request_rejected",`${u.reference.id} source binding is invalid: ${Zr(u.sourceValidator.errors)}`);let f=Ta(u.reference);if(s.has(f))throw new R("contract_digest_conflict",`Event contract ${f} is repeated by one declaration.`);s.set(f,{contract:u,requirement:d,...l.binding===void 0?{}:{binding:structuredClone(l.binding)},...l.ordering===void 0?{}:{ordering:[...l.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:l,requirement:u,binding:d,ordering:f})=>({requirement:structuredClone(u),resolved:structuredClone(l.reference),...d===void 0?{}:{binding:d},...f===void 0?{}:{ordering:f}}))},a={...o,declaration_digest:await _i(o)};tn(this.eventSourceDeclarationValidator,a,"request_rejected","Event-source declaration"),this.commitContracts([...s.values()].map(({contract:l})=>l)),this.eventSources.set(i,{id:i,clientId:e,declaration:structuredClone(a),contracts:new Map([...s.entries()].map(([l,u])=>[l,{contract:u.contract,...u.binding===void 0?{}:{binding:u.binding}}]))}),n.sources.add(i);let c=!0;return{declaration:structuredClone(a),dispose:()=>{c&&(c=!1,this.removeEventSource(i))}}}async publishEvent(e,t){let n=this.requireClient(e),i=Ta(t.contract),s=[...n.sources].map(m=>this.eventSources.get(m)).find(m=>m?.contracts.has(i));if(!s)throw new R("unknown_contract",`This client has not registered event contract ${t.contract.id} ${t.contract.version}.`);let o=s.contracts.get(i)?.contract;if(!o)throw new R("unknown_contract",`Event contract ${i} is unavailable.`);if(t.contract.digest&&t.contract.digest!==o.reference.digest)throw new R("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}}),rf(t.data,"invalid_event_data",`Event ${o.reference.id} data`),ba(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=t.extensions??{};for(let m of Object.keys(a))if(vT.has(m))throw new R("request_rejected",`Event extension ${m} is reserved.`);let c={...structuredClone(a),specversion:"1.0",id:t.id??this.idFactory("evt"),source:ST(n.identity),type:o.reference.id,time:t.time??this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:p_(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}};tn(this.eventValidator,c,"invalid_event_data","Event envelope"),nf(this.transport,c),$T(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 R("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)),f_(this.recentEvents,this.recentEventLimit);let d=[...this.subscriptions.values()].filter(({subscription:m})=>Ia(m.contract,o.reference)),f=await Promise.allSettled(d.map(async m=>await this.isAuthorized({operation:"subscribe_event",principal:m.principal,contract:o.reference,...c.subject===void 0?{}:{subject:c.subject}})?(await m.handler(structuredClone(c)),!0):!1)),p=0;for(let m of f)m.status==="fulfilled"&&m.value?p+=1:m.status==="rejected"&&this.report({severity:"error",code:"event_consumer_failed",message:`An event consumer failed while handling ${c.type}.`,contract:o.reference,cause:m.reason});return{event:structuredClone(c),deliveries:p,duplicate:!1}}async subscribeEvents(e,t,n){let i=this.requireClient(e);sf(t.contract),xT(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){let n=this.requireClient(e);if(t.handlers.length===0)throw new R("request_rejected","An action-provider declaration must include a handler.");let i=`${e}:${t.declaration_id}`;if(this.actionProviders.has(i))throw new R("request_rejected",`Action-provider declaration ${t.declaration_id} is already registered.`);let s=[],o=new Set;for(let d of t.handlers){if(o.has(d.handler_id))throw new R("request_rejected",`Handler ${d.handler_id} is repeated.`);o.add(d.handler_id);let f=await this.prepareActionContract(d.contract),p=l_(d.requirement,f.reference);if(d_(p,f.reference),await this.assertAuthorized({operation:"register_action_provider",principal:n.identity,contract:f.reference,provider:n.identity}),f.providerValidator&&!f.providerValidator(d.binding??{}))throw new R("request_rejected",`${f.reference.id} provider binding is invalid: ${Zr(f.providerValidator.errors)}`);let m=d.contract.behavior?.idempotency??"none";if(d.idempotency?.mode==="request"&&m==="none")throw new R("request_rejected",`${f.reference.id} does not permit request deduplication.`);if(m==="required"&&d.idempotency?.mode!=="request")throw new R("request_rejected",`${f.reference.id} requires a provider with request deduplication.`);let h=d.contract.behavior?.cancellation??"none";if(d.cancellation==="cooperative"&&h!=="cooperative")throw new R("request_rejected",`${f.reference.id} does not declare cooperative cancellation.`);s.push({contract:f,declaration:{handler_id:d.handler_id,requirement:p,resolved:structuredClone(f.reference),...d.binding===void 0?{}:{binding:structuredClone(d.binding)},...d.idempotency===void 0?{}:{idempotency:structuredClone(d.idempotency)},...d.cancellation===void 0?{}:{cancellation:d.cancellation},...d.max_concurrency===void 0?{}:{max_concurrency:d.max_concurrency}},handler:d.handler})}let a={kind:"mdbase.action-provider",profile_version:"0.1",declaration_id:t.declaration_id,provider:structuredClone(n.identity),handlers:s.map(({declaration:d})=>structuredClone(d))},c={...a,declaration_digest:await _i(a)};tn(this.actionProviderDeclarationValidator,c,"request_rejected","Action-provider declaration"),this.commitContracts(s.map(({contract:d})=>d));let l=s.map(({contract:d,declaration:f,handler:p})=>({registrationId:i,clientId:e,declaration:structuredClone(c),handlerDeclaration:structuredClone(f),contract:d,handler:p,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){let n=this.requireClient(e);sf(t.contract);let i=t.request_id??this.idFactory("req");this.cleanCompletedActions(),rf(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:t.created_at??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)};tn(this.actionRequestValidator,s,"request_rejected","Action request"),nf(this.transport,s);let o=await this.acquireAdmission(i);try{let a=await _i(ET(s)),c=this.activeActions.get(i);if(c){if(u_(e,i,a,c),c.handler.handlerDeclaration.idempotency?.mode!=="request")throw new R("request_rejected",`Action request ${i} is already active without deduplication.`);return structuredClone(await c.promise)}let l=this.completedActions.get(i);if(l){if(u_(e,i,a,l),!l.reusable)throw new R("request_rejected",`Action request ${i} was already completed without deduplication.`);return structuredClone(l.outcome)}if(s.deadline&&new Date(s.deadline).getTime()<=this.now().getTime())throw new R("deadline_exceeded",`Action request ${i} passed its deadline before admission.`);if(s.deadline&&!this.transport.deadlines)throw new R("unsupported_transport_capability","The active transport cannot enforce action deadlines.");let u=this.resolveActionCandidates(s.contract,s.requested_provider);u.length===0&&this.throwResolutionFailure(s.contract,s.requested_provider);let d=[];for(let x of u)await this.isAuthorized({operation:"invoke_action",principal:n.identity,contract:x.contract.reference,provider:x.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}})&&d.push(x);if(d.length===0)throw new R("unauthorized",`No authorized provider can execute ${s.contract.id}.`);if(d.length>1)throw new R("ambiguous_provider",`Action ${s.contract.id} has ${d.length} eligible providers; select one explicitly.`);let f=d[0];if(f.handlerDeclaration.max_concurrency!==void 0&&f.active>=f.handlerDeclaration.max_concurrency)throw new R("request_rejected",`Provider ${f.declaration.provider.implementation} is at capacity.`);if((f.contract.artifact.behavior?.idempotency??"none")==="required"&&!s.idempotency_key)throw new R("request_rejected",`${f.contract.reference.id} requires an idempotency key.`);ba(f.contract.inputValidator,s.input,"invalid_action_input",`Action ${f.contract.reference.id} input`);let m={operation:"invoke_action",principal:n.identity,contract:f.contract.reference,provider:f.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}},h=await this.options.authorizationContext?.(m),y={kind:"mdbase.action.invocation",profile_version:"0.1",invocation_id:this.idFactory("inv"),attempt_id:this.idFactory("attempt"),request_id:i,contract:structuredClone(f.contract.reference),caller:structuredClone(n.identity),provider:structuredClone(f.declaration.provider),provider_declaration_digest:f.declaration.declaration_digest,handler_id:f.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},...h===void 0?{}:{authorization_context:h},input:structuredClone(s.input)};tn(this.actionInvocationValidator,y,"request_rejected","Action invocation"),await this.options.onInvocation?.(structuredClone(y));let g=new AbortController,v;if(y.deadline){let x=Math.max(0,new Date(y.deadline).getTime()-this.now().getTime());v=setTimeout(()=>g.abort(new R("deadline_exceeded",`Action request ${i} exceeded its deadline.`)),x)}f.active+=1;let _=this.executeAction(f,y,g).finally(()=>{v!==void 0&&clearTimeout(v),f.active=Math.max(0,f.active-1),this.activeActions.delete(i)});this.activeActions.set(i,{clientId:e,requestId:i,requestDigest:a,handler:f,invocation:y,controller:g,promise:_}),o();let w=await _,A=f.handlerDeclaration.idempotency?.retention_seconds??300;return this.completedActions.set(i,{clientId:e,requestDigest:a,outcome:structuredClone(w),reusable:f.handlerDeclaration.idempotency?.mode==="request",expiresAt:this.now().getTime()+A*1e3}),f_(this.completedActions,this.completedRequestLimit),structuredClone(w)}finally{o()}}async executeAction(e,t,n){try{let i=await e.handler(structuredClone(t.input),{invocation:structuredClone(t),signal:n.signal});if(n.signal.aborted){let o=n.signal.reason;return o instanceof R&&o.code==="deadline_exceeded"?this.failureOutcome(t,"failed",o.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}rf(i,"invalid_action_output",`Action ${e.contract.reference.id} output`),ba(e.contract.outputValidator,i,"invalid_action_output",`Action ${e.contract.reference.id} output`);let s={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 tn(this.actionOutcomeValidator,s,"invalid_action_output","Action outcome"),nf(this.transport,s),s}catch(i){if(i instanceof Zi)return e.contract.errorValidator&&!e.contract.errorValidator(i.error.details??{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${Zr(e.contract.errorValidator.errors)}`}):this.failureOutcome(t,i.status,i.error);if(i instanceof R)return this.failureOutcome(t,i.code==="cancelled"?"cancelled":i.code==="outcome_indeterminate"?"outcome_indeterminate":"failed",i.toPortableError());if(n.signal.aborted||kT(i)){let s=n.signal.reason;return s instanceof R&&s.code==="deadline_exceeded"?this.failureOutcome(t,"failed",s.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 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 tn(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 R("unauthorized",`Action request ${t} belongs to another caller.`);return a?structuredClone(a.outcome):null}if(o.clientId!==e)throw new R("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 R("unsupported_transport_capability","The active transport cannot deliver cancellation.");if(o.handler.handlerDeclaration.cancellation!=="cooperative")throw new R("cancellation_unsupported",`Provider ${o.invocation.provider.implementation} does not support cancellation.`);return o.controller.abort(new R("cancelled",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})=>Ia(e,s.reference)&&AT(t,o.provider)),i=(0,Ar.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)=>s.declaration.provider.application.localeCompare(o.declaration.provider.application)||s.declaration.provider.implementation.localeCompare(o.declaration.provider.implementation)||(s.declaration.provider.instance_id??"").localeCompare(o.declaration.provider.instance_id??"")||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 R("unknown_contract",`Action contract ${e.id} is unknown.`):n.some(({reference:i})=>Ia(e,i))?t?new R("requested_provider_unavailable",`The requested provider is unavailable for ${e.id}.`):new R("no_provider",`No provider is registered for ${e.id}.`):new R("unsupported_contract_version",`No ${e.id} artifact satisfies ${e.version}.`)}async prepareEventContract(e){if(this.assertContractArtifact(e),e.contract_type!=="event")throw new R("unknown_contract",`${e.id} is not an event contract.`);let t={id:e.id,version:e.version,digest:await ga(e)};this.assertNoContractConflict(t);let n=yg(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 R("unknown_contract",`${e.id} is not an action contract.`);let t={id:e.id,version:e.version,digest:await ga(e)};this.assertNoContractConflict(t);let n=gg(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(tn(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,Ar.valid)(e.version))throw new R("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(Ta(e));if(t&&t.reference.digest!==e.digest)throw new R("contract_digest_conflict",`Contract ${e.id} ${e.version} conflicts with the registered artifact.`)}commitContracts(e){let t=new Map;for(let n of e){let i=Ta(n.reference),s=t.get(i)??this.contracts.get(i);if(s&&s.reference.digest!==n.reference.digest)throw new R("contract_digest_conflict",`Contract ${n.reference.id} ${n.reference.version} conflicts within the registration.`);t.set(i,n)}for(let[n,i]of t)this.contracts.has(n)||this.contracts.set(n,i)}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 R("cancelled","The caller unloaded.")),i.handler.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new R("cancelled","The provider unloaded."));this.clients.delete(e),t||this.assertActive()}}removeEventSource(e){let t=this.eventSources.get(e);t&&(this.eventSources.delete(e),this.clients.get(t.clientId)?.sources.delete(e))}removeActionProvider(e){let t=this.actionProviders.get(e);if(t){this.actionProviders.delete(e),this.clients.get(t.clientId)?.providers.delete(e);for(let n of this.activeActions.values())n.handler.registrationId===e&&n.handler.handlerDeclaration.cancellation==="cooperative"&&n.controller.abort(new R("cancelled","The provider unloaded."))}}removeSubscription(e){let t=this.subscriptions.get(e);t&&(this.subscriptions.delete(e),this.clients.get(t.clientId)?.subscriptions.delete(e))}requireClient(e){this.assertActive();let t=this.clients.get(e);if(!t||t.disposed)throw new R("transport_unavailable","Interop client is disposed.");return t}assertActive(){if(this.disposed)throw new R("transport_unavailable","Interop bridge is disposed.")}async assertAuthorized(e){if(!await this.isAuthorized(e))throw new R("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){let t=this.admissionLocks.get(e)??Promise.resolve(),n,i=new Promise(a=>{n=a}),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){this.options.onDiagnostic?.(structuredClone(e))}};function tn(r,e,t,n){if(!r(e))throw new R(t,`${n} is invalid: ${Zr(r.errors)}`)}function wT(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 R("request_rejected",`Implementation identity ${e} is invalid.`);if(!(0,Ar.valid)(r.version))throw new R("request_rejected","Implementation identity version must be exact SemVer.")}function sf(r){if(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(r.id))throw new R("unknown_contract",`Contract ID ${r.id} is invalid.`);if(!(0,Ar.validRange)(r.version,{includePrerelease:!0}))throw new R("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 R("contract_digest_conflict","Contract digest is invalid.")}function l_(r,e){let t=r??{id:e.id,version:e.version,digest:e.digest};return sf(t),structuredClone(t)}function d_(r,e){if(!Ia(r,e))throw new R("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function Ia(r,e){return r.id===e.id&&(0,Ar.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function Ta(r){return`${r.id}@${r.version}`}function p_(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function ST(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function $T(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==p_(e))throw new R("contract_digest_conflict","Event contract evidence is inconsistent.")}function ET(r){let{created_at:e,...t}=r;return t}function u_(r,e,t,n){if(n.clientId!==r)throw new R("unauthorized",`Action request ${e} belongs to another caller.`);if(n.requestDigest!==t)throw new R("request_rejected",`Action request ${e} was reused with different content.`)}function rf(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 R(e,`${t}${o} must be a finite JSON number.`)}if(typeof s!="object")throw new R(e,`${t}${o} is not a JSON value.`);if(n.has(s))throw new R(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 R(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 nf(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 R("unsupported_transport_capability",`The portable envelope is ${n} bytes; the active transport allows ${r.max_payload_bytes}.`)}function AT(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 xT(r,e){if(e){if(e.delivery?.some(t=>!r.delivery.includes(t)))throw new R("unsupported_transport_capability","The active transport lacks a required delivery capability.");if(e.ordering?.some(t=>!r.ordering.includes(t)))throw new R("unsupported_transport_capability","The active transport lacks a required ordering capability.");for(let t of["cancellation","deadlines","provider_discovery","request_deduplication","cross_process_identity"])if(e[t]===!0&&r[t]!==!0)throw new R("unsupported_transport_capability",`The active transport lacks ${t}.`);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 kT(r){return r instanceof Error&&r.name==="AbortError"}var Ra=class{constructor(e,t){this.app=e;this.profileVersion="0.1";this.bridge=new Ds({authorize:()=>t(),transport:{delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},onDiagnostic:n=>{(n.severity==="error"?console.error:console.warn)(`[mdbase/interop] ${n.code}: ${n.message}`,n.cause??"")}}),this.transport=this.bridge.describe().transport}connect(e){let t=e.manifest?.id,n=e.manifest?.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 de=require("obsidian"),q_=vn(wu(),1),F_=vn(Tu(),1),wf=vn(gf(),1),La=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},Rt={spec_version:"0.3.0",name:"My mdbase collection",description:"Typed markdown collection",settings:{types_folder:"_types",contracts_folder:"_contracts",explicit_type_keys:["type","types"],default_strict:!1,include_subfolders:!0,exclude:["_types",".obsidian",".git","node_modules",".trash",".mdbase"]}},Us=null;function lI(){return Us||(Us=new q_.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,F_.default)(Us),Us)}function G(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function ze(r){return JSON.parse(JSON.stringify(r))}function dI(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function bf(r){return Array.isArray(r)?`[${r.map(e=>bf(e)).join(",")}]`:G(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${bf(r[t])}`).join(",")}}`:JSON.stringify(r)}function uI(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 fI(r){let e=new Map,t=new Set,n=i=>{let s=e.get(i);if(s)return s;let o=r.get(i);if(!o)return null;if(t.has(i)){let l={...o,fields:ze(o.fields)};return e.set(i,l),l}t.add(i);let a=o.extends?n(o.extends):null;t.delete(i);let c={...o,fields:a?{...ze(a.fields),...ze(o.fields)}:ze(o.fields),display_name_key:o.display_name_key??a?.display_name_key,path_pattern:o.path_pattern??a?.path_pattern,filename_pattern:o.filename_pattern??a?.filename_pattern,strict:o.strict!==void 0?o.strict:a?.strict,match:o.match??a?.match};return e.set(i,c),c};for(let i of r.keys())n(i);return e}function U_(r){let e=(0,de.normalizePath)(r),t=e.lastIndexOf("/");return t>=0?e.slice(0,t):""}function B_(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 V_(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function z_(r,e,t){let n=B_(t);if(!n||V_(n))return null;let i=new Set,s=(0,de.normalizePath)(n);i.add(s),s.endsWith(".md")||i.add(`${s}.md`);let o=U_(e);if(o){let c=(0,de.normalizePath)(`${o}/${n}`);i.add(c),c.endsWith(".md")||i.add(`${c}.md`)}for(let c of i){let l=r.getAbstractFileByPath(c);if(l instanceof de.TFile)return l}let a=n.replace(/\.md$/i,"");return r.getMarkdownFiles().find(c=>c.basename===a)??null}function pI(r,e,t){return V_(B_(t))||z_(r,e,t)!==null}function dt(r){let e=(0,de.getFrontMatterInfo)(r);if(!e.exists)return{hasFrontmatter:!1,frontmatter:{},body:r};try{let t=e.frontmatter,n=(0,de.parseYaml)(t);return n==null&&t.trim()!==""?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:"Frontmatter must be a YAML object"}:n!=null&&!G(n)?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:"Frontmatter must be a YAML object"}:{hasFrontmatter:!0,frontmatter:n??{},body:r.slice(e.contentStart)}}catch(t){return{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:t instanceof Error?t.message:String(t)}}}function bt(r,e=""){if(Object.keys(r).length===0)return e;let t=(0,de.stringifyYaml)(r).trimEnd(),n=e.replace(/^\n+/,"");return`--- + deps: ${t}}`};var dk={keyword:"dependencies",type:"object",schemaType:"object",error:cr.error,code(r){let[e,t]=uk(r);$y(r,e),Ey(r,t)}};function uk({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 $y(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,Jd._)`${c} && (${(0,Ds.checkMissingProp)(r,a,s)})`),(0,Ds.reportMissingProp)(r,s),t.else())}}cr.validatePropertyDeps=$y;function Ey(r,e=r.schema){let{gen:t,data:n,keyword:i,it:s}=r,o=t.name("valid");for(let a in e)(0,lk.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))}cr.validateSchemaDeps=Ey;cr.default=dk});var Ay=E(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var xy=B(),fk=X(),pk={message:"property name must be valid",params:({params:r})=>(0,xy._)`{propertyName: ${r.propertyName}}`},hk={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:pk,code(r){let{gen:e,schema:t,data:n,it:i}=r;if((0,fk.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,xy.not)(s),()=>{r.error(!0),i.allErrors||e.break()})}),r.ok(s)}};Yd.default=hk});var Qd=E(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var va=Ct(),Ut=B(),mk=Pt(),_a=X(),yk={message:"must NOT have additional properties",params:({params:r})=>(0,Ut._)`{additionalProperty: ${r.additionalProperty}}`},gk={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:yk,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,_a.alwaysValidSchema)(o,t))return;let l=(0,va.allSchemaProperties)(n.properties),u=(0,va.allSchemaProperties)(n.patternProperties);d(),r.ok((0,Ut._)`${s} === ${mk.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 g;if(l.length>8){let _=(0,_a.schemaRefOrVal)(o,n.properties,"properties");g=(0,va.isOwnProperty)(e,_,y)}else l.length?g=(0,Ut.or)(...l.map(_=>(0,Ut._)`${y} === ${_}`)):g=Ut.nil;return u.length&&(g=(0,Ut.or)(g,...u.map(_=>(0,Ut._)`${(0,va.usePattern)(r,_)}.test(${y})`))),(0,Ut.not)(g)}function p(y){e.code((0,Ut._)`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,_a.alwaysValidSchema)(o,t)){let g=e.name("valid");c.removeAdditional==="failing"?(h(y,g,!1),e.if((0,Ut.not)(g),()=>{r.reset(),p(y)})):(h(y,g),a||e.if((0,Ut.not)(g),()=>e.break()))}}function h(y,g,_){let v={keyword:"additionalProperties",dataProp:y,dataPropType:_a.Type.Str};_===!1&&Object.assign(v,{compositeRule:!0,createErrors:!1,allErrors:!1}),r.subschema(v,g)}}};Xd.default=gk});var Cy=E(eu=>{"use strict";Object.defineProperty(eu,"__esModule",{value:!0});var bk=mi(),ky=Ct(),Zd=X(),Py=Qd(),vk={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&&Py.default.code(new bk.KeywordCxt(s,Py.default,"additionalProperties"));let o=(0,ky.allSchemaProperties)(t);for(let d of o)s.definedProperties.add(d);s.opts.unevaluated&&o.length&&s.props!==!0&&(s.props=Zd.mergeEvaluated.props(e,(0,Zd.toHash)(o),s.props));let a=o.filter(d=>!(0,Zd.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,ky.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)}}};eu.default=vk});var Ry=E(tu=>{"use strict";Object.defineProperty(tu,"__esModule",{value:!0});var My=Ct(),wa=B(),Iy=X(),Ty=X(),_k={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,My.allSchemaProperties)(t),c=a.filter(h=>(0,Iy.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 wa.Name)&&(s.props=(0,Ty.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,Iy.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,wa._)`${(0,My.usePattern)(r,h)}.test(${y})`,()=>{let g=c.includes(h);g||r.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:Ty.Type.Str},u),s.opts.unevaluated&&d!==!0?e.assign((0,wa._)`${d}[${y}]`,!0):!g&&!s.allErrors&&e.if((0,wa.not)(u),()=>e.break())})})}}};tu.default=_k});var Oy=E(ru=>{"use strict";Object.defineProperty(ru,"__esModule",{value:!0});var wk=X(),Sk={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(r){let{gen:e,schema:t,it:n}=r;if((0,wk.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"}};ru.default=Sk});var Ny=E(nu=>{"use strict";Object.defineProperty(nu,"__esModule",{value:!0});var $k=Ct(),Ek={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:$k.validateUnion,error:{message:"must match a schema in anyOf"}};nu.default=Ek});var Dy=E(iu=>{"use strict";Object.defineProperty(iu,"__esModule",{value:!0});var Sa=B(),xk=X(),Ak={message:"must match exactly one schema in oneOf",params:({params:r})=>(0,Sa._)`{passingSchemas: ${r.passing}}`},kk={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Ak,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,xk.alwaysValidSchema)(i,u)?e.var(c,!0):f=r.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Sa._)`${c} && ${o}`).assign(o,!1).assign(a,(0,Sa._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(o,!0),e.assign(a,d),f&&r.mergeEvaluated(f,Sa.Name)})})}}};iu.default=kk});var Ly=E(su=>{"use strict";Object.defineProperty(su,"__esModule",{value:!0});var Pk=X(),Ck={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,Pk.alwaysValidSchema)(n,s))return;let a=r.subschema({keyword:"allOf",schemaProp:o},i);r.ok(i),r.mergeEvaluated(a)})}};su.default=Ck});var Fy=E(ou=>{"use strict";Object.defineProperty(ou,"__esModule",{value:!0});var $a=B(),qy=X(),Mk={message:({params:r})=>(0,$a.str)`must match "${r.ifClause}" schema`,params:({params:r})=>(0,$a._)`{failingKeyword: ${r.ifClause}}`},Ik={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Mk,code(r){let{gen:e,parentSchema:t,it:n}=r;t.then===void 0&&t.else===void 0&&(0,qy.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=jy(n,"then"),s=jy(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,$a.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,$a._)`${u}`):r.setParams({ifClause:u})}}}};function jy(r,e){let t=r.schema[e];return t!==void 0&&!(0,qy.alwaysValidSchema)(r,t)}ou.default=Ik});var Uy=E(au=>{"use strict";Object.defineProperty(au,"__esModule",{value:!0});var Tk=X(),Rk={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:r,parentSchema:e,it:t}){e.if===void 0&&(0,Tk.checkStrictMode)(t,`"${r}" without "if" is ignored`)}};au.default=Rk});var lu=E(cu=>{"use strict";Object.defineProperty(cu,"__esModule",{value:!0});var Ok=zd(),Nk=vy(),Dk=Hd(),Lk=wy(),jk=Sy(),qk=ba(),Fk=Ay(),Uk=Qd(),Bk=Cy(),Vk=Ry(),zk=Oy(),Hk=Ny(),Kk=Dy(),Wk=Ly(),Gk=Fy(),Jk=Uy();function Yk(r=!1){let e=[zk.default,Hk.default,Kk.default,Wk.default,Gk.default,Jk.default,Fk.default,Uk.default,qk.default,Bk.default,Vk.default];return r?e.push(Nk.default,Lk.default):e.push(Ok.default,Dk.default),e.push(jk.default),e}cu.default=Yk});var uu=E(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});Ls.dynamicAnchor=void 0;var du=B(),Xk=Pt(),By=Ss(),Qk=fa(),Zk={keyword:"$dynamicAnchor",schemaType:"string",code:r=>Vy(r,r.schema)};function Vy(r,e){let{gen:t,it:n}=r;n.schemaEnv.root.dynamicAnchors[e]=!0;let i=(0,du._)`${Xk.default.dynamicAnchors}${(0,du.getProperty)(e)}`,s=n.errSchemaPath==="#"?n.validateName:eP(r);t.if((0,du._)`!${i}`,()=>t.assign(i,s))}Ls.dynamicAnchor=Vy;function eP(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 By.SchemaEnv({schema:t,schemaId:c,root:i,baseId:s,localRefs:o,meta:a});return By.compileSchema.call(n,l),(0,Qk.getValidate)(r,l)}Ls.default=Zk});var fu=E(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});js.dynamicRef=void 0;var zy=B(),tP=Pt(),Hy=fa(),rP={keyword:"$dynamicRef",schemaType:"string",code:r=>Ky(r,r.schema)};function Ky(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,zy._)`${tP.default.dynamicAnchors}${(0,zy.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,Hy.callRef)(r,c),t.let(l,!0)}):()=>(0,Hy.callRef)(r,c)}}js.dynamicRef=Ky;js.default=rP});var Wy=E(pu=>{"use strict";Object.defineProperty(pu,"__esModule",{value:!0});var nP=uu(),iP=X(),sP={keyword:"$recursiveAnchor",schemaType:"boolean",code(r){r.schema?(0,nP.dynamicAnchor)(r,""):(0,iP.checkStrictMode)(r.it,"$recursiveAnchor: false is ignored")}};pu.default=sP});var Gy=E(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});var oP=fu(),aP={keyword:"$recursiveRef",schemaType:"string",code:r=>(0,oP.dynamicRef)(r,r.schema)};hu.default=aP});var Jy=E(mu=>{"use strict";Object.defineProperty(mu,"__esModule",{value:!0});var cP=uu(),lP=fu(),dP=Wy(),uP=Gy(),fP=[cP.default,lP.default,dP.default,uP.default];mu.default=fP});var Xy=E(yu=>{"use strict";Object.defineProperty(yu,"__esModule",{value:!0});var Yy=ba(),pP={keyword:"dependentRequired",type:"object",schemaType:"object",error:Yy.error,code:r=>(0,Yy.validatePropertyDeps)(r)};yu.default=pP});var Qy=E(gu=>{"use strict";Object.defineProperty(gu,"__esModule",{value:!0});var hP=ba(),mP={keyword:"dependentSchemas",type:"object",schemaType:"object",code:r=>(0,hP.validateSchemaDeps)(r)};gu.default=mP});var Zy=E(bu=>{"use strict";Object.defineProperty(bu,"__esModule",{value:!0});var yP=X(),gP={keyword:["maxContains","minContains"],type:"array",schemaType:"number",code({keyword:r,parentSchema:e,it:t}){e.contains===void 0&&(0,yP.checkStrictMode)(t,`"${r}" without "contains" is ignored`)}};bu.default=gP});var eg=E(vu=>{"use strict";Object.defineProperty(vu,"__esModule",{value:!0});var bP=Xy(),vP=Qy(),_P=Zy(),wP=[bP.default,vP.default,_P.default];vu.default=wP});var rg=E(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});var rn=B(),tg=X(),SP=Pt(),$P={message:"must NOT have unevaluated properties",params:({params:r})=>(0,rn._)`{unevaluatedProperty: ${r.unevaluatedProperty}}`},EP={keyword:"unevaluatedProperties",type:"object",schemaType:["boolean","object"],trackErrors:!0,error:$P,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 rn.Name?e.if((0,rn._)`${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,rn._)`${i} === ${SP.default.errors}`);function c(d){if(t===!1){r.setParams({unevaluatedProperty:d}),r.error(),o||e.break();return}if(!(0,tg.alwaysValidSchema)(s,t)){let f=e.name("valid");r.subschema({keyword:"unevaluatedProperties",dataProp:d,dataPropType:tg.Type.Str},f),o||e.if((0,rn.not)(f),()=>e.break())}}function l(d,f){return(0,rn._)`!${d} || !${d}[${f}]`}function u(d,f){let p=[];for(let m in d)d[m]===!0&&p.push((0,rn._)`${f} !== ${m}`);return(0,rn.and)(...p)}}};_u.default=EP});var ig=E(wu=>{"use strict";Object.defineProperty(wu,"__esModule",{value:!0});var qn=B(),ng=X(),xP={message:({params:{len:r}})=>(0,qn.str)`must NOT have more than ${r} items`,params:({params:{len:r}})=>(0,qn._)`{limit: ${r}}`},AP={keyword:"unevaluatedItems",type:"array",schemaType:["boolean","object"],error:xP,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,qn._)`${n}.length`);if(t===!1)r.setParams({len:s}),r.fail((0,qn._)`${o} > ${s}`);else if(typeof t=="object"&&!(0,ng.alwaysValidSchema)(i,t)){let c=e.var("valid",(0,qn._)`${o} <= ${s}`);e.if((0,qn.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:ng.Type.Num},c),i.allErrors||e.if((0,qn.not)(c),()=>e.break())})}}};wu.default=AP});var sg=E(Su=>{"use strict";Object.defineProperty(Su,"__esModule",{value:!0});var kP=rg(),PP=ig(),CP=[kP.default,PP.default];Su.default=CP});var og=E($u=>{"use strict";Object.defineProperty($u,"__esModule",{value:!0});var xe=B(),MP={message:({schemaCode:r})=>(0,xe.str)`must match format "${r}"`,params:({schemaCode:r})=>(0,xe._)`{format: ${r}}`},IP={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:MP,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"),g=t.let("format");t.if((0,xe._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>t.assign(y,(0,xe._)`${h}.type || "string"`).assign(g,(0,xe._)`${h}.validate`),()=>t.assign(y,(0,xe._)`"string"`).assign(g,h)),r.fail$data((0,xe.or)(_(),v()));function _(){return c.strictSchema===!1?xe.nil:(0,xe._)`${o} && !${g}`}function v(){let w=u.$async?(0,xe._)`(${h}.async ? await ${g}(${n}) : ${g}(${n}))`:(0,xe._)`${g}(${n})`,S=(0,xe._)`(typeof ${g} == "function" ? ${w} : ${g}.test(${n}))`;return(0,xe._)`${g} && ${g} !== true && ${y} === ${e} && !${S}`}}function p(){let m=d.formats[s];if(!m){_();return}if(m===!0)return;let[h,y,g]=v(m);h===e&&r.pass(w());function _(){if(c.strictSchema===!1){d.logger.warn(S());return}throw new Error(S());function S(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function v(S){let x=S instanceof RegExp?(0,xe.regexpCode)(S):c.code.formats?(0,xe._)`${c.code.formats}${(0,xe.getProperty)(s)}`:void 0,C=t.scopeValue("formats",{key:s,ref:S,code:x});return typeof S=="object"&&!(S instanceof RegExp)?[S.type||"string",S.validate,(0,xe._)`${C}.validate`]:["string",S,C]}function w(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,xe._)`await ${g}(${n})`}return typeof y=="function"?(0,xe._)`${g}(${n})`:(0,xe._)`${g}.test(${n})`}}}};$u.default=IP});var xu=E(Eu=>{"use strict";Object.defineProperty(Eu,"__esModule",{value:!0});var TP=og(),RP=[TP.default];Eu.default=RP});var Au=E(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.contentVocabulary=wi.metadataVocabulary=void 0;wi.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];wi.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var cg=E(ku=>{"use strict";Object.defineProperty(ku,"__esModule",{value:!0});var OP=Ad(),NP=Bd(),DP=lu(),LP=Jy(),jP=eg(),qP=sg(),FP=xu(),ag=Au(),UP=[LP.default,OP.default,NP.default,(0,DP.default)(!0),FP.default,ag.metadataVocabulary,ag.contentVocabulary,jP.default,qP.default];ku.default=UP});var dg=E(Ea=>{"use strict";Object.defineProperty(Ea,"__esModule",{value:!0});Ea.DiscrError=void 0;var lg;(function(r){r.Tag="tag",r.Mapping="mapping"})(lg||(Ea.DiscrError=lg={}))});var Mu=E(Cu=>{"use strict";Object.defineProperty(Cu,"__esModule",{value:!0});var Si=B(),Pu=dg(),ug=Ss(),BP=yi(),VP=X(),zP={message:({params:{discrError:r,tagName:e}})=>r===Pu.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:r,tag:e,tagName:t}})=>(0,Si._)`{error: ${r}, tag: ${t}, tagValue: ${e}}`},HP={keyword:"discriminator",type:"object",schemaType:"object",error:zP,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,Si._)`${t}${(0,Si.getProperty)(a)}`);e.if((0,Si._)`typeof ${l} == "string"`,()=>u(),()=>r.error(!1,{discrError:Pu.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,Si._)`${l} === ${m}`),e.assign(c,d(p[m]));e.else(),r.error(!1,{discrError:Pu.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,Si.Name),m}function f(){var p;let m={},h=g(i),y=!0;for(let w=0;w{KP.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 pg=E((a2,WP)=>{WP.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 hg=E((c2,GP)=>{GP.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 mg=E((l2,JP)=>{JP.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 yg=E((d2,YP)=>{YP.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 gg=E((u2,XP)=>{XP.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 bg=E((f2,QP)=>{QP.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 vg=E((p2,ZP)=>{ZP.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 _g=E(Iu=>{"use strict";Object.defineProperty(Iu,"__esModule",{value:!0});var e1=fg(),t1=pg(),r1=hg(),n1=mg(),i1=yg(),s1=gg(),o1=bg(),a1=vg(),c1=["/properties"];function l1(r){return[e1,t1,r1,n1,i1,e(this,s1),o1,e(this,a1)].forEach(t=>this.addMetaSchema(t,void 0,!1)),this;function e(t,n){return r?t.$dataMetaSchema(n,c1):n}}Iu.default=l1});var Ou=E((ge,Ru)=>{"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.Ajv2020=void 0;var d1=$d(),u1=cg(),f1=Mu(),p1=_g(),Tu="https://json-schema.org/draft/2020-12/schema",$i=class extends d1.default{constructor(e={}){super({...e,dynamicRef:!0,next:!0,unevaluated:!0})}_addVocabularies(){super._addVocabularies(),u1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(f1.default)}_addDefaultMetaSchema(){super._addDefaultMetaSchema();let{$data:e,meta:t}=this.opts;t&&(p1.default.call(this,e),this.refs["http://json-schema.org/schema"]=Tu)}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Tu)?Tu:void 0)}};ge.Ajv2020=$i;Ru.exports=ge=$i;Ru.exports.Ajv2020=$i;Object.defineProperty(ge,"__esModule",{value:!0});ge.default=$i;var h1=mi();Object.defineProperty(ge,"KeywordCxt",{enumerable:!0,get:function(){return h1.KeywordCxt}});var Ei=B();Object.defineProperty(ge,"_",{enumerable:!0,get:function(){return Ei._}});Object.defineProperty(ge,"str",{enumerable:!0,get:function(){return Ei.str}});Object.defineProperty(ge,"stringify",{enumerable:!0,get:function(){return Ei.stringify}});Object.defineProperty(ge,"nil",{enumerable:!0,get:function(){return Ei.nil}});Object.defineProperty(ge,"Name",{enumerable:!0,get:function(){return Ei.Name}});Object.defineProperty(ge,"CodeGen",{enumerable:!0,get:function(){return Ei.CodeGen}});var m1=ws();Object.defineProperty(ge,"ValidationError",{enumerable:!0,get:function(){return m1.default}});var y1=yi();Object.defineProperty(ge,"MissingRefError",{enumerable:!0,get:function(){return y1.default}})});var Pg=E(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.formatNames=dr.fastFormats=dr.fullFormats=void 0;function lr(r,e){return{validate:r,compare:e}}dr.fullFormats={date:lr(Eg,ju),time:lr(Du(!0),qu),"date-time":lr(wg(!0),Ag),"iso-time":lr(Du(),xg),"iso-date-time":lr(wg(),kg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:S1,"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:C1,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:$1,int32:{type:"number",validate:A1},int64:{type:"number",validate:k1},float:{type:"number",validate:$g},double:{type:"number",validate:$g},password:!0,binary:!0};dr.fastFormats={...dr.fullFormats,date:lr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ju),time:lr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,qu),"date-time":lr(/^\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,Ag),"iso-time":lr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,xg),"iso-date-time":lr(/^\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,kg),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};dr.formatNames=Object.keys(dr.fullFormats);function g1(r){return r%4===0&&(r%100!==0||r%400===0)}var b1=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,v1=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Eg(r){let e=b1.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&&g1(t)?29:v1[n])}function ju(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 qu(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 xg(r,e){if(!(r&&e))return;let t=Nu.exec(r),n=Nu.exec(e);if(t&&n)return r=t[1]+t[2]+t[3],e=n[1]+n[2]+n[3],r>e?1:r=E1}function k1(r){return Number.isInteger(r)}function $g(){return!0}var P1=/[^\\]\\Z/;function C1(r){if(P1.test(r))return!1;try{return new RegExp(r),!0}catch{return!1}}});var Mg=E(Fu=>{"use strict";Object.defineProperty(Fu,"__esModule",{value:!0});var M1=Ad(),I1=Bd(),T1=lu(),R1=xu(),Cg=Au(),O1=[M1.default,I1.default,(0,T1.default)(),R1.default,Cg.metadataVocabulary,Cg.contentVocabulary];Fu.default=O1});var Ig=E((g2,N1)=>{N1.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 Rg=E((be,Uu)=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.MissingRefError=be.ValidationError=be.CodeGen=be.Name=be.nil=be.stringify=be.str=be._=be.KeywordCxt=be.Ajv=void 0;var D1=$d(),L1=Mg(),j1=Mu(),Tg=Ig(),q1=["/properties"],xa="http://json-schema.org/draft-07/schema",xi=class extends D1.default{_addVocabularies(){super._addVocabularies(),L1.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(j1.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Tg,q1):Tg;this.addMetaSchema(e,xa,!1),this.refs["http://json-schema.org/schema"]=xa}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(xa)?xa:void 0)}};be.Ajv=xi;Uu.exports=be=xi;Uu.exports.Ajv=xi;Object.defineProperty(be,"__esModule",{value:!0});be.default=xi;var F1=mi();Object.defineProperty(be,"KeywordCxt",{enumerable:!0,get:function(){return F1.KeywordCxt}});var Ai=B();Object.defineProperty(be,"_",{enumerable:!0,get:function(){return Ai._}});Object.defineProperty(be,"str",{enumerable:!0,get:function(){return Ai.str}});Object.defineProperty(be,"stringify",{enumerable:!0,get:function(){return Ai.stringify}});Object.defineProperty(be,"nil",{enumerable:!0,get:function(){return Ai.nil}});Object.defineProperty(be,"Name",{enumerable:!0,get:function(){return Ai.Name}});Object.defineProperty(be,"CodeGen",{enumerable:!0,get:function(){return Ai.CodeGen}});var U1=ws();Object.defineProperty(be,"ValidationError",{enumerable:!0,get:function(){return U1.default}});var B1=yi();Object.defineProperty(be,"MissingRefError",{enumerable:!0,get:function(){return B1.default}})});var Og=E(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.formatLimitDefinition=void 0;var V1=Rg(),Bt=B(),nn=Bt.operators,Aa={formatMaximum:{okStr:"<=",ok:nn.LTE,fail:nn.GT},formatMinimum:{okStr:">=",ok:nn.GTE,fail:nn.LT},formatExclusiveMaximum:{okStr:"<",ok:nn.LT,fail:nn.GTE},formatExclusiveMinimum:{okStr:">",ok:nn.GT,fail:nn.LTE}},z1={message:({keyword:r,schemaCode:e})=>(0,Bt.str)`should be ${Aa[r].okStr} ${e}`,params:({keyword:r,schemaCode:e})=>(0,Bt._)`{comparison: ${Aa[r].okStr}, limit: ${e}}`};ki.formatLimitDefinition={keyword:Object.keys(Aa),type:"string",schemaType:"string",$data:!0,error:z1,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 V1.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,Bt._)`${f}[${c.schemaCode}]`);r.fail$data((0,Bt.or)((0,Bt._)`typeof ${p} != "object"`,(0,Bt._)`${p} instanceof RegExp`,(0,Bt._)`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,Bt._)`${o.code.formats}${(0,Bt.getProperty)(f)}`:void 0});r.fail$data(d(m))}function d(f){return(0,Bt._)`${f}.compare(${t}, ${n}) ${Aa[i].fail} 0`}},dependencies:["format"]};var H1=r=>(r.addKeyword(ki.formatLimitDefinition),r);ki.default=H1});var zu=E((qs,Lg)=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});var Pi=Pg(),K1=Og(),Bu=B(),Ng=new Bu.Name("fullFormats"),W1=new Bu.Name("fastFormats"),Vu=(r,e={keywords:!0})=>{if(Array.isArray(e))return Dg(r,e,Pi.fullFormats,Ng),r;let[t,n]=e.mode==="fast"?[Pi.fastFormats,W1]:[Pi.fullFormats,Ng],i=e.formats||Pi.formatNames;return Dg(r,i,t,n),e.keywords&&(0,K1.default)(r),r};Vu.get=(r,e="full")=>{let n=(e==="fast"?Pi.fastFormats:Pi.fullFormats)[r];if(!n)throw new Error(`Unknown format "${r}"`);return n};function Dg(r,e,t,n){var i,s;(i=(s=r.opts.code).formats)!==null&&i!==void 0||(s.formats=(0,Bu._)`require("ajv-formats/dist/formats").${n}`);for(let o of e)r.addFormat(o,t[o])}Lg.exports=qs=Vu;Object.defineProperty(qs,"__esModule",{value:!0});qs.default=Vu});var Fs=E((v2,Bg)=>{"use strict";var jg="[^\\\\/]",G1="(?=.)",qg="[^/]",Hu="(?:\\/|$)",Fg="(?:^|\\/)",Ku=`\\.{1,2}${Hu}`,J1="(?!\\.)",Y1=`(?!${Fg}${Ku})`,X1=`(?!\\.{0,1}${Hu})`,Q1=`(?!${Ku})`,Z1="[^.\\/]",eC=`${qg}*?`,tC="/",Ug={DOT_LITERAL:"\\.",PLUS_LITERAL:"\\+",QMARK_LITERAL:"\\?",SLASH_LITERAL:"\\/",ONE_CHAR:G1,QMARK:qg,END_ANCHOR:Hu,DOTS_SLASH:Ku,NO_DOT:J1,NO_DOTS:Y1,NO_DOT_SLASH:X1,NO_DOTS_SLASH:Q1,QMARK_NO_DOT:Z1,STAR:eC,START_ANCHOR:Fg,SEP:tC},rC={...Ug,SLASH_LITERAL:"[\\\\/]",QMARK:jg,STAR:`${jg}*?`,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:"\\"},nC={__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"};Bg.exports={DEFAULT_MAX_EXTGLOB_RECURSION:0,MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:nC,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?rC:Ug}}});var Us=E(pt=>{"use strict";var{REGEX_BACKSLASH:iC,REGEX_REMOVE_BACKSLASH:sC,REGEX_SPECIAL_CHARS:oC,REGEX_SPECIAL_CHARS_GLOBAL:aC}=Fs();pt.isObject=r=>r!==null&&typeof r=="object"&&!Array.isArray(r);pt.hasRegexChars=r=>oC.test(r);pt.isRegexChar=r=>r.length===1&&pt.hasRegexChars(r);pt.escapeRegex=r=>r.replace(aC,"\\$1");pt.toPosixSlashes=r=>r.replace(iC,"/");pt.isWindows=()=>{if(typeof navigator<"u"&&navigator.platform){let r=navigator.platform.toLowerCase();return r==="win32"||r==="windows"}return typeof process<"u"&&process.platform?process.platform==="win32":!1};pt.removeBackslashes=r=>r.replace(sC,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 Yg=E((w2,Jg)=>{"use strict";var Vg=Us(),{CHAR_ASTERISK:Wu,CHAR_AT:cC,CHAR_BACKWARD_SLASH:Bs,CHAR_COMMA:lC,CHAR_DOT:Gu,CHAR_EXCLAMATION_MARK:Ju,CHAR_FORWARD_SLASH:Gg,CHAR_LEFT_CURLY_BRACE:Yu,CHAR_LEFT_PARENTHESES:Xu,CHAR_LEFT_SQUARE_BRACKET:dC,CHAR_PLUS:uC,CHAR_QUESTION_MARK:zg,CHAR_RIGHT_CURLY_BRACE:fC,CHAR_RIGHT_PARENTHESES:Hg,CHAR_RIGHT_SQUARE_BRACKET:pC}=Fs(),Kg=r=>r===Gg||r===Bs,Wg=r=>{r.isPrefix!==!0&&(r.depth=r.isGlobstar?1/0:1)},hC=(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,g=!1,_=!1,v=!1,w=!1,S=!1,x=0,C,$,M={value:"",depth:0,isGlob:!1},A=()=>l>=n,W=()=>c.charCodeAt(l+1),q=()=>(C=$,c.charCodeAt(++l));for(;l0&&(P=c.slice(0,u),c=c.slice(u),d-=u),oe&&m===!0&&d>0?(oe=c.slice(0,d),k=c.slice(d)):m===!0?(oe="",k=c):oe=c,oe&&oe!==""&&oe!=="/"&&oe!==c&&Kg(oe.charCodeAt(oe.length-1))&&(oe=oe.slice(0,-1)),t.unescape===!0&&(k&&(k=Vg.removeBackslashes(k)),oe&&_===!0&&(oe=Vg.removeBackslashes(oe)));let F={prefix:P,input:r,start:u,base:oe,glob:k,isBrace:f,isBracket:p,isGlob:m,isExtglob:h,isGlobstar:y,negated:v,negatedExtglob:w};if(t.tokens===!0&&(F.maxDepth=0,Kg($)||o.push(M),F.tokens=o),t.parts===!0||t.tokens===!0){let Q;for(let fe=0;fe{"use strict";var Vs=Fs(),_t=Us(),{MAX_LENGTH:ka,POSIX_REGEX_SOURCE:mC,REGEX_NON_SPECIAL_CHARS:yC,REGEX_SPECIAL_CHARS_BACKREF:gC,REPLACEMENTS:Xg}=Vs,bC=(r,e)=>{if(typeof e.expandRange=="function")return e.expandRange(...r,e);r.sort();let t=`[${r.join("-")}]`;try{new RegExp(t)}catch{return r.map(i=>_t.escapeRegex(i)).join("..")}return t},Ci=(r,e)=>`Missing ${r}: "${e}" - use "\\\\${e}" to match literal characters`,Qg=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},vC=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},Zu=r=>{let e=r.trim(),t=!0;for(;t===!0;)t=!1,/^@\([^\\()[\]{}|]+\)$/.test(e)&&(e=e.slice(2,-1),t=!0);if(vC(e))return e.replace(/\\(.)/g,"$1")},_C=r=>{let e=r.map(Zu).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}}}}},wC=r=>`${r.length===1?_t.escapeRegex(r[0]):`[${r.map(t=>_t.escapeRegex(t)).join("")}]`}*`,SC=r=>{let e=0,t=[];for(;eo.trim());if(i.length!==1)return;let s=Zu(i[0]);if(!s||s.length!==1)return;t.push(s),e+=n.end+1}if(!(t.length<1))return t},$C=r=>{let e=0,t=r.trim(),n=Qu(t);for(;n;)e++,t=n.body.trim(),n=Qu(t);return e},EC=(r,e)=>{if(e.maxExtglobRecursion===!1)return{risky:!1};let t=typeof e.maxExtglobRecursion=="number"?e.maxExtglobRecursion:Vs.DEFAULT_MAX_EXTGLOB_RECURSION,n=Qg(r).map(a=>a.trim());if(n.length>1&&(n.some(a=>a==="")||n.some(a=>/^[*?]+$/.test(a))||_C(n)))return{risky:!0};let i=[],s=!1,o=!0;for(let a of n){let c=SC(a);if(c){s=!0,i.push(...c);continue}let l=Zu(a);if(l&&l.length===1){i.push(l);continue}if(o=!1,$C(a)>t)return{risky:!0}}return s?o?{risky:!0,safeOutput:wC([...new Set(i)])}:{risky:!0}:{risky:!1}},ef=(r,e)=>{if(typeof r!="string")throw new TypeError("Expected a string");r=Xg[r]||r;let t={...e},n=typeof t.maxLength=="number"?Math.min(ka,t.maxLength):ka,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=Vs.globChars(t.windows),l=Vs.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:g,QMARK:_,QMARK_NO_DOT:v,STAR:w,START_ANCHOR:S}=c,x=T=>`(${a}(?:(?!${S}${T.dot?m:u}).)*?)`,C=t.dot?"":h,$=t.dot?_:v,M=t.bash===!0?x(t):w;t.capture&&(M=`(${M})`),typeof t.noext=="boolean"&&(t.noextglob=t.noext);let A={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,A),i=r.length;let W=[],q=[],oe=[],P=s,k,F=()=>A.index===i-1,Q=A.peek=(T=1)=>r[A.index+T],fe=A.advance=()=>r[++A.index]||"",Xe=()=>r.slice(A.index+1),Ue=(T="",we=0)=>{A.consumed+=T,A.index+=we},Wr=T=>{A.output+=T.output!=null?T.output:T.value,Ue(T.value)},gS=()=>{let T=1;for(;Q()==="!"&&(Q(2)!=="("||Q(3)==="?");)fe(),A.start++,T++;return T%2===0?!1:(A.negated=!0,A.start++,!0)},Bo=T=>{A[T]++,oe.push(T)},Gr=T=>{A[T]--,oe.pop()},Z=T=>{if(P.type==="globstar"){let we=A.braces>0&&(T.type==="comma"||T.type==="brace"),I=T.extglob===!0||W.length&&(T.type==="pipe"||T.type==="paren");T.type!=="slash"&&T.type!=="paren"&&!we&&!I&&(A.output=A.output.slice(0,-P.output.length),P.type="star",P.value="*",P.output=M,A.output+=P.output)}if(W.length&&T.type!=="paren"&&(W[W.length-1].inner+=T.value),(T.value||T.output)&&Wr(T),P&&P.type==="text"&&T.type==="text"){P.output=(P.output||P.value)+T.value,P.value+=T.value;return}T.prev=P,o.push(T),P=T},Vo=(T,we)=>{let I={...l[we],conditions:1,inner:""};I.prev=P,I.parens=A.parens,I.output=A.output,I.startIndex=A.index,I.tokensIndex=o.length;let ee=(t.capture?"(":"")+I.open;Bo("parens"),Z({type:T,value:we,output:A.output?"":p}),Z({type:"paren",extglob:!0,value:fe(),output:ee}),W.push(I)},bS=T=>{let we=r.slice(T.startIndex,A.index+1),I=r.slice(T.startIndex+2,A.index),ee=EC(I,t);if((T.type==="plus"||T.type==="star")&&ee.risky){let he=ee.safeOutput?(T.output?"":p)+(t.capture?`(${ee.safeOutput})`:ee.safeOutput):void 0,ir=o[T.tokensIndex];ir.type="text",ir.value=we,ir.output=he||_t.escapeRegex(we);for(let sr=T.tokensIndex+1;sr1&&T.inner.includes("/")&&(he=x(t)),(he!==M||F()||/^\)+$/.test(Xe()))&&(me=T.close=`)$))${he}`),T.inner.includes("*")&&(Ce=Xe())&&/^\.[^\\/.]+$/.test(Ce)){let ir=ef(Ce,{...e,fastpaths:!1}).output;me=T.close=`)${ir})${he})`}T.prev.type==="bos"&&(A.negatedExtglob=!0)}Z({type:"paren",extglob:!0,value:k,output:me}),Gr("parens")};if(t.fastpaths!==!1&&!/(^[*!]|[/()[\]{}"])/.test(r)){let T=!1,we=r.replace(gC,(I,ee,me,Ce,he,ir)=>Ce==="\\"?(T=!0,I):Ce==="?"?ee?ee+Ce+(he?_.repeat(he.length):""):ir===0?$+(he?_.repeat(he.length):""):_.repeat(me.length):Ce==="."?u.repeat(me.length):Ce==="*"?ee?ee+Ce+(he?M:""):M:ee?I:`\\${I}`);return T===!0&&(t.unescape===!0?we=we.replace(/\\/g,""):we=we.replace(/\\+/g,I=>I.length%2===0?"\\\\":I?"\\":"")),we===r&&t.contains===!0?(A.output=r,A):(A.output=_t.wrapOutput(we,A,e),A)}for(;!F();){if(k=fe(),k==="\0")continue;if(k==="\\"){let I=Q();if(I==="/"&&t.bash!==!0||I==="."||I===";")continue;if(!I){k+="\\",Z({type:"text",value:k});continue}let ee=/^\\+/.exec(Xe()),me=0;if(ee&&ee[0].length>2&&(me=ee[0].length,A.index+=me,me%2!==0&&(k+="\\")),t.unescape===!0?k=fe():k+=fe(),A.brackets===0){Z({type:"text",value:k});continue}}if(A.brackets>0&&(k!=="]"||P.value==="["||P.value==="[^")){if(t.posix!==!1&&k===":"){let I=P.value.slice(1);if(I.includes("[")&&(P.posix=!0,I.includes(":"))){let ee=P.value.lastIndexOf("["),me=P.value.slice(0,ee),Ce=P.value.slice(ee+2),he=mC[Ce];if(he){P.value=me+he,A.backtrack=!0,fe(),!s.output&&o.indexOf(P)===1&&(s.output=p);continue}}}(k==="["&&Q()!==":"||k==="-"&&Q()==="]")&&(k=`\\${k}`),k==="]"&&(P.value==="["||P.value==="[^")&&(k=`\\${k}`),t.posix===!0&&k==="!"&&P.value==="["&&(k="^"),P.value+=k,Wr({value:k});continue}if(A.quotes===1&&k!=='"'){k=_t.escapeRegex(k),P.value+=k,Wr({value:k});continue}if(k==='"'){A.quotes=A.quotes===1?0:1,t.keepQuotes===!0&&Z({type:"text",value:k});continue}if(k==="("){Bo("parens"),Z({type:"paren",value:k});continue}if(k===")"){if(A.parens===0&&t.strictBrackets===!0)throw new SyntaxError(Ci("opening","("));let I=W[W.length-1];if(I&&A.parens===I.parens+1){bS(W.pop());continue}Z({type:"paren",value:k,output:A.parens?")":"\\)"}),Gr("parens");continue}if(k==="["){if(t.nobracket===!0||!Xe().includes("]")){if(t.nobracket!==!0&&t.strictBrackets===!0)throw new SyntaxError(Ci("closing","]"));k=`\\${k}`}else Bo("brackets");Z({type:"bracket",value:k});continue}if(k==="]"){if(t.nobracket===!0||P&&P.type==="bracket"&&P.value.length===1){Z({type:"text",value:k,output:`\\${k}`});continue}if(A.brackets===0){if(t.strictBrackets===!0)throw new SyntaxError(Ci("opening","["));Z({type:"text",value:k,output:`\\${k}`});continue}Gr("brackets");let I=P.value.slice(1);if(P.posix!==!0&&I[0]==="^"&&!I.includes("/")&&(k=`/${k}`),P.value+=k,Wr({value:k}),t.literalBrackets===!1||_t.hasRegexChars(I))continue;let ee=_t.escapeRegex(P.value);if(A.output=A.output.slice(0,-P.value.length),t.literalBrackets===!0){A.output+=ee,P.value=ee;continue}P.value=`(${a}${ee}|${P.value})`,A.output+=P.value;continue}if(k==="{"&&t.nobrace!==!0){Bo("braces");let I={type:"brace",value:k,output:"(",outputIndex:A.output.length,tokensIndex:A.tokens.length};q.push(I),Z(I);continue}if(k==="}"){let I=q[q.length-1];if(t.nobrace===!0||!I){Z({type:"text",value:k,output:k});continue}let ee=")";if(I.dots===!0){let me=o.slice(),Ce=[];for(let he=me.length-1;he>=0&&(o.pop(),me[he].type!=="brace");he--)me[he].type!=="dots"&&Ce.unshift(me[he].value);ee=bC(Ce,t),A.backtrack=!0}if(I.comma!==!0&&I.dots!==!0){let me=A.output.slice(0,I.outputIndex),Ce=A.tokens.slice(I.tokensIndex);I.value=I.output="\\{",k=ee="\\}",A.output=me;for(let he of Ce)A.output+=he.output||he.value}Z({type:"brace",value:k,output:ee}),Gr("braces"),q.pop();continue}if(k==="|"){W.length>0&&W[W.length-1].conditions++,Z({type:"text",value:k});continue}if(k===","){let I=k,ee=q[q.length-1];ee&&oe[oe.length-1]==="braces"&&(ee.comma=!0,I="|"),Z({type:"comma",value:k,output:I});continue}if(k==="/"){if(P.type==="dot"&&A.index===A.start+1){A.start=A.index+1,A.consumed="",A.output="",o.pop(),P=s;continue}Z({type:"slash",value:k,output:f});continue}if(k==="."){if(A.braces>0&&P.type==="dot"){P.value==="."&&(P.output=u);let I=q[q.length-1];P.type="dots",P.output+=k,P.value+=k,I.dots=!0;continue}if(A.braces+A.parens===0&&P.type!=="bos"&&P.type!=="slash"){Z({type:"text",value:k,output:u});continue}Z({type:"dot",value:k,output:u});continue}if(k==="?"){if(!(P&&P.value==="(")&&t.noextglob!==!0&&Q()==="("&&Q(2)!=="?"){Vo("qmark",k);continue}if(P&&P.type==="paren"){let ee=Q(),me=k;(P.value==="("&&!/[!=<:]/.test(ee)||ee==="<"&&!/<([!=]|\w+>)/.test(Xe()))&&(me=`\\${k}`),Z({type:"text",value:k,output:me});continue}if(t.dot!==!0&&(P.type==="slash"||P.type==="bos")){Z({type:"qmark",value:k,output:v});continue}Z({type:"qmark",value:k,output:_});continue}if(k==="!"){if(t.noextglob!==!0&&Q()==="("&&(Q(2)!=="?"||!/[!=<:]/.test(Q(3)))){Vo("negate",k);continue}if(t.nonegate!==!0&&A.index===0){gS();continue}}if(k==="+"){if(t.noextglob!==!0&&Q()==="("&&Q(2)!=="?"){Vo("plus",k);continue}if(P&&P.value==="("||t.regex===!1){Z({type:"plus",value:k,output:d});continue}if(P&&(P.type==="bracket"||P.type==="paren"||P.type==="brace")||A.parens>0){Z({type:"plus",value:k});continue}Z({type:"plus",value:d});continue}if(k==="@"){if(t.noextglob!==!0&&Q()==="("&&Q(2)!=="?"){Z({type:"at",extglob:!0,value:k,output:""});continue}Z({type:"text",value:k});continue}if(k!=="*"){(k==="$"||k==="^")&&(k=`\\${k}`);let I=yC.exec(Xe());I&&(k+=I[0],A.index+=I[0].length),Z({type:"text",value:k});continue}if(P&&(P.type==="globstar"||P.star===!0)){P.type="star",P.star=!0,P.value+=k,P.output=M,A.backtrack=!0,A.globstar=!0,Ue(k);continue}let T=Xe();if(t.noextglob!==!0&&/^\([^?]/.test(T)){Vo("star",k);continue}if(P.type==="star"){if(t.noglobstar===!0){Ue(k);continue}let I=P.prev,ee=I.prev,me=I.type==="slash"||I.type==="bos",Ce=ee&&(ee.type==="star"||ee.type==="globstar");if(t.bash===!0&&(!me||T[0]&&T[0]!=="/")){Z({type:"star",value:k,output:""});continue}let he=A.braces>0&&(I.type==="comma"||I.type==="brace"),ir=W.length&&(I.type==="pipe"||I.type==="paren");if(!me&&I.type!=="paren"&&!he&&!ir){Z({type:"star",value:k,output:""});continue}for(;T.slice(0,3)==="/**";){let sr=r[A.index+4];if(sr&&sr!=="/")break;T=T.slice(3),Ue("/**",3)}if(I.type==="bos"&&F()){P.type="globstar",P.value+=k,P.output=x(t),A.output=P.output,A.globstar=!0,Ue(k);continue}if(I.type==="slash"&&I.prev.type!=="bos"&&!Ce&&F()){A.output=A.output.slice(0,-(I.output+P.output).length),I.output=`(?:${I.output}`,P.type="globstar",P.output=x(t)+(t.strictSlashes?")":"|$)"),P.value+=k,A.globstar=!0,A.output+=I.output+P.output,Ue(k);continue}if(I.type==="slash"&&I.prev.type!=="bos"&&T[0]==="/"){let sr=T[1]!==void 0?"|$":"";A.output=A.output.slice(0,-(I.output+P.output).length),I.output=`(?:${I.output}`,P.type="globstar",P.output=`${x(t)}${f}|${f}${sr})`,P.value+=k,A.output+=I.output+P.output,A.globstar=!0,Ue(k+fe()),Z({type:"slash",value:"/",output:""});continue}if(I.type==="bos"&&T[0]==="/"){P.type="globstar",P.value+=k,P.output=`(?:^|${f}|${x(t)}${f})`,A.output=P.output,A.globstar=!0,Ue(k+fe()),Z({type:"slash",value:"/",output:""});continue}A.output=A.output.slice(0,-P.output.length),P.type="globstar",P.output=x(t),P.value+=k,A.output+=P.output,A.globstar=!0,Ue(k);continue}let we={type:"star",value:k,output:M};if(t.bash===!0){we.output=".*?",(P.type==="bos"||P.type==="slash")&&(we.output=C+we.output),Z(we);continue}if(P&&(P.type==="bracket"||P.type==="paren")&&t.regex===!0){we.output=k,Z(we);continue}(A.index===A.start||P.type==="slash"||P.type==="dot")&&(P.type==="dot"?(A.output+=y,P.output+=y):t.dot===!0?(A.output+=g,P.output+=g):(A.output+=C,P.output+=C),Q()!=="*"&&(A.output+=p,P.output+=p)),Z(we)}for(;A.brackets>0;){if(t.strictBrackets===!0)throw new SyntaxError(Ci("closing","]"));A.output=_t.escapeLast(A.output,"["),Gr("brackets")}for(;A.parens>0;){if(t.strictBrackets===!0)throw new SyntaxError(Ci("closing",")"));A.output=_t.escapeLast(A.output,"("),Gr("parens")}for(;A.braces>0;){if(t.strictBrackets===!0)throw new SyntaxError(Ci("closing","}"));A.output=_t.escapeLast(A.output,"{"),Gr("braces")}if(t.strictSlashes!==!0&&(P.type==="star"||P.type==="bracket")&&Z({type:"maybe_slash",value:"",output:`${f}?`}),A.backtrack===!0){A.output="";for(let T of A.tokens)A.output+=T.output!=null?T.output:T.value,T.suffix&&(A.output+=T.suffix)}return A};ef.fastpaths=(r,e)=>{let t={...e},n=typeof t.maxLength=="number"?Math.min(ka,t.maxLength):ka,i=r.length;if(i>n)throw new SyntaxError(`Input length: ${i}, exceeds maximum allowed length: ${n}`);r=Xg[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}=Vs.globChars(t.windows),m=t.dot?u:l,h=t.dot?d:l,y=t.capture?"":"?:",g={negated:!1,prefix:""},_=t.bash===!0?".*?":f;t.capture&&(_=`(${_})`);let v=C=>C.noglobstar===!0?_:`(${y}(?:(?!${p}${C.dot?c:s}).)*?)`,w=C=>{switch(C){case"*":return`${m}${a}${_}`;case".*":return`${s}${a}${_}`;case"*.*":return`${m}${_}${s}${a}${_}`;case"*/*":return`${m}${_}${o}${a}${h}${_}`;case"**":return m+v(t);case"**/*":return`(?:${m}${v(t)}${o})?${h}${a}${_}`;case"**/*.*":return`(?:${m}${v(t)}${o})?${h}${_}${s}${a}${_}`;case"**/.*":return`(?:${m}${v(t)}${o})?${s}${a}${_}`;default:{let $=/^(.*?)\.(\w+)$/.exec(C);if(!$)return;let M=w($[1]);return M?M+s+$[2]:void 0}}},S=_t.removePrefix(r,g),x=w(S);return x&&t.strictSlashes!==!0&&(x+=`${o}?`),x};Zg.exports=ef});var nb=E(($2,rb)=>{"use strict";var xC=Yg(),tf=eb(),tb=Us(),AC=Fs(),kC=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=kC(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?Ae.compileRe(r,e):Ae.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=Ae(i.ignore,u,t)}let l=(u,d=!1)=>{let{isMatch:f,match:p,output:m}=Ae.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};Ae.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?tb.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=Ae.matchBase(r,e,t,i):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(tb.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)):tf(r,{...e,fastpaths:!1});Ae.scan=(r,e)=>xC(r,e);Ae.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=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 i={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(r[0]==="."||r[0]==="*")&&(i.output=tf.fastpaths(r,e)),i.output||(i=tf(r,e)),Ae.compileRe(i,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=AC;rb.exports=Ae});var rf=E((E2,ob)=>{"use strict";var ib=nb(),PC=Us();function sb(r,e,t=!1){return e&&(e.windows===null||e.windows===void 0)&&(e={...e,windows:PC.isWindows()}),ib(r,e,t)}Object.assign(sb,ib);ob.exports=sb});var Ni=E((D2,qb)=>{"use strict";var iM="2.0.0",sM=Number.MAX_SAFE_INTEGER||9007199254740991,oM=16,aM=250,cM=["major","premajor","minor","preminor","patch","prepatch","prerelease"];qb.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:oM,MAX_SAFE_BUILD_LENGTH:aM,MAX_SAFE_INTEGER:sM,RELEASE_TYPES:cM,SEMVER_SPEC_VERSION:iM,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Ws=E((L2,Fb)=>{"use strict";var lM=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...r)=>console.error("SEMVER",...r):()=>{};Fb.exports=lM});var Di=E((fr,Ub)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:hf,MAX_SAFE_BUILD_LENGTH:dM,MAX_LENGTH:uM}=Ni(),fM=Ws();fr=Ub.exports={};var pM=fr.re=[],hM=fr.safeRe=[],N=fr.src=[],mM=fr.safeSrc=[],D=fr.t={},yM=0,mf="[a-zA-Z0-9-]",gM=[["\\s",1],["\\d",uM],[mf,dM]],bM=r=>{for(let[e,t]of gM)r=r.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return r},V=(r,e,t)=>{let n=bM(e),i=yM++;fM(r,i,e),D[r]=i,N[i]=e,mM[i]=n,pM[i]=new RegExp(e,t?"g":void 0),hM[i]=new RegExp(n,t?"g":void 0)};V("NUMERICIDENTIFIER","0|[1-9]\\d*");V("NUMERICIDENTIFIERLOOSE","\\d+");V("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${mf}*`);V("MAINVERSION",`(${N[D.NUMERICIDENTIFIER]})\\.(${N[D.NUMERICIDENTIFIER]})\\.(${N[D.NUMERICIDENTIFIER]})`);V("MAINVERSIONLOOSE",`(${N[D.NUMERICIDENTIFIERLOOSE]})\\.(${N[D.NUMERICIDENTIFIERLOOSE]})\\.(${N[D.NUMERICIDENTIFIERLOOSE]})`);V("PRERELEASEIDENTIFIER",`(?:${N[D.NONNUMERICIDENTIFIER]}|${N[D.NUMERICIDENTIFIER]})`);V("PRERELEASEIDENTIFIERLOOSE",`(?:${N[D.NONNUMERICIDENTIFIER]}|${N[D.NUMERICIDENTIFIERLOOSE]})`);V("PRERELEASE",`(?:-(${N[D.PRERELEASEIDENTIFIER]}(?:\\.${N[D.PRERELEASEIDENTIFIER]})*))`);V("PRERELEASELOOSE",`(?:-?(${N[D.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${N[D.PRERELEASEIDENTIFIERLOOSE]})*))`);V("BUILDIDENTIFIER",`${mf}+`);V("BUILD",`(?:\\+(${N[D.BUILDIDENTIFIER]}(?:\\.${N[D.BUILDIDENTIFIER]})*))`);V("FULLPLAIN",`v?${N[D.MAINVERSION]}${N[D.PRERELEASE]}?${N[D.BUILD]}?`);V("FULL",`^${N[D.FULLPLAIN]}$`);V("LOOSEPLAIN",`[v=\\s]*${N[D.MAINVERSIONLOOSE]}${N[D.PRERELEASELOOSE]}?${N[D.BUILD]}?`);V("LOOSE",`^${N[D.LOOSEPLAIN]}$`);V("GTLT","((?:<|>)?=?)");V("XRANGEIDENTIFIERLOOSE",`${N[D.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);V("XRANGEIDENTIFIER",`${N[D.NUMERICIDENTIFIER]}|x|X|\\*`);V("XRANGEPLAIN",`[v=\\s]*(${N[D.XRANGEIDENTIFIER]})(?:\\.(${N[D.XRANGEIDENTIFIER]})(?:\\.(${N[D.XRANGEIDENTIFIER]})(?:${N[D.PRERELEASE]})?${N[D.BUILD]}?)?)?`);V("XRANGEPLAINLOOSE",`[v=\\s]*(${N[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${N[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${N[D.XRANGEIDENTIFIERLOOSE]})(?:${N[D.PRERELEASELOOSE]})?${N[D.BUILD]}?)?)?`);V("XRANGE",`^${N[D.GTLT]}\\s*${N[D.XRANGEPLAIN]}$`);V("XRANGELOOSE",`^${N[D.GTLT]}\\s*${N[D.XRANGEPLAINLOOSE]}$`);V("COERCEPLAIN",`(^|[^\\d])(\\d{1,${hf}})(?:\\.(\\d{1,${hf}}))?(?:\\.(\\d{1,${hf}}))?`);V("COERCE",`${N[D.COERCEPLAIN]}(?:$|[^\\d])`);V("COERCEFULL",N[D.COERCEPLAIN]+`(?:${N[D.PRERELEASE]})?(?:${N[D.BUILD]})?(?:$|[^\\d])`);V("COERCERTL",N[D.COERCE],!0);V("COERCERTLFULL",N[D.COERCEFULL],!0);V("LONETILDE","(?:~>?)");V("TILDETRIM",`(\\s*)${N[D.LONETILDE]}\\s+`,!0);fr.tildeTrimReplace="$1~";V("TILDE",`^${N[D.LONETILDE]}${N[D.XRANGEPLAIN]}$`);V("TILDELOOSE",`^${N[D.LONETILDE]}${N[D.XRANGEPLAINLOOSE]}$`);V("LONECARET","(?:\\^)");V("CARETTRIM",`(\\s*)${N[D.LONECARET]}\\s+`,!0);fr.caretTrimReplace="$1^";V("CARET",`^${N[D.LONECARET]}${N[D.XRANGEPLAIN]}$`);V("CARETLOOSE",`^${N[D.LONECARET]}${N[D.XRANGEPLAINLOOSE]}$`);V("COMPARATORLOOSE",`^${N[D.GTLT]}\\s*(${N[D.LOOSEPLAIN]})$|^$`);V("COMPARATOR",`^${N[D.GTLT]}\\s*(${N[D.FULLPLAIN]})$|^$`);V("COMPARATORTRIM",`(\\s*)${N[D.GTLT]}\\s*(${N[D.LOOSEPLAIN]}|${N[D.XRANGEPLAIN]})`,!0);fr.comparatorTrimReplace="$1$2$3";V("HYPHENRANGE",`^\\s*(${N[D.XRANGEPLAIN]})\\s+-\\s+(${N[D.XRANGEPLAIN]})\\s*$`);V("HYPHENRANGELOOSE",`^\\s*(${N[D.XRANGEPLAINLOOSE]})\\s+-\\s+(${N[D.XRANGEPLAINLOOSE]})\\s*$`);V("STAR","(<|>)?=?\\s*\\*");V("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");V("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var Ra=E((j2,Bb)=>{"use strict";var vM=Object.freeze({loose:!0}),_M=Object.freeze({}),wM=r=>r?typeof r!="object"?vM:r:_M;Bb.exports=wM});var yf=E((q2,Hb)=>{"use strict";var Vb=/^[0-9]+$/,zb=(r,e)=>{if(typeof r=="number"&&typeof e=="number")return r===e?0:rzb(e,r);Hb.exports={compareIdentifiers:zb,rcompareIdentifiers:SM}});var Le=E((F2,Wb)=>{"use strict";var Oa=Ws(),{MAX_LENGTH:Kb,MAX_SAFE_INTEGER:Na}=Ni(),{safeRe:Da,t:La}=Di(),$M=Ra(),{compareIdentifiers:gf}=yf(),EM=(r,e)=>{let t=e.split(".");if(t.length>r.length)return!1;for(let n=0;nKb)throw new TypeError(`version is longer than ${Kb} characters`);Oa("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let n=e.trim().match(t.loose?Da[La.LOOSE]:Da[La.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>Na||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Na||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Na||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(Oa("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 gf(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(Oa("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 gf(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?Da[La.PRERELEASELOOSE]:Da[La.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]),EM(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}};Wb.exports=bf});var an=E((U2,Jb)=>{"use strict";var Gb=Le(),xM=(r,e,t=!1)=>{if(r instanceof Gb)return r;try{return new Gb(r,e)}catch(n){if(!t)return null;throw n}};Jb.exports=xM});var Xb=E((B2,Yb)=>{"use strict";var AM=an(),kM=(r,e)=>{let t=AM(r,e);return t?t.version:null};Yb.exports=kM});var Zb=E((V2,Qb)=>{"use strict";var PM=an(),CM=(r,e)=>{let t=PM(r.trim().replace(/^[=v]+/,""),e);return t?t.version:null};Qb.exports=CM});var rv=E((z2,tv)=>{"use strict";var ev=Le(),MM=(r,e,t,n,i)=>{typeof t=="string"&&(i=n,n=t,t=void 0);try{return new ev(r instanceof ev?r.version:r,t).inc(e,n,i).version}catch{return null}};tv.exports=MM});var sv=E((H2,iv)=>{"use strict";var nv=an(),IM=(r,e)=>{let t=nv(r,null,!0),n=nv(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"};iv.exports=IM});var av=E((K2,ov)=>{"use strict";var TM=Le(),RM=(r,e)=>new TM(r,e).major;ov.exports=RM});var lv=E((W2,cv)=>{"use strict";var OM=Le(),NM=(r,e)=>new OM(r,e).minor;cv.exports=NM});var uv=E((G2,dv)=>{"use strict";var DM=Le(),LM=(r,e)=>new DM(r,e).patch;dv.exports=LM});var pv=E((J2,fv)=>{"use strict";var jM=an(),qM=(r,e)=>{let t=jM(r,e);return t&&t.prerelease.length?t.prerelease:null};fv.exports=qM});var Ot=E((Y2,mv)=>{"use strict";var hv=Le(),FM=(r,e,t)=>new hv(r,t).compare(new hv(e,t));mv.exports=FM});var gv=E((X2,yv)=>{"use strict";var UM=Ot(),BM=(r,e,t)=>UM(e,r,t);yv.exports=BM});var vv=E((Q2,bv)=>{"use strict";var VM=Ot(),zM=(r,e)=>VM(r,e,!0);bv.exports=zM});var ja=E((Z2,wv)=>{"use strict";var _v=Le(),HM=(r,e,t)=>{let n=new _v(r,t),i=new _v(e,t);return n.compare(i)||n.compareBuild(i)};wv.exports=HM});var $v=E((ej,Sv)=>{"use strict";var KM=ja(),WM=(r,e)=>r.sort((t,n)=>KM(t,n,e));Sv.exports=WM});var xv=E((tj,Ev)=>{"use strict";var GM=ja(),JM=(r,e)=>r.sort((t,n)=>GM(n,t,e));Ev.exports=JM});var Gs=E((rj,Av)=>{"use strict";var YM=Ot(),XM=(r,e,t)=>YM(r,e,t)>0;Av.exports=XM});var qa=E((nj,kv)=>{"use strict";var QM=Ot(),ZM=(r,e,t)=>QM(r,e,t)<0;kv.exports=ZM});var vf=E((ij,Pv)=>{"use strict";var eI=Ot(),tI=(r,e,t)=>eI(r,e,t)===0;Pv.exports=tI});var _f=E((sj,Cv)=>{"use strict";var rI=Ot(),nI=(r,e,t)=>rI(r,e,t)!==0;Cv.exports=nI});var Fa=E((oj,Mv)=>{"use strict";var iI=Ot(),sI=(r,e,t)=>iI(r,e,t)>=0;Mv.exports=sI});var Ua=E((aj,Iv)=>{"use strict";var oI=Ot(),aI=(r,e,t)=>oI(r,e,t)<=0;Iv.exports=aI});var wf=E((cj,Tv)=>{"use strict";var cI=vf(),lI=_f(),dI=Gs(),uI=Fa(),fI=qa(),pI=Ua(),hI=(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 cI(r,t,n);case"!=":return lI(r,t,n);case">":return dI(r,t,n);case">=":return uI(r,t,n);case"<":return fI(r,t,n);case"<=":return pI(r,t,n);default:throw new TypeError(`Invalid operator: ${e}`)}};Tv.exports=hI});var Ov=E((lj,Rv)=>{"use strict";var mI=Le(),yI=an(),{safeRe:Ba,t:Va}=Di(),gI=(r,e)=>{if(r instanceof mI)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?Ba[Va.COERCEFULL]:Ba[Va.COERCE]);else{let c=e.includePrerelease?Ba[Va.COERCERTLFULL]:Ba[Va.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 yI(`${n}.${i}.${s}${o}${a}`,e)};Rv.exports=gI});var Dv=E((dj,Nv)=>{"use strict";var bI=an(),vI=Ni(),_I=Le(),wI=(r,e,t)=>{if(!vI.RELEASE_TYPES.includes(e))return null;let n=SI(r,t);return n&&$I(n,e)},SI=(r,e)=>{let t=r instanceof _I?r.version:r;return bI(t,e)},$I=(r,e)=>{if(EI(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()},EI=r=>r.startsWith("pre");Nv.exports=wI});var jv=E((uj,Lv)=>{"use strict";var Sf=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}};Lv.exports=Sf});var Nt=E((fj,Bv)=>{"use strict";var xI=/\s+/g,$f=class r{constructor(e,t){if(t=kI(t),e instanceof r)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new r(e.raw,t);if(e instanceof Ef)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(xI," "),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=>!Fv(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&&DI(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(NI,"");let n=((this.options.includePrerelease&&RI)|(this.options.loose&&OI))+":"+e,i=qv.get(n);if(i)return i;let s=this.options.loose,o=s?tt[je.HYPHENRANGELOOSE]:tt[je.HYPHENRANGE];e=e.replace(o,WI(this.options.includePrerelease)),ve("hyphen replace",e),e=e.replace(tt[je.COMPARATORTRIM],MI),ve("comparator trim",e),e=e.replace(tt[je.TILDETRIM],II),ve("tilde trim",e),e=e.replace(tt[je.CARETTRIM],TI),ve("caret trim",e);let a=e.split(" ").map(d=>LI(d,this.options)).join(" ").split(/\s+/).map(d=>KI(d,this.options));s&&(a=a.filter(d=>(ve("loose invalid filter",d,this.options),!!d.match(tt[je.COMPARATORLOOSE])))),ve("range list",a);let c=new Map,l=a.map(d=>new Ef(d,this.options));for(let d of l){if(Fv(d))return[d];c.set(d.value,d)}c.size>1&&c.has("")&&c.delete("");let u=[...c.values()];return qv.set(n,u),u}intersects(e,t){if(!(e instanceof r))throw new TypeError("a Range is required");return this.set.some(n=>Uv(n,t)&&e.set.some(i=>Uv(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 PI(e,this.options)}catch{return!1}for(let t=0;tr.value==="<0.0.0-0",DI=r=>r.value==="",Uv=(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},LI=(r,e)=>(r=r.replace(tt[je.BUILD],""),ve("comp",r,e),r=UI(r,e),ve("caret",r),r=qI(r,e),ve("tildes",r),r=VI(r,e),ve("xrange",r),r=HI(r,e),ve("stars",r),r),Ie=r=>!r||r.toLowerCase()==="x"||r==="*",jI=(r,e,t)=>Ie(r)&&!Ie(e)||Ie(e)&&t&&!Ie(t),qI=(r,e)=>r.trim().split(/\s+/).map(t=>FI(t,e)).join(" "),FI=(r,e)=>{let t=e.loose?tt[je.TILDELOOSE]:tt[je.TILDE],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{ve("tilde",r,i,s,o,a,c);let l;return Ie(s)?l="":Ie(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Ie(a)?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:c?(ve("replaceTilde pr",c),l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`):l=`>=${s}.${o}.${a} <${s}.${+o+1}.0-0`,ve("tilde return",l),l})},UI=(r,e)=>r.trim().split(/\s+/).map(t=>BI(t,e)).join(" "),BI=(r,e)=>{ve("caret",r,e);let t=e.loose?tt[je.CARETLOOSE]:tt[je.CARET],n=e.includePrerelease?"-0":"";return r.replace(t,(i,s,o,a,c)=>{ve("caret",r,i,s,o,a,c);let l;return Ie(s)?l="":Ie(o)?l=`>=${s}.0.0${n} <${+s+1}.0.0-0`:Ie(a)?s==="0"?l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`:l=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`:c?(ve("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`):(ve("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`),ve("caret return",l),l})},VI=(r,e)=>(ve("replaceXRanges",r,e),r.split(/\s+/).map(t=>zI(t,e)).join(" ")),zI=(r,e)=>{r=r.trim();let t=e.loose?tt[je.XRANGELOOSE]:tt[je.XRANGE];return r.replace(t,(n,i,s,o,a,c)=>{if(ve("xRange",r,n,i,s,o,a,c),jI(s,o,a))return r;let l=Ie(s),u=l||Ie(o),d=u||Ie(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`),ve("xRange return",n),n})},HI=(r,e)=>(ve("replaceStars",r,e),r.trim().replace(tt[je.STAR],"")),KI=(r,e)=>(ve("replaceGTE0",r,e),r.trim().replace(tt[e.includePrerelease?je.GTE0PRE:je.GTE0],"")),WI=r=>(e,t,n,i,s,o,a,c,l,u,d,f)=>(Ie(n)?t="":Ie(i)?t=`>=${n}.0.0${r?"-0":""}`:Ie(s)?t=`>=${n}.${i}.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()),GI=(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 Js=E((pj,Gv)=>{"use strict";var Ys=Symbol("SemVer ANY"),kf=class r{static get ANY(){return Ys}constructor(e,t){if(t=Vv(t),e instanceof r){if(e.loose===!!t.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),Af("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Ys?this.value="":this.value=this.operator+this.semver.version,Af("comp",this)}parse(e){let t=this.options.loose?zv[Hv.COMPARATORLOOSE]:zv[Hv.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 Kv(n[2],this.options.loose):this.semver=Ys}toString(){return this.value}test(e){if(Af("Comparator.test",e,this.options.loose),this.semver===Ys||e===Ys)return!0;if(typeof e=="string")try{e=new Kv(e,this.options)}catch{return!1}return xf(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 Wv(e.value,t).test(this.value):e.operator===""?e.value===""?!0:new Wv(this.value,t).test(e.semver):(t=Vv(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("=")||xf(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||xf(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Gv.exports=kf;var Vv=Ra(),{safeRe:zv,t:Hv}=Di(),xf=wf(),Af=Ws(),Kv=Le(),Wv=Nt()});var Xs=E((hj,Jv)=>{"use strict";var JI=Nt(),YI=(r,e,t)=>{try{e=new JI(e,t)}catch{return!1}return e.test(r)};Jv.exports=YI});var Xv=E((mj,Yv)=>{"use strict";var XI=Nt(),QI=(r,e)=>new XI(r,e).set.map(t=>t.map(n=>n.value).join(" ").trim().split(" "));Yv.exports=QI});var Zv=E((yj,Qv)=>{"use strict";var ZI=Le(),eT=Nt(),tT=(r,e,t)=>{let n=null,i=null,s=null;try{s=new eT(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===-1)&&(n=o,i=new ZI(n,t))}),n};Qv.exports=tT});var t_=E((gj,e_)=>{"use strict";var rT=Le(),nT=Nt(),iT=(r,e,t)=>{let n=null,i=null,s=null;try{s=new nT(e,t)}catch{return null}return r.forEach(o=>{s.test(o)&&(!n||i.compare(o)===1)&&(n=o,i=new rT(n,t))}),n};e_.exports=iT});var i_=E((bj,n_)=>{"use strict";var Pf=Le(),sT=Nt(),r_=Gs(),oT=(r,e)=>{r=new sT(r,e);let t=new Pf("0.0.0");if(r.test(t)||(t=new Pf("0.0.0-0"),r.test(t)))return t;t=null;for(let n=0;n{let a=new Pf(o.semver.version);switch(o.operator){case">":a.prerelease.length===0?a.patch++:a.prerelease.push(0),a.raw=a.format();case"":case">=":(!s||r_(a,s))&&(s=a);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${o.operator}`)}}),s&&(!t||r_(t,s))&&(t=s)}return t&&r.test(t)?t:null};n_.exports=oT});var o_=E((vj,s_)=>{"use strict";var aT=Nt(),cT=(r,e)=>{try{return new aT(r,e).range||"*"}catch{return null}};s_.exports=cT});var za=E((_j,d_)=>{"use strict";var lT=Le(),l_=Js(),{ANY:dT}=l_,uT=Nt(),fT=Xs(),a_=Gs(),c_=qa(),pT=Ua(),hT=Fa(),mT=(r,e,t,n)=>{r=new lT(r,n),e=new uT(e,n);let i,s,o,a,c;switch(t){case">":i=a_,s=pT,o=c_,a=">",c=">=";break;case"<":i=c_,s=hT,o=a_,a="<",c="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(fT(r,e,n))return!1;for(let l=0;l{p.semver===dT&&(p=new l_(">=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};d_.exports=mT});var f_=E((wj,u_)=>{"use strict";var yT=za(),gT=(r,e,t)=>yT(r,e,">",t);u_.exports=gT});var h_=E((Sj,p_)=>{"use strict";var bT=za(),vT=(r,e,t)=>bT(r,e,"<",t);p_.exports=vT});var g_=E(($j,y_)=>{"use strict";var m_=Nt(),_T=(r,e,t)=>(r=new m_(r,t),e=new m_(e,t),r.intersects(e,t));y_.exports=_T});var v_=E((Ej,b_)=>{"use strict";var wT=Xs(),ST=Ot();b_.exports=(r,e,t)=>{let n=[],i=null,s=null,o=r.sort((u,d)=>ST(u,d,t));for(let u of o)wT(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 __=Nt(),If=Js(),{ANY:Cf}=If,Mf=Xs(),Tf=Ot(),$T=(r,e,t={})=>{if(r===e)return!0;r=new __(r,t),e=new __(e,t);let n=!1;e:for(let i of r.set){for(let s of e.set){let o=xT(i,s,t);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},ET=[new If(">=0.0.0-0")],w_=[new If(">=0.0.0")],xT=(r,e,t)=>{if(r===e)return!0;if(r.length===1&&r[0].semver===Cf){if(e.length===1&&e[0].semver===Cf)return!0;t.includePrerelease?r=ET:r=w_}if(e.length===1&&e[0].semver===Cf){if(t.includePrerelease)return!0;e=w_}let n=new Set,i,s;for(let p of r)p.operator===">"||p.operator===">="?i=S_(i,p,t):p.operator==="<"||p.operator==="<="?s=$_(s,p,t):n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=Tf(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&&!Mf(p,String(i),t)||s&&!Mf(p,String(s),t))return null;for(let m of e)if(!Mf(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=S_(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=$_(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)},S_=(r,e,t)=>{if(!r)return e;let n=Tf(r.semver,e.semver,t);return n>0?r:n<0||e.operator===">"&&r.operator===">="?e:r},$_=(r,e,t)=>{if(!r)return e;let n=Tf(r.semver,e.semver,t);return n<0?r:n>0||e.operator==="<"&&r.operator==="<="?e:r};E_.exports=$T});var C_=E((Aj,P_)=>{"use strict";var Rf=Di(),A_=Ni(),AT=Le(),k_=yf(),kT=an(),PT=Xb(),CT=Zb(),MT=rv(),IT=sv(),TT=av(),RT=lv(),OT=uv(),NT=pv(),DT=Ot(),LT=gv(),jT=vv(),qT=ja(),FT=$v(),UT=xv(),BT=Gs(),VT=qa(),zT=vf(),HT=_f(),KT=Fa(),WT=Ua(),GT=wf(),JT=Ov(),YT=Dv(),XT=Js(),QT=Nt(),ZT=Xs(),eR=Xv(),tR=Zv(),rR=t_(),nR=i_(),iR=o_(),sR=za(),oR=f_(),aR=h_(),cR=g_(),lR=v_(),dR=x_();P_.exports={parse:kT,valid:PT,clean:CT,inc:MT,diff:IT,major:TT,minor:RT,patch:OT,prerelease:NT,compare:DT,rcompare:LT,compareLoose:jT,compareBuild:qT,sort:FT,rsort:UT,gt:BT,lt:VT,eq:zT,neq:HT,gte:KT,lte:WT,cmp:GT,coerce:JT,truncate:YT,Comparator:XT,Range:QT,satisfies:ZT,toComparators:eR,maxSatisfying:tR,minSatisfying:rR,minVersion:nR,validRange:iR,outside:sR,gtr:oR,ltr:aR,intersects:cR,simplifyRange:lR,subset:dR,SemVer:AT,re:Rf.re,src:Rf.src,tokens:Rf.t,SEMVER_SPEC_VERSION:A_.SEMVER_SPEC_VERSION,RELEASE_TYPES:A_.RELEASE_TYPES,compareIdentifiers:k_.compareIdentifiers,rcompareIdentifiers:k_.rcompareIdentifiers}});var OD={};ES(OD,{default:()=>wl});module.exports=xS(OD);var Cb=require("obsidian");var de=require("obsidian"),lb=An(Ou(),1),db=An(zu(),1),af=An(rf(),1),Ma=class extends Error{constructor(t,n){super(n);this.code=t;this.name="MdbasePathError"}},Rt={spec_version:"0.3.0",name:"My mdbase collection",description:"Typed markdown collection",settings:{types_folder:"_types",contracts_folder:"_contracts",explicit_type_keys:["type","types"],default_strict:!1,include_subfolders:!0,exclude:["_types",".obsidian",".git","node_modules",".trash",".mdbase"]}},zs=null;function CC(){return zs||(zs=new lb.Ajv2020({allErrors:!0,strict:!1,allowUnionTypes:!0}),(0,db.default)(zs),zs)}function G(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function Ke(r){return JSON.parse(JSON.stringify(r))}function MC(r){if(r===!0)return!0;if(r===!1)return!1;if(r==="warn")return"warn"}function nf(r){return Array.isArray(r)?`[${r.map(e=>nf(e)).join(",")}]`:G(r)?`{${Object.keys(r).sort().map(t=>`${JSON.stringify(t)}:${nf(r[t])}`).join(",")}}`:JSON.stringify(r)}function IC(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 TC(r){let e=new Map,t=new Set,n=i=>{let s=e.get(i);if(s)return s;let o=r.get(i);if(!o)return null;if(t.has(i)){let l={...o,fields:Ke(o.fields)};return e.set(i,l),l}t.add(i);let a=o.extends?n(o.extends):null;t.delete(i);let c={...o,fields:a?{...Ke(a.fields),...Ke(o.fields)}:Ke(o.fields),display_name_key:o.display_name_key??a?.display_name_key,path_pattern:o.path_pattern??a?.path_pattern,filename_pattern:o.filename_pattern??a?.filename_pattern,strict:o.strict!==void 0?o.strict:a?.strict,match:o.match??a?.match};return e.set(i,c),c};for(let i of r.keys())n(i);return e}function ub(r){let e=(0,de.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 pb(r){return/^[a-z][a-z0-9+.-]*:\/\//i.test(r)}function hb(r,e,t){let n=fb(t);if(!n||pb(n))return null;let i=new Set,s=(0,de.normalizePath)(n);i.add(s),s.endsWith(".md")||i.add(`${s}.md`);let o=ub(e);if(o){let c=(0,de.normalizePath)(`${o}/${n}`);i.add(c),c.endsWith(".md")||i.add(`${c}.md`)}for(let c of i){let l=r.getAbstractFileByPath(c);if(l instanceof de.TFile)return l}let a=n.replace(/\.md$/i,"");return r.getMarkdownFiles().find(c=>c.basename===a)??null}function RC(r,e,t){return pb(fb(t))||hb(r,e,t)!==null}function et(r){let e=(0,de.getFrontMatterInfo)(r);if(!e.exists)return{hasFrontmatter:!1,frontmatter:{},body:r};try{let t=e.frontmatter,n=(0,de.parseYaml)(t);return n==null&&t.trim()!==""?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:"Frontmatter must be a YAML object"}:n!=null&&!G(n)?{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:"Frontmatter must be a YAML object"}:{hasFrontmatter:!0,frontmatter:n??{},body:r.slice(e.contentStart)}}catch(t){return{hasFrontmatter:!0,frontmatter:{},body:r.slice(e.contentStart),error:t instanceof Error?t.message:String(t)}}}function Vt(r,e=""){if(Object.keys(r).length===0)return e;let t=(0,de.stringifyYaml)(r).trimEnd(),n=e.replace(/^\n+/,"");return`--- ${t} --- -${n}`}async function Ei(r){let e=r.getAbstractFileByPath("mdbase.yaml");if(!(e instanceof de.TFile))return null;try{let t=await r.cachedRead(e),n=(0,de.parseYaml)(t);if(!G(n))return null;let i=G(n.settings)?n.settings:{},s=G(n.runtime)?n.runtime:void 0;return{spec_version:typeof n.spec_version=="string"?n.spec_version:Rt.spec_version,name:typeof n.name=="string"?n.name:Rt.name,description:typeof n.description=="string"?n.description:Rt.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:Rt.settings.types_folder,contracts_folder:typeof i.contracts_folder=="string"?i.contracts_folder:Rt.settings.contracts_folder,explicit_type_keys:Array.isArray(i.explicit_type_keys)?i.explicit_type_keys.filter(o=>typeof o=="string"):[...Rt.settings.explicit_type_keys],default_strict:typeof i.default_strict=="boolean"?i.default_strict:Rt.settings.default_strict,include_subfolders:typeof i.include_subfolders=="boolean"?i.include_subfolders:Rt.settings.include_subfolders,exclude:Array.isArray(i.exclude)?i.exclude.filter(o=>typeof o=="string"):[...Rt.settings.exclude]}}}catch{return null}}async function H_(r){let e=[];if(!(r.getAbstractFileByPath("mdbase.yaml")instanceof de.TFile)){let c=(0,de.stringifyYaml)(Rt).trimEnd()+` -`;await r.create("mdbase.yaml",c),e.push("mdbase.yaml")}let n=await Ei(r)??Rt,i=n.settings.types_folder;await r.adapter.exists(i)||(await r.createFolder(i),e.push(i));let o=(0,de.normalizePath)(`${i}/note.md`);if(!await r.adapter.exists(o)){let c=RI("note",void 0,n.spec_version);await r.create(o,c),e.push(o)}return{created:e}}function K_(r,e){let t=G(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=ze(t.enum)):n==="array"?(i.type="list",i.items=K_(t.items,!1)):n==="object"?(i.type="object",i.fields=On(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=ze(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 On(r){let e=G(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,K_(i,t.has(n))]))}function W_(r,e){let t={...ze(e)},n=r.type??"string",i=()=>{delete t.properties,delete t.required,delete t.additionalProperties},s=()=>{delete t.items};if(n==="enum")delete t.type,t.enum=ze(r.values??[]),delete t.format,i(),s();else if(n==="list")t.type="array",delete t.enum,delete t.format,i(),t.items=W_(r.items??{type:"any"},G(t.items)?t.items:{});else if(n==="object"){t.type="object",delete t.enum,delete t.format,s();let c=Bs(r.fields??{},G(t)?t:{},!1);t.properties=c.properties,c.required?t.required=c.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=ze(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 Bs(r,e={},t=!1){let n=G(e.properties)?e.properties:{},i=Object.create(null),s=[];for(let[a,c]of Object.entries(r))i[a]=W_(c,G(n[a])?n[a]:{}),c.required===!0&&s.push(a);let o={...ze(e),type:"object",properties:i,additionalProperties:!t};return s.length>0?o.required=s:delete o.required,o}function hI(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(G(t)&&i in t)t=t[i];else return}return t}async function G_(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=U_(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,de.normalizePath)(o.join("/")),c=r.getAbstractFileByPath(a);if(!(c instanceof de.TFile))return null;try{let l=JSON.parse(await r.cachedRead(c)),u=hI(l,i);return G(u)?u:null}catch{return null}}async function J_(r,e){let t=new Map,n=`${(0,de.normalizePath)(e.settings.types_folder)}/`;for(let i of r.getMarkdownFiles()){if(!i.path.startsWith(n))continue;let s=await r.cachedRead(i),o=dt(s);if(!o.hasFrontmatter||o.error)continue;let a=o.frontmatter;if(e.spec_version.startsWith("0.3.")){if(a.kind!=="mdbase.type"||typeof a.name!="string"||!G(a.schema))continue;let u=a.schema,d=G(u.value)?u.value:null;if(!d&&typeof u.ref=="string"&&(d=await G_(r,i.path,u.ref)),!d)continue;let f=G(a.collection)?ze(a.collection):void 0,p=On(d);for(let m of f?.unique??[])typeof m.field=="string"&&p[m.field]&&(p[m.field].unique=!0,p[m.field].unique_scope=m.scope);for(let[m,h]of Object.entries(f?.links??{}))p[m]&&(p[m].target=h.target_type,p[m].validate_exists=h.validate_exists);t.set(a.name,{name:a.name,version:typeof a.version=="number"?a.version:void 0,description:typeof a.description=="string"?a.description:void 0,display_name_key:f?.display?.name_field,path_pattern:f?.path?.pattern,strict:d.additionalProperties===!1,match:G(a.match)?a.match:void 0,fields:p,filePath:i.path,specProfile:"v0.3",schema:ze(d),collection:f,originalFrontmatter:ze(a)});continue}if(!G(a.fields))continue;let c=typeof a.name=="string"&&a.name.trim().length>0?a.name.trim():i.basename,l={};for(let[u,d]of Object.entries(a.fields))G(d)&&(l[u]=d);t.set(c,{name:c,extends:typeof a.extends=="string"?a.extends:void 0,display_name_key:typeof a.display_name_key=="string"?a.display_name_key:void 0,path_pattern:typeof a.path_pattern=="string"?a.path_pattern:void 0,filename_pattern:typeof a.filename_pattern=="string"?a.filename_pattern:void 0,strict:dI(a.strict),match:G(a.match)?a.match:void 0,fields:l,filePath:i.path,specProfile:"v0.2",originalFrontmatter:ze(a)})}return fI(t)}async function Y_(r,e){let t=new Map,n=`${(0,de.normalizePath)(e.settings.contracts_folder||"_contracts")}/`;for(let i of r.getMarkdownFiles()){if(!i.path.startsWith(n))continue;let s=dt(await r.cachedRead(i));if(!s.hasFrontmatter||s.error)continue;let o=s.frontmatter;if(o.kind!=="mdbase.contract"||o.contract_type!=="record"||typeof o.id!="string"||typeof o.version!="string")continue;let a=G(o.record_schema)?o.record_schema:{},c=G(o.binding_schema)?o.binding_schema:void 0,l=await L_(r,i.path,a);if(!l)continue;let u=c?await L_(r,i.path,c):null,d=`${o.id}@${o.version}`;t.set(d,{contract_type:"record",id:o.id,version:o.version,digest:typeof o.digest=="string"?o.digest:"",schema:l,...u?{binding_schema:u}:{},implementations:[]})}return t}async function L_(r,e,t){return G(t.value)?ze(t.value):typeof t.ref!="string"?null:G_(r,e,t.ref)}function mI(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 Sf(r,e){return r.replace(/\{([^}]+)\}/g,(t,n)=>{let i=e[n];return i==null?"":Array.isArray(i)?i.filter(s=>["string","number","boolean"].includes(typeof s)).map(String).join("-"):typeof i=="string"?i:typeof i=="number"||typeof i=="boolean"?String(i):""})}function Rn(r){let e=r.replace(/\\/g,"/");if(!e||e.startsWith("/")||/^[A-Za-z]:\//.test(e)||e.includes("\0"))throw new La("invalid_path",`Invalid collection-relative path: ${r}`);let t=e.split("/");if(t.includes(".."))throw new La("path_traversal",`Path escapes the collection root: ${r}`);return(0,de.normalizePath)(t.filter(n=>n&&n!==".").join("/"))}function yI(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 gI(r,e){if(r.path_pattern){let t=(0,de.normalizePath)(Sf(r.path_pattern,e));if(t.endsWith(".md")){let n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}return t.replace(/\/+$/,"")}return r.match?.path_glob?yI(r.match.path_glob):""}function bI(r,e){let t=r.display_name_key??"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 o=(0,de.normalizePath)(Sf(r.filename_pattern,e)),c=(o.split("/").pop()??o).replace(/\.md$/i,"").trim();if(c.length>0)return`${j_(c)}.md`}return`${j_(s)}.md`}function $i(r){return Array.isArray(r)?`[${r.map($i).join(",")}]`:G(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${$i(r[e])}`).join(",")}}`:JSON.stringify(r)}function _I(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(!G(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 Na(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 vI(r,e,t,n){let i=(s,o)=>$i(s)===$i(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 Na(r.value,t,(s,o)=>s>o);case"gte":return Na(r.value,t,(s,o)=>s>=o);case"lt":return Na(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"&&typeof t=="string"&&r.value.startsWith(t);case"endsWith":case"ends_with":return typeof r.value=="string"&&typeof t=="string"&&r.value.endsWith(t);case"matches":try{return typeof r.value=="string"&&typeof t=="string"&&new RegExp(t.replace(/\\\\/g,"\\")).test(r.value)}catch{return!1}default:return!1}}function Da(r,e,t){if("and"in r)return Array.isArray(r.and)&&r.and.every(n=>G(n)&&Da(n,e,t));if("or"in r)return Array.isArray(r.or)&&r.or.some(n=>G(n)&&Da(n,e,t));if("not"in r)return G(r.not)&&!Da(r.not,e,t);for(let[n,i]of Object.entries(r)){let s=_I(e,n);if(!G(i)){if(!s.present||$i(s.value)!==$i(i))return!1;continue}for(let[o,a]of Object.entries(i))if(!vI(s,o,a,t))return!1}return!0}function rn(r,e,t,n){let i=mI(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,wf.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&&G(c.where)&&(l=Da(c.where,e,t.spec_version)),l&&typeof c.where=="string"&&(l=!1),l&&s.push(o)}return s}function X_(r){return r==null||typeof r=="string"&&r.trim().length===0}function wI(r){return/^\d{4}-\d{2}-\d{2}$/.test(r)}function SI(r){return/^\d{2}:\d{2}(:\d{2})?$/.test(r)}function $I(r){return typeof r=="string"||Array.isArray(r)?r.length:null}function Te(r,e,t,n,i,s){r.push({path:e,code:n,message:i,severity:t,field:s})}function It(r,e,t,n,i){typeof r=="number"&&(typeof e.min=="number"&&r= ${e.min}`,t),typeof e.max=="number"&&r>e.max&&Te(i,n,"error","above_max",`Field '${t}' must be <= ${e.max}`,t));let s=$I(r);if(s!=null&&(typeof e.min_length=="number"&&s= ${e.min_length}`,t),typeof e.max_length=="number"&&s>e.max_length&&Te(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)||Te(i,n,"error","pattern_mismatch",`Field '${t}' must match pattern /${e.pattern}/`,t)}catch(o){Te(i,n,"warn","invalid_pattern",`Field '${t}' has invalid regex pattern: ${o instanceof Error?o.message:String(o)}`,t)}}function _f(r,e,t,n,i,s){let o=e.type??"any";if(r==null)return;e.deprecated===!0&&Te(i,n,"warn","deprecated_field",`Field '${t}' is marked deprecated`,t);let a=c=>{Te(i,n,"error","invalid_type",`Field '${t}' expected ${c}`,t)};switch(o){case"any":It(r,e,t,n,i);return;case"string":if(typeof r!="string"){a("a string");return}It(r,e,t,n,i);return;case"integer":if(typeof r!="number"||!Number.isInteger(r)){a("an integer");return}It(r,e,t,n,i);return;case"number":if(typeof r!="number"||Number.isNaN(r)){a("a number");return}It(r,e,t,n,i);return;case"boolean":typeof r!="boolean"&&a("a boolean");return;case"date":if(typeof r!="string"||!wI(r)){a("a date (YYYY-MM-DD)");return}It(r,e,t,n,i);return;case"datetime":if(typeof r!="string"||Number.isNaN(Date.parse(r))){a("a datetime string");return}It(r,e,t,n,i);return;case"time":if(typeof r!="string"||!SI(r)){a("a time string (HH:MM)");return}It(r,e,t,n,i);return;case"enum":{let c=Array.isArray(e.values)?e.values:[];if(!c.includes(r)){Te(i,n,"error","invalid_enum",`Field '${t}' must be one of: ${c.map(l=>String(l)).join(", ")}`,t);return}It(r,e,t,n,i);return}case"list":{if(!Array.isArray(r)){a("a list");return}It(r,e,t,n,i),e.items&&r.forEach((c,l)=>{_f(c,e.items,`${t}[${l}]`,n,i,s)});return}case"object":{if(!G(r)){a("an object");return}if(e.fields&&G(e.fields))for(let[c,l]of Object.entries(e.fields)){if(!G(l))continue;let u=l,d=`${t}.${c}`,f=r[c];if(u.required&&X_(f)){Te(i,n,"error","missing_required",`Missing required field '${d}'`,d);continue}_f(f,u,d,n,i,s)}return}case"link":{if(typeof r!="string"&&!G(r)){a("a link string");return}if(e.validate_exists===!0&&s){let c=typeof r=="string"?r:typeof r.path=="string"?r.path:typeof r.file=="string"?r.file:"";(!c||!pI(s,n,c))&&Te(i,n,"error","missing_link_target",`Field '${t}' references a missing note`,t)}return}case"tags":if(typeof r=="string"){It(r,e,t,n,i);return}if(Array.isArray(r)&&r.every(c=>typeof c=="string")){It(r,e,t,n,i);return}a("a tag string or list of strings");return;default:It(r,e,t,n,i);return}}function EI(r){return r.replace(/^\//,"").split("/").filter(Boolean).map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")||void 0}function AI(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function xI(r,e,t){let n=r.params,i=EI(r.instancePath),s=typeof n.missingProperty=="string"?n.missingProperty:typeof n.additionalProperty=="string"?n.additionalProperty:void 0,o=i&&s?`${i}.${s}`:s??i,a=r.keyword==="format"?"format_invalid":`schema_${AI(r.keyword)}`;return{path:e,code:a,message:`JSON Schema ${r.keyword} failed for type '${t}': ${r.message??"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 vf(r){if(Array.isArray(r)){for(let e of r){let t=vf(e);if(t)return t}return null}if(!G(r))return null;if(typeof r.$ref=="string"&&!r.$ref.startsWith("#"))return r.$ref;for(let e of Object.values(r)){let t=vf(e);if(t)return t}return null}function kI(r,e,t,n){if(!t.schema)return;let i=vf(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 s=lI().compile(t.schema);if(s(e))return;for(let o of s.errors??[])n.push(xI(o,r,t.name))}catch(s){n.push({path:r,code:"invalid_embedded_schema",message:s instanceof Error?s.message:String(s),severity:"error",type:t.name})}}async function PI(r,e,t,n,i,s,o){for(let[a,c]of Object.entries(n.collection?.links??{})){let l=t[a],u=Array.isArray(l)?l:[l];for(let d of u){if(d==null||typeof d!="string")continue;let f=z_(r,e,d);if(!f&&c.validate_exists===!0){Te(o,e,"error","link_not_found",`Field '${a}' references a missing note`,a);continue}if(f&&c.target_type&&c.target_type!=="any"){let p=dt(await r.cachedRead(f));rn(f.path,p.frontmatter,i,s).includes(c.target_type)||Te(o,e,"error","link_wrong_type",`Field '${a}' must reference type '${c.target_type}'`,a)}}}}function CI(r,e,t,n,i){if(t.specProfile==="v0.3"){kI(r,e,t,n);return}for(let[s,o]of Object.entries(t.fields)){if(!G(o))continue;let a=o,c=e[s];if(a.required&&X_(c)){Te(n,r,"error","missing_required",`Missing required field '${s}' for type '${t.name}'`,s);continue}_f(c,a,s,r,n,i)}}function MI(r){let e=new Set;for(let t of r)for(let n of Object.keys(t.fields))e.add(n);return e}function TI(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 Ai(r,e){let t=(0,de.normalizePath)(r),n=(0,de.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,wf.default)(i,{dot:!0,matchBase:!i.includes("/")})(t)||!i.includes("*")&&!i.includes("?")&&!i.includes("/")&&t.startsWith(`${i}/`))return!0;return!1}async function $f(r,e,t,n){if(Ai(e.path,t))return[];let i=[],s=await r.cachedRead(e),o=dt(s);if(o.error)return Te(i,e.path,"error","invalid_frontmatter",o.error),i;let a=o.frontmatter,c=rn(e.path,a,t,n);if(c.length===0)return Te(i,e.path,"warn","no_matching_type","No type could be resolved for this file"),i;let l=c.map(f=>n.get(f)).filter(f=>!!f),u=c.filter(f=>!n.has(f));if(u.length>0&&Te(i,e.path,"error","unknown_type",`Resolved types are not defined: ${u.join(", ")}`),l.length===0)return i;for(let f of l)CI(e.path,a,f,i,r),f.specProfile==="v0.3"&&await PI(r,e.path,a,f,t,n,i);let d=t.spec_version.startsWith("0.3.")?!1:TI(l,t);if(d!==!1){let f=MI(l),p=new Set(t.settings.explicit_type_keys),m=d===!0?"error":"warn";for(let h of Object.keys(a))f.has(h)||p.has(h)||Te(i,e.path,m,"unknown_field",`Unknown field '${h}' in strict mode`,h)}return i}async function II(r,e,t){let n=new Map;for(let s of r.getMarkdownFiles()){if(Ai(s.path,e))continue;let o=await r.cachedRead(s),a=dt(o);if(a.error)continue;let l=rn(s.path,a.frontmatter,e,t).map(u=>t.get(u)).filter(u=>!!u);for(let u of l)for(let[d,f]of Object.entries(u.fields)){if(!G(f))continue;let p=f;if(p.unique!==!0)continue;let m=a.frontmatter[d];if(m==null)continue;let h=bf(m),y=p.unique_scope==="collection"?"collection":"type",g=`${y==="collection"?"*":u.name}::${d}::${h}`,v=n.get(g)??[];v.some(_=>_.path===s.path)||(v.push({path:s.path,typeName:u.name,fieldName:d,scope:y,specProfile:u.specProfile,value:m,fingerprint:h}),n.set(g,v))}}let i=[];for(let s of n.values())if(!(s.length<=1))for(let o of s){let a=s.filter(c=>c.path!==o.path).map(c=>c.path).join(", ");Te(i,o.path,"error",o.specProfile==="v0.3"?"duplicate_value":"duplicate_unique",o.scope==="collection"?`Field '${o.fieldName}' must be unique across the collection. Duplicate found in: ${a}`:`Field '${o.fieldName}' must be unique for type '${o.typeName}'. Duplicate found in: ${a}`,o.fieldName)}return i}async function Q_(r,e,t){let n=[];for(let s of r.getMarkdownFiles()){if(Ai(s.path,e))continue;let o=await $f(r,s,e,t);n.push(...o)}let i=await II(r,e,t);return n.push(...i),n}function RI(r,e,t=Rt.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()}),`${bt(i,`# ${r} +${n}`}async function Ii(r){let e=r.getAbstractFileByPath("mdbase.yaml");if(!(e instanceof de.TFile))return null;try{let t=await r.cachedRead(e),n=(0,de.parseYaml)(t);if(!G(n))return null;let i=G(n.settings)?n.settings:{},s=G(n.runtime)?n.runtime:void 0;return{spec_version:typeof n.spec_version=="string"?n.spec_version:Rt.spec_version,name:typeof n.name=="string"?n.name:Rt.name,description:typeof n.description=="string"?n.description:Rt.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:Rt.settings.types_folder,contracts_folder:typeof i.contracts_folder=="string"?i.contracts_folder:Rt.settings.contracts_folder,explicit_type_keys:Array.isArray(i.explicit_type_keys)?i.explicit_type_keys.filter(o=>typeof o=="string"):[...Rt.settings.explicit_type_keys],default_strict:typeof i.default_strict=="boolean"?i.default_strict:Rt.settings.default_strict,include_subfolders:typeof i.include_subfolders=="boolean"?i.include_subfolders:Rt.settings.include_subfolders,exclude:Array.isArray(i.exclude)?i.exclude.filter(o=>typeof o=="string"):[...Rt.settings.exclude]}}}catch{return null}}async function mb(r){let e=[];if(!(r.getAbstractFileByPath("mdbase.yaml")instanceof de.TFile)){let c=(0,de.stringifyYaml)(Rt).trimEnd()+` +`;await r.create("mdbase.yaml",c),e.push("mdbase.yaml")}let n=await Ii(r)??Rt,i=n.settings.types_folder;await r.adapter.exists(i)||(await r.createFolder(i),e.push(i));let o=(0,de.normalizePath)(`${i}/note.md`);if(!await r.adapter.exists(o)){let c=ZC("note",void 0,n.spec_version);await r.create(o,c),e.push(o)}return{created:e}}function yb(r,e){let t=G(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=Ke(t.enum)):n==="array"?(i.type="list",i.items=yb(t.items,!1)):n==="object"?(i.type="object",i.fields=Un(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=Ke(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 Un(r){let e=G(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,yb(i,t.has(n))]))}function gb(r,e){let t={...Ke(e)},n=r.type??"string",i=()=>{delete t.properties,delete t.required,delete t.additionalProperties},s=()=>{delete t.items};if(n==="enum")delete t.type,t.enum=Ke(r.values??[]),delete t.format,i(),s();else if(n==="list")t.type="array",delete t.enum,delete t.format,i(),t.items=gb(r.items??{type:"any"},G(t.items)?t.items:{});else if(n==="object"){t.type="object",delete t.enum,delete t.format,s();let c=Hs(r.fields??{},G(t)?t:{},!1);t.properties=c.properties,c.required?t.required=c.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=Ke(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 Hs(r,e={},t=!1){let n=G(e.properties)?e.properties:{},i=Object.create(null),s=[];for(let[a,c]of Object.entries(r))i[a]=gb(c,G(n[a])?n[a]:{}),c.required===!0&&s.push(a);let o={...Ke(e),type:"object",properties:i,additionalProperties:!t};return s.length>0?o.required=s:delete o.required,o}function OC(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(G(t)&&i in t)t=t[i];else return}return t}async function bb(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=ub(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,de.normalizePath)(o.join("/")),c=r.getAbstractFileByPath(a);if(!(c instanceof de.TFile))return null;try{let l=JSON.parse(await r.cachedRead(c)),u=OC(l,i);return G(u)?u:null}catch{return null}}async function vb(r,e){let t=new Map,n=`${(0,de.normalizePath)(e.settings.types_folder)}/`;for(let i of r.getMarkdownFiles()){if(!i.path.startsWith(n))continue;let s=await r.cachedRead(i),o=et(s);if(!o.hasFrontmatter||o.error)continue;let a=o.frontmatter;if(e.spec_version.startsWith("0.3.")){if(a.kind!=="mdbase.type"||typeof a.name!="string"||!G(a.schema))continue;let u=a.schema,d=G(u.value)?u.value:null;if(!d&&typeof u.ref=="string"&&(d=await bb(r,i.path,u.ref)),!d)continue;let f=G(a.collection)?Ke(a.collection):void 0,p=Un(d);for(let m of f?.unique??[])typeof m.field=="string"&&p[m.field]&&(p[m.field].unique=!0,p[m.field].unique_scope=m.scope);for(let[m,h]of Object.entries(f?.links??{}))p[m]&&(p[m].target=h.target_type,p[m].validate_exists=h.validate_exists);t.set(a.name,{name:a.name,version:typeof a.version=="number"?a.version:void 0,description:typeof a.description=="string"?a.description:void 0,display_name_key:f?.display?.name_field,path_pattern:f?.path?.pattern,strict:d.additionalProperties===!1,match:G(a.match)?a.match:void 0,fields:p,filePath:i.path,specProfile:"v0.3",schema:Ke(d),collection:f,originalFrontmatter:Ke(a)});continue}if(!G(a.fields))continue;let c=typeof a.name=="string"&&a.name.trim().length>0?a.name.trim():i.basename,l={};for(let[u,d]of Object.entries(a.fields))G(d)&&(l[u]=d);t.set(c,{name:c,extends:typeof a.extends=="string"?a.extends:void 0,display_name_key:typeof a.display_name_key=="string"?a.display_name_key:void 0,path_pattern:typeof a.path_pattern=="string"?a.path_pattern:void 0,filename_pattern:typeof a.filename_pattern=="string"?a.filename_pattern:void 0,strict:MC(a.strict),match:G(a.match)?a.match:void 0,fields:l,filePath:i.path,specProfile:"v0.2",originalFrontmatter:Ke(a)})}return TC(t)}async function _b(r,e){let t=new Map,n=`${(0,de.normalizePath)(e.settings.contracts_folder||"_contracts")}/`;for(let i of r.getMarkdownFiles()){if(!i.path.startsWith(n))continue;let s=et(await r.cachedRead(i));if(!s.hasFrontmatter||s.error)continue;let o=s.frontmatter;if(o.kind!=="mdbase.contract"||o.contract_type!=="record"||typeof o.id!="string"||typeof o.version!="string")continue;let a=G(o.record_schema)?o.record_schema:{},c=G(o.binding_schema)?o.binding_schema:void 0,l=await ab(r,i.path,a);if(!l)continue;let u=c?await ab(r,i.path,c):null,d=`${o.id}@${o.version}`;t.set(d,{contract_type:"record",id:o.id,version:o.version,digest:typeof o.digest=="string"?o.digest:"",schema:l,...u?{binding_schema:u}:{},implementations:[]})}return t}async function ab(r,e,t){return G(t.value)?Ke(t.value):typeof t.ref!="string"?null:bb(r,e,t.ref)}function NC(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 cf(r,e){return r.replace(/\{([^}]+)\}/g,(t,n)=>{let i=e[n];return i==null?"":Array.isArray(i)?i.filter(s=>["string","number","boolean"].includes(typeof s)).map(String).join("-"):typeof i=="string"?i:typeof i=="number"||typeof i=="boolean"?String(i):""})}function Fn(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,de.normalizePath)(t.filter(n=>n&&n!==".").join("/"))}function DC(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 LC(r,e){if(r.path_pattern){let t=(0,de.normalizePath)(cf(r.path_pattern,e));if(t.endsWith(".md")){let n=t.lastIndexOf("/");return n>=0?t.slice(0,n):""}return t.replace(/\/+$/,"")}return r.match?.path_glob?DC(r.match.path_glob):""}function jC(r,e){let t=r.display_name_key??"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 o=(0,de.normalizePath)(cf(r.filename_pattern,e)),c=(o.split("/").pop()??o).replace(/\.md$/i,"").trim();if(c.length>0)return`${cb(c)}.md`}return`${cb(s)}.md`}function Mi(r){return Array.isArray(r)?`[${r.map(Mi).join(",")}]`:G(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Mi(r[e])}`).join(",")}}`:JSON.stringify(r)}function qC(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(!G(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 FC(r,e,t,n){let i=(s,o)=>Mi(s)===Mi(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"&&typeof t=="string"&&r.value.startsWith(t);case"endsWith":case"ends_with":return typeof r.value=="string"&&typeof t=="string"&&r.value.endsWith(t);case"matches":try{return typeof r.value=="string"&&typeof t=="string"&&new RegExp(t.replace(/\\\\/g,"\\")).test(r.value)}catch{return!1}default:return!1}}function Ca(r,e,t){if("and"in r)return Array.isArray(r.and)&&r.and.every(n=>G(n)&&Ca(n,e,t));if("or"in r)return Array.isArray(r.or)&&r.or.some(n=>G(n)&&Ca(n,e,t));if("not"in r)return G(r.not)&&!Ca(r.not,e,t);for(let[n,i]of Object.entries(r)){let s=qC(e,n);if(!G(i)){if(!s.present||Mi(s.value)!==Mi(i))return!1;continue}for(let[o,a]of Object.entries(i))if(!FC(s,o,a,t))return!1}return!0}function sn(r,e,t,n){let i=NC(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,af.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&&G(c.where)&&(l=Ca(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 UC(r){return/^\d{4}-\d{2}-\d{2}$/.test(r)}function BC(r){return/^\d{2}:\d{2}(:\d{2})?$/.test(r)}function VC(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 Tt(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=VC(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 sf(r,e,t,n,i,s){let o=e.type??"any";if(r==null)return;e.deprecated===!0&&Me(i,n,"warn","deprecated_field",`Field '${t}' is marked deprecated`,t);let a=c=>{Me(i,n,"error","invalid_type",`Field '${t}' expected ${c}`,t)};switch(o){case"any":Tt(r,e,t,n,i);return;case"string":if(typeof r!="string"){a("a string");return}Tt(r,e,t,n,i);return;case"integer":if(typeof r!="number"||!Number.isInteger(r)){a("an integer");return}Tt(r,e,t,n,i);return;case"number":if(typeof r!="number"||Number.isNaN(r)){a("a number");return}Tt(r,e,t,n,i);return;case"boolean":typeof r!="boolean"&&a("a boolean");return;case"date":if(typeof r!="string"||!UC(r)){a("a date (YYYY-MM-DD)");return}Tt(r,e,t,n,i);return;case"datetime":if(typeof r!="string"||Number.isNaN(Date.parse(r))){a("a datetime string");return}Tt(r,e,t,n,i);return;case"time":if(typeof r!="string"||!BC(r)){a("a time string (HH:MM)");return}Tt(r,e,t,n,i);return;case"enum":{let c=Array.isArray(e.values)?e.values:[];if(!c.includes(r)){Me(i,n,"error","invalid_enum",`Field '${t}' must be one of: ${c.map(l=>String(l)).join(", ")}`,t);return}Tt(r,e,t,n,i);return}case"list":{if(!Array.isArray(r)){a("a list");return}Tt(r,e,t,n,i),e.items&&r.forEach((c,l)=>{sf(c,e.items,`${t}[${l}]`,n,i,s)});return}case"object":{if(!G(r)){a("an object");return}if(e.fields&&G(e.fields))for(let[c,l]of Object.entries(e.fields)){if(!G(l))continue;let u=l,d=`${t}.${c}`,f=r[c];if(u.required&&wb(f)){Me(i,n,"error","missing_required",`Missing required field '${d}'`,d);continue}sf(f,u,d,n,i,s)}return}case"link":{if(typeof r!="string"&&!G(r)){a("a link string");return}if(e.validate_exists===!0&&s){let c=typeof r=="string"?r:typeof r.path=="string"?r.path:typeof r.file=="string"?r.file:"";(!c||!RC(s,n,c))&&Me(i,n,"error","missing_link_target",`Field '${t}' references a missing note`,t)}return}case"tags":if(typeof r=="string"){Tt(r,e,t,n,i);return}if(Array.isArray(r)&&r.every(c=>typeof c=="string")){Tt(r,e,t,n,i);return}a("a tag string or list of strings");return;default:Tt(r,e,t,n,i);return}}function zC(r){return r.replace(/^\//,"").split("/").filter(Boolean).map(t=>t.replace(/~1/g,"/").replace(/~0/g,"~")).join(".")||void 0}function HC(r){return r.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function KC(r,e,t){let n=r.params,i=zC(r.instancePath),s=typeof n.missingProperty=="string"?n.missingProperty:typeof n.additionalProperty=="string"?n.additionalProperty:void 0,o=i&&s?`${i}.${s}`:s??i,a=r.keyword==="format"?"format_invalid":`schema_${HC(r.keyword)}`;return{path:e,code:a,message:`JSON Schema ${r.keyword} failed for type '${t}': ${r.message??"invalid value"}`,severity:"error",field:o,type:t,schema_location:`embedded://type/schema#${r.schemaPath}`,details:{instance_path:r.instancePath,schema_path:r.schemaPath,...s===void 0?{}:{property:s}}}}function of(r){if(Array.isArray(r)){for(let e of r){let t=of(e);if(t)return t}return null}if(!G(r))return null;if(typeof r.$ref=="string"&&!r.$ref.startsWith("#"))return r.$ref;for(let e of Object.values(r)){let t=of(e);if(t)return t}return null}function WC(r,e,t,n){if(!t.schema)return;let i=of(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 s=CC().compile(t.schema);if(s(e))return;for(let o of s.errors??[])n.push(KC(o,r,t.name))}catch(s){n.push({path:r,code:"invalid_embedded_schema",message:s instanceof Error?s.message:String(s),severity:"error",type:t.name})}}async function GC(r,e,t,n,i,s,o){for(let[a,c]of Object.entries(n.collection?.links??{})){let l=t[a],u=Array.isArray(l)?l:[l];for(let d of u){if(d==null||typeof d!="string")continue;let f=hb(r,e,d);if(!f&&c.validate_exists===!0){Me(o,e,"error","link_not_found",`Field '${a}' references a missing note`,a);continue}if(f&&c.target_type&&c.target_type!=="any"){let p=et(await r.cachedRead(f));sn(f.path,p.frontmatter,i,s).includes(c.target_type)||Me(o,e,"error","link_wrong_type",`Field '${a}' must reference type '${c.target_type}'`,a)}}}}function JC(r,e,t,n,i){if(t.specProfile==="v0.3"){WC(r,e,t,n);return}for(let[s,o]of Object.entries(t.fields)){if(!G(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}sf(c,a,s,r,n,i)}}function YC(r){let e=new Set;for(let t of r)for(let n of Object.keys(t.fields))e.add(n);return e}function XC(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 Ti(r,e){let t=(0,de.normalizePath)(r),n=(0,de.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,af.default)(i,{dot:!0,matchBase:!i.includes("/")})(t)||!i.includes("*")&&!i.includes("?")&&!i.includes("/")&&t.startsWith(`${i}/`))return!0;return!1}async function lf(r,e,t,n){if(Ti(e.path,t))return[];let i=[],s=await r.cachedRead(e),o=et(s);if(o.error)return Me(i,e.path,"error","invalid_frontmatter",o.error),i;let a=o.frontmatter,c=sn(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(f=>n.get(f)).filter(f=>!!f),u=c.filter(f=>!n.has(f));if(u.length>0&&Me(i,e.path,"error","unknown_type",`Resolved types are not defined: ${u.join(", ")}`),l.length===0)return i;for(let f of l)JC(e.path,a,f,i,r),f.specProfile==="v0.3"&&await GC(r,e.path,a,f,t,n,i);let d=t.spec_version.startsWith("0.3.")?!1:XC(l,t);if(d!==!1){let f=YC(l),p=new Set(t.settings.explicit_type_keys),m=d===!0?"error":"warn";for(let h of Object.keys(a))f.has(h)||p.has(h)||Me(i,e.path,m,"unknown_field",`Unknown field '${h}' in strict mode`,h)}return i}async function QC(r,e,t){let n=new Map;for(let s of r.getMarkdownFiles()){if(Ti(s.path,e))continue;let o=await r.cachedRead(s),a=et(o);if(a.error)continue;let l=sn(s.path,a.frontmatter,e,t).map(u=>t.get(u)).filter(u=>!!u);for(let u of l)for(let[d,f]of Object.entries(u.fields)){if(!G(f))continue;let p=f;if(p.unique!==!0)continue;let m=a.frontmatter[d];if(m==null)continue;let h=nf(m),y=p.unique_scope==="collection"?"collection":"type",g=`${y==="collection"?"*":u.name}::${d}::${h}`,_=n.get(g)??[];_.some(v=>v.path===s.path)||(_.push({path:s.path,typeName:u.name,fieldName:d,scope:y,specProfile:u.specProfile,value:m,fingerprint:h}),n.set(g,_))}}let i=[];for(let s of n.values())if(!(s.length<=1))for(let o of s){let a=s.filter(c=>c.path!==o.path).map(c=>c.path).join(", ");Me(i,o.path,"error",o.specProfile==="v0.3"?"duplicate_value":"duplicate_unique",o.scope==="collection"?`Field '${o.fieldName}' must be unique across the collection. Duplicate found in: ${a}`:`Field '${o.fieldName}' must be unique for type '${o.typeName}'. Duplicate found in: ${a}`,o.fieldName)}return i}async function Sb(r,e,t){let n=[];for(let s of r.getMarkdownFiles()){if(Ti(s.path,e))continue;let o=await lf(r,s,e,t);n.push(...o)}let i=await QC(r,e,t);return n.push(...i),n}function ZC(r,e,t=Rt.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()}),`${Vt(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()}),`${bt(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()}),`${Vt(n,`# ${r} Type definition for ${r}.`)} -`}function Z_(r,e){let t={},n=e.settings.explicit_type_keys[0]??"type";t[n]=n==="types"?[r.name]:r.name;for(let[i,s]of Object.entries(r.fields)){if(!G(s))continue;let o=s;o.default!==void 0&&(t[i]=ze(o.default))}return t}function ev(r,e){let t=[];for(let[n,i]of Object.entries(r.fields)){if(!G(i))continue;let s=i;s.computed||s.required&&e[n]===void 0&&t.push([n,s])}return t}function Ef(r,e){let t=r.trim();switch(e.type??"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(s=>s.trim()).filter(s=>s.length>0);return e.items?i.map(s=>Ef(s,e.items)):i}case"object":{let i=(0,de.parseYaml)(t);if(!G(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 j_(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 tv(r,e){let t=(0,de.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 OI(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,de.normalizePath)(Sf(r.path_pattern,e));return t.endsWith(".md")?t:null}async function rv(r,e,t){let n=OI(e,t),i=gI(e,t),s=n?n.split("/").pop()??n:bI(e,t),o=Rn(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 tv(r,a.slice(0,l)),a}async function nv(r,e,t,n=""){let i=Rn(e),s=i.lastIndexOf("/");if(s>0&&await tv(r,i.slice(0,s)),await r.adapter.exists(i))throw new Error(`File already exists: ${i}`);let o=`${bt(t,n)} -`;return r.create(i,o)}function ja(r){return uI(r)}var te=require("obsidian"),m0=vn(gf(),1);var qa=Symbol.for("yaml.alias"),Fa=Symbol.for("yaml.document"),Ut=Symbol.for("yaml.map"),Af=Symbol.for("yaml.pair"),_t=Symbol.for("yaml.scalar"),xr=Symbol.for("yaml.seq"),Ze=Symbol.for("yaml.node.type"),Bt=r=>!!r&&typeof r=="object"&&r[Ze]===qa,lr=r=>!!r&&typeof r=="object"&&r[Ze]===Fa,Vt=r=>!!r&&typeof r=="object"&&r[Ze]===Ut,re=r=>!!r&&typeof r=="object"&&r[Ze]===Af,K=r=>!!r&&typeof r=="object"&&r[Ze]===_t,zt=r=>!!r&&typeof r=="object"&&r[Ze]===xr;function le(r){if(r&&typeof r=="object")switch(r[Ze]){case Ut:case xr:return!0}return!1}function ie(r){if(r&&typeof r=="object")switch(r[Ze]){case qa:case Ut:case _t:case xr:return!0}return!1}var Ua=r=>(K(r)||le(r))&&!!r.anchor;var ut=Symbol("break visit"),iv=Symbol("skip children"),dr=Symbol("remove node");function ur(r,e){let t=sv(e);lr(r)?xi(null,r.contents,t,Object.freeze([r]))===dr&&(r.contents=null):xi(null,r,t,Object.freeze([]))}ur.BREAK=ut;ur.SKIP=iv;ur.REMOVE=dr;function xi(r,e,t,n){let i=ov(r,e,t,n);if(ie(i)||re(i))return av(r,n,i),xi(r,i,t,n);if(typeof i!="symbol"){if(le(e)){n=Object.freeze(n.concat(e));for(let s=0;sr.replace(/[!,[\]{}]/g,e=>NI[e]),fr=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+DI(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&&ie(e.contents)){let s={};ur(e.contents,(o,a)=>{ie(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(` -`)}};fr.defaultYaml={explicit:!1,version:"1.2"};fr.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 xf(r){let e=new Set;return ur(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function kf(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function cv(r,e){let t=[],n=new Map,i=null;return{onAnchor:s=>{t.push(s),i??(i=xf(r));let o=kf(e,i);return i.add(o),o},setAnchors:()=>{for(let s of t){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(K(o.node)||le(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 nn(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;iIe(n,String(i),t));if(r&&typeof r.toJSON=="function"){if(!t||!Ua(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?.keep?Number(r):r}var sn=class{constructor(e){Object.defineProperty(this,Ze,{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(!lr(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=Ie(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof s=="function"?nn(s,{"":a},"",a):a}};var kr=class extends sn{constructor(e){super(qa),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],ur(e,{Node:(s,o)=>{(Bt(o)||Ua(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||(Ie(o,null,t),a=n.get(o)),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=za(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 za(r,e,t){if(Bt(e)){let n=e.resolve(r),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(le(e)){let n=0;for(let i of e.items){let s=za(r,i,t);s>n&&(n=s)}return n}else if(re(e)){let n=za(r,e.key,t),i=za(r,e.value,t);return Math.max(n,i)}return 1}var Ha=r=>!r||typeof r!="function"&&typeof r!="object",L=class extends sn{constructor(e){super(_t),this.value=e}toJSON(e,t){return t?.keep?this.value:Ie(this.value,e,t)}toString(){return String(this.value)}};L.BLOCK_FOLDED="BLOCK_FOLDED";L.BLOCK_LITERAL="BLOCK_LITERAL";L.PLAIN="PLAIN";L.QUOTE_DOUBLE="QUOTE_DOUBLE";L.QUOTE_SINGLE="QUOTE_SINGLE";var LI="tag:yaml.org,2002:";function jI(r,e,t){if(e){let n=t.filter(s=>s.tag===e),i=n.find(s=>!s.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(n=>n.identify?.(r)&&!n.format)}function Pr(r,e,t){if(lr(r)&&(r=r.contents),ie(r))return r;if(re(r)){let d=t.schema[Ut].createNode?.(t.schema,null,t);return d.items.push(r),d}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt<"u"&&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 c.anchor??(c.anchor=i(r)),new kr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=LI+e.slice(2));let l=jI(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let d=new L(r);return c&&(c.node=d),d}l=r instanceof Map?o[Ut]:Symbol.iterator in Object(r)?o[xr]:o[Ut]}s&&(s(l),delete t.onTagObj);let u=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new L(r);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}function Vs(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 Pr(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 Ci=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,Pi=class extends sn{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=>ie(n)||re(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Ci(e))this.add(t);else{let[n,...i]=e,s=this.get(n,!0);if(le(s))s.addIn(i,t);else if(s===void 0&&this.schema)this.set(n,Vs(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(le(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&&K(s)?s.value:s:le(s)?s.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!re(t))return!1;let n=t.value;return n==null||e&&K(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 le(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(le(s))s.setIn(i,t);else if(s===void 0&&this.schema)this.set(n,Vs(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};var lv=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Ot(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var pr=(r,e,t)=>r.endsWith(` -`)?Ot(t,e):t.includes(` +`}function $b(r,e){let t={},n=e.settings.explicit_type_keys[0]??"type";t[n]=n==="types"?[r.name]:r.name;for(let[i,s]of Object.entries(r.fields)){if(!G(s))continue;let o=s;o.default!==void 0&&(t[i]=Ke(o.default))}return t}function Eb(r,e){let t=[];for(let[n,i]of Object.entries(r.fields)){if(!G(i))continue;let s=i;s.computed||s.required&&e[n]===void 0&&t.push([n,s])}return t}function df(r,e){let t=r.trim();switch(e.type??"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(s=>s.trim()).filter(s=>s.length>0);return e.items?i.map(s=>df(s,e.items)):i}case"object":{let i=(0,de.parseYaml)(t);if(!G(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 cb(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,de.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 eM(r,e){if(!r.path_pattern||r.path_pattern.trim().length===0)return null;let t=(0,de.normalizePath)(cf(r.path_pattern,e));return t.endsWith(".md")?t:null}async function Ab(r,e,t){let n=eM(e,t),i=LC(e,t),s=n?n.split("/").pop()??n:jC(e,t),o=Fn(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 kb(r,e,t,n=""){let i=Fn(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=`${Vt(t,n)} +`;return r.create(i,o)}function Pb(r){return IC(r)}function Mb(r,e){let t=et(r);if(t.error)throw new Error(`Invalid frontmatter: ${t.error}`);return tM(t.frontmatter,e)?{content:`--- +${(0,Cb.stringifyYaml)(t.frontmatter).trimEnd()} +--- +${t.body}`,changed:!0}:{content:r,changed:!1}}function Ib(r){if(!r.field)return null;if(["unknown_field","missing_required"].includes(r.code))return/[.[\]]/.test(r.field)?null:[r.field];if(!["schema_additional_properties","schema_required"].includes(r.code))return null;let e=r.details?.instance_path,t=r.details?.property;return typeof e!="string"||typeof t!="string"?null:[...e===""?[]:e.slice(1).split("/").map(n=>n.replace(/~1/g,"/").replace(/~0/g,"~")),t]}function Tb(r){return Ib(r)?["unknown_field","schema_additional_properties"].includes(r.code)?"Remove field":"Add placeholder":null}function tM(r,e){let t=Ib(e);if(!t?.length)return!1;let n=r;for(let a of t.slice(0,-1)){if(!n||typeof n!="object"||!Object.prototype.hasOwnProperty.call(n,a))return!1;n=n[a]}if(!n||typeof n!="object"||Array.isArray(n))return!1;let i=n,s=t[t.length-1],o=Object.prototype.hasOwnProperty.call(i,s);if(["unknown_field","schema_additional_properties"].includes(e.code)){if(!o)return!1;delete i[s]}else{if(o)return!1;Object.defineProperty(i,s,{value:"TODO",enumerable:!0,configurable:!0,writable:!0})}return!0}var O=require("obsidian");var R=class extends Error{code;details;constructor(e,t,n){super(t),this.code=e,this.details=n,this.name="InteropError"}toPortableError(e){return{code:this.code,message:this.message,...this.details===void 0?{}:{details:this.details},...e===void 0?{}:{retryable:e}}}},Ks=class extends Error{status;error;constructor(e,t){super(t.message),this.status=e,this.error=t,this.name="ActionHandlerError"}};var Rb=An(Ou(),1),Ob=An(zu(),1);var uf={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 rM=Ob.default;function Nb(){return Object.fromEntries(Object.entries(uf).map(([r,e])=>[r,structuredClone(e)]))}function ff(){let r=new Rb.Ajv2020({allErrors:!0,strict:!1,validateFormats:!0});rM(r);let e=Nb();r.addSchema(e.profile);for(let[t,n]of Object.entries(e))t!=="profile"&&r.addSchema(n);return r}function Cr(r,e){let t=String(uf[e].$id),n=r.getSchema(t);if(!n)throw new Error(`Canonical interoperability schema is unavailable: ${e}`);return n}function on(r){return(r??[]).map(e=>`${e.instancePath||"/"} ${e.message??e.keyword}`).join("; ")}function ur(r,e){if(!("value"in r))throw new R("contract_digest_conflict",`${e} must be resolved to an inline JSON Schema before runtime registration.`);return structuredClone(r.value)}function Db(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=ur(r.record_schema,"record_schema"),r.binding_schema&&(e.binding_schema=ur(r.binding_schema,"binding_schema"));break;case"event":e.data_schema=ur(r.data_schema,"data_schema"),r.source_schema&&(e.source_schema=ur(r.source_schema,"source_schema"));break;case"action":e.input_schema=ur(r.input_schema,"input_schema"),r.output_schema&&(e.output_schema=ur(r.output_schema,"output_schema")),r.error_schema&&(e.error_schema=ur(r.error_schema,"error_schema")),r.provider_schema&&(e.provider_schema=ur(r.provider_schema,"provider_schema")),r.behavior&&(e.behavior=structuredClone(r.behavior));break}return e}async function Ia(r){return Oi(Db(r))}async function Oi(r){return`sha256:${await nM(pf(r))}`}function Lb(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 jb(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 Ta(r,e,t,n){if(!(!r||r(e)))throw new R(t,`${n} failed JSON Schema validation: ${on(r.errors)}`)}function Ri(r,e,t){try{return r.compile(ur(e,t))}catch(n){throw new R("contract_digest_conflict",`${t} could not be compiled: ${n instanceof Error?n.message:String(n)}`)}}function pf(r){return r===null||typeof r!="object"?JSON.stringify(r):Array.isArray(r)?`[${r.map(pf).join(",")}]`:`{${Object.entries(r).filter(([,t])=>t!==void 0).sort(([t],[n])=>tn?1:0).map(([t,n])=>`${JSON.stringify(t)}:${pf(n)}`).join(",")}}`}async function nM(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 Ir=An(C_(),1);var Of={delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},uR=new Set(["specversion","id","source","type","time","subject","datacontenttype","dataschema","data","mdbaseprofile","mdbasecontractversion","mdbasecontractdigest","mdbaseapplication","mdbaseimplementation","mdbaseimplementationversion","mdbaseinstanceid","correlationid","causationid"]),Qs=class{options;profileVersion="0.1";transport;ajv=ff();contractValidator=Cr(this.ajv,"contract");eventValidator=Cr(this.ajv,"event");actionRequestValidator=Cr(this.ajv,"actionRequest");actionInvocationValidator=Cr(this.ajv,"actionInvocation");actionOutcomeValidator=Cr(this.ajv,"actionOutcome");eventSourceDeclarationValidator=Cr(this.ajv,"eventSourceDeclaration");actionProviderDeclarationValidator=Cr(this.ajv,"actionProviderDeclaration");contracts=new Map;clients=new Map;eventSources=new Map;actionProviders=new Map;subscriptions=new Map;activeActions=new Map;completedActions=new Map;admissionLocks=new Map;recentEvents=new Map;authorize;now;idFactory;recentEventLimit;completedRequestLimit;nextSequence=0;disposed=!1;constructor(e={}){this.options=e,this.authorize=e.authorize??(()=>!1),this.now=e.now??(()=>new Date),this.idFactory=e.idFactory??(t=>{this.nextSequence+=1;let n=typeof globalThis.crypto?.randomUUID=="function"?globalThis.crypto.randomUUID():`${this.now().getTime().toString(36)}-${this.nextSequence.toString(36)}`;return`${t}_${n}`}),this.recentEventLimit=Math.max(1,e.recentEventLimit??1e3),this.completedRequestLimit=Math.max(1,e.completedRequestLimit??1e3),this.transport={...Of,...structuredClone(e.transport??{}),delivery:[...e.transport?.delivery??Of.delivery],ordering:[...e.transport?.ordering??Of.ordering]}}connect(e){this.assertActive(),fR(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){let n=this.requireClient(e);if(t.contracts.length===0)throw new R("request_rejected","An event-source declaration must include a contract.");let i=`${e}:${t.declaration_id}`;if(this.eventSources.has(i))throw new R("request_rejected",`Event-source declaration ${t.declaration_id} is already registered.`);let s=new Map;for(let l of t.contracts){let u=await this.prepareEventContract(l.contract),d=M_(l.requirement,u.reference);if(I_(d,u.reference),await this.assertAuthorized({operation:"register_event_source",principal:n.identity,contract:u.reference}),u.sourceValidator&&!u.sourceValidator(l.binding??{}))throw new R("request_rejected",`${u.reference.id} source binding is invalid: ${on(u.sourceValidator.errors)}`);let f=Ha(u.reference);if(s.has(f))throw new R("contract_digest_conflict",`Event contract ${f} is repeated by one declaration.`);s.set(f,{contract:u,requirement:d,...l.binding===void 0?{}:{binding:structuredClone(l.binding)},...l.ordering===void 0?{}:{ordering:[...l.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:l,requirement:u,binding:d,ordering:f})=>({requirement:structuredClone(u),resolved:structuredClone(l.reference),...d===void 0?{}:{binding:d},...f===void 0?{}:{ordering:f}}))},a={...o,declaration_digest:await Oi(o)};cn(this.eventSourceDeclarationValidator,a,"request_rejected","Event-source declaration"),this.commitContracts([...s.values()].map(({contract:l})=>l)),this.eventSources.set(i,{id:i,clientId:e,declaration:structuredClone(a),contracts:new Map([...s.entries()].map(([l,u])=>[l,{contract:u.contract,...u.binding===void 0?{}:{binding:u.binding}}]))}),n.sources.add(i);let c=!0;return{declaration:structuredClone(a),dispose:()=>{c&&(c=!1,this.removeEventSource(i))}}}async publishEvent(e,t){let n=this.requireClient(e),i=Ha(t.contract),s=[...n.sources].map(m=>this.eventSources.get(m)).find(m=>m?.contracts.has(i));if(!s)throw new R("unknown_contract",`This client has not registered event contract ${t.contract.id} ${t.contract.version}.`);let o=s.contracts.get(i)?.contract;if(!o)throw new R("unknown_contract",`Event contract ${i} is unavailable.`);if(t.contract.digest&&t.contract.digest!==o.reference.digest)throw new R("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}}),Nf(t.data,"invalid_event_data",`Event ${o.reference.id} data`),Ta(o.dataValidator,t.data,"invalid_event_data",`Event ${o.reference.id} data`);let a=t.extensions??{};for(let m of Object.keys(a))if(uR.has(m))throw new R("request_rejected",`Event extension ${m} is reserved.`);let c={...structuredClone(a),specversion:"1.0",id:t.id??this.idFactory("evt"),source:pR(n.identity),type:o.reference.id,time:t.time??this.now().toISOString(),...t.subject===void 0?{}:{subject:t.subject},datacontenttype:"application/json",dataschema:O_(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}};cn(this.eventValidator,c,"invalid_event_data","Event envelope"),Df(this.transport,c),hR(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 R("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)),R_(this.recentEvents,this.recentEventLimit);let d=[...this.subscriptions.values()].filter(({subscription:m})=>Ka(m.contract,o.reference)),f=await Promise.allSettled(d.map(async m=>await this.isAuthorized({operation:"subscribe_event",principal:m.principal,contract:o.reference,...c.subject===void 0?{}:{subject:c.subject}})?(await m.handler(structuredClone(c)),!0):!1)),p=0;for(let m of f)m.status==="fulfilled"&&m.value?p+=1:m.status==="rejected"&&this.report({severity:"error",code:"event_consumer_failed",message:`An event consumer failed while handling ${c.type}.`,contract:o.reference,cause:m.reason});return{event:structuredClone(c),deliveries:p,duplicate:!1}}async subscribeEvents(e,t,n){let i=this.requireClient(e);Lf(t.contract),gR(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){let n=this.requireClient(e);if(t.handlers.length===0)throw new R("request_rejected","An action-provider declaration must include a handler.");let i=`${e}:${t.declaration_id}`;if(this.actionProviders.has(i))throw new R("request_rejected",`Action-provider declaration ${t.declaration_id} is already registered.`);let s=[],o=new Set;for(let d of t.handlers){if(o.has(d.handler_id))throw new R("request_rejected",`Handler ${d.handler_id} is repeated.`);o.add(d.handler_id);let f=await this.prepareActionContract(d.contract),p=M_(d.requirement,f.reference);if(I_(p,f.reference),await this.assertAuthorized({operation:"register_action_provider",principal:n.identity,contract:f.reference,provider:n.identity}),f.providerValidator&&!f.providerValidator(d.binding??{}))throw new R("request_rejected",`${f.reference.id} provider binding is invalid: ${on(f.providerValidator.errors)}`);let m=d.contract.behavior?.idempotency??"none";if(d.idempotency?.mode==="request"&&m==="none")throw new R("request_rejected",`${f.reference.id} does not permit request deduplication.`);if(m==="required"&&d.idempotency?.mode!=="request")throw new R("request_rejected",`${f.reference.id} requires a provider with request deduplication.`);let h=d.contract.behavior?.cancellation??"none";if(d.cancellation==="cooperative"&&h!=="cooperative")throw new R("request_rejected",`${f.reference.id} does not declare cooperative cancellation.`);s.push({contract:f,declaration:{handler_id:d.handler_id,requirement:p,resolved:structuredClone(f.reference),...d.binding===void 0?{}:{binding:structuredClone(d.binding)},...d.idempotency===void 0?{}:{idempotency:structuredClone(d.idempotency)},...d.cancellation===void 0?{}:{cancellation:d.cancellation},...d.max_concurrency===void 0?{}:{max_concurrency:d.max_concurrency}},handler:d.handler})}let a={kind:"mdbase.action-provider",profile_version:"0.1",declaration_id:t.declaration_id,provider:structuredClone(n.identity),handlers:s.map(({declaration:d})=>structuredClone(d))},c={...a,declaration_digest:await Oi(a)};cn(this.actionProviderDeclarationValidator,c,"request_rejected","Action-provider declaration"),this.commitContracts(s.map(({contract:d})=>d));let l=s.map(({contract:d,declaration:f,handler:p})=>({registrationId:i,clientId:e,declaration:structuredClone(c),handlerDeclaration:structuredClone(f),contract:d,handler:p,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){let n=this.requireClient(e);Lf(t.contract);let i=t.request_id??this.idFactory("req");this.cleanCompletedActions(),Nf(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:t.created_at??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)};cn(this.actionRequestValidator,s,"request_rejected","Action request"),Df(this.transport,s);let o=await this.acquireAdmission(i);try{let a=await Oi(mR(s)),c=this.activeActions.get(i);if(c){if(T_(e,i,a,c),c.handler.handlerDeclaration.idempotency?.mode!=="request")throw new R("request_rejected",`Action request ${i} is already active without deduplication.`);return structuredClone(await c.promise)}let l=this.completedActions.get(i);if(l){if(T_(e,i,a,l),!l.reusable)throw new R("request_rejected",`Action request ${i} was already completed without deduplication.`);return structuredClone(l.outcome)}if(s.deadline&&new Date(s.deadline).getTime()<=this.now().getTime())throw new R("deadline_exceeded",`Action request ${i} passed its deadline before admission.`);if(s.deadline&&!this.transport.deadlines)throw new R("unsupported_transport_capability","The active transport cannot enforce action deadlines.");let u=this.resolveActionCandidates(s.contract,s.requested_provider);u.length===0&&this.throwResolutionFailure(s.contract,s.requested_provider);let d=[];for(let x of u)await this.isAuthorized({operation:"invoke_action",principal:n.identity,contract:x.contract.reference,provider:x.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}})&&d.push(x);if(d.length===0)throw new R("unauthorized",`No authorized provider can execute ${s.contract.id}.`);if(d.length>1)throw new R("ambiguous_provider",`Action ${s.contract.id} has ${d.length} eligible providers; select one explicitly.`);let f=d[0];if(f.handlerDeclaration.max_concurrency!==void 0&&f.active>=f.handlerDeclaration.max_concurrency)throw new R("request_rejected",`Provider ${f.declaration.provider.implementation} is at capacity.`);if((f.contract.artifact.behavior?.idempotency??"none")==="required"&&!s.idempotency_key)throw new R("request_rejected",`${f.contract.reference.id} requires an idempotency key.`);Ta(f.contract.inputValidator,s.input,"invalid_action_input",`Action ${f.contract.reference.id} input`);let m={operation:"invoke_action",principal:n.identity,contract:f.contract.reference,provider:f.declaration.provider,...s.subject===void 0?{}:{subject:s.subject}},h=await this.options.authorizationContext?.(m),y={kind:"mdbase.action.invocation",profile_version:"0.1",invocation_id:this.idFactory("inv"),attempt_id:this.idFactory("attempt"),request_id:i,contract:structuredClone(f.contract.reference),caller:structuredClone(n.identity),provider:structuredClone(f.declaration.provider),provider_declaration_digest:f.declaration.declaration_digest,handler_id:f.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},...h===void 0?{}:{authorization_context:h},input:structuredClone(s.input)};cn(this.actionInvocationValidator,y,"request_rejected","Action invocation"),await this.options.onInvocation?.(structuredClone(y));let g=new AbortController,_;if(y.deadline){let x=Math.max(0,new Date(y.deadline).getTime()-this.now().getTime());_=setTimeout(()=>g.abort(new R("deadline_exceeded",`Action request ${i} exceeded its deadline.`)),x)}f.active+=1;let v=this.executeAction(f,y,g).finally(()=>{_!==void 0&&clearTimeout(_),f.active=Math.max(0,f.active-1),this.activeActions.delete(i)});this.activeActions.set(i,{clientId:e,requestId:i,requestDigest:a,handler:f,invocation:y,controller:g,promise:v}),o();let w=await v,S=f.handlerDeclaration.idempotency?.retention_seconds??300;return this.completedActions.set(i,{clientId:e,requestDigest:a,outcome:structuredClone(w),reusable:f.handlerDeclaration.idempotency?.mode==="request",expiresAt:this.now().getTime()+S*1e3}),R_(this.completedActions,this.completedRequestLimit),structuredClone(w)}finally{o()}}async executeAction(e,t,n){try{let i=await e.handler(structuredClone(t.input),{invocation:structuredClone(t),signal:n.signal});if(n.signal.aborted){let o=n.signal.reason;return o instanceof R&&o.code==="deadline_exceeded"?this.failureOutcome(t,"failed",o.toPortableError()):this.failureOutcome(t,"cancelled",{code:"cancelled",message:`Action request ${t.request_id} was cancelled.`})}Nf(i,"invalid_action_output",`Action ${e.contract.reference.id} output`),Ta(e.contract.outputValidator,i,"invalid_action_output",`Action ${e.contract.reference.id} output`);let s={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 cn(this.actionOutcomeValidator,s,"invalid_action_output","Action outcome"),Df(this.transport,s),s}catch(i){if(i instanceof Ks)return e.contract.errorValidator&&!e.contract.errorValidator(i.error.details??{})?this.failureOutcome(t,"failed",{code:"handler_failure",message:`Provider returned invalid declared error details: ${on(e.contract.errorValidator.errors)}`}):this.failureOutcome(t,i.status,i.error);if(i instanceof R)return this.failureOutcome(t,i.code==="cancelled"?"cancelled":i.code==="outcome_indeterminate"?"outcome_indeterminate":"failed",i.toPortableError());if(n.signal.aborted||bR(i)){let s=n.signal.reason;return s instanceof R&&s.code==="deadline_exceeded"?this.failureOutcome(t,"failed",s.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 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 cn(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 R("unauthorized",`Action request ${t} belongs to another caller.`);return a?structuredClone(a.outcome):null}if(o.clientId!==e)throw new R("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 R("unsupported_transport_capability","The active transport cannot deliver cancellation.");if(o.handler.handlerDeclaration.cancellation!=="cooperative")throw new R("cancellation_unsupported",`Provider ${o.invocation.provider.implementation} does not support cancellation.`);return o.controller.abort(new R("cancelled",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})=>Ka(e,s.reference)&&yR(t,o.provider)),i=(0,Ir.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)=>s.declaration.provider.application.localeCompare(o.declaration.provider.application)||s.declaration.provider.implementation.localeCompare(o.declaration.provider.implementation)||(s.declaration.provider.instance_id??"").localeCompare(o.declaration.provider.instance_id??"")||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 R("unknown_contract",`Action contract ${e.id} is unknown.`):n.some(({reference:i})=>Ka(e,i))?t?new R("requested_provider_unavailable",`The requested provider is unavailable for ${e.id}.`):new R("no_provider",`No provider is registered for ${e.id}.`):new R("unsupported_contract_version",`No ${e.id} artifact satisfies ${e.version}.`)}async prepareEventContract(e){if(this.assertContractArtifact(e),e.contract_type!=="event")throw new R("unknown_contract",`${e.id} is not an event contract.`);let t={id:e.id,version:e.version,digest:await Ia(e)};this.assertNoContractConflict(t);let n=Lb(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 R("unknown_contract",`${e.id} is not an action contract.`);let t={id:e.id,version:e.version,digest:await Ia(e)};this.assertNoContractConflict(t);let n=jb(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(cn(this.contractValidator,e,"contract_digest_conflict",`Contract ${e.id||""}`),!(0,Ir.valid)(e.version))throw new R("unsupported_contract_version",`${e.id} version must be exact SemVer.`)}assertNoContractConflict(e){let t=this.contracts.get(Ha(e));if(t&&t.reference.digest!==e.digest)throw new R("contract_digest_conflict",`Contract ${e.id} ${e.version} conflicts with the registered artifact.`)}commitContracts(e){let t=new Map;for(let n of e){let i=Ha(n.reference),s=t.get(i)??this.contracts.get(i);if(s&&s.reference.digest!==n.reference.digest)throw new R("contract_digest_conflict",`Contract ${n.reference.id} ${n.reference.version} conflicts within the registration.`);t.set(i,n)}for(let[n,i]of t)this.contracts.has(n)||this.contracts.set(n,i)}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 R("cancelled","The caller unloaded.")),i.handler.clientId===e&&i.handler.handlerDeclaration.cancellation==="cooperative"&&i.controller.abort(new R("cancelled","The provider unloaded."));this.clients.delete(e),t||this.assertActive()}}removeEventSource(e){let t=this.eventSources.get(e);t&&(this.eventSources.delete(e),this.clients.get(t.clientId)?.sources.delete(e))}removeActionProvider(e){let t=this.actionProviders.get(e);if(t){this.actionProviders.delete(e),this.clients.get(t.clientId)?.providers.delete(e);for(let n of this.activeActions.values())n.handler.registrationId===e&&n.handler.handlerDeclaration.cancellation==="cooperative"&&n.controller.abort(new R("cancelled","The provider unloaded."))}}removeSubscription(e){let t=this.subscriptions.get(e);t&&(this.subscriptions.delete(e),this.clients.get(t.clientId)?.subscriptions.delete(e))}requireClient(e){this.assertActive();let t=this.clients.get(e);if(!t||t.disposed)throw new R("transport_unavailable","Interop client is disposed.");return t}assertActive(){if(this.disposed)throw new R("transport_unavailable","Interop bridge is disposed.")}async assertAuthorized(e){if(!await this.isAuthorized(e))throw new R("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){let t=this.admissionLocks.get(e)??Promise.resolve(),n,i=new Promise(a=>{n=a}),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){this.options.onDiagnostic?.(structuredClone(e))}};function cn(r,e,t,n){if(!r(e))throw new R(t,`${n} is invalid: ${on(r.errors)}`)}function fR(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 R("request_rejected",`Implementation identity ${e} is invalid.`);if(!(0,Ir.valid)(r.version))throw new R("request_rejected","Implementation identity version must be exact SemVer.")}function Lf(r){if(!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(r.id))throw new R("unknown_contract",`Contract ID ${r.id} is invalid.`);if(!(0,Ir.validRange)(r.version,{includePrerelease:!0}))throw new R("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 R("contract_digest_conflict","Contract digest is invalid.")}function M_(r,e){let t=r??{id:e.id,version:e.version,digest:e.digest};return Lf(t),structuredClone(t)}function I_(r,e){if(!Ka(r,e))throw new R("unsupported_contract_version",`${e.id} ${e.version} does not satisfy its implementation requirement.`)}function Ka(r,e){return r.id===e.id&&(0,Ir.satisfies)(e.version,r.version,{includePrerelease:!0})&&(!r.digest||r.digest===e.digest)}function Ha(r){return`${r.id}@${r.version}`}function O_(r){return`urn:mdbase:contract:${r.id}:${r.version}:${r.digest}`}function pR(r){return`urn:mdbase:app:${[r.application,r.implementation,...r.instance_id?[r.instance_id]:[]].map(encodeURIComponent).join(":")}`}function hR(r,e){if(r.type!==e.id||r.mdbasecontractversion!==e.version||r.mdbasecontractdigest!==e.digest||r.dataschema!==O_(e))throw new R("contract_digest_conflict","Event contract evidence is inconsistent.")}function mR(r){let{created_at:e,...t}=r;return t}function T_(r,e,t,n){if(n.clientId!==r)throw new R("unauthorized",`Action request ${e} belongs to another caller.`);if(n.requestDigest!==t)throw new R("request_rejected",`Action request ${e} was reused with different content.`)}function Nf(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 R(e,`${t}${o} must be a finite JSON number.`)}if(typeof s!="object")throw new R(e,`${t}${o} is not a JSON value.`);if(n.has(s))throw new R(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 R(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 Df(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 R("unsupported_transport_capability",`The portable envelope is ${n} bytes; the active transport allows ${r.max_payload_bytes}.`)}function yR(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 gR(r,e){if(e){if(e.delivery?.some(t=>!r.delivery.includes(t)))throw new R("unsupported_transport_capability","The active transport lacks a required delivery capability.");if(e.ordering?.some(t=>!r.ordering.includes(t)))throw new R("unsupported_transport_capability","The active transport lacks a required ordering capability.");for(let t of["cancellation","deadlines","provider_discovery","request_deduplication","cross_process_identity"])if(e[t]===!0&&r[t]!==!0)throw new R("unsupported_transport_capability",`The active transport lacks ${t}.`);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 bR(r){return r instanceof Error&&r.name==="AbortError"}var Wa=class{constructor(e,t){this.app=e;this.profileVersion="0.1";this.bridge=new Qs({authorize:()=>t(),transport:{delivery:["ephemeral"],ordering:["none"],cancellation:!0,deadlines:!0,provider_discovery:!0,request_deduplication:!0,cross_process_identity:!1},onDiagnostic:n=>{(n.severity==="error"?console.error:console.warn)(`[mdbase/interop] ${n.code}: ${n.message}`,n.cause??"")}}),this.transport=this.bridge.describe().transport}connect(e){let t=e.manifest?.id,n=e.manifest?.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 te=require("obsidian"),W0=An(rf(),1);var Ga=Symbol.for("yaml.alias"),Ja=Symbol.for("yaml.document"),zt=Symbol.for("yaml.map"),jf=Symbol.for("yaml.pair"),wt=Symbol.for("yaml.scalar"),Tr=Symbol.for("yaml.seq"),rt=Symbol.for("yaml.node.type"),Ht=r=>!!r&&typeof r=="object"&&r[rt]===Ga,pr=r=>!!r&&typeof r=="object"&&r[rt]===Ja,Kt=r=>!!r&&typeof r=="object"&&r[rt]===zt,re=r=>!!r&&typeof r=="object"&&r[rt]===jf,H=r=>!!r&&typeof r=="object"&&r[rt]===wt,Wt=r=>!!r&&typeof r=="object"&&r[rt]===Tr;function le(r){if(r&&typeof r=="object")switch(r[rt]){case zt:case Tr:return!0}return!1}function ie(r){if(r&&typeof r=="object")switch(r[rt]){case Ga:case zt:case wt:case Tr:return!0}return!1}var Ya=r=>(H(r)||le(r))&&!!r.anchor;var ht=Symbol("break visit"),N_=Symbol("skip children"),hr=Symbol("remove node");function mr(r,e){let t=D_(e);pr(r)?Li(null,r.contents,t,Object.freeze([r]))===hr&&(r.contents=null):Li(null,r,t,Object.freeze([]))}mr.BREAK=ht;mr.SKIP=N_;mr.REMOVE=hr;function Li(r,e,t,n){let i=L_(r,e,t,n);if(ie(i)||re(i))return j_(r,n,i),Li(r,i,t,n);if(typeof i!="symbol"){if(le(e)){n=Object.freeze(n.concat(e));for(let s=0;sr.replace(/[!,[\]{}]/g,e=>vR[e]),yr=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+_R(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&&ie(e.contents)){let s={};mr(e.contents,(o,a)=>{ie(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(` +`)}};yr.defaultYaml={explicit:!1,version:"1.2"};yr.defaultTags={"!!":"tag:yaml.org,2002:"};function Qa(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 qf(r){let e=new Set;return mr(r,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}function Ff(r,e){for(let t=1;;++t){let n=`${r}${t}`;if(!e.has(n))return n}}function q_(r,e){let t=[],n=new Map,i=null;return{onAnchor:s=>{t.push(s),i??(i=qf(r));let o=Ff(e,i);return i.add(o),o},setAnchors:()=>{for(let s of t){let o=n.get(s);if(typeof o=="object"&&o.anchor&&(H(o.node)||le(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 ln(r,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,s=n.length;iTe(n,String(i),t));if(r&&typeof r.toJSON=="function"){if(!t||!Ya(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?.keep?Number(r):r}var dn=class{constructor(e){Object.defineProperty(this,rt,{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(!pr(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=Te(this,"",o);if(typeof i=="function")for(let{count:c,res:l}of o.anchors.values())i(l,c);return typeof s=="function"?ln(s,{"":a},"",a):a}};var Rr=class extends dn{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?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],mr(e,{Node:(s,o)=>{(Ht(o)||Ya(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||(Te(o,null,t),a=n.get(o)),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=Za(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(Qa(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 Za(r,e,t){if(Ht(e)){let n=e.resolve(r),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(le(e)){let n=0;for(let i of e.items){let s=Za(r,i,t);s>n&&(n=s)}return n}else if(re(e)){let n=Za(r,e.key,t),i=Za(r,e.value,t);return Math.max(n,i)}return 1}var ec=r=>!r||typeof r!="function"&&typeof r!="object",L=class extends dn{constructor(e){super(wt),this.value=e}toJSON(e,t){return t?.keep?this.value:Te(this.value,e,t)}toString(){return String(this.value)}};L.BLOCK_FOLDED="BLOCK_FOLDED";L.BLOCK_LITERAL="BLOCK_LITERAL";L.PLAIN="PLAIN";L.QUOTE_DOUBLE="QUOTE_DOUBLE";L.QUOTE_SINGLE="QUOTE_SINGLE";var wR="tag:yaml.org,2002:";function SR(r,e,t){if(e){let n=t.filter(s=>s.tag===e),i=n.find(s=>!s.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(n=>n.identify?.(r)&&!n.format)}function Or(r,e,t){if(pr(r)&&(r=r.contents),ie(r))return r;if(re(r)){let d=t.schema[zt].createNode?.(t.schema,null,t);return d.items.push(r),d}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt<"u"&&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 c.anchor??(c.anchor=i(r)),new Rr(c.anchor);c={anchor:null,node:null},a.set(r,c)}e?.startsWith("!!")&&(e=wR+e.slice(2));let l=SR(r,e,o.tags);if(!l){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let d=new L(r);return c&&(c.node=d),d}l=r instanceof Map?o[zt]:Symbol.iterator in Object(r)?o[Tr]:o[zt]}s&&(s(l),delete t.onTagObj);let u=l?.createNode?l.createNode(t.schema,r,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,r,t):new L(r);return e?u.tag=e:l.default||(u.tag=l.tag),c&&(c.node=u),u}function Zs(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 Or(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 Fi=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,qi=class extends dn{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=>ie(n)||re(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Fi(e))this.add(t);else{let[n,...i]=e,s=this.get(n,!0);if(le(s))s.addIn(i,t);else if(s===void 0&&this.schema)this.set(n,Zs(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(le(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&&H(s)?s.value:s:le(s)?s.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!re(t))return!1;let n=t.value;return n==null||e&&H(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 le(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(le(s))s.setIn(i,t);else if(s===void 0&&this.schema)this.set(n,Zs(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}};var F_=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Dt(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var gr=(r,e,t)=>r.endsWith(` +`)?Dt(t,e):t.includes(` `)?` -`+Ot(t,e):(r.endsWith(" ")?"":" ")+t;var Pf="flow",Ka="block",zs="quoted";function Hs(r,e,t="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return r;ii-Math.max(2,s)?l.push(0):d=i-n);let f,p,m=!1,h=-1,y=-1,g=-1;t===Ka&&(h=dv(r,h,e.length),h!==-1&&(d=h+c));for(let _;_=r[h+=1];){if(t===zs&&_==="\\"){switch(y=h,r[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(_===` -`)t===Ka&&(h=dv(r,h,e.length)),d=h+e.length+c,f=void 0;else{if(_===" "&&p&&p!==" "&&p!==` +`+Dt(t,e):(r.endsWith(" ")?"":" ")+t;var Uf="flow",tc="block",eo="quoted";function to(r,e,t="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:s=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return r;ii-Math.max(2,s)?l.push(0):d=i-n);let f,p,m=!1,h=-1,y=-1,g=-1;t===tc&&(h=U_(r,h,e.length),h!==-1&&(d=h+c));for(let v;v=r[h+=1];){if(t===eo&&v==="\\"){switch(y=h,r[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}g=h}if(v===` +`)t===tc&&(h=U_(r,h,e.length)),d=h+e.length+c,f=void 0;else{if(v===" "&&p&&p!==" "&&p!==` `&&p!==" "){let w=r[h+1];w&&w!==" "&&w!==` -`&&w!==" "&&(f=h)}if(h>=d)if(f)l.push(f),d=f+c,f=void 0;else if(t===zs){for(;p===" "||p===" ";)p=_,_=r[h+=1],m=!0;let w=h>g+1?h-2:y-1;if(u[w])return r;l.push(w),u[w]=!0,d=w+c,f=void 0}else m=!0}p=_}if(m&&a&&a(),l.length===0)return r;o&&o();let v=r.slice(0,l[0]);for(let _=0;_({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),Ja=r=>/^(%|---|\.\.\.)/m.test(r);function qI(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 Ks(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(Ja(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=d)if(f)l.push(f),d=f+c,f=void 0;else if(t===eo){for(;p===" "||p===" ";)p=v,v=r[h+=1],m=!0;let w=h>g+1?h-2:y-1;if(u[w])return r;l.push(w),u[w]=!0,d=w+c,f=void 0}else m=!0}p=v}if(m&&a&&a(),l.length===0)return r;o&&o();let _=r.slice(0,l[0]);for(let v=0;v({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),ic=r=>/^(%|---|\.\.\.)/m.test(r);function $R(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 ro(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,s=e.indent||(ic(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 A=t[f-1];if(A!==` -`&&A!==" "&&A!==" ")break}let p=t.substring(f),m=p.indexOf(` +`;let d,f;for(f=t.length;f>0;--f){let S=t[f-1];if(S!==` +`&&S!==" "&&S!==" ")break}let p=t.substring(f),m=p.indexOf(` `);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(Mf,`$&${l}`));let h=!1,y,g=-1;for(y=0;y{x=!0});let S=Hs(`${v}${A}${p}`,l,Ka,M);if(!x)return`>${w} -${l}${S}`}return t=t.replace(/\n+/g,`$&${l}`),`|${w} -${l}${v}${t}${p}`}function FI(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 Mi(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes(` -`)?Mi(s,e):Wa(r,e,t,n);if(!a&&!u&&i!==L.PLAIN&&s.includes(` -`))return Wa(r,e,t,n);if(Ja(s)){if(c==="")return e.forceBlockIndent=!0,Wa(r,e,t,n);if(a&&c===l)return Mi(s,e)}let d=s.replace(/\n+/g,`$& -${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:m}=e.doc.schema;if(m.some(f)||p?.some(f))return Mi(s,e)}return a?d:Hs(d,c,Pf,Ga(e,!1))}function Nn(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!==L.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=L.QUOTE_DOUBLE);let c=u=>{switch(u){case L.BLOCK_FOLDED:case L.BLOCK_LITERAL:return i||s?Mi(o.value,e):Wa(o,e,t,n);case L.QUOTE_DOUBLE:return Ks(o.value,e);case L.QUOTE_SINGLE:return Cf(o.value,e);case L.PLAIN:return FI(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 Ya(r,e){let t=Object.assign({blockQuote:!0,commentString:lv,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 UI(r,e){if(e.tag){let i=r.filter(s=>s.tag===e.tag);if(i.length>0)return i.find(s=>s.format===e.format)??i[0]}let t,n;if(K(e)){n=e.value;let i=r.filter(s=>s.identify?.(n));if(i.length>1){let s=i.filter(o=>o.test);s.length>0&&(i=s)}t=i.find(s=>s.format===e.format)??i.find(s=>!s.format)}else n=e,t=r.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!t){let i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return t}function BI(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let i=[],s=(K(r)||le(r))&&r.anchor;s&&Va(s)&&(t.add(s),i.push(`&${s}`));let o=r.tag??(e.default?null:e.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Cr(r,e,t,n){if(re(r))return r.toString(e,t,n);if(Bt(r)){if(e.doc.directives)return r.toString(e);if(e.resolvedAliases?.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=ie(r)?r:e.doc.createNode(r,{onTagObj:c=>i=c});i??(i=UI(e.doc.schema.tags,s));let o=BI(s,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,e,t,n):K(s)?Nn(s,e,t,n):s.toString(e,t,n);return o?K(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} -${e.indent}${a}`:a}function uv({key:r,value:e},t,n,i){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=t,f=ie(r)&&r.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(le(r)||!ie(r)&&typeof r=="object"){let M="With simple keys, collection cannot be used as a key value";throw new Error(M)}}let p=!d&&(!r||f&&e==null&&!t.inFlow||le(r)||(K(r)?r.type===L.BLOCK_FOLDED||r.type===L.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(d||!s),indent:a+c});let m=!1,h=!1,y=Cr(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+=pr(y,t.indent,l(f)):h&&i&&i(),y;m&&(f=null),p?(f&&(y+=pr(y,t.indent,l(f))),y=`? ${y} -${a}:`):(y=`${y}:`,f&&(y+=pr(y,t.indent,l(f))));let g,v,_;ie(e)?(g=!!e.spaceBefore,v=e.commentBefore,_=e.comment):(g=!1,v=null,_=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&K(e)&&(t.indentAtStart=y.length+1),h=!1,!u&&c.length>=2&&!t.inFlow&&!p&&zt(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let w=!1,A=Cr(e,t,()=>w=!0,()=>h=!0),x=" ";if(f||g||v){if(x=g?` -`:"",v){let M=l(v);x+=` -${Ot(M,t.indent)}`}A===""&&!t.inFlow?x===` -`&&_&&(x=` +`&&(p=p.slice(0,-1)),p=p.replace(Vf,`$&${l}`));let h=!1,y,g=-1;for(y=0;y{x=!0});let $=to(`${_}${S}${p}`,l,tc,C);if(!x)return`>${w} +${l}${$}`}return t=t.replace(/\n+/g,`$&${l}`),`|${w} +${l}${_}${t}${p}`}function ER(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 Ui(s,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(s))return a||u||!s.includes(` +`)?Ui(s,e):rc(r,e,t,n);if(!a&&!u&&i!==L.PLAIN&&s.includes(` +`))return rc(r,e,t,n);if(ic(s)){if(c==="")return e.forceBlockIndent=!0,rc(r,e,t,n);if(a&&c===l)return Ui(s,e)}let d=s.replace(/\n+/g,`$& +${c}`);if(o){let f=h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),{compat:p,tags:m}=e.doc.schema;if(m.some(f)||p?.some(f))return Ui(s,e)}return a?d:to(d,c,Uf,nc(e,!1))}function Bn(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!==L.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=L.QUOTE_DOUBLE);let c=u=>{switch(u){case L.BLOCK_FOLDED:case L.BLOCK_LITERAL:return i||s?Ui(o.value,e):rc(o,e,t,n);case L.QUOTE_DOUBLE:return ro(o.value,e);case L.QUOTE_SINGLE:return Bf(o.value,e);case L.PLAIN:return ER(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 sc(r,e){let t=Object.assign({blockQuote:!0,commentString:F_,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 xR(r,e){if(e.tag){let i=r.filter(s=>s.tag===e.tag);if(i.length>0)return i.find(s=>s.format===e.format)??i[0]}let t,n;if(H(e)){n=e.value;let i=r.filter(s=>s.identify?.(n));if(i.length>1){let s=i.filter(o=>o.test);s.length>0&&(i=s)}t=i.find(s=>s.format===e.format)??i.find(s=>!s.format)}else n=e,t=r.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!t){let i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return t}function AR(r,e,{anchors:t,doc:n}){if(!n.directives)return"";let i=[],s=(H(r)||le(r))&&r.anchor;s&&Qa(s)&&(t.add(s),i.push(`&${s}`));let o=r.tag??(e.default?null:e.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}function Nr(r,e,t,n){if(re(r))return r.toString(e,t,n);if(Ht(r)){if(e.doc.directives)return r.toString(e);if(e.resolvedAliases?.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=ie(r)?r:e.doc.createNode(r,{onTagObj:c=>i=c});i??(i=xR(e.doc.schema.tags,s));let o=AR(s,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof i.stringify=="function"?i.stringify(s,e,t,n):H(s)?Bn(s,e,t,n):s.toString(e,t,n);return o?H(s)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o} +${e.indent}${a}`:a}function B_({key:r,value:e},t,n,i){let{allNullValues:s,doc:o,indent:a,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=t,f=ie(r)&&r.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(le(r)||!ie(r)&&typeof r=="object"){let C="With simple keys, collection cannot be used as a key value";throw new Error(C)}}let p=!d&&(!r||f&&e==null&&!t.inFlow||le(r)||(H(r)?r.type===L.BLOCK_FOLDED||r.type===L.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(d||!s),indent:a+c});let m=!1,h=!1,y=Nr(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+=gr(y,t.indent,l(f)):h&&i&&i(),y;m&&(f=null),p?(f&&(y+=gr(y,t.indent,l(f))),y=`? ${y} +${a}:`):(y=`${y}:`,f&&(y+=gr(y,t.indent,l(f))));let g,_,v;ie(e)?(g=!!e.spaceBefore,_=e.commentBefore,v=e.comment):(g=!1,_=null,v=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!f&&H(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 w=!1,S=Nr(e,t,()=>w=!0,()=>h=!0),x=" ";if(f||g||_){if(x=g?` +`:"",_){let C=l(_);x+=` +${Dt(C,t.indent)}`}S===""&&!t.inFlow?x===` +`&&v&&(x=` `):x+=` -${t.indent}`}else if(!p&&le(e)){let M=A[0],S=A.indexOf(` -`),C=S!==-1,$=t.inFlow??e.flow??e.items.length===0;if(C||!$){let V=!1;if(C&&(M==="&"||M==="!")){let q=A.indexOf(" ");M==="&"&&q!==-1&&qr===Qa||typeof r=="symbol"&&r.description===Qa,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new L(Symbol(Qa)),{addToJSMap:If}),stringify:()=>Qa},fv=(r,e)=>(Ht.identify(e)||K(e)&&(!e.type||e.type===L.PLAIN)&&Ht.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===Ht.tag&&t.default);function If(r,e,t){let n=pv(r,t);if(zt(n))for(let i of n.items)Tf(r,e,i);else if(Array.isArray(n))for(let i of n)Tf(r,e,i);else Tf(r,e,n)}function Tf(r,e,t){let n=pv(r,t);if(!Vt(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 pv(r,e){return r&&Bt(e)?e.resolve(r.doc,r):e}function Za(r,e,{key:t,value:n}){if(ie(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(fv(r,t))If(r,e,n);else{let i=Ie(t,"",r);if(e instanceof Map)e.set(i,Ie(n,i,r));else if(e instanceof Set)e.add(i);else{let s=VI(t,i,r),o=Ie(n,s,r);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function VI(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(ie(r)&&t?.doc){let n=Ya(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)+'..."'),Xa(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 Ti(r,e,t){let n=Pr(r,void 0,t),i=Pr(e,void 0,t);return new $e(n,i)}var $e=class r{constructor(e,t=null){Object.defineProperty(this,Ze,{value:Af}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return ie(t)&&(t=t.clone(e)),ie(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return Za(t,n,this)}toString(e,t,n){return e?.doc?uv(this,e,t,n):JSON.stringify(this)}};function tc(r,e,t){return(e.inFlow??r.flow?HI:zI)(r,e,t)}function zI({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&&(g+=pr(g,s,l(y))),d&&y&&(d=!1),f.push(n+g)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let m=1;mr===ac||typeof r=="symbol"&&r.description===ac,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new L(Symbol(ac)),{addToJSMap:Hf}),stringify:()=>ac},V_=(r,e)=>(Gt.identify(e)||H(e)&&(!e.type||e.type===L.PLAIN)&&Gt.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===Gt.tag&&t.default);function Hf(r,e,t){let n=z_(r,t);if(Wt(n))for(let i of n.items)zf(r,e,i);else if(Array.isArray(n))for(let i of n)zf(r,e,i);else zf(r,e,n)}function zf(r,e,t){let n=z_(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 z_(r,e){return r&&Ht(e)?e.resolve(r.doc,r):e}function cc(r,e,{key:t,value:n}){if(ie(t)&&t.addToJSMap)t.addToJSMap(r,e,n);else if(V_(r,t))Hf(r,e,n);else{let i=Te(t,"",r);if(e instanceof Map)e.set(i,Te(n,i,r));else if(e instanceof Set)e.add(i);else{let s=kR(t,i,r),o=Te(n,s,r);s in e?Object.defineProperty(e,s,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[s]=o}}return e}function kR(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(ie(r)&&t?.doc){let n=sc(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)+'..."'),oc(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 Bi(r,e,t){let n=Or(r,void 0,t),i=Or(e,void 0,t);return new Ee(n,i)}var Ee=class r{constructor(e,t=null){Object.defineProperty(this,rt,{value:jf}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return ie(t)&&(t=t.clone(e)),ie(n)&&(n=n.clone(e)),new r(t,n)}toJSON(e,t){let n=t?.mapAsMap?new Map:{};return cc(t,n,this)}toString(e,t,n){return e?.doc?B_(this,e,t,n):JSON.stringify(this)}};function dc(r,e,t){return(e.inFlow??r.flow?CR:PR)(r,e,t)}function PR({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&&(g+=gr(g,s,l(y))),d&&y&&(d=!1),f.push(n+g)}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||g.includes(` -`)),m0&&(l||(l=d.reduce((v,_)=>v+_.length+2,2)+(g.length+2)>e.options.lineWidth)),l&&(g+=",")),y&&(g+=pr(g,n,a(y))),d.push(g),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?` +`+Dt(l(r),c),a&&a()):d&&o&&o(),p}function CR({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||g.includes(` +`)),m0&&(l||(l=d.reduce((_,v)=>_+v.length+2,2)+(g.length+2)>e.options.lineWidth)),l&&(g+=",")),y&&(g+=gr(g,n,a(y))),d.push(g),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} -${i}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function ec({indent:r,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=Ot(e(n),r);t.push(s.trimStart())}}function on(r,e){let t=K(e)?e.value:e;for(let n of r)if(re(n)&&(n.key===e||n.key===t||K(n.key)&&n.key.value===t))return n}var ke=class extends Pi{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ut,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(Ti(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){let n;re(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new $e(e,e?.value):n=new $e(e.key,e.value);let i=on(this.items,n.key),s=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);K(i.value)&&Ha(n.value)?i.value.value=n.value:i.value=n.value}else if(s){let o=this.items.findIndex(a=>s(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){let t=on(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let i=on(this.items,e)?.value;return(!t&&K(i)?i.value:i)??void 0}has(e){return!!on(this.items,e)}set(e,t){this.add(new $e(e,t),!0)}toJSON(e,t,n){let i=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(let s of this.items)Za(t,i,s);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!re(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})),tc(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var Kt={collection:"map",default:!0,nodeClass:ke,tag:"tag:yaml.org,2002:map",resolve(r,e){return Vt(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>ke.from(r,e,t)};var He=class extends Pi{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(xr,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=rc(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=rc(e);if(typeof n!="number")return;let i=this.items[n];return!t&&K(i)?i.value:i}has(e){let t=rc(e);return typeof t=="number"&&t=0?e:null}var Wt={collection:"seq",default:!0,nodeClass:He,tag:"tag:yaml.org,2002:seq",resolve(r,e){return zt(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>He.from(r,e,t)};var an={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),Nn(r,e,t,n)}};var Dn={identify:r=>r==null,createNode:()=>new L(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new L(null),stringify:({source:r},e)=>typeof r=="string"&&Dn.test.test(r)?r:e.options.nullStr};var Ws={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new L(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&Ws.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 Ke({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 nc={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:Ke},ic={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():Ke(r)}},sc={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 L(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:Ke};var oc=r=>typeof r=="bigint"||Number.isInteger(r),Rf=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function hv(r,e,t){let{value:n}=r;return oc(n)&&n>=0?t+n.toString(e):Ke(r)}var ac={identify:r=>oc(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>Rf(r,2,8,t),stringify:r=>hv(r,8,"0o")},cc={identify:oc,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>Rf(r,0,10,t),stringify:Ke},lc={identify:r=>oc(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>Rf(r,2,16,t),stringify:r=>hv(r,16,"0x")};var mv=[Kt,Wt,an,Dn,Ws,ac,cc,lc,nc,ic,sc];function yv(r){return typeof r=="bigint"||Number.isInteger(r)}var dc=({value:r})=>JSON.stringify(r),KI=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:dc},{identify:r=>r==null,createNode:()=>new L(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:dc},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:dc},{identify:yv,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})=>yv(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:dc}],WI={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},gv=[Kt,Wt].concat(KI,WI);var Gs={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 i=n.items[0]||new $e(new L(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore} +${i}${p}`}else return`${f}${o}${d.join(" ")}${o}${p}`}function lc({indent:r,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){let s=Dt(e(n),r);t.push(s.trimStart())}}function un(r,e){let t=H(e)?e.value:e;for(let n of r)if(re(n)&&(n.key===e||n.key===t||H(n.key)&&n.key.value===t))return n}var ke=class extends qi{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(zt,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(Bi(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){let n;re(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Ee(e,e?.value):n=new Ee(e.key,e.value);let i=un(this.items,n.key),s=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);H(i.value)&&ec(n.value)?i.value.value=n.value:i.value=n.value}else if(s){let o=this.items.findIndex(a=>s(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){let t=un(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let i=un(this.items,e)?.value;return(!t&&H(i)?i.value:i)??void 0}has(e){return!!un(this.items,e)}set(e,t){this.add(new Ee(e,t),!0)}toJSON(e,t,n){let i=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(let s of this.items)cc(t,i,s);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(let i of this.items)if(!re(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})),dc(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}};var Jt={collection:"map",default:!0,nodeClass:ke,tag:"tag:yaml.org,2002:map",resolve(r,e){return Kt(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>ke.from(r,e,t)};var We=class extends qi{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Tr,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=uc(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let n=uc(e);if(typeof n!="number")return;let i=this.items[n];return!t&&H(i)?i.value:i}has(e){let t=uc(e);return typeof t=="number"&&t=0?e:null}var Yt={collection:"seq",default:!0,nodeClass:We,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Wt(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>We.from(r,e,t)};var fn={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),Bn(r,e,t,n)}};var Vn={identify:r=>r==null,createNode:()=>new L(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new L(null),stringify:({source:r},e)=>typeof r=="string"&&Vn.test.test(r)?r:e.options.nullStr};var no={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new L(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&no.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 Ge({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 fc={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:Ge},pc={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():Ge(r)}},hc={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 L(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:Ge};var mc=r=>typeof r=="bigint"||Number.isInteger(r),Kf=(r,e,t,{intAsBigInt:n})=>n?BigInt(r):parseInt(r.substring(e),t);function H_(r,e,t){let{value:n}=r;return mc(n)&&n>=0?t+n.toString(e):Ge(r)}var yc={identify:r=>mc(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>Kf(r,2,8,t),stringify:r=>H_(r,8,"0o")},gc={identify:mc,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>Kf(r,0,10,t),stringify:Ge},bc={identify:r=>mc(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>Kf(r,2,16,t),stringify:r=>H_(r,16,"0x")};var K_=[Jt,Yt,fn,Vn,no,yc,gc,bc,fc,pc,hc];function W_(r){return typeof r=="bigint"||Number.isInteger(r)}var vc=({value:r})=>JSON.stringify(r),MR=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:vc},{identify:r=>r==null,createNode:()=>new L(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:vc},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:vc},{identify:W_,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})=>W_(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:vc}],IR={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},G_=[Jt,Yt].concat(MR,IR);var io={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 i=n.items[0]||new Ee(new L(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore} ${i.key.commentBefore}`:n.commentBefore),n.comment){let s=i.value??i.key;s.comment=s.comment?`${n.comment} -${s.comment}`:n.comment}n=i}r.items[t]=re(n)?n:new $e(n)}}else e("Expected a sequence for this tag");return r}function Nf(r,e,t){let{replacer:n}=t,i=new He(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(Ti(a,c,t))}return i}var Js={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Of,createNode:Nf};var Ii=class r extends He{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?.onCreate&&t.onCreate(n);for(let i of this.items){let s,o;if(re(i)?(s=Ie(i.key,"",t),o=Ie(i.value,s,t)):s=Ie(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=Nf(e,t,n),s=new this;return s.items=i.items,s}};Ii.tag="tag:yaml.org,2002:omap";var Ys={collection:"seq",identify:r=>r instanceof Map,nodeClass:Ii,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Of(r,e),n=[];for(let{key:i}of t.items)K(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new Ii,t)},createNode:(r,e,t)=>Ii.from(r,e,t)};function bv({value:r,source:e},t){return e&&(r?Df:Lf).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Df={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 L(!0),stringify:bv},Lf={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 L(!1),stringify:bv};var _v={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:Ke},vv={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():Ke(r)}},wv={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 L(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:Ke};var Xs=r=>typeof r=="bigint"||Number.isInteger(r);function uc(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 jf(r,e,t){let{value:n}=r;if(Xs(n)){let i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return Ke(r)}var Sv={identify:Xs,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>uc(r,2,2,t),stringify:r=>jf(r,2,"0b")},$v={identify:Xs,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>uc(r,1,8,t),stringify:r=>jf(r,8,"0")},Ev={identify:Xs,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>uc(r,0,10,t),stringify:Ke},Av={identify:Xs,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>uc(r,2,16,t),stringify:r=>jf(r,16,"0x")};var Ri=class r extends ke{constructor(e){super(e),this.tag=r.tag}add(e){let t;re(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),on(this.items,t.key)||this.items.push(t)}get(e,t){let n=on(this.items,e);return!t&&re(n)?K(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=on(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: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(Ti(o,null,n));return s}};Ri.tag="tag:yaml.org,2002:set";var Qs={collection:"map",identify:r=>r instanceof Set,nodeClass:Ri,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>Ri.from(r,e,t),resolve(r,e){if(Vt(r)){if(r.hasAllNullValues(!0))return Object.assign(new Ri,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function qf(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 xv(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Ke(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 fc={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})=>qf(r,t),stringify:xv},pc={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=>qf(r,!1),stringify:xv},Oi={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(Oi.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=qf(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};var Ff=[Kt,Wt,an,Dn,Df,Lf,Sv,$v,Ev,Av,_v,vv,wv,Gs,Ht,Ys,Js,Qs,fc,pc,Oi];var kv=new Map([["core",mv],["failsafe",[Kt,Wt,an]],["json",gv],["yaml11",Ff],["yaml-1.1",Ff]]),Pv={binary:Gs,bool:Ws,float:sc,floatExp:ic,floatNaN:nc,floatTime:pc,int:cc,intHex:lc,intOct:ac,intTime:fc,map:Kt,merge:Ht,null:Dn,omap:Ys,pairs:Js,seq:Wt,set:Qs,timestamp:Oi},Cv={"tag:yaml.org,2002:binary":Gs,"tag:yaml.org,2002:merge":Ht,"tag:yaml.org,2002:omap":Ys,"tag:yaml.org,2002:pairs":Js,"tag:yaml.org,2002:set":Qs,"tag:yaml.org,2002:timestamp":Oi};function hc(r,e,t){let n=kv.get(e);if(n&&!r)return t&&!n.includes(Ht)?n.concat(Ht):n.slice();let i=n;if(!i)if(Array.isArray(r))i=[];else{let s=Array.from(kv.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(Ht)),i.reduce((s,o)=>{let a=typeof o=="string"?Pv[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(Pv).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 GI=(r,e)=>r.keye.key?1:0,Zs=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?hc(e,"compat"):e?hc(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?Cv:{},this.tags=hc(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Ut,{value:Kt}),Object.defineProperty(this,_t,{value:an}),Object.defineProperty(this,xr,{value:Wt}),this.sortMapEntries=typeof o=="function"?o:o===!0?GI:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function Mv(r,e){let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let c=r.directives.toString(r);c?(t.push(c),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let i=Ya(r,e),{commentString:s}=i.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=s(r.commentBefore);t.unshift(Ot(c,""))}let o=!1,a=null;if(r.contents){if(ie(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let u=s(r.contents.commentBefore);t.push(Ot(u,""))}i.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Cr(r.contents,i,()=>a=null,c);a&&(l+=pr(l,"",s(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Cr(r.contents,i));if(r.directives?.docEnd)if(r.comment){let c=s(r.comment);c.includes(` -`)?(t.push("..."),t.push(Ot(c,""))):t.push(`... ${c}`)}else t.push("...");else{let c=r.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(Ot(s(c),"")))}return t.join(` +${s.comment}`:n.comment}n=i}r.items[t]=re(n)?n:new Ee(n)}}else e("Expected a sequence for this tag");return r}function Gf(r,e,t){let{replacer:n}=t,i=new We(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(Bi(a,c,t))}return i}var so={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Wf,createNode:Gf};var Vi=class r extends We{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?.onCreate&&t.onCreate(n);for(let i of this.items){let s,o;if(re(i)?(s=Te(i.key,"",t),o=Te(i.value,s,t)):s=Te(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=Gf(e,t,n),s=new this;return s.items=i.items,s}};Vi.tag="tag:yaml.org,2002:omap";var oo={collection:"seq",identify:r=>r instanceof Map,nodeClass:Vi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=Wf(r,e),n=[];for(let{key:i}of t.items)H(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new Vi,t)},createNode:(r,e,t)=>Vi.from(r,e,t)};function J_({value:r,source:e},t){return e&&(r?Jf:Yf).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var Jf={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 L(!0),stringify:J_},Yf={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 L(!1),stringify:J_};var Y_={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:Ge},X_={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():Ge(r)}},Q_={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 L(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:Ge};var ao=r=>typeof r=="bigint"||Number.isInteger(r);function _c(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 Xf(r,e,t){let{value:n}=r;if(ao(n)){let i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return Ge(r)}var Z_={identify:ao,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>_c(r,2,2,t),stringify:r=>Xf(r,2,"0b")},ew={identify:ao,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>_c(r,1,8,t),stringify:r=>Xf(r,8,"0")},tw={identify:ao,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>_c(r,0,10,t),stringify:Ge},rw={identify:ao,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>_c(r,2,16,t),stringify:r=>Xf(r,16,"0x")};var zi=class r extends ke{constructor(e){super(e),this.tag=r.tag}add(e){let t;re(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),un(this.items,t.key)||this.items.push(t)}get(e,t){let n=un(this.items,e);return!t&&re(n)?H(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=un(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(Bi(o,null,n));return s}};zi.tag="tag:yaml.org,2002:set";var co={collection:"map",identify:r=>r instanceof Set,nodeClass:zi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>zi.from(r,e,t),resolve(r,e){if(Kt(r)){if(r.hasAllNullValues(!0))return Object.assign(new zi,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};function Qf(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 nw(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Ge(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 wc={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})=>Qf(r,t),stringify:nw},Sc={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=>Qf(r,!1),stringify:nw},Hi={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(Hi.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=Qf(u,!1);Math.abs(d)<30&&(d*=60),l-=6e4*d}return new Date(l)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};var Zf=[Jt,Yt,fn,Vn,Jf,Yf,Z_,ew,tw,rw,Y_,X_,Q_,io,Gt,oo,so,co,wc,Sc,Hi];var iw=new Map([["core",K_],["failsafe",[Jt,Yt,fn]],["json",G_],["yaml11",Zf],["yaml-1.1",Zf]]),sw={binary:io,bool:no,float:hc,floatExp:pc,floatNaN:fc,floatTime:Sc,int:gc,intHex:bc,intOct:yc,intTime:wc,map:Jt,merge:Gt,null:Vn,omap:oo,pairs:so,seq:Yt,set:co,timestamp:Hi},ow={"tag:yaml.org,2002:binary":io,"tag:yaml.org,2002:merge":Gt,"tag:yaml.org,2002:omap":oo,"tag:yaml.org,2002:pairs":so,"tag:yaml.org,2002:set":co,"tag:yaml.org,2002:timestamp":Hi};function $c(r,e,t){let n=iw.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(iw.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"?sw[o]:o;if(!a){let c=JSON.stringify(o),l=Object.keys(sw).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 TR=(r,e)=>r.keye.key?1:0,lo=class r{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:s,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?$c(e,"compat"):e?$c(null,e):null,this.name=typeof s=="string"&&s||"core",this.knownTags=i?ow:{},this.tags=$c(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,zt,{value:Jt}),Object.defineProperty(this,wt,{value:fn}),Object.defineProperty(this,Tr,{value:Yt}),this.sortMapEntries=typeof o=="function"?o:o===!0?TR:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};function aw(r,e){let t=[],n=e.directives===!0;if(e.directives!==!1&&r.directives){let c=r.directives.toString(r);c?(t.push(c),n=!0):r.directives.docStart&&(n=!0)}n&&t.push("---");let i=sc(r,e),{commentString:s}=i.options;if(r.commentBefore){t.length!==1&&t.unshift("");let c=s(r.commentBefore);t.unshift(Dt(c,""))}let o=!1,a=null;if(r.contents){if(ie(r.contents)){if(r.contents.spaceBefore&&n&&t.push(""),r.contents.commentBefore){let u=s(r.contents.commentBefore);t.push(Dt(u,""))}i.forceBlockIndent=!!r.comment,a=r.contents.comment}let c=a?void 0:()=>o=!0,l=Nr(r.contents,i,()=>a=null,c);a&&(l+=gr(l,"",s(a))),(l[0]==="|"||l[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${l}`:t.push(l)}else t.push(Nr(r.contents,i));if(r.directives?.docEnd)if(r.comment){let c=s(r.comment);c.includes(` +`)?(t.push("..."),t.push(Dt(c,""))):t.push(`... ${c}`)}else t.push("...");else{let c=r.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(Dt(s(c),"")))}return t.join(` `)+` -`}var cn=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ze,{value:Fa});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?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new fr({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(r.prototype,{[Ze]:{value:Fa}});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=ie(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Ni(this.contents)&&this.contents.add(e)}addIn(e,t){Ni(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=xf(this);e.anchor=!t||n.has(t)?kf(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=v=>typeof v=="number"||v instanceof String||v instanceof Number,g=t.filter(y).map(String);g.length>0&&(t=t.concat(g)),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??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=cv(this,o||"a"),m={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},h=Pr(e,u,m);return a&&le(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 $e(i,s)}delete(e){return Ni(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ci(e)?this.contents==null?!1:(this.contents=null,!0):Ni(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return le(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Ci(e)?!t&&K(this.contents)?this.contents.value:this.contents:le(this.contents)?this.contents.getIn(e,t):void 0}has(e){return le(this.contents)?this.contents.has(e):!1}hasIn(e){return Ci(e)?this.contents!==void 0:le(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Vs(this.schema,[e],t):Ni(this.contents)&&this.contents.set(e,t)}setIn(e,t){Ci(e)?this.contents=t:this.contents==null?this.contents=Vs(this.schema,Array.from(e),t):Ni(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 fr({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 fr({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 Zs(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=Ie(this.contents,t??"",a);if(typeof s=="function")for(let{count:l,res:u}of a.anchors.values())s(u,l);return typeof o=="function"?nn(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 Mv(this,e)}};function Ni(r){if(le(r))return!0;throw new Error("Expected a YAML collection as document contents")}var eo=class extends Error{constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}},Gt=class extends eo{constructor(e,t,n){super("YAMLParseError",e,t,n)}},to=class extends eo{constructor(e,t,n){super("YAMLWarning",e,t,n)}},Uf=(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 +`}var pn=class r{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,rt,{value:Ja});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?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new yr({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let e=Object.create(r.prototype,{[rt]:{value:Ja}});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=ie(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Ki(this.contents)&&this.contents.add(e)}addIn(e,t){Ki(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=qf(this);e.anchor=!t||n.has(t)?Ff(t||"a",n):t}return new Rr(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=_=>typeof _=="number"||_ instanceof String||_ instanceof Number,g=t.filter(y).map(String);g.length>0&&(t=t.concat(g)),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??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=q_(this,o||"a"),m={aliasDuplicateObjects:s??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:l,replacer:i,schema:this.schema,sourceObjects:p},h=Or(e,u,m);return a&&le(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 Ki(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Fi(e)?this.contents==null?!1:(this.contents=null,!0):Ki(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return le(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Fi(e)?!t&&H(this.contents)?this.contents.value:this.contents:le(this.contents)?this.contents.getIn(e,t):void 0}has(e){return le(this.contents)?this.contents.has(e):!1}hasIn(e){return Fi(e)?this.contents!==void 0:le(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Zs(this.schema,[e],t):Ki(this.contents)&&this.contents.set(e,t)}setIn(e,t){Fi(e)?this.contents=t:this.contents==null?this.contents=Zs(this.schema,Array.from(e),t):Ki(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 yr({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 yr({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 lo(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=Te(this.contents,t??"",a);if(typeof s=="function")for(let{count:l,res:u}of a.anchors.values())s(u,l);return typeof o=="function"?ln(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 aw(this,e)}};function Ki(r){if(le(r))return!0;throw new Error("Expected a YAML collection as document contents")}var uo=class extends Error{constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}},Xt=class extends uo{constructor(e,t,n){super("YAMLParseError",e,t,n)}},fo=class extends uo{constructor(e,t,n){super("YAMLWarning",e,t,n)}},ep=(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?.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 hr(r,{flow:e,indicator:t,next:n,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,d="",f="",p=!1,m=!1,h=null,y=null,g=null,v=null,_=null,w=null,A=null;for(let S of r)switch(m&&(S.type!=="space"&&S.type!=="newline"&&S.type!=="comma"&&s(S.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&S.type!=="comment"&&S.type!=="newline"&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),S.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&S.source.includes(" ")&&(h=S),u=!0;break;case"comment":{u||s(S,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let C=S.source.substring(1)||" ";d?d+=f+C:d=C,f="",l=!1;break}case"newline":l?d?d+=S.source:(!w||t!=="seq-item-ind")&&(c=!0):f+=S.source,l=!0,p=!0,(y||g)&&(v=S),u=!0;break;case"anchor":y&&s(S,"MULTIPLE_ANCHORS","A node can have at most one anchor"),S.source.endsWith(":")&&s(S.offset+S.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=S,A??(A=S.offset),l=!1,u=!1,m=!0;break;case"tag":{g&&s(S,"MULTIPLE_TAGS","A node can have at most one tag"),g=S,A??(A=S.offset),l=!1,u=!1,m=!0;break}case t:(y||g)&&s(S,"BAD_PROP_ORDER",`Anchors and tags must be after the ${S.source} indicator`),w&&s(S,"UNEXPECTED_TOKEN",`Unexpected ${S.source} in ${e??"collection"}`),w=S,l=t==="seq-item-ind"||t==="explicit-key-ind",u=!1;break;case"comma":if(e){_&&s(S,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),_=S,l=!1,u=!1;break}default:s(S,"UNEXPECTED_TOKEN",`Unexpected ${S.type} token`),l=!1,u=!1}let x=r[r.length-1],M=x?x.offset+x.source.length:i;return m&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&s(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:_,found:w,spaceBefore:c,comment:d,hasNewline:p,anchor:y,tag:g,newlineAfterProp:v,end:M,start:A??M}}function ln(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(ln(e.key)||ln(e.value))return!0}return!1;default:return!0}}function ro(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&ln(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function mc(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let i=typeof n=="function"?n:(s,o)=>s===o||K(s)&&K(o)&&s.value===o.value;return e.some(s=>i(s.key,t))}var Tv="All mapping items must start at the same column";function Iv({composeNode:r,composeEmptyNode:e},t,n,i,s){let o=s?.nodeClass??ke,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let u of n.items){let{start:d,key:f,sep:p,value:m}=u,h=hr(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),y=!h.found;if(y){if(f&&(f.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&i(c,"BAD_INDENT",Tv)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(a.comment?a.comment+=` -`+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||ln(f))&&i(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&i(c,"BAD_INDENT",Tv);t.atKey=!0;let g=h.end,v=f?r(t,f,h,i):e(t,g,d,null,h,i);t.schema.compat&&ro(n.indent,f,i),t.atKey=!1,mc(t,a.items,v)&&i(g,"DUPLICATE_KEY","Map keys must be unique");let _=hr(p??[],{indicator:"map-value-ind",next:m,offset:v.range[2],onError:i,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=_.end,_.found){y&&(m?.type==="block-map"&&!_.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&h.start<_.found.offset-1024&&i(v.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let w=m?r(t,m,_,i):e(t,c,p,null,_,i);t.schema.compat&&ro(n.indent,m,i),c=w.range[2];let A=new $e(v,w);t.options.keepSourceTokens&&(A.srcToken=u),a.items.push(A)}else{y&&i(v.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),_.comment&&(v.comment?v.comment+=` -`+_.comment:v.comment=_.comment);let w=new $e(v);t.options.keepSourceTokens&&(w.srcToken=u),a.items.push(w)}}return l&&lr&&(r.type==="block-map"||r.type==="block-seq");function Ov({composeNode:r,composeEmptyNode:e},t,n,i,s){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?ke:He),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 y=0;y0){let y=mr(m,h,t.options.strict,i);y.comment&&(l.comment?l.comment+=` -`+y.comment:l.comment=y.comment),l.range=[n.offset,h,y.offset]}else l.range=[n.offset,h,h];return l}function zf(r,e,t,n,i,s){let o=t.type==="block-map"?Iv(r,e,t,n,s):t.type==="block-seq"?Rv(r,e,t,n,s):Ov(r,e,t,n,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function Nv(r,e,t,n,i){let s=n.tag,o=s?e.directives.tagName(s.source,f=>i(s,"TAG_RESOLVE_FAILED",f)):null;if(t.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=n,m=f&&s?f.offset>s.offset?f:s:f??s;m&&(!p||p.offsetf.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?i(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),zf(r,e,t,i,o)}let l=zf(r,e,t,i,o,c),u=c.resolve?.(l,f=>i(s,"TAG_RESOLVE_FAILED",f),e.options)??l,d=ie(u)?u:new L(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function Hf(r,e,t){let n=e.offset,i=JI(e,r.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let s=i.mode===">"?L.BLOCK_FOLDED:L.BLOCK_LITERAL,o=e.source?YI(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?` +`}};function br(r,{flow:e,indicator:t,next:n,offset:i,onError:s,parentIndent:o,startOnNewline:a}){let c=!1,l=a,u=a,d="",f="",p=!1,m=!1,h=null,y=null,g=null,_=null,v=null,w=null,S=null;for(let $ of r)switch(m&&($.type!=="space"&&$.type!=="newline"&&$.type!=="comma"&&s($.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(l&&$.type!=="comment"&&$.type!=="newline"&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),$.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&$.source.includes(" ")&&(h=$),u=!0;break;case"comment":{u||s($,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let M=$.source.substring(1)||" ";d?d+=f+M:d=M,f="",l=!1;break}case"newline":l?d?d+=$.source:(!w||t!=="seq-item-ind")&&(c=!0):f+=$.source,l=!0,p=!0,(y||g)&&(_=$),u=!0;break;case"anchor":y&&s($,"MULTIPLE_ANCHORS","A node can have at most one anchor"),$.source.endsWith(":")&&s($.offset+$.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=$,S??(S=$.offset),l=!1,u=!1,m=!0;break;case"tag":{g&&s($,"MULTIPLE_TAGS","A node can have at most one tag"),g=$,S??(S=$.offset),l=!1,u=!1,m=!0;break}case t:(y||g)&&s($,"BAD_PROP_ORDER",`Anchors and tags must be after the ${$.source} indicator`),w&&s($,"UNEXPECTED_TOKEN",`Unexpected ${$.source} in ${e??"collection"}`),w=$,l=t==="seq-item-ind"||t==="explicit-key-ind",u=!1;break;case"comma":if(e){v&&s($,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),v=$,l=!1,u=!1;break}default:s($,"UNEXPECTED_TOKEN",`Unexpected ${$.type} token`),l=!1,u=!1}let x=r[r.length-1],C=x?x.offset+x.source.length:i;return m&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&s(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(l&&h.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&s(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:v,found:w,spaceBefore:c,comment:d,hasNewline:p,anchor:y,tag:g,newlineAfterProp:_,end:C,start:S??C}}function hn(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(hn(e.key)||hn(e.value))return!0}return!1;default:return!0}}function po(r,e,t){if(e?.type==="flow-collection"){let n=e.end[0];n.indent===r&&(n.source==="]"||n.source==="}")&&hn(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}function Ec(r,e,t){let{uniqueKeys:n}=r.options;if(n===!1)return!1;let i=typeof n=="function"?n:(s,o)=>s===o||H(s)&&H(o)&&s.value===o.value;return e.some(s=>i(s.key,t))}var cw="All mapping items must start at the same column";function lw({composeNode:r,composeEmptyNode:e},t,n,i,s){let o=s?.nodeClass??ke,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,l=null;for(let u of n.items){let{start:d,key:f,sep:p,value:m}=u,h=br(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),y=!h.found;if(y){if(f&&(f.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&i(c,"BAD_INDENT",cw)),!h.anchor&&!h.tag&&!p){l=h.end,h.comment&&(a.comment?a.comment+=` +`+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||hn(f))&&i(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&i(c,"BAD_INDENT",cw);t.atKey=!0;let g=h.end,_=f?r(t,f,h,i):e(t,g,d,null,h,i);t.schema.compat&&po(n.indent,f,i),t.atKey=!1,Ec(t,a.items,_)&&i(g,"DUPLICATE_KEY","Map keys must be unique");let v=br(p??[],{indicator:"map-value-ind",next:m,offset:_.range[2],onError:i,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(c=v.end,v.found){y&&(m?.type==="block-map"&&!v.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&h.startr&&(r.type==="block-map"||r.type==="block-seq");function uw({composeNode:r,composeEmptyNode:e},t,n,i,s){let o=n.start.source==="{",a=o?"flow map":"flow sequence",c=s?.nodeClass??(o?ke:We),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 y=0;y0){let y=vr(m,h,t.options.strict,i);y.comment&&(l.comment?l.comment+=` +`+y.comment:l.comment=y.comment),l.range=[n.offset,h,y.offset]}else l.range=[n.offset,h,h];return l}function np(r,e,t,n,i,s){let o=t.type==="block-map"?lw(r,e,t,n,s):t.type==="block-seq"?dw(r,e,t,n,s):uw(r,e,t,n,s),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}function fw(r,e,t,n,i){let s=n.tag,o=s?e.directives.tagName(s.source,f=>i(s,"TAG_RESOLVE_FAILED",f)):null;if(t.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=n,m=f&&s?f.offset>s.offset?f:s:f??s;m&&(!p||p.offsetf.tag===o&&f.collection===a);if(!c){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),c=f;else return f?i(s,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),np(r,e,t,i,o)}let l=np(r,e,t,i,o,c),u=c.resolve?.(l,f=>i(s,"TAG_RESOLVE_FAILED",f),e.options)??l,d=ie(u)?u:new L(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}function ip(r,e,t){let n=e.offset,i=RR(e,r.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};let s=i.mode===">"?L.BLOCK_FOLDED:L.BLOCK_LITERAL,o=e.source?OR(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||g[0]===" "?(f===" "?f=` `:!p&&f===` `&&(f=` @@ -105,74 +108,76 @@ ${l} `+o[h][0].slice(c);d[d.length-1]!==` `&&(d+=` `);break;default:d+=` -`}let m=n+i.length+e.source.length;return{value:d,type:s,comment:i.comment,range:[n,m,m]}}function JI({offset:r,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:i}=e[0],s=i[0],o=0,a="",c=-1;for(let f=1;ft(n+f,p,m);switch(i){case"scalar":a=L.PLAIN,c=XI(s,l);break;case"single-quoted-scalar":a=L.QUOTE_SINGLE,c=QI(s,l);break;case"double-quoted-scalar":a=L.QUOTE_DOUBLE,c=ZI(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=mr(o,u,e,t);return{value:c,type:a,comment:d.comment,range:[n,u,d.offset]}}function XI(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}`),Dv(r)}function QI(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),Dv(r.slice(1,-1)).replace(/''/g,"'")}function Dv(r){let e,t;try{e=new RegExp(`(.*?)(?t(n+f,p,m);switch(i){case"scalar":a=L.PLAIN,c=NR(s,l);break;case"single-quoted-scalar":a=L.QUOTE_SINGLE,c=DR(s,l);break;case"double-quoted-scalar":a=L.QUOTE_DOUBLE,c=LR(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=vr(o,u,e,t);return{value:c,type:a,comment:d.comment,range:[n,u,d.offset]}}function NR(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}`),pw(r)}function DR(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),pw(r.slice(1,-1)).replace(/''/g,"'")}function pw(r){let e,t;try{e=new RegExp(`(.*?)(?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 eR(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 jR(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 tR={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:` -`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function rR(r,e,t,n){let i=r.substr(e,t),o=i.length===t&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(o)}catch{let a=r.substr(e-2,t+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}function Wf(r,e,t,n){let{value:i,type:s,comment:o,range:a}=e.type==="block-scalar"?Hf(r,e,n):Kf(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[_t]:c?l=nR(r.schema,i,c,t,n):e.type==="scalar"?l=iR(r,i,e,n):l=r.schema[_t];let u;try{let d=l.resolve(i,f=>n(t??e,"TAG_RESOLVE_FAILED",f),r.options);u=K(d)?d:new L(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(t??e,"TAG_RESOLVE_FAILED",f),u=new L(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 nR(r,e,t,n,i){if(t==="!")return r[_t];let s=[];for(let a of r.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;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[_t])}function iR({atKey:r,directives:e,schema:t},n,i,s){let o=t.tags.find(a=>(a.default===!0||r&&a.default==="key")&&a.test?.test(n))||t[_t];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[_t];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),u=`Value may be parsed as either ${c} or ${l}`;s(i,"TAG_RESOLVE_FAILED",u,!0)}}return o}function Lv(r,e,t){if(e){t??(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?.type==="space";)r+=i.source.length,i=e[++n];break}}return r}var sR={composeNode:Gf,composeEmptyNode:yc};function Gf(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=oR(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=Wf(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=Nv(sR,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??(l=yc(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&&(!K(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(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 yc(r,e,t,n,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:Lv(e,t,n),indent:-1,source:""},d=Wf(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 oR({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=mr(n,o,r.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}function jv(r,e,{offset:t,start:n,value:i,end:s},o){let a=Object.assign({_directives:e},r),c=new cn(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=hr(n,{indicator:"doc-start",next:i??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?Gf(l,i,u,o):yc(l,u.end,n,null,u,o);let d=c.contents.range[2],f=mr(s,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,d,f.offset],c}function no(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 qv(r){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[wt]:c?l=UR(r.schema,i,c,t,n):e.type==="scalar"?l=BR(r,i,e,n):l=r.schema[wt];let u;try{let d=l.resolve(i,f=>n(t??e,"TAG_RESOLVE_FAILED",f),r.options);u=H(d)?d:new L(d)}catch(d){let f=d instanceof Error?d.message:String(d);n(t??e,"TAG_RESOLVE_FAILED",f),u=new L(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 UR(r,e,t,n,i){if(t==="!")return r[wt];let s=[];for(let a of r.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)s.push(a);else return a;for(let a of s)if(a.test?.test(e))return a;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[wt])}function BR({atKey:r,directives:e,schema:t},n,i,s){let o=t.tags.find(a=>(a.default===!0||r&&a.default==="key")&&a.test?.test(n))||t[wt];if(t.compat){let a=t.compat.find(c=>c.default&&c.test?.test(n))??t[wt];if(o.tag!==a.tag){let c=e.tagString(o.tag),l=e.tagString(a.tag),u=`Value may be parsed as either ${c} or ${l}`;s(i,"TAG_RESOLVE_FAILED",u,!0)}}return o}function hw(r,e,t){if(e){t??(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?.type==="space";)r+=i.source.length,i=e[++n];break}}return r}var VR={composeNode:ap,composeEmptyNode:xc};function ap(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=zR(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=op(r,e,c,n),a&&(l.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{l=fw(VR,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??(l=xc(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&&(!H(l)||typeof l.value!="string"||l.tag&&l.tag!=="tag:yaml.org,2002:str")&&n(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 xc(r,e,t,n,{spaceBefore:i,comment:s,anchor:o,tag:a,end:c},l){let u={type:"scalar",offset:hw(e,t,n),indent:-1,source:""},d=op(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 zR({options:r},{offset:e,source:t,end:n},i){let s=new Rr(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=vr(n,o,r.strict,i);return s.range=[e,o,a.offset],a.comment&&(s.comment=a.comment),s}function mw(r,e,{offset:t,start:n,value:i,end:s},o){let a=Object.assign({_directives:e},r),c=new pn(void 0,a),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=br(n,{indicator:"doc-start",next:i??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?ap(l,i,u,o):xc(l,u.end,n,null,u,o);let d=c.contents.range[2],f=vr(s,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[t,d,f.offset],c}function ho(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 yw(r){let e="",t=!1,n=!1;for(let i=0;i{let o=no(t);s?this.warnings.push(new to(o,n,i)):this.errors.push(new Gt(o,n,i))},this.directives=new fr({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:i}=qv(this.prelude);if(n){let s=e.contents;if(t)e.comment=e.comment?`${e.comment} +`)+(s.substring(1)||" "),t=!0,n=!1;break;case"%":r[i+1]?.[0]!=="#"&&(i+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}var mo=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,i,s)=>{let o=ho(t);s?this.warnings.push(new fo(o,n,i)):this.errors.push(new Xt(o,n,i))},this.directives=new yr({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:i}=yw(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(le(s)&&!s.flow&&s.items.length>0){let o=s.items[0];re(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=no(e);s[0]+=t,this.onError(s,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=jv(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 Gt(no(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 Gt(no(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=mr(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 Gt(no(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 cn(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 Jf=Symbol("break visit"),aR=Symbol("skip children"),Fv=Symbol("remove item");function Ln(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),Uv(Object.freeze([]),r,e)}Ln.BREAK=Jf;Ln.SKIP=aR;Ln.REMOVE=Fv;Ln.itemAtPath=(r,e)=>{let t=r;for(let[n,i]of e){let s=t?.[n];if(s&&"items"in s)t=s.items[i];else return}return t};Ln.parentCollection=(r,e)=>{let t=Ln.itemAtPath(r,e.slice(0,-1)),n=e[e.length-1][0],i=t?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function Uv(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{let s=ho(e);s[0]+=t,this.onError(s,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=mw(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(ho(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(ho(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;let t=vr(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(ho(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 pn(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 cp=Symbol("break visit"),HR=Symbol("skip children"),gw=Symbol("remove item");function zn(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),bw(Object.freeze([]),r,e)}zn.BREAK=cp;zn.SKIP=HR;zn.REMOVE=gw;zn.itemAtPath=(r,e)=>{let t=r;for(let[n,i]of e){let s=t?.[n];if(s&&"items"in s)t=s.items[i];else return}return t};zn.parentCollection=(r,e)=>{let t=zn.itemAtPath(r,e.slice(0,-1)),n=e[e.length-1][0],i=t?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function bw(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 Jt(r){switch(r){case void 0:case" ":case` -`:case"\r":case" ":return!0;default:return!1}}var Vv=new Set("0123456789ABCDEFabcdef"),lR=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),bc=new Set(",[]{}"),dR=new Set(` ,[]{} -\r `),Zf=r=>!r||dR.has(r),so=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){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=this.next??"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 _w=new Set("0123456789ABCDEFabcdef"),WR=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),kc=new Set(",[]{}"),GR=new Set(` ,[]{} +\r `),fp=r=>!r||GR.has(r),yo=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){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=this.next??"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 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==="...")&&Jt(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&ethis.indentValue&&!Jt(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===":")&&Jt(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(Zf),"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=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(fp),"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=>Jt(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` +`,s)}i!==-1&&(t=i-(n[i-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"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 gc,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(Jt(s)||e&&bc.has(s))break;t=n}else if(Jt(i)){let s=this.buffer[n+1];if(i==="\r"&&(s===` +`&&s>=this.pos&&s+1+t>a)e=s;else break}while(!0);return yield Ac,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&&kc.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&&bc.has(s))break;if(i===` -`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&bc.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield gc,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(Zf),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,n=this.charAt(1);if(Jt(n)||t&&bc.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(;!Jt(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(lR.has(t))t=this.buffer[++e];else if(t==="%"&&Vv.has(this.buffer[e+1])&&Vv.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===` +`,s=this.buffer[n+1]):t=n),s==="#"||e&&kc.has(s))break;if(i===` +`){let o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&kc.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield Ac,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(fp),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,n=this.charAt(1);if(Qt(n)||t&&kc.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(WR.has(t))t=this.buffer[++e];else if(t==="%"&&_w.has(this.buffer[e+1])&&_w.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 i=t-this.pos;return i>0&&(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 oo=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(;r[++e]?.type==="space";);return r.splice(e,r.length)}function vc(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?.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??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"&&Hv(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&&zv(i.start)===-1&&(t.indent===0||i.start.every(s=>s.type!=="comment"||s.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 go=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(;r[++e]?.type==="space";);return r.splice(e,r.length)}function Cc(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?.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??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"&&Sw(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&&ww(i.start)===-1&&(t.indent===0||i.start.every(s=>s.type!=="comment"||s.indent=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,i=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",s=[];if(i&&t.sep&&!t.value){let o=[];for(let a=0;ae.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(s.push(this.sourceToken),e.items.push({start:s}),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?(s.push(this.sourceToken),e.items.push({start:s,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(dn(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(Kv(t.key)&&!dn(t.sep,"newline")){let o=Di(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?t.sep=t.sep.concat(s,this.sourceToken):t.sep.push(this.sourceToken);else if(dn(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=Di(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:s,key:null,sep:[this.sourceToken]}):dn(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 o=this.flowScalar(this.type);i||t.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!dn(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 n&&e.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.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]?.value?.end;if(Array.isArray(i)){vc(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||dn(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);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?.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=_c(n),s=Di(i);Hv(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(` +`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.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]?.value?.end;if(Array.isArray(i)){Cc(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,i=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",s=[];if(i&&t.sep&&!t.value){let o=[];for(let a=0;ae.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(s=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(s.push(this.sourceToken),e.items.push({start:s}),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?(s.push(this.sourceToken),e.items.push({start:s,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(mn(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if($w(t.key)&&!mn(t.sep,"newline")){let o=Wi(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else s.length>0?t.sep=t.sep.concat(s,this.sourceToken):t.sep.push(this.sourceToken);else if(mn(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=Wi(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:s,key:null,sep:[this.sourceToken]}):mn(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 o=this.flowScalar(this.type);i||t.value?(e.items.push({start:s,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!mn(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 n&&e.items.push({start:s});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.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]?.value?.end;if(Array.isArray(i)){Cc(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||mn(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let n=this.startBlockValue(e);if(n){this.stack.push(n);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?.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=Pc(n),s=Wi(i);Sw(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=_c(e),n=Di(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=_c(e),n=Di(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 uR(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new oo||null,prettyErrors:e}}function Wv(r,e={}){let{lineCounter:t,prettyErrors:n}=uR(e),i=new ao(t?.addNewLine),s=new io(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 Gt(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Uf(r,t)),o.warnings.forEach(Uf(r,t))),o}function Li(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let i=Wv(r,t);if(!i)return null;if(i.warnings.forEach(s=>Xa(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 hR(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function wc(r,e,t=""){let n=hR(r),i=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 ep(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 Gv(r,e){wc(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length='+t)}function un(...r){for(let e=0;e>>e}function $c(r,e){return r<>>32-e>>>0}var mR=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",yR=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Re(r){if(wc(r),mR)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 Jv=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Ac(r,e,t){return r&e^~r&t}function xc(r,e,t){return r&e^r&t^e&t}var ji=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,i){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Sc(this.buffer)}update(e){ep(this),wc(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=Yt(p,17)^Yt(p,19)^p>>>10;fn[d]=h+fn[d-7]+m+fn[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=Yt(a,6)^Yt(a,11)^Yt(a,25),p=u+f+Ac(a,c,l)+gR[d]+fn[d]|0,h=(Yt(n,2)^Yt(n,13)^Yt(n,22))+xc(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(){un(fn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),un(this.buffer)}},rp=class extends tp{A=Mr[0]|0;B=Mr[1]|0;C=Mr[2]|0;D=Mr[3]|0;E=Mr[4]|0;F=Mr[5]|0;G=Mr[6]|0;H=Mr[7]|0;constructor(){super(32)}};var We=Ec(()=>new rp,Jv(1));var b=class extends Error{code;constructor(e,t){super(t),this.code=e}};var Ir=new TextEncoder,bR=new Set(["null","true","false"]),Tr=Symbol("invalid-json-projection");function _R(r){return Re(We(Ir.encode(r)))}function Xv(r){return`sha256:${_R(r)}`}function kc(r){if(typeof r.document!="string")throw new b("invalid_authority_record",`Authority record ${r.path} omitted its exact Markdown document.`);return r.document}function Qv(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=ft(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=Yv(o);if(a!==null){if(t=ft(r,s,t),t<0||(t=ft(r,": ",t),t<0)||(t=ft(r,a,t),t<0)||(t=ft(r,` -`,t),t<0))return!1;continue}if(!Array.isArray(o))return null;if(o.length===0){if(t=ft(r,s,t),t<0||(t=ft(r,`: [] -`,t),t<0))return!1;continue}if(t=ft(r,s,t),t<0||(t=ft(r,`: -`,t),t<0))return!1;for(let c of o){let l=Yv(c);if(l===null)return null;if(t=ft(r," - ",t),t<0||(t=ft(r,l,t),t<0)||(t=ft(r,` -`,t),t<0))return!1}}if(!n)return r===e.body;if(t=ft(r,`--- +`,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=Pc(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=Pc(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 JR(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new go||null,prettyErrors:e}}function Ew(r,e={}){let{lineCounter:t,prettyErrors:n}=JR(e),i=new bo(t?.addNewLine),s=new mo(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(ep(r,t)),o.warnings.forEach(ep(r,t))),o}function Hn(r,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);let i=Ew(r,t);if(!i)return null;if(i.warnings.forEach(s=>oc(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 QR(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in r&&r.BYTES_PER_ELEMENT===1}function Mc(r,e,t=""){let n=QR(r),i=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 pp(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 xw(r,e){Mc(r,void 0,"digestInto() output");let t=e.outputLen;if(r.length='+t)}function yn(...r){for(let e=0;e>>e}function Tc(r,e){return r<>>32-e>>>0}var ZR=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",eO=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Oe(r){if(Mc(r),ZR)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 Aw=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Oc(r,e,t){return r&e^~r&t}function Nc(r,e,t){return r&e^r&t^e&t}var Gi=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,i){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Ic(this.buffer)}update(e){pp(this),Mc(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;gn[d]=h+gn[d-7]+m+gn[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+Oc(a,c,l)+tO[d]+gn[d]|0,h=(Zt(n,2)^Zt(n,13)^Zt(n,22))+Nc(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(){yn(gn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),yn(this.buffer)}},mp=class extends hp{A=Dr[0]|0;B=Dr[1]|0;C=Dr[2]|0;D=Dr[3]|0;E=Dr[4]|0;F=Dr[5]|0;G=Dr[6]|0;H=Dr[7]|0;constructor(){super(32)}};var Je=Rc(()=>new mp,Aw(1));var b=class extends Error{code;constructor(e,t){super(t),this.code=e}};function Kn(r){return r instanceof Error?r:Error(String(r))}function Wn(r,e){return r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:e}function Re(r){return new b("invalid_mirror_state",r)}var jr=new TextEncoder,rO=new Set(["null","true","false"]),Lr=Symbol("invalid-json-projection");function Pw(r){let e=nO(r);if(e===null)return{outcome:"parsed"};let t;try{t=Hn(e,{mapAsMap:!0,uniqueKeys:!0})}catch{return{outcome:"invalid_yaml"}}return t===null&&e.trim()===""?{outcome:"parsed"}:t instanceof Map?{outcome:"parsed"}:{outcome:"non_mapping_frontmatter"}}function nO(r){let e=r.startsWith("\uFEFF")?r.slice(1):r,t=e.indexOf(` +`);if(t<0||e.slice(0,t).trimEnd()!=="---")return null;let n=t+1;for(let i=n;i=0&&r.startsWith(i,t)&&t+i.length===r.length}function Pc(r,e){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=Li(t[1],{mapAsMap:!0})}catch{return{frontmatter:{},body:r}}if(n===null&&t[1].trim()==="")return{frontmatter:{},body:t[2]??""};let i=np(n,new Set);return i===Tr||!vR(i)?{frontmatter:{},body:r}:{frontmatter:i,body:t[2]??""}}function np(r,e){if(r===null||typeof r=="string"||typeof r=="boolean")return r;if(typeof r=="number")return Number.isFinite(r)?r:Tr;if(!r||typeof r!="object"||e.has(r))return Tr;e.add(r);try{if(Array.isArray(r)){let n=[];for(let i of r){let s=np(i,e);if(s===Tr)return Tr;n.push(s)}return n}if(!(r instanceof Map))return Tr;let t={};for(let[n,i]of r){if(typeof n!="string")return Tr;let s=np(i,e);if(s===Tr)return Tr;Object.defineProperty(t,n,{value:s,enumerable:!0,configurable:!0,writable:!0})}return t}finally{e.delete(r)}}function vR(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Yv(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&&bR.has(r.toLowerCase())?null:r}function ft(r,e,t){return r.startsWith(e,t)?t+e.length:-1}function Cc(r){let e=We.create().update(Ir.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 b("file_sync_unsupported","This replica cannot materialize collection file changes yet. Upgrade it before continuing sync.")}function Zv(r){SR([r])}var W=class extends b{status;constructor(e,t,n,i){super(e,t),this.status=n,this.name="AuthorityAdoptionError",i?.cause!==void 0&&(this.cause=i.cause)}},Rr=class extends W{sourceMustRemainFenced=!0;constructor(e,t){super("authority_adoption_outcome_unknown",e,void 0,t),this.name="AuthorityAdoptionOutcomeUnknownError"}};var qi=/^[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 jn(r,e){if(!qi.test(r))throw new W("invalid_authority_adoption",`${e} must be a UUID.`);return r.toLowerCase()}var co=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),pn=new Uint32Array(80),sp=class extends ji{A=co[0]|0;B=co[1]|0;C=co[2]|0;D=co[3]|0;E=co[4]|0;constructor(){super(64,20,8,!1)}get(){let{A:e,B:t,C:n,D:i,E:s}=this;return[e,t,n,i,s]}set(e,t,n,i,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=i|0,this.E=s|0}process(e,t){for(let c=0;c<16;c++,t+=4)pn[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)pn[c]=$c(pn[c-3]^pn[c-8]^pn[c-14]^pn[c-16],1);let{A:n,B:i,C:s,D:o,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=Ac(i,s,o),u=1518500249):c<40?(l=i^s^o,u=1859775393):c<60?(l=xc(i,s,o),u=2400959708):(l=i^s^o,u=3395469782);let d=$c(n,5)+l+a+u+pn[c]|0;a=o,o=s,s=$c(i,30),i=n,n=d}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,this.set(n,i,s,o,a)}roundClean(){un(pn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),un(this.buffer)}},Tc=Ec(()=>new sp);var $R=1e4,ER=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,AR=new TextEncoder;async function tw(r,e,t,n,i){let s=kR(n,t.media_type);if(s.size!==t.size||await PR(s,i.signal)!==t.content_digest)throw new W("authority_adoption_file_changed",`File bytes no longer match the fenced snapshot for ${t.path}.`);let o=CR(e.import_id,t),a=await op(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(TR(a,o,t.size),a.strategy.kind!=="object_put"&&a.strategy.kind!=="object_multipart")throw pt("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>$R)throw pt("Authority import returned too many file parts.");let u=new Set(a.received),d=new Map((a.uploaded_parts??[]).map(h=>[h.part_number-1,h]));if(a.received.length===l&&await ew(r,e,t,o,[...d.values()],i.signal))return;let f=Array(l);for(let[h,y]of d)f[h]=y;let p=[...u].reduce((h,y)=>h+Math.min(c,Math.max(0,t.size-y*c)),0);for(let h=0;hh!==void 0);if(!await ew(r,e,t,o,m,i.signal))throw new W("authority_adoption_file_upload_incomplete",`Connect could not commit ${t.path}.`)}async function ew(r,e,t,n,i,s){try{let o=await op(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||!NR(o.file,t))throw pt("Connect returned an invalid authority import file receipt.");return!0}catch(o){if(i.length===0&&o instanceof W&&o.code==="file_upload_incomplete")return!1;throw o}}async function op(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{throw Ic(i),new W("authority_adoption_unreachable","Connect could not be reached for collection adoption.")}if(s.status<200||s.status>=300)throw DR(s);return s.body}async function xR(r,e,t,n){RR(e.url);let i;try{i=await r({url:e.url,method:"PUT",headers:OR(e.headers),body:t,rawBody:!0,...n?{signal:n}:{}})}catch{throw Ic(n),new W("authority_adoption_unreachable","Connect could not be reached for collection adoption.")}if(i.status<200||i.status>=300)throw new W("authority_adoption_object_upload_failed","Object storage rejected an authority import file part.",i.status);return i}function kR(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 PR(r,e){let t=We.create(),n=r.stream().getReader();try{for(;;){Ic(e);let i=await n.read();if(i.done)break;t.update(i.value)}}finally{n.releaseLock()}return`sha256:${Re(t.digest())}`}function CR(r,e){let t=MR(r),n=AR.encode(`mdbase-authority-import-file-v1\0${e.file_id}\0${e.revision}\0${e.content_digest}`),i=Tc(new Uint8Array([...t,...n])).slice(0,16);i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=Re(i);return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function MR(r){if(!ER.test(r))throw pt("Authority import ID is invalid.");return Uint8Array.from(r.replaceAll("-","").match(/../g).map(e=>Number.parseInt(e,16)))}function TR(r,e,t){let n=r?.strategy;if(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 pt("Connect returned an invalid authority import file session.");if(n.kind!=="object_put"&&n.kind!=="object_multipart")throw pt("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(a=>!Number.isSafeInteger(a)||a<0||a>=s))throw pt("Connect returned invalid authority import file progress.");let o=r.uploaded_parts??[];if(!Array.isArray(o)||o.some((a,c)=>!Number.isSafeInteger(a?.part_number)||a.part_number<1||a.part_number>s||typeof a.etag!="string"||a.etag.length===0||a.etag.length>255||c>0&&o[c-1].part_number>=a.part_number)||(n.kind==="object_multipart"?o.length!==r.received.length||o.some((a,c)=>a.part_number-1!==r.received[c]):o.length!==0))throw pt("Connect returned invalid authority import part receipts.")}function IR(r,e,t,n,i){if(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))||!ap(r.headers))throw pt("Connect returned an invalid prepared authority import file part.")}function RR(r){let e;try{e=new URL(r)}catch{throw pt("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 pt("Connect returned an unsafe object storage URL.")}function OR(r){let e={};for(let[t,n]of Object.entries(r)){if(["authorization","cookie","host","proxy-authorization"].includes(t.toLowerCase()))throw pt("Connect returned unsafe object storage headers.");if(/\r|\n/.test(t)||/\r|\n/.test(n))throw pt("Connect returned invalid object storage headers.");e[t]=n}return e}function NR(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 DR(r){let e=ap(r.body)&&ap(r.body.error)?r.body.error:{};return new W(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 pt(r){return new W("invalid_authority_adoption_response",r)}function Ic(r){if(r?.aborted)throw new W("authority_adoption_cancelled","Collection adoption was cancelled.")}function ap(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var cp=1500,LR=250,jR=3e4,aw=1440*60*1e3,Or=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Rc=class{request;now;wait;constructor(e={}){this.request=e.request??qR,this.now=e.now??Date.now,this.wait=e.wait??VR}async begin(e,t={}){qn(t.signal);let n=Nr(e.controlUrl),i=e.mirrorName.trim();if(!i||i.length>200)throw new Ge("invalid_mirror_name","Mirror name must contain between 1 and 200 characters.");if(!["read_only","read_write"].includes(e.mode))throw new Ge("invalid_mirror_mode","Mirror mode must be read-only or read-write.");if(e.collectionId!==void 0&&!Or.test(e.collectionId))throw new Ge("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{throw qn(t.signal),sw()}let o=iw(s,201);if(!Fi(o)||!Or.test(vt(o.pairing_id))||!lo(o.pairing_secret)||!zR(o.expires_in)||Number(o.expires_in)*1e3>aw)throw Xt("Connect returned an invalid mirror approval.");let a=lw(n,vt(o.verification_uri),vt(o.pairing_id));return{controlUrl:n,pairingId:vt(o.pairing_id),refreshCredential:vt(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={}){FR(e,this.now());let n=ow(t.pollIntervalMs),i=Date.parse(e.expiresAt),s=0;for(;this.now()=500){let a=lp(o);if(await this.retry(i,o.retryAfterMs??n,t,s,{code:a.code,message:a.message})===null)break;continue}throw lp(o)}throw new Ge("mirror_enrollment_expired","Mirror approval expired before it was completed.")}async renew(e,t={}){UR(e),qn(t.signal);let n;try{n=await this.request({url:nw(e.controlUrl,e.enrollmentId,"renew"),method:"POST",headers:{authorization:`Bearer ${e.refreshCredential}`},...t.signal?{signal:t.signal}:{}})}catch{throw qn(t.signal),sw()}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 rw(i,iw(n,200),{replicaId:e.replicaId})}async retry(e,t,n,i,s){let o=e-this.now();if(o<=0)return null;let a=Math.min(ow(t),o),c=new Date(this.now()+a).toISOString();return n.onStatus?.({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}},Ge=class extends b{status;constructor(e,t,n){super(e,t),this.status=n,this.name="MirrorEnrollmentError"}};function Nr(r){let e;try{e=new URL(r)}catch{throw new Ge("invalid_connect_url","Connect URL must be an absolute HTTPS origin.")}if(e.pathname!=="/"||e.search||e.hash||e.username||e.password)throw new Ge("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 Ge("invalid_connect_url","Connect URL must use HTTPS outside loopback development.");return e.origin}async function qR(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:BR(n)}}}function rw(r,e,t){if(!Fi(e)||e.status!=="paired"||!Fi(e.replica))throw Xt("Connect returned an invalid mirror enrollment.");let n=e.replica,i=vt(n.id),s=vt(n.collection_id),o=vt(n.name).trim(),a=n.mode,c=vt(e.token),l=vt(e.token_expires_at);if(!Or.test(i)||!Or.test(s)||!o||!["read_only","read_write"].includes(String(a))||!lo(c)||!uw(l))throw Xt("Connect returned invalid mirror credentials.");if(a!==r.requested.mode)throw Xt("Connect returned a mirror with a different access mode.");if(r.requested.collectionId&&s!==r.requested.collectionId)throw Xt("Connect returned a different collection.");if(t.mirrorName!==void 0&&o!==t.mirrorName)throw Xt("Connect returned a mirror with a different name.");if(t.replicaId!==void 0&&i!==t.replicaId)throw Xt("Connect returned a different mirror replica.");let u;try{u=cw(vt(e.sync_url),s)}catch{throw Xt("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 FR(r,e){Nr(r.controlUrl);let t=Date.parse(r.expiresAt);if(!Or.test(r.pairingId)||!lo(r.refreshCredential)||!Number.isFinite(t)||t-e>aw||!r.requested.mirrorName.trim()||r.requested.mirrorName.length>200||!["read_only","read_write"].includes(r.requested.mode)||r.requested.collectionId!==void 0&&!Or.test(r.requested.collectionId))throw new Ge("invalid_mirror_enrollment_session","Mirror enrollment session is invalid.");lw(r.controlUrl,r.verificationUri,r.pairingId)}function UR(r){if(Nr(r.controlUrl),cw(r.syncUrl,r.collectionId),!Or.test(r.collectionId)||!Or.test(r.replicaId)||!Or.test(r.enrollmentId)||!lo(r.accessToken)||!lo(r.refreshCredential)||!uw(r.accessTokenExpiresAt)||!r.name.trim()||r.name.length>200||!["read_only","read_write"].includes(r.mode))throw new Ge("invalid_mirror_enrollment","Stored mirror enrollment is invalid.")}function cw(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 lw(r,e,t){let n;try{n=new URL(e)}catch{throw Xt("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 Xt("Connect returned an untrusted mirror verification URI.");return n.href}function nw(r,e,t){return`${Nr(r)}/v1/mirror-pairing-requests/${encodeURIComponent(e)}/${t}`}function iw(r,e){if(r.status!==e)throw lp(r);return r.body}function lp(r){let e=Fi(r.body)&&Fi(r.body.error)?r.body.error:{};return new Ge(vt(e.code)||"mirror_enrollment_request_failed",vt(e.message)||`Mirror enrollment request failed with status ${r.status}.`,r.status)}function Xt(r){return new Ge("invalid_mirror_enrollment_response",r)}function dw(r){return{code:"mirror_enrollment_unreachable",message:"Connect could not be reached for mirror enrollment."}}function sw(){let r=dw(void 0);return new Ge(r.code,r.message)}function ow(r=cp){return Number.isFinite(r)?Math.min(jR,Math.max(LR,Math.round(r))):cp}function BR(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()):cp}function VR(r,e){return qn(e),new Promise((t,n)=>{let i=setTimeout(o,r),s=()=>{clearTimeout(i),e?.removeEventListener("abort",s),n(new Ge("mirror_enrollment_cancelled","Mirror enrollment was cancelled."))};function o(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}function qn(r){if(r?.aborted)throw new Ge("mirror_enrollment_cancelled","Mirror enrollment was cancelled.")}function uw(r){let e=Date.parse(r);return Number.isFinite(e)}function zR(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function lo(r){return typeof r=="string"&&r.length>=16}function vt(r){return typeof r=="string"?r:""}function Fi(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var HR=/(?:^|\/)(?:\.{1,2}|)(?:\/|$)/u,KR=/[\p{Cc}:?<>|*"]/u,WR=/[. ](?:\/|$)/u,GR=/(?:^|\/)(?:CON|PRN|AUX|NUL|COM[1-9¹²³]|LPT[1-9¹²³])(?:\.|\/|$)/iu;function Qt(r){if(!r||r.startsWith("/")||r.includes("\\")||HR.test(r)||KR.test(r)||WR.test(r)||GR.test(r))throw new b("invalid_path",`Mirror received an unsafe path: ${r}.`)}function wt(r){return Qt(r),Ui(r)}function Ui(r){return/^[\x20-\x7e]+$/u.test(r)?/[A-Z]/u.test(r)?r.toLowerCase():r:r.normalize("NFC").toLowerCase().normalize("NFC")}var pw=new Set(["image","audio","video","pdf","other"]),fw=["image","audio","video","pdf","other"],JR=new Set([".mdbase",".git","node_modules","_contracts","_schemas","_types","_views"]),YR=/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu,XR=/^sha256:[0-9a-f]{64}$/u,QR=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,ZR=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/u;function Fn(r){let e={file_classes:[...r?.file_classes??[]],excluded_folders:[...r?.excluded_folders??[]]};if(e.excluded_folders.length>100)throw new b("invalid_file_materialization","Selective sync supports at most 100 excluded folders.");let t=new Set;for(let s of e.file_classes){if(!pw.has(s)||t.has(s))throw new b("invalid_file_materialization","Selected file media classes must be valid and unique.");t.add(s)}let n=new Set,i=new Set;for(let s of e.excluded_folders){mw(s,!0);let o=wt(s);if(n.has(s)||i.has(o))throw new b("invalid_file_materialization","Excluded folders must be unique on portable filesystems.");n.add(s),i.add(o)}return e.file_classes.sort((s,o)=>fw.indexOf(s)-fw.indexOf(o)),e.excluded_folders.sort((s,o)=>wt(s).localeCompare(wt(o))),e}function Un(r,e){let t=wt(e);return!r.excluded_folders.some(n=>{let i=wt(n);return t===i||t.startsWith(`${i}/`)})}function Nc(r,e){return r.file_classes.includes(e.media_class)&&Un(r,e.path)}function dp(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 hw(r,e){return r.file_classes.includes(dp(e))&&Un(r,e)}function ht(r){if(mw(r.path,!1),typeof r.file_id!="string"||!QR.test(r.file_id)||typeof r.revision!="string"||!r.revision||r.revision.length>255||!XR.test(r.content_digest)||!Number.isSafeInteger(r.size)||r.size<0||!pw.has(r.media_class)||typeof r.modified_at!="string"||!ZR.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 b("invalid_snapshot",`Collection file ${r.path} has invalid metadata.`)}function mw(r,e){if(Qt(r),r.length>1024)throw new b("invalid_file_path","Collection file paths cannot exceed 1024 characters.");if(r.split("/").some(i=>i.startsWith(".")||/[<>"|?*]/u.test(i)||YR.test(i)||JR.has(i.toLowerCase()))||!e&&/\.md$/iu.test(r))throw new b("invalid_file_path",`Collection file path ${r} is hidden, reserved, or non-portable.`)}async function yw(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 b("invalid_snapshot","Authority file snapshot boundary changed during download.");for(let o of s.files)ht(o);if(await t(s.files),n=s.next_page,n!==void 0&&i.has(n))throw new b("invalid_snapshot","Authority file snapshot repeated a page cursor.");n!==void 0&&i.add(n)}while(n)}function Dr(r,e){return r?.size===e.size&&r.content_digest===e.content_digest}async function*Oc(r,e){let t=We.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 b("file_integrity_failed","A file transport returned invalid bytes.")}if(n+=i.byteLength,!Number.isSafeInteger(n)||n>e.size)throw new b("file_integrity_failed",`Downloaded bytes for ${e.path} are oversized.`);t.update(i),yield i}if(n!==e.size||`sha256:${Re(t.digest())}`!==e.content_digest)throw new b("file_integrity_failed",`Downloaded bytes for ${e.path} failed integrity verification.`)}async function*gw(r,e,t){let n=We.create(),i=0;for await(let s of r){if(!(s instanceof Uint8Array))throw new b("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 b("pending_local_changed",`Local file ${t} changed while being staged.`);n.update(s),yield s}}if(i!==e.size||`sha256:${Re(n.digest())}`!==e.content_digest)throw new b("pending_local_changed",`Local file ${t} changed while being staged.`)}async function Dc(r,e,t){if(ht(t),await e.has(t.content_digest))try{for await(let n of Oc(e.read(t.content_digest),t));return}catch{await e.remove(t.content_digest)}try{await e.write(t.content_digest,Oc(r.downloadFile(t),t))}catch(n){throw await e.remove(t.content_digest).catch(()=>{}),n}if(!await e.has(t.content_digest))throw new b("file_integrity_failed","The verified file blob was not persisted.")}var hn=new TextEncoder;function pp(r){let e=jn(r.collectionId,"Collection ID"),t=r.sourceHead??0;if(!Number.isSafeInteger(t)||t<0)throw new W("invalid_authority_snapshot","Source head must be a non-negative integer.");let n=new Set,i=r.resources.map(d=>{let f=Lc(d.path);if(n.add(f)||up(f),!["configuration","lock","contract","schema","type","view"].includes(d.kind))throw new W("invalid_authority_snapshot",`Unsupported collection resource kind for ${f}.`);return{path:f,kind:d.kind,revision:bw(d.document),document:d.document}}).sort(tO);if(i[0]?.path!=="mdbase.yaml"||i[0].kind!=="configuration"||i.filter(({kind:d})=>d==="configuration").length!==1)throw new W("invalid_authority_snapshot","A portable snapshot requires one mdbase.yaml configuration resource.");let s=r.records.map(d=>{let f=Lc(d.path);return n.add(f)||up(f),{record_id:d.recordId?jn(d.recordId,`Record ID for ${f}`):jc(e,f),path:f,document:d.document}}).sort((d,f)=>fp(d.path,f.path)),o=new Set,a=(r.files??[]).map(d=>{let f=Lc(d.path);n.add(f)||up(f);let p=jn(d.file_id,`File ID for ${f}`);if(!o.add(p))throw new W("invalid_authority_snapshot",`Collection snapshot contains file ID more than once: ${p}`);return eO(d,f),{...d,file_id:p,path:f}}).sort((d,f)=>fp(d.path,f.path)),c=_w(i.flatMap(({path:d,revision:f})=>[d,f])),l=_w([...i.flatMap(({path:d,revision:f})=>["resource",d,f]),...s.flatMap(d=>["record",d.path,bw(d.document)]),...a.flatMap(d=>["file",d.path,d.file_id,d.revision,d.content_digest,String(d.size),d.media_type??"",d.media_class])]),u=Cc([...i.map(({path:d,document:f})=>({kind:"resource",path:d,identity:"",document_hash:Re(We(hn.encode(f)))})),...s.map(d=>({kind:"record",path:d.path,identity:d.record_id,document_hash:Re(We(hn.encode(d.document)))})),...a.map(d=>({kind:"file",path:d.path,identity:d.file_id,document_hash:Mc(d)}))]);return{protocol_version:1,collection_id:e,source_head:t,source_revision:l,manifest_digest:u,resources:{revision:c,spec_version:r.specVersion,types:r.types??[],contracts:r.contracts??[],documents:i},records:s,files:a}}function eO(r,e){try{ht({...r,path:e})}catch{throw new W("invalid_authority_snapshot",`File descriptor is invalid for ${e}.`)}if(r.media_class!==dp(e))throw new W("invalid_authority_snapshot",`File media class does not match its path for ${e}.`)}function jc(r,e){let t=rO(jn(r,"Collection ID")),i=Tc(new Uint8Array([...t,...hn.encode(Lc(e))])).slice(0,16);i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=Re(i);return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function bw(r){return`sha256:${Re(We(hn.encode(r)))}`}function _w(r){let e=We.create();for(let t of r){let n=BigInt(hn.encode(t).length),i=new Uint8Array(8);new DataView(i.buffer).setBigUint64(0,n),e.update(i),e.update(hn.encode(t))}return`sha256:${Re(e.digest())}`}function tO(r,e){return r.kind==="configuration"&&e.kind!=="configuration"?-1:e.kind==="configuration"&&r.kind!=="configuration"?1:fp(r.path,e.path)}function fp(r,e){let t=hn.encode(r),n=hn.encode(e),i=Math.min(t.length,n.length);for(let s=0;s!t||t==="."||t===".."))throw new W("invalid_authority_snapshot",`Collection path is unsafe: ${r}`);return e}function up(r){throw new W("invalid_authority_snapshot",`Collection snapshot contains the path more than once: ${r}`)}function rO(r){return Uint8Array.from(r.replaceAll("-","").match(/../g).map(e=>Number.parseInt(e,16)))}var nO=/^sha256:[a-f0-9]{64}$/,iO=/^[a-f0-9]{64}$/,mp=1500,yp=1440*60*1e3,sO=200,vw=8*1024*1024,oO=new TextEncoder,qc=class{request;now;wait;constructor(e={}){this.request=e.request??dO,this.now=e.now??Date.now,this.wait=e.wait??lO}async begin(e,t={}){Vn(t.signal);let n=Nr(e.controlUrl),i=jn(e.collectionId,"Collection ID"),s=hp(e.displayName,"Collection name"),o=hp(e.sourceName,"Source name"),a=e.retainMirror??!0,c=a?hp(e.mirrorName??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{throw Vn(t.signal),Ew()}let u=cO(l,201);if(!Lr(u)||!qi.test(et(u.adoption_id))||!gp(u.adoption_secret)||!hO(u.expires_in)||Number(u.expires_in)*1e3>yp)throw tt("Connect returned an invalid collection adoption request.");let d=Cw(n,et(u.verification_uri),et(u.adoption_id));return{controlUrl:n,adoptionId:et(u.adoption_id),credential:et(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={}){Bi(e,this.now());let n=Aw(t.pollIntervalMs),i=Date.parse(e.expiresAt),s=0;for(;this.now()=500){let a=Bn(o);if(!await this.retry(i,o.retryAfterMs??n,s,t,{code:a.code,message:a.message}))break;continue}throw Bn(o)}throw new W("authority_adoption_expired","Collection adoption approval expired before upload began.")}async exchange(e,t={}){Bi(e,this.now(),!0);let n=await this.controlRequest(e,"exchange","POST",{},t.signal);if(n.status===202)throw new W("authority_adoption_pending","Collection adoption is still awaiting approval.",202);if(n.status!==200)throw Bn(n);return Sw(e,n.body)}async uploadSnapshot(e,t,n,i={}){Bi(e,this.now(),!0),kw(e,t),ww(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=oO.encode(JSON.stringify(l)).length;if(u>vw)throw new W("authority_adoption_record_too_large",`Record ${l.path} is too large to adopt.`);a.length>0&&(a.length===sO||c+u>vw)&&(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 W("authority_adoption_file_source_required",`File bytes are required to adopt ${l.path}.`);let u=await i.fileSource(l);await tw(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={}){Bi(e,this.now(),!0),ww(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 Vn(n.signal),new Rr("Connect could not confirm whether hosted authority activated.",{cause:a})}if(i.status>=500)throw new Rr("Connect could not confirm whether hosted authority activated.");if(i.status!==200)throw Bn(i);let s=i.body;if(!Lr(s)||s.status!=="completed")throw tt("Connect returned an invalid adoption completion.");let o=Pw(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 tt("Connect completed a different adoption snapshot.");return{status:"completed",adoption:o}}async cancel(e,t={}){Bi(e,this.now(),!0);let n=await this.controlRequest(e,void 0,"DELETE",void 0,t.signal);if(n.status!==200)throw Bn(n)}mirrorEnrollmentSession(e,t){if(Bi(e,this.now(),!0),t.status!=="completed"||t.adoption.collection_id!==e.requested.collectionId)throw tt("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()+yp).toISOString(),requested:{mirrorName:e.requested.mirrorName??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{throw Vn(s),Ew()}if(o.status<200||o.status>=300)throw Bn(o)}controlRequest(e,t,n,i,s){return this.request({url:$w(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){let o=e-this.now();if(o<=0)return!1;let a=Math.min(Aw(t),o),c=new Date(this.now()+a).toISOString();return i.onStatus?.({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 Bi(r,e,t=!1){Nr(r.controlUrl);let n=Date.parse(r.expiresAt);if(!qi.test(r.adoptionId)||!gp(r.credential)||!Number.isFinite(n)||n-e>yp||!t&&n<=e||!qi.test(r.requested.collectionId)||!r.requested.displayName.trim()||!r.requested.sourceName.trim())throw new W("invalid_authority_adoption_session","Stored collection adoption state is invalid.");Cw(r.controlUrl,r.verificationUri,r.adoptionId)}function kw(r,e){if(e.status!=="ready"||e.adoption.id!==r.adoptionId||e.adoption.collection_id!==r.requested.collectionId)throw tt("Prepared adoption does not belong to this session.");let t=e.import;if(!qi.test(t.import_id)||!gp(t.access_token))throw tt("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=aO(s,t.import_id,o);if(!a||i!==void 0&&a.origin!==i)throw tt("Connect returned an invalid authority import capability.");i=a.origin}}function ww(r,e){if(e.protocol_version!==1||e.collection_id!==r.requested.collectionId||!Number.isSafeInteger(e.source_head)||e.source_head<0||!nO.test(e.source_revision)||!iO.test(e.manifest_digest)||e.resources.documents?.length===0||!Array.isArray(e.files))throw new W("invalid_authority_snapshot","Authority snapshot does not belong to this adoption.")}function Sw(r,e){if(!Lr(e)||!["ready","activating","completed"].includes(et(e.status)))throw tt("Connect returned an invalid adoption exchange.");let t=Pw(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 tt("Connect omitted the authority import capability.");let n=e.import,i=e.staged,s={status:"ready",adoption:t,import:{import_id:et(n.import_id),manifest_url:et(n.manifest_url),records_url:et(n.records_url),files_url:et(n.files_url),finalize_url:et(n.finalize_url),access_token:et(n.access_token)},staged:{state:i.state,manifest_digest:xw(i.manifest_digest),source_revision:xw(i.source_revision),source_head:pO(i.source_head)}};if(kw(r,s),!["receiving","uploaded"].includes(s.staged.state))throw tt("Connect returned an invalid staged import state.");return s}function Pw(r,e){if(!Lr(e))throw tt("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||!fO(t.expires_at))throw tt("Connect returned invalid collection adoption state.");return t}function aO(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{return null}}function Cw(r,e,t){let n;try{n=new URL(e)}catch{throw tt("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 tt("Connect returned an untrusted adoption verification URI.");return n.href}function $w(r,e){let t=e?`/${e}`:"";return`${Nr(r.controlUrl)}/v1/authority-adoptions/${encodeURIComponent(r.adoptionId)}${t}`}function hp(r,e){let t=r.trim();if(!t||t.length>200)throw new W("invalid_authority_adoption",`${e} must contain between 1 and 200 characters.`);return t}function cO(r,e){if(r.status!==e)throw Bn(r);return r.body}function Bn(r){let e=Lr(r.body)&&Lr(r.body.error)?r.body.error:{};return new W(et(e.code)||"authority_adoption_request_failed",et(e.message)||`Collection adoption request failed with status ${r.status}.`,r.status)}function tt(r){return new W("invalid_authority_adoption_response",r)}function Mw(r){return{code:"authority_adoption_unreachable",message:"Connect could not be reached for collection adoption."}}function Ew(){let r=Mw(void 0);return new W(r.code,r.message)}function Aw(r=mp){return Number.isFinite(r)?Math.min(3e4,Math.max(250,Math.round(r))):mp}function lO(r,e){return Vn(e),new Promise((t,n)=>{let i=setTimeout(o,r),s=()=>{clearTimeout(i),e?.removeEventListener("abort",s),n(new W("authority_adoption_cancelled","Collection adoption was cancelled."))};function o(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}function Vn(r){if(r?.aborted)throw new W("authority_adoption_cancelled","Collection adoption was cancelled.")}async function dO(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:uO(n)}:{}}}function uO(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()):mp}function fO(r){return Number.isFinite(Date.parse(r))}function xw(r){return r===null?null:et(r)}function pO(r){return r===null?null:typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:Number.NaN}function hO(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function gp(r){return typeof r=="string"&&r.length>=16}function et(r){return typeof r=="string"?r:""}function Lr(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var mO=new TextEncoder,fo=Object.freeze({digest:r=>Re(We(mO.encode(r))),randomId:()=>{if(typeof globalThis.crypto?.randomUUID!="function")throw new b("mirror_random_unavailable","This runtime must provide crypto.randomUUID() or a MirrorRuntime adapter.");return globalThis.crypto.randomUUID()},now:()=>new Date().toISOString()});var uo=class{held=!1;async runExclusive(e){if(this.held)throw new b("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 Tw(r,e,t){if(r.engine_version!==3)throw new b("mirror_state_upgrade_required","Rebuild this prerelease mirror with the plan-only exact-document sync engine.");if(r.protocol_version!==1||r.replica_id!==e)throw new Error;if(r.resources??={},r.generation??=0,r.files??={},r.selective_sync=Fn(r.selective_sync),r.planned_conflicts??={},r.local_bindings??={},r.mode??="read_only",r.mode!==t)throw new b("mirror_mode_mismatch",`Mirror metadata belongs to a ${r.mode.replace("_","-")} replica.`);let n=[];for(let[i,s]of Object.entries(r.records))if(n.push(wt(s.path)),s.record&&(s.record.record_id!==i||s.record.path!==s.path))throw new Error;for(let[i,s]of Object.entries(r.resources)){if(Qt(i),i!==s.path)throw new Error;n.push(wt(s.path))}for(let[i,s]of Object.entries(r.files)){if(ht(s.file),s.file.file_id!==i)throw new Error;n.push(wt(s.file.path))}n.sort();for(let i=1;ic.kind==="configuration"&&c.path==="mdbase.yaml");if(n.length!==1)throw new b("invalid_snapshot","Hosted snapshot requires exactly one canonical mdbase.yaml resource.");let i=Ow(n[0].document,e),s=Lw(n[0].document).settings??{},o=Vi(s.types_folder,"_types"),a=Vi(s.contracts_folder,"_contracts");for(let c of r){let l=c.path.split(".").at(-1),u=c.path.split("/"),d=u.some(p=>p.startsWith(".")),f=!1;if(c.kind==="configuration")f=c.path==="mdbase.yaml";else if(c.kind==="lock")f=c.path==="mdbase.lock.yaml"&&bO(c.document);else if(c.kind==="type")f=bp(c.path,o)&&l==="md"&&Iw(c.document,c.path)==="mdbase.type";else if(c.kind==="contract")f=bp(c.path,a)&&l==="md"&&Iw(c.document,c.path)==="mdbase.contract";else if(c.kind==="schema"){let p=gO(c.document);f=!d&&l==="json"&&u.some(m=>m==="schemas"||m==="_schemas")&&p!==null}else c.kind==="view"&&(f=!d&&l==="base");if(!f)throw new b("invalid_snapshot",`Hosted resource ${c.path} is not valid for kind ${c.kind}.`)}return i}function Rw(r){return{reservedFolders:new Set(["_types","_contracts","_types/_migrations",".mdbase"]),resourcePaths:r}}function Ow(r,e){let t=Lw(r).settings??{},n=Vi(t.types_folder,"_types");return{reservedFolders:new Set([n,Vi(t.contracts_folder,"_contracts"),Vi(t.migrations_folder,`${n}/_migrations`),Vi(t.cache_folder,".mdbase",!0)]),resourcePaths:e}}async function Nw(r,e){if(r.length===0)return Rw(new Set);let t=await e();if(t===null)throw new b("invalid_mirror_state","Mirror collection configuration is missing.");return Ow(t,new Set(r))}function mn(r,e){if(Qt(r),/(?:^|\/)\./u.test(r)||e.resourcePaths.has(r)||yO(r,e.reservedFolders)||!r.endsWith(".md"))throw new b("invalid_record_path",`Mirror record path ${r} is outside the configured record namespace.`)}function yO(r,e){for(let t of e)if(bp(r,t))return!0;return!1}function Dw(r,e){return r.filter(t=>{try{return mn(t,e),!0}catch{return!1}})}function Lw(r){let e;try{e=Li(r)}catch{throw new b("invalid_snapshot","Hosted mdbase.yaml is not valid YAML.")}if(!e||typeof e!="object"||Array.isArray(e))throw new b("invalid_snapshot","Hosted mdbase.yaml requires an object document.");let t=e;if(typeof t.spec_version!="string")throw new b("invalid_snapshot","Hosted mdbase.yaml requires spec_version.");return t}function Vi(r,e,t=!1){let n=typeof r=="string"?r:e;if(Qt(n),!t&&n.split("/").some(i=>i.startsWith(".")))throw new b("invalid_snapshot",`Collection control folder ${n} must not be hidden.`);return n}function bp(r,e){return r===e||r.startsWith(`${e}/`)}function gO(r){try{let e=JSON.parse(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function bO(r){try{let e=Li(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.kind==="mdbase.type-pack-lock"&&e.lock_version===1&&Array.isArray(e.packs)}catch{return!1}}function Iw(r,e){try{return Pc(r,e).frontmatter.kind}catch{return null}}function St(r){return Ui(r)}function jw(r,e,t,n,i=[]){let s=St(r);for(let o of t)if(St(o)===s)throw new b("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)&&St(a.path)===s)throw new b("invalid_record_path",`Mirror record paths ${a.path} and ${r} alias on a supported filesystem.`);for(let[,o]of i)if(St(o.file.path)===s)throw new b("invalid_record_path",`Mirror record path ${r} aliases collection file ${o.file.path} on a supported filesystem.`)}function qw(r,e,t){let n=St(r);for(let i of Object.values(t.resources??{}))if(St(i.path)===n)throw new b("invalid_file_path",`Collection file ${r} aliases authority resource ${i.path}.`);for(let i of Object.values(t.records))if(St(i.path)===n)throw new b("invalid_file_path",`Collection file ${r} aliases record ${i.path}.`);for(let[i,s]of Object.entries(t.files??{}))if((i!==e||s.file.path!==r)&&St(s.file.path)===n)throw new b("invalid_file_path",`Collection files ${s.file.path} and ${r} alias on a supported filesystem.`)}function po(r){let e=new Map;for(let t of r){let n=St(t),i=e.get(n);if(i!==void 0&&i!==t)throw new b("invalid_record_path",`Mirror paths ${i} and ${t} alias on a supported filesystem.`);e.set(n,t)}}var Uc=class{pathPolicy;digest;recordIds=new Set;physicalPaths=new Set;constructor(e,t,n){this.pathPolicy=e,this.digest=n;for(let i of t)this.physicalPaths.add(Ui(i.path))}validate(e){let t=e.document,n=e;if(mn(n.path,this.pathPolicy),this.recordIds.has(n.record_id))throw new b("invalid_snapshot",`Hosted snapshot repeats record identity ${n.record_id}.`);this.recordIds.add(n.record_id);let i=Ui(n.path);if(this.physicalPaths.has(i))throw new b("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 b("invalid_snapshot",`Hosted record ${n.path} does not match its declared revision.`);if(Qv(t,n)!==!0){let a;try{a=Pc(t,n.path)}catch{throw new b("invalid_snapshot",`Hosted record ${n.path} is not valid Markdown.`)}if(!_p(a.frontmatter,n.frontmatter)||!_O(a.body,n.body))throw new b("invalid_snapshot",`Hosted record ${n.path} does not match its declared document.`)}return{record:n,document:t,hash:s}}};async function Fw(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 b("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 b("invalid_snapshot","Authority snapshot repeated a page cursor.");n!==void 0&&i.add(n)}while(n)}function _O(r,e){return r===e||r.startsWith(` +`)?e.body.slice(1):e.body;return t=mt(r,` +`,t),t>=0&&r.startsWith(i,t)&&t+i.length===r.length}function Lc(r,e){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=Hn(t[1],{mapAsMap:!0})}catch{return{frontmatter:{},body:r}}if(n===null&&t[1].trim()==="")return{frontmatter:{},body:t[2]??""};let i=yp(n,new Set);return i===Lr||!sO(i)?{frontmatter:{},body:r}:{frontmatter:i,body:t[2]??""}}function yp(r,e){if(r===null||typeof r=="string"||typeof r=="boolean")return r;if(typeof r=="number")return Number.isFinite(r)?r:Lr;if(!r||typeof r!="object"||e.has(r))return Lr;e.add(r);try{if(Array.isArray(r)){let n=[];for(let i of r){let s=yp(i,e);if(s===Lr)return Lr;n.push(s)}return n}if(!(r instanceof Map))return Lr;let t={};for(let[n,i]of r){if(typeof n!="string")return Lr;let s=yp(i,e);if(s===Lr)return Lr;Object.defineProperty(t,n,{value:s,enumerable:!0,configurable:!0,writable:!0})}return t}finally{e.delete(r)}}function sO(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function kw(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&&rO.has(r.toLowerCase())?null:r}function mt(r,e,t){return r.startsWith(e,t)?t+e.length:-1}function jc(r){let e=Je.create().update(jr.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 b("file_sync_unsupported","This replica cannot materialize collection file changes yet. Upgrade it before continuing sync.")}function Iw(r){aO([r])}var K=class extends b{status;constructor(e,t,n,i){super(e,t),this.status=n,this.name="AuthorityAdoptionError",i?.cause!==void 0&&(this.cause=i.cause)}},qr=class extends K{sourceMustRemainFenced=!0;constructor(e,t){super("authority_adoption_outcome_unknown",e,void 0,t),this.name="AuthorityAdoptionOutcomeUnknownError"}};var Ji=/^[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 Gn(r,e){if(!Ji.test(r))throw new K("invalid_authority_adoption",`${e} must be a UUID.`);return r.toLowerCase()}var vo=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),bn=new Uint32Array(80),bp=class extends Gi{A=vo[0]|0;B=vo[1]|0;C=vo[2]|0;D=vo[3]|0;E=vo[4]|0;constructor(){super(64,20,8,!1)}get(){let{A:e,B:t,C:n,D:i,E:s}=this;return[e,t,n,i,s]}set(e,t,n,i,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=i|0,this.E=s|0}process(e,t){for(let c=0;c<16;c++,t+=4)bn[c]=e.getUint32(t,!1);for(let c=16;c<80;c++)bn[c]=Tc(bn[c-3]^bn[c-8]^bn[c-14]^bn[c-16],1);let{A:n,B:i,C:s,D:o,E:a}=this;for(let c=0;c<80;c++){let l,u;c<20?(l=Oc(i,s,o),u=1518500249):c<40?(l=i^s^o,u=1859775393):c<60?(l=Nc(i,s,o),u=2400959708):(l=i^s^o,u=3395469782);let d=Tc(n,5)+l+a+u+bn[c]|0;a=o,o=s,s=Tc(i,30),i=n,n=d}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,this.set(n,i,s,o,a)}roundClean(){yn(bn)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0),yn(this.buffer)}},Fc=Rc(()=>new bp);var cO=1e4,lO=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,dO=new TextEncoder;async function Rw(r,e,t,n,i){let s=fO(n,t.media_type);if(s.size!==t.size||await pO(s,i.signal)!==t.content_digest)throw new K("authority_adoption_file_changed",`File bytes no longer match the fenced snapshot for ${t.path}.`);let o=hO(e.import_id,t),a=await vp(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(yO(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>cO)throw yt("Authority import returned too many file parts.");let u=new Set(a.received),d=new Map((a.uploaded_parts??[]).map(h=>[h.part_number-1,h]));if(a.received.length===l&&await Tw(r,e,t,o,[...d.values()],i.signal))return;let f=Array(l);for(let[h,y]of d)f[h]=y;let p=[...u].reduce((h,y)=>h+Math.min(c,Math.max(0,t.size-y*c)),0);for(let h=0;hh!==void 0);if(!await Tw(r,e,t,o,m,i.signal))throw new K("authority_adoption_file_upload_incomplete",`Connect could not commit ${t.path}.`)}async function Tw(r,e,t,n,i,s){try{let o=await vp(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||!_O(o.file,t))throw yt("Connect returned an invalid authority import file receipt.");return!0}catch(o){if(i.length===0&&o instanceof K&&o.code==="file_upload_incomplete")return!1;throw o}}async function vp(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{throw Uc(i),new K("authority_adoption_unreachable","Connect could not be reached for collection adoption.")}if(s.status<200||s.status>=300)throw wO(s);return s.body}async function uO(r,e,t,n){bO(e.url);let i;try{i=await r({url:e.url,method:"PUT",headers:vO(e.headers),body:t,rawBody:!0,...n?{signal:n}:{}})}catch{throw Uc(n),new K("authority_adoption_unreachable","Connect could not be reached for collection adoption.")}if(i.status<200||i.status>=300)throw new K("authority_adoption_object_upload_failed","Object storage rejected an authority import file part.",i.status);return i}function fO(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 pO(r,e){let t=Je.create(),n=r.stream().getReader();try{for(;;){Uc(e);let i=await n.read();if(i.done)break;t.update(i.value)}}finally{n.releaseLock()}return`sha256:${Oe(t.digest())}`}function hO(r,e){let t=mO(r),n=dO.encode(`mdbase-authority-import-file-v1\0${e.file_id}\0${e.revision}\0${e.content_digest}`),i=Fc(new Uint8Array([...t,...n])).slice(0,16);i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=Oe(i);return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function mO(r){if(!lO.test(r))throw yt("Authority import ID is invalid.");return Uint8Array.from(r.replaceAll("-","").match(/../g).map(e=>Number.parseInt(e,16)))}function yO(r,e,t){let n=r?.strategy;if(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(a=>!Number.isSafeInteger(a)||a<0||a>=s))throw yt("Connect returned invalid authority import file progress.");let o=r.uploaded_parts??[];if(!Array.isArray(o)||o.some((a,c)=>!Number.isSafeInteger(a?.part_number)||a.part_number<1||a.part_number>s||typeof a.etag!="string"||a.etag.length===0||a.etag.length>255||c>0&&o[c-1].part_number>=a.part_number)||(n.kind==="object_multipart"?o.length!==r.received.length||o.some((a,c)=>a.part_number-1!==r.received[c]):o.length!==0))throw yt("Connect returned invalid authority import part receipts.")}function gO(r,e,t,n,i){if(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))||!_p(r.headers))throw yt("Connect returned an invalid prepared authority import file part.")}function bO(r){let e;try{e=new URL(r)}catch{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 vO(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 _O(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 wO(r){let e=_p(r.body)&&_p(r.body.error)?r.body.error:{};return new K(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 K("invalid_authority_adoption_response",r)}function Uc(r){if(r?.aborted)throw new K("authority_adoption_cancelled","Collection adoption was cancelled.")}function _p(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var wp=1500,SO=250,$O=3e4,qw=1440*60*1e3,Fr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Bc=class{request;now;wait;constructor(e={}){this.request=e.request??EO,this.now=e.now??Date.now,this.wait=e.wait??PO}async begin(e,t={}){Jn(t.signal);let n=Ur(e.controlUrl),i=e.mirrorName.trim();if(!i||i.length>200)throw new Ye("invalid_mirror_name","Mirror name must contain between 1 and 200 characters.");if(!["read_only","read_write"].includes(e.mode))throw new Ye("invalid_mirror_mode","Mirror mode must be read-only or read-write.");if(e.collectionId!==void 0&&!Fr.test(e.collectionId))throw new Ye("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{throw Jn(t.signal),Lw()}let o=Dw(s,201);if(!Yi(o)||!Fr.test(St(o.pairing_id))||!_o(o.pairing_secret)||!CO(o.expires_in)||Number(o.expires_in)*1e3>qw)throw er("Connect returned an invalid mirror approval.");let a=Uw(n,St(o.verification_uri),St(o.pairing_id));return{controlUrl:n,pairingId:St(o.pairing_id),refreshCredential:St(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={}){xO(e,this.now());let n=jw(t.pollIntervalMs),i=Date.parse(e.expiresAt),s=0;for(;this.now()=500){let a=Sp(o);if(await this.retry(i,o.retryAfterMs??n,t,s,{code:a.code,message:a.message})===null)break;continue}throw Sp(o)}throw new Ye("mirror_enrollment_expired","Mirror approval expired before it was completed.")}async renew(e,t={}){AO(e),Jn(t.signal);let n;try{n=await this.request({url:Nw(e.controlUrl,e.enrollmentId,"renew"),method:"POST",headers:{authorization:`Bearer ${e.refreshCredential}`},...t.signal?{signal:t.signal}:{}})}catch{throw Jn(t.signal),Lw()}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 Ow(i,Dw(n,200),{replicaId:e.replicaId})}async retry(e,t,n,i,s){let o=e-this.now();if(o<=0)return null;let a=Math.min(jw(t),o),c=new Date(this.now()+a).toISOString();return n.onStatus?.({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}},Ye=class extends b{status;constructor(e,t,n){super(e,t),this.status=n,this.name="MirrorEnrollmentError"}};function Ur(r){let e;try{e=new URL(r)}catch{throw new Ye("invalid_connect_url","Connect URL must be an absolute HTTPS origin.")}if(e.pathname!=="/"||e.search||e.hash||e.username||e.password)throw new Ye("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 Ye("invalid_connect_url","Connect URL must use HTTPS outside loopback development.");return e.origin}async function EO(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:kO(n)}}}function Ow(r,e,t){if(!Yi(e)||e.status!=="paired"||!Yi(e.replica))throw er("Connect returned an invalid mirror enrollment.");let n=e.replica,i=St(n.id),s=St(n.collection_id),o=St(n.name).trim(),a=n.mode,c=St(e.token),l=St(e.token_expires_at);if(!Fr.test(i)||!Fr.test(s)||!o||!["read_only","read_write"].includes(String(a))||!_o(c)||!Vw(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=Fw(St(e.sync_url),s)}catch{throw er("Connect returned an invalid authority sync URL.")}return{controlUrl:Ur(r.controlUrl),syncUrl:u,collectionId:s,replicaId:i,mode:a,name:o,enrollmentId:r.pairingId,accessToken:c,refreshCredential:r.refreshCredential,accessTokenExpiresAt:l}}function xO(r,e){Ur(r.controlUrl);let t=Date.parse(r.expiresAt);if(!Fr.test(r.pairingId)||!_o(r.refreshCredential)||!Number.isFinite(t)||t-e>qw||!r.requested.mirrorName.trim()||r.requested.mirrorName.length>200||!["read_only","read_write"].includes(r.requested.mode)||r.requested.collectionId!==void 0&&!Fr.test(r.requested.collectionId))throw new Ye("invalid_mirror_enrollment_session","Mirror enrollment session is invalid.");Uw(r.controlUrl,r.verificationUri,r.pairingId)}function AO(r){if(Ur(r.controlUrl),Fw(r.syncUrl,r.collectionId),!Fr.test(r.collectionId)||!Fr.test(r.replicaId)||!Fr.test(r.enrollmentId)||!_o(r.accessToken)||!_o(r.refreshCredential)||!Vw(r.accessTokenExpiresAt)||!r.name.trim()||r.name.length>200||!["read_only","read_write"].includes(r.mode))throw new Ye("invalid_mirror_enrollment","Stored mirror enrollment is invalid.")}function Fw(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 Uw(r,e,t){let n;try{n=new URL(e)}catch{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 Nw(r,e,t){return`${Ur(r)}/v1/mirror-pairing-requests/${encodeURIComponent(e)}/${t}`}function Dw(r,e){if(r.status!==e)throw Sp(r);return r.body}function Sp(r){let e=Yi(r.body)&&Yi(r.body.error)?r.body.error:{};return new Ye(St(e.code)||"mirror_enrollment_request_failed",St(e.message)||`Mirror enrollment request failed with status ${r.status}.`,r.status)}function er(r){return new Ye("invalid_mirror_enrollment_response",r)}function Bw(r){return{code:"mirror_enrollment_unreachable",message:"Connect could not be reached for mirror enrollment."}}function Lw(){let r=Bw(void 0);return new Ye(r.code,r.message)}function jw(r=wp){return Number.isFinite(r)?Math.min($O,Math.max(SO,Math.round(r))):wp}function kO(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()):wp}function PO(r,e){return Jn(e),new Promise((t,n)=>{let i=setTimeout(o,r),s=()=>{clearTimeout(i),e?.removeEventListener("abort",s),n(new Ye("mirror_enrollment_cancelled","Mirror enrollment was cancelled."))};function o(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}function Jn(r){if(r?.aborted)throw new Ye("mirror_enrollment_cancelled","Mirror enrollment was cancelled.")}function Vw(r){let e=Date.parse(r);return Number.isFinite(e)}function CO(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function _o(r){return typeof r=="string"&&r.length>=16}function St(r){return typeof r=="string"?r:""}function Yi(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var MO=/(?:^|\/)(?:\.{1,2}|)(?:\/|$)/u,IO=/[\p{Cc}:?<>|*"]/u,TO=/[. ](?:\/|$)/u,RO=/(?:^|\/)(?:CON|PRN|AUX|NUL|COM[1-9¹²³]|LPT[1-9¹²³])(?:\.|\/|$)/iu;function tr(r){if(!r||r.startsWith("/")||r.includes("\\")||MO.test(r)||IO.test(r)||TO.test(r)||RO.test(r))throw new b("invalid_path",`Mirror received an unsafe path: ${r}.`)}function $t(r){return tr(r),Xi(r)}function Xi(r){return/^[\x20-\x7e]+$/u.test(r)?/[A-Z]/u.test(r)?r.toLowerCase():r:r.normalize("NFC").toLowerCase().normalize("NFC")}var Hw=new Set(["image","audio","video","pdf","other"]),zw=["image","audio","video","pdf","other"],OO=new Set([".mdbase",".git","node_modules","_contracts","_schemas","_types","_views"]),NO=/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu,DO=/^sha256:[0-9a-f]{64}$/u,LO=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,jO=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/u;function Yn(r){let e={file_classes:[...r?.file_classes??[]],excluded_folders:[...r?.excluded_folders??[]]};if(e.excluded_folders.length>100)throw new b("invalid_file_materialization","Selective sync supports at most 100 excluded folders.");let t=new Set;for(let s of e.file_classes){if(!Hw.has(s)||t.has(s))throw new b("invalid_file_materialization","Selected file media classes must be valid and unique.");t.add(s)}let n=new Set,i=new Set;for(let s of e.excluded_folders){Ww(s,!0);let o=$t(s);if(n.has(s)||i.has(o))throw new b("invalid_file_materialization","Excluded folders must be unique on portable filesystems.");n.add(s),i.add(o)}return e.file_classes.sort((s,o)=>zw.indexOf(s)-zw.indexOf(o)),e.excluded_folders.sort((s,o)=>$t(s).localeCompare($t(o))),e}function Xn(r,e){let t=$t(e);return!r.excluded_folders.some(n=>{let i=$t(n);return t===i||t.startsWith(`${i}/`)})}function zc(r,e){return r.file_classes.includes(e.media_class)&&Xn(r,e.path)}function $p(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 Kw(r,e){return r.file_classes.includes($p(e))&&Xn(r,e)}function gt(r){if(Ww(r.path,!1),typeof r.file_id!="string"||!LO.test(r.file_id)||typeof r.revision!="string"||!r.revision||r.revision.length>255||!DO.test(r.content_digest)||!Number.isSafeInteger(r.size)||r.size<0||!Hw.has(r.media_class)||typeof r.modified_at!="string"||!jO.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 b("invalid_snapshot",`Collection file ${r.path} has invalid metadata.`)}function Ww(r,e){if(tr(r),r.length>1024)throw new b("invalid_file_path","Collection file paths cannot exceed 1024 characters.");if(r.split("/").some(i=>i.startsWith(".")||/[<>"|?*]/u.test(i)||NO.test(i)||OO.has(i.toLowerCase()))||!e&&/\.md$/iu.test(r))throw new b("invalid_file_path",`Collection file path ${r} is hidden, reserved, or non-portable.`)}async function Gw(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 b("invalid_snapshot","Authority file snapshot boundary changed during download.");for(let o of s.files)gt(o);if(await t(s.files),n=s.next_page,n!==void 0&&i.has(n))throw new b("invalid_snapshot","Authority file snapshot repeated a page cursor.");n!==void 0&&i.add(n)}while(n)}function Br(r,e){return r?.size===e.size&&r.content_digest===e.content_digest}async function*Vc(r,e){let t=Je.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 b("file_integrity_failed","A file transport returned invalid bytes.")}if(n+=i.byteLength,!Number.isSafeInteger(n)||n>e.size)throw new b("file_integrity_failed",`Downloaded bytes for ${e.path} are oversized.`);t.update(i),yield i}if(n!==e.size||`sha256:${Oe(t.digest())}`!==e.content_digest)throw new b("file_integrity_failed",`Downloaded bytes for ${e.path} failed integrity verification.`)}async function*Jw(r,e,t){let n=Je.create(),i=0;for await(let s of r){if(!(s instanceof Uint8Array))throw new b("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 b("pending_local_changed",`Local file ${t} changed while being staged.`);n.update(s),yield s}}if(i!==e.size||`sha256:${Oe(n.digest())}`!==e.content_digest)throw new b("pending_local_changed",`Local file ${t} changed while being staged.`)}async function Hc(r,e,t){if(gt(t),await e.has(t.content_digest))try{for await(let n of Vc(e.read(t.content_digest),t));return}catch{await e.remove(t.content_digest)}try{await e.write(t.content_digest,Vc(r.downloadFile(t),t))}catch(n){throw await e.remove(t.content_digest).catch(()=>{}),n}if(!await e.has(t.content_digest))throw new b("file_integrity_failed","The verified file blob was not persisted.")}var vn=new TextEncoder;function Ap(r){let e=Gn(r.collectionId,"Collection ID"),t=r.sourceHead??0;if(!Number.isSafeInteger(t)||t<0)throw new K("invalid_authority_snapshot","Source head must be a non-negative integer.");let n=new Set,i=r.resources.map(d=>{let f=Kc(d.path);if(n.add(f)||Ep(f),!["configuration","lock","contract","schema","type","view"].includes(d.kind))throw new K("invalid_authority_snapshot",`Unsupported collection resource kind for ${f}.`);return{path:f,kind:d.kind,revision:Yw(d.document),document:d.document}}).sort(FO);if(i[0]?.path!=="mdbase.yaml"||i[0].kind!=="configuration"||i.filter(({kind:d})=>d==="configuration").length!==1)throw new K("invalid_authority_snapshot","A portable snapshot requires one mdbase.yaml configuration resource.");let s=r.records.map(d=>{let f=Kc(d.path);return n.add(f)||Ep(f),{record_id:d.recordId?Gn(d.recordId,`Record ID for ${f}`):Wc(e,f),path:f,document:d.document}}).sort((d,f)=>xp(d.path,f.path)),o=new Set,a=(r.files??[]).map(d=>{let f=Kc(d.path);n.add(f)||Ep(f);let p=Gn(d.file_id,`File ID for ${f}`);if(!o.add(p))throw new K("invalid_authority_snapshot",`Collection snapshot contains file ID more than once: ${p}`);return qO(d,f),{...d,file_id:p,path:f}}).sort((d,f)=>xp(d.path,f.path)),c=Xw(i.flatMap(({path:d,revision:f})=>[d,f])),l=Xw([...i.flatMap(({path:d,revision:f})=>["resource",d,f]),...s.flatMap(d=>["record",d.path,Yw(d.document)]),...a.flatMap(d=>["file",d.path,d.file_id,d.revision,d.content_digest,String(d.size),d.media_type??"",d.media_class])]),u=jc([...i.map(({path:d,document:f})=>({kind:"resource",path:d,identity:"",document_hash:Oe(Je(vn.encode(f)))})),...s.map(d=>({kind:"record",path:d.path,identity:d.record_id,document_hash:Oe(Je(vn.encode(d.document)))})),...a.map(d=>({kind:"file",path:d.path,identity:d.file_id,document_hash:qc(d)}))]);return{protocol_version:1,collection_id:e,source_head:t,source_revision:l,manifest_digest:u,resources:{revision:c,spec_version:r.specVersion,types:r.types??[],contracts:r.contracts??[],documents:i},records:s,files:a}}function qO(r,e){try{gt({...r,path:e})}catch{throw new K("invalid_authority_snapshot",`File descriptor is invalid for ${e}.`)}if(r.media_class!==$p(e))throw new K("invalid_authority_snapshot",`File media class does not match its path for ${e}.`)}function Wc(r,e){let t=UO(Gn(r,"Collection ID")),i=Fc(new Uint8Array([...t,...vn.encode(Kc(e))])).slice(0,16);i[6]=i[6]&15|80,i[8]=i[8]&63|128;let s=Oe(i);return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}function Yw(r){return`sha256:${Oe(Je(vn.encode(r)))}`}function Xw(r){let e=Je.create();for(let t of r){let n=BigInt(vn.encode(t).length),i=new Uint8Array(8);new DataView(i.buffer).setBigUint64(0,n),e.update(i),e.update(vn.encode(t))}return`sha256:${Oe(e.digest())}`}function FO(r,e){return r.kind==="configuration"&&e.kind!=="configuration"?-1:e.kind==="configuration"&&r.kind!=="configuration"?1:xp(r.path,e.path)}function xp(r,e){let t=vn.encode(r),n=vn.encode(e),i=Math.min(t.length,n.length);for(let s=0;s!t||t==="."||t===".."))throw new K("invalid_authority_snapshot",`Collection path is unsafe: ${r}`);return e}function Ep(r){throw new K("invalid_authority_snapshot",`Collection snapshot contains the path more than once: ${r}`)}function UO(r){return Uint8Array.from(r.replaceAll("-","").match(/../g).map(e=>Number.parseInt(e,16)))}var BO=/^sha256:[a-f0-9]{64}$/,VO=/^[a-f0-9]{64}$/,Pp=1500,Cp=1440*60*1e3,zO=200,Qw=8*1024*1024,HO=new TextEncoder,Gc=class{request;now;wait;constructor(e={}){this.request=e.request??JO,this.now=e.now??Date.now,this.wait=e.wait??GO}async begin(e,t={}){Zn(t.signal);let n=Ur(e.controlUrl),i=Gn(e.collectionId,"Collection ID"),s=kp(e.displayName,"Collection name"),o=kp(e.sourceName,"Source name"),a=e.retainMirror??!0,c=a?kp(e.mirrorName??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{throw Zn(t.signal),r0()}let u=WO(l,201);if(!Vr(u)||!Ji.test(nt(u.adoption_id))||!Mp(u.adoption_secret)||!ZO(u.expires_in)||Number(u.expires_in)*1e3>Cp)throw it("Connect returned an invalid collection adoption request.");let d=a0(n,nt(u.verification_uri),nt(u.adoption_id));return{controlUrl:n,adoptionId:nt(u.adoption_id),credential:nt(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={}){Qi(e,this.now());let n=n0(t.pollIntervalMs),i=Date.parse(e.expiresAt),s=0;for(;this.now()=500){let a=Qn(o);if(!await this.retry(i,o.retryAfterMs??n,s,t,{code:a.code,message:a.message}))break;continue}throw Qn(o)}throw new K("authority_adoption_expired","Collection adoption approval expired before upload began.")}async exchange(e,t={}){Qi(e,this.now(),!0);let n=await this.controlRequest(e,"exchange","POST",{},t.signal);if(n.status===202)throw new K("authority_adoption_pending","Collection adoption is still awaiting approval.",202);if(n.status!==200)throw Qn(n);return e0(e,n.body)}async uploadSnapshot(e,t,n,i={}){Qi(e,this.now(),!0),s0(e,t),Zw(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=HO.encode(JSON.stringify(l)).length;if(u>Qw)throw new K("authority_adoption_record_too_large",`Record ${l.path} is too large to adopt.`);a.length>0&&(a.length===zO||c+u>Qw)&&(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 K("authority_adoption_file_source_required",`File bytes are required to adopt ${l.path}.`);let u=await i.fileSource(l);await Rw(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={}){Qi(e,this.now(),!0),Zw(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 Zn(n.signal),new qr("Connect could not confirm whether hosted authority activated.",{cause:a})}if(i.status>=500)throw new qr("Connect could not confirm whether hosted authority activated.");if(i.status!==200)throw Qn(i);let s=i.body;if(!Vr(s)||s.status!=="completed")throw it("Connect returned an invalid adoption completion.");let o=o0(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 it("Connect completed a different adoption snapshot.");return{status:"completed",adoption:o}}async cancel(e,t={}){Qi(e,this.now(),!0);let n=await this.controlRequest(e,void 0,"DELETE",void 0,t.signal);if(n.status!==200)throw Qn(n)}mirrorEnrollmentSession(e,t){if(Qi(e,this.now(),!0),t.status!=="completed"||t.adoption.collection_id!==e.requested.collectionId)throw it("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()+Cp).toISOString(),requested:{mirrorName:e.requested.mirrorName??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{throw Zn(s),r0()}if(o.status<200||o.status>=300)throw Qn(o)}controlRequest(e,t,n,i,s){return this.request({url:t0(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){let o=e-this.now();if(o<=0)return!1;let a=Math.min(n0(t),o),c=new Date(this.now()+a).toISOString();return i.onStatus?.({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 Qi(r,e,t=!1){Ur(r.controlUrl);let n=Date.parse(r.expiresAt);if(!Ji.test(r.adoptionId)||!Mp(r.credential)||!Number.isFinite(n)||n-e>Cp||!t&&n<=e||!Ji.test(r.requested.collectionId)||!r.requested.displayName.trim()||!r.requested.sourceName.trim())throw new K("invalid_authority_adoption_session","Stored collection adoption state is invalid.");a0(r.controlUrl,r.verificationUri,r.adoptionId)}function s0(r,e){if(e.status!=="ready"||e.adoption.id!==r.adoptionId||e.adoption.collection_id!==r.requested.collectionId)throw it("Prepared adoption does not belong to this session.");let t=e.import;if(!Ji.test(t.import_id)||!Mp(t.access_token))throw it("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=KO(s,t.import_id,o);if(!a||i!==void 0&&a.origin!==i)throw it("Connect returned an invalid authority import capability.");i=a.origin}}function Zw(r,e){if(e.protocol_version!==1||e.collection_id!==r.requested.collectionId||!Number.isSafeInteger(e.source_head)||e.source_head<0||!BO.test(e.source_revision)||!VO.test(e.manifest_digest)||e.resources.documents?.length===0||!Array.isArray(e.files))throw new K("invalid_authority_snapshot","Authority snapshot does not belong to this adoption.")}function e0(r,e){if(!Vr(e)||!["ready","activating","completed"].includes(nt(e.status)))throw it("Connect returned an invalid adoption exchange.");let t=o0(r,e.adoption);if(e.status==="completed")return{status:"completed",adoption:t};if(e.status==="activating")return{status:"activating",adoption:t};if(!Vr(e.import)||!Vr(e.staged))throw it("Connect omitted the authority import capability.");let n=e.import,i=e.staged,s={status:"ready",adoption:t,import:{import_id:nt(n.import_id),manifest_url:nt(n.manifest_url),records_url:nt(n.records_url),files_url:nt(n.files_url),finalize_url:nt(n.finalize_url),access_token:nt(n.access_token)},staged:{state:i.state,manifest_digest:i0(i.manifest_digest),source_revision:i0(i.source_revision),source_head:QO(i.source_head)}};if(s0(r,s),!["receiving","uploaded"].includes(s.staged.state))throw it("Connect returned an invalid staged import state.");return s}function o0(r,e){if(!Vr(e))throw it("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||!XO(t.expires_at))throw it("Connect returned invalid collection adoption state.");return t}function KO(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{return null}}function a0(r,e,t){let n;try{n=new URL(e)}catch{throw it("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 it("Connect returned an untrusted adoption verification URI.");return n.href}function t0(r,e){let t=e?`/${e}`:"";return`${Ur(r.controlUrl)}/v1/authority-adoptions/${encodeURIComponent(r.adoptionId)}${t}`}function kp(r,e){let t=r.trim();if(!t||t.length>200)throw new K("invalid_authority_adoption",`${e} must contain between 1 and 200 characters.`);return t}function WO(r,e){if(r.status!==e)throw Qn(r);return r.body}function Qn(r){let e=Vr(r.body)&&Vr(r.body.error)?r.body.error:{};return new K(nt(e.code)||"authority_adoption_request_failed",nt(e.message)||`Collection adoption request failed with status ${r.status}.`,r.status)}function it(r){return new K("invalid_authority_adoption_response",r)}function c0(r){return{code:"authority_adoption_unreachable",message:"Connect could not be reached for collection adoption."}}function r0(){let r=c0(void 0);return new K(r.code,r.message)}function n0(r=Pp){return Number.isFinite(r)?Math.min(3e4,Math.max(250,Math.round(r))):Pp}function GO(r,e){return Zn(e),new Promise((t,n)=>{let i=setTimeout(o,r),s=()=>{clearTimeout(i),e?.removeEventListener("abort",s),n(new K("authority_adoption_cancelled","Collection adoption was cancelled."))};function o(){e?.removeEventListener("abort",s),t()}e?.addEventListener("abort",s,{once:!0})})}function Zn(r){if(r?.aborted)throw new K("authority_adoption_cancelled","Collection adoption was cancelled.")}async function JO(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:YO(n)}:{}}}function YO(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()):Pp}function XO(r){return Number.isFinite(Date.parse(r))}function i0(r){return r===null?null:nt(r)}function QO(r){return r===null?null:typeof r=="number"&&Number.isSafeInteger(r)&&r>=0?r:Number.NaN}function ZO(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function Mp(r){return typeof r=="string"&&r.length>=16}function nt(r){return typeof r=="string"?r:""}function Vr(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}var eN=new TextEncoder,So=Object.freeze({digest:r=>Oe(Je(eN.encode(r))),randomId:()=>{if(typeof globalThis.crypto?.randomUUID!="function")throw new b("mirror_random_unavailable","This runtime must provide crypto.randomUUID() or a MirrorRuntime adapter.");return globalThis.crypto.randomUUID()},now:()=>new Date().toISOString()});var wo=class{held=!1;async runExclusive(e){if(this.held)throw new b("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 l0(r,e,t){if(r.engine_version!==3)throw new b("mirror_state_upgrade_required","Rebuild this prerelease mirror with the plan-only exact-document sync engine.");if(r.protocol_version!==1||r.replica_id!==e)throw new Error;if(r.resources??={},r.generation??=0,r.files??={},r.selective_sync=Yn(r.selective_sync),r.planned_conflicts??={},r.local_bindings??={},r.mode??="read_only",r.mode!==t)throw new b("mirror_mode_mismatch",`Mirror metadata belongs to a ${r.mode.replace("_","-")} replica.`);let n=[];for(let[i,s]of Object.entries(r.records))if(n.push($t(s.path)),s.record&&(s.record.record_id!==i||s.record.path!==s.path))throw new Error;for(let[i,s]of Object.entries(r.resources)){if(tr(i),i!==s.path)throw new Error;n.push($t(s.path))}for(let[i,s]of Object.entries(r.files)){if(gt(s.file),s.file.file_id!==i)throw new Error;n.push($t(s.file.path))}n.sort();for(let i=1;ic.kind==="configuration"&&c.path==="mdbase.yaml");if(n.length!==1)throw new b("invalid_snapshot","Hosted snapshot requires exactly one canonical mdbase.yaml resource.");let i=f0(n[0].document,e),s=m0(n[0].document).settings??{},o=Zi(s.types_folder,"_types"),a=Zi(s.contracts_folder,"_contracts");for(let c of r){let l=c.path.split(".").at(-1),u=c.path.split("/"),d=u.some(p=>p.startsWith(".")),f=!1;if(c.kind==="configuration")f=c.path==="mdbase.yaml";else if(c.kind==="lock")f=c.path==="mdbase.lock.yaml"&&nN(c.document);else if(c.kind==="type")f=Ip(c.path,o)&&l==="md"&&d0(c.document,c.path)==="mdbase.type";else if(c.kind==="contract")f=Ip(c.path,a)&&l==="md"&&d0(c.document,c.path)==="mdbase.contract";else if(c.kind==="schema"){let p=rN(c.document);f=!d&&l==="json"&&u.some(m=>m==="schemas"||m==="_schemas")&&p!==null}else c.kind==="view"&&(f=!d&&l==="base");if(!f)throw new b("invalid_snapshot",`Hosted resource ${c.path} is not valid for kind ${c.kind}.`)}return i}function u0(r){return{reservedFolders:new Set(["_types","_contracts","_types/_migrations",".mdbase"]),resourcePaths:r}}function f0(r,e){let t=m0(r).settings??{},n=Zi(t.types_folder,"_types");return{reservedFolders:new Set([n,Zi(t.contracts_folder,"_contracts"),Zi(t.migrations_folder,`${n}/_migrations`),Zi(t.cache_folder,".mdbase",!0)]),resourcePaths:e}}async function p0(r,e){if(r.length===0)return u0(new Set);let t=await e();if(t===null)throw Re("Mirror collection configuration is missing.");return f0(t,new Set(r))}function _n(r,e){if(tr(r),/(?:^|\/)\./u.test(r)||e.resourcePaths.has(r)||tN(r,e.reservedFolders)||!r.endsWith(".md"))throw new b("invalid_record_path",`Mirror record path ${r} is outside the configured record namespace.`)}function tN(r,e){for(let t of e)if(Ip(r,t))return!0;return!1}function h0(r,e){return r.filter(t=>{try{return _n(t,e),!0}catch{return!1}})}function m0(r){let e;try{e=Hn(r)}catch{throw new b("invalid_snapshot","Hosted mdbase.yaml is not valid YAML.")}if(!e||typeof e!="object"||Array.isArray(e))throw new b("invalid_snapshot","Hosted mdbase.yaml requires an object document.");let t=e;if(typeof t.spec_version!="string")throw new b("invalid_snapshot","Hosted mdbase.yaml requires spec_version.");return t}function Zi(r,e,t=!1){let n=typeof r=="string"?r:e;if(tr(n),!t&&n.split("/").some(i=>i.startsWith(".")))throw new b("invalid_snapshot",`Collection control folder ${n} must not be hidden.`);return n}function Ip(r,e){return r===e||r.startsWith(`${e}/`)}function rN(r){try{let e=JSON.parse(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function nN(r){try{let e=Hn(r);return e!==null&&typeof e=="object"&&!Array.isArray(e)&&e.kind==="mdbase.type-pack-lock"&&e.lock_version===1&&Array.isArray(e.packs)}catch{return!1}}function d0(r,e){try{return Lc(r,e).frontmatter.kind}catch{return null}}function Et(r){return Xi(r)}function y0(r,e,t,n,i=[]){let s=Et(r);for(let o of t)if(Et(o)===s)throw new b("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)&&Et(a.path)===s)throw new b("invalid_record_path",`Mirror record paths ${a.path} and ${r} alias on a supported filesystem.`);for(let[,o]of i)if(Et(o.file.path)===s)throw new b("invalid_record_path",`Mirror record path ${r} aliases collection file ${o.file.path} on a supported filesystem.`)}function g0(r,e,t){let n=Et(r);for(let i of Object.values(t.resources??{}))if(Et(i.path)===n)throw new b("invalid_file_path",`Collection file ${r} aliases authority resource ${i.path}.`);for(let i of Object.values(t.records))if(Et(i.path)===n)throw new b("invalid_file_path",`Collection file ${r} aliases record ${i.path}.`);for(let[i,s]of Object.entries(t.files??{}))if((i!==e||s.file.path!==r)&&Et(s.file.path)===n)throw new b("invalid_file_path",`Collection files ${s.file.path} and ${r} alias on a supported filesystem.`)}function $o(r){let e=new Map;for(let t of r){let n=Et(t),i=e.get(n);if(i!==void 0&&i!==t)throw new b("invalid_record_path",`Mirror paths ${i} and ${t} alias on a supported filesystem.`);e.set(n,t)}}var Yc=class{pathPolicy;digest;recordIds=new Set;physicalPaths=new Set;constructor(e,t,n){this.pathPolicy=e,this.digest=n;for(let i of t)this.physicalPaths.add(Xi(i.path))}validate(e){let t=e.document,n=e;if(_n(n.path,this.pathPolicy),this.recordIds.has(n.record_id))throw new b("invalid_snapshot",`Hosted snapshot repeats record identity ${n.record_id}.`);this.recordIds.add(n.record_id);let i=Xi(n.path);if(this.physicalPaths.has(i))throw new b("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 b("invalid_snapshot",`Hosted record ${n.path} does not match its declared revision.`);if(Mw(t,n)!==!0){let a;try{a=Lc(t,n.path)}catch{throw new b("invalid_snapshot",`Hosted record ${n.path} is not valid Markdown.`)}if(!Tp(a.frontmatter,n.frontmatter)||!iN(a.body,n.body))throw new b("invalid_snapshot",`Hosted record ${n.path} does not match its declared document.`)}return{record:n,document:t,hash:s}}};async function b0(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 b("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 b("invalid_snapshot","Authority snapshot repeated a page cursor.");n!==void 0&&i.add(n)}while(n)}function iN(r,e){return r===e||r.startsWith(` `)&&r.slice(1)===e||e.startsWith(` -`)&&e.slice(1)===r}function _p(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)=>_p(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)&&_p(s,n[i]))}var zi=class{fileSystem;runtime;mode;blobStore;constructor(e,t,n,i){this.fileSystem=e,this.runtime=t,this.mode=n,this.blobStore=i}async recordPathPolicy(e){return Nw(Object.keys(e.resources??{}),()=>this.fileSystem.read("mdbase.yaml"))}async put(e,t,n={}){let{managedState:i=e,acceptedHash:s,materialized:o,inspectionPreflighted:a=!1}=n;a||mn(t.path,await this.recordPathPolicy(e)),o===void 0&&!a&&jw(t.path,t.record_id,Object.keys(e.resources??{}),Object.entries(e.records),Object.entries(e.files??{}));let c=o?.document??kc(t),l=await this.fileSystem.read(t.path),u=i?.records[t.record_id];if(l!==null&&l!==c){let p=this.runtime.digest(l);if(!(u!==void 0&&u.path===t.path&&p===u.hash)&&(s===void 0||p!==s))throw new mt(t.record_id,t.path)}u&&u.path!==t.path&&await this.remove(i,t.record_id,u.path);let d=this.runtime.digest(c);typeof s=="string"&&s===d&&l!==null&&this.runtime.digest(l)===d||await this.fileSystem.write(t.path,c),e.records[t.record_id]={path:t.path,revision:t.revision,hash:o?.hash??d,...this.mode==="read_write"?{record:t}:{}}}async putFile(e,t,n=e,i){if(ht(t),!this.blobStore)throw new b("file_storage_unavailable","Selected collection files require a content-addressed blob store adapter.");qw(t.path,t.file_id,e),e.files??={};let s=n.files?.[t.file_id],o=await this.fileSystem.inspectBinary(t.path),a=St(t.path),c=Object.values(n.files??{}).find(m=>St(m.file.path)===a),l=[...Object.values(n.resources??{}),...Object.values(n.records)].find(m=>St(m.path)===a),u=l?await this.fileSystem.read(t.path):null,d=s?.file.path===t.path&&Dr(o,s.file),f=c!==void 0&&Dr(o,c.file),p=l!==void 0&&u!==null&&this.runtime.digest(u)===l.hash;if(o!==null&&!Dr(o,t)&&!d&&!f&&!p&&!(i!==void 0&&o?.size===i.size&&o.content_digest===i.content_digest))throw new mt(t.file_id,t.path);if(s&&s.file.path!==t.path){let m=await this.fileSystem.inspectBinary(s.file.path);if(m!==null&&!Dr(m,s.file))throw new mt(t.file_id,s.file.path)}Dr(o,t)||await this.fileSystem.writeBinary(t.path,Oc(this.blobStore.read(t.content_digest),t)),s&&s.file.path!==t.path&&await this.fileSystem.remove(s.file.path),e.files[t.file_id]={file:t}}async removeFile(e,t){let n=e.files?.[t];if(!n)return;let i=await this.fileSystem.inspectBinary(n.file.path);if(i!==null&&!Dr(i,n.file))throw new mt(t,n.file.path);i!==null&&await this.fileSystem.remove(n.file.path),delete e.files[t]}async remove(e,t,n,i={}){let s=e.records[t],o=s?.path??n;i.inspectionPreflighted||mn(o,await this.recordPathPolicy(e));let a=await this.fileSystem.read(o);if(a!==null&&s&&this.runtime.digest(a)!==s.hash)throw new mt(t,s.path);a!==null&&await this.fileSystem.remove(o),delete e.records[t]}async putResource(e,t,n){let i=await this.fileSystem.read(t.path),s=n?.resources?.[t.path];if(i!==null&&i!==t.document&&(!s||this.runtime.digest(i)!==s.hash))throw new mt(`resource:${t.path}`,t.path);await this.fileSystem.write(t.path,t.document),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 mt(`resource:${t}`,t);i!==null&&await this.fileSystem.remove(t),e.resources&&delete e.resources[t]}};async function Uw(r,e,t,n){for(let i in r.records){if(!Object.hasOwn(r.records,i))continue;let s=r.records[i];mn(s.path,e);let o=await t.read(s.path);if(o===null||n(o)!==s.hash)throw new mt(i,s.path)}for(let[i,s]of Object.entries(r.resources??{})){let o=await t.read(s.path);if(o===null||n(o)!==s.hash)throw new mt(`resource:${i}`,s.path)}for(let[i,s]of Object.entries(r.files??{})){let o=await t.inspectBinary(s.file.path);if(!Dr(o,s.file))throw new mt(i,s.file.path)}}async function Bw(r){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 b("promotion_incomplete_file_projection","Moving the source of truth requires every collection file class with no excluded folders.");if(Object.keys(e.planned_conflicts??{}).length>0||e.batch!==void 0)throw new b("promotion_not_converged","Upload or resolve every local change before moving the source of truth.");await Uw(e,i,n,s);let o=new Set(Object.keys(e.resources??{})),a=new Set(Object.values(e.records).map(d=>d.path)),c=(await n.listMarkdown(o)).filter(d=>!a.has(d));if(c.length>0)throw new b("promotion_unmanaged_files",`Synchronize unmanaged Markdown before promotion: ${c.join(", ")}.`);if(!n.listBinary)throw new b("promotion_file_scan_unavailable","Moving the source of truth requires binary file enumeration.");let l=new Set(Object.values(e.files??{}).map(d=>d.file.path)),u=(await n.listBinary(new Set([...o,...a]))).filter(d=>!l.has(d));if(u.length>0)throw new b("promotion_unmanaged_files",`Synchronize unmanaged files before moving the source of truth: ${u.join(", ")}.`);return{cursor:e.cursor,digest:Cc([...Object.entries(e.resources??{}).map(([d,f])=>({kind:"resource",path:d,identity:"",document_hash:ip(f.hash)})),...Object.entries(e.records).map(([d,f])=>({kind:"record",path:f.path,identity:d,document_hash:ip(f.hash)})),...Object.values(e.files??{}).map(({file:d})=>({kind:"file",path:d.path,identity:d.file_id,document_hash:Mc(d)}))])}}function jr(r,e,t,n,i){return{status:r,plan_fingerprint:e.fingerprint,applied:n,pending:t.pending,checkpoint_cursor:t.cursor,conflicts:t.conflicts.length,issues:e.issues,...i?{failure:i}:{}}}function Vw(r,e){return["planned","applying","cancelled","stale","blocked","failed"].includes(r.state)?r:r.conflicts.length>0||r.local_issues.length>0||e.summary.blocking_issues>0||e.summary.conflicts>0?{...r,state:"attention"}:{...r,state:e.actions.some(t=>t.command!=="advance_checkpoint")?"changes_waiting":"up_to_date"}}function yr(r,e){if(!r)return{state:"not_initialized",mode:e,pending:0,pending_files:0,conflicts:[],local_issues:[],cursor:null,last_synced_at:null};let t=[];for(let[o,a]of Object.entries(r.planned_conflicts??{})){let c=t.findIndex(({entity:u,object_id:d})=>u===a.entity&&d===o);c!==-1&&t.splice(c,1);let l=a.local.state==="exact"?a.local.object.path:a.remote.state==="exact"?a.remote.object.path:null;t.push({entity:a.entity,object_id:o,decision_id:a.decision_id??"",path:l,kind:a.conflict_kind==="rejected"?"rejected":"conflicted",message:a.conflict_kind==="rejected"?"The authority rejected this local change.":"Local and authority changes need a decision."})}let n=[],i=r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(o=>o.command!=="advance_checkpoint").length:0;return{state:(r.batch?r.batch.phase==="prepared"?"planned":r.batch.phase==="applying"||r.batch.phase==="effects_complete"?"applying":r.batch.phase==="cancelled"?"cancelled":r.batch.failure?.code==="sync_plan_stale"?"stale":"blocked":null)??(t.length?"attention":"up_to_date"),mode:e,pending:i,pending_files:r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(o=>o.command!=="advance_checkpoint"&&("target"in o&&o.target.entity==="file"||"source"in o&&o.source.entity==="file"||"entity"in o&&o.entity==="file")).length:0,conflicts:t,local_issues:n,cursor:r.batch?.checkpoint_before.cursor??r.cursor,last_synced_at:r.last_synced_at??null,generation:r.generation??0,pending_checkpoint:r.batch?.checkpoint_after.cursor??null,...r.batch?{plan_fingerprint:r.batch.plan.fingerprint}:{},...r.last_completed_plan?{last_completed_plan:r.last_completed_plan}:{},recovery_required:r.batch!==void 0,...r.batch?.failure?{failure:r.batch.failure}:{}}}async function vO(r,e,t){let n=await e.openSession();if(n.protocol_version!==1||n.protocol_profile!=="exact_document_v1"||n.replica_id!==r||n.mode!==t)throw new b("sync_protocol_incompatible",`Filesystem mirror requires exact-document v1 and its own ${t.replace("_","-")} replica.`);return n}async function Bc(r,e,t,n,i){let s=await vO(r,e,t),o=s.resources.documents??[],a=Fc(o),c=new Uc(a,o,i.digest),l=[];await Fw(e,s,async f=>{for(let p of f){let m=c.validate(p);Un(n,m.record.path)&&l.push(m)}});let u=[],d=new Set;return await yw(e,s,async f=>{for(let p of f)if(Nc(n,p)){if(d.has(p.file_id))throw new b("invalid_snapshot",`Hosted snapshot repeats file identity ${p.file_id}.`);d.add(p.file_id),u.push(p)}}),po([...o.map(f=>f.path),...l.map(({record:f})=>f.path),...u.map(f=>f.path)]),{session:s,resources:o,records:l,files:u}}var Vc="exact_document_plan_only_v1",zc="three_way_exact_document_v1",Hc="portable_mirror_projection_v1";function Kc(r){return JSON.stringify(vp(r))}function zn(r,e){return`sha256:${e(Kc(r))}`}function vp(r){if(r===null||typeof r=="string"||typeof r=="boolean")return r;if(typeof r=="number"){if(!Number.isSafeInteger(r))throw new b("invalid_sync_plan","Sync plans contain only safe integer numeric values.");return r}if(Array.isArray(r))return r.map(vp);if(typeof r=="object"){let e={};for(let t of Object.keys(r).sort()){let n=r[t];if(n===void 0)throw new b("invalid_sync_plan",`Sync plan field ${t} is undefined rather than an explicit state.`);e[t]=vp(n)}return e}throw new b("invalid_sync_plan","Sync plans contain only canonical I-JSON values.")}function Gw(r,e,t){let n=new Map(r.base.map(u=>[u.identity,u])),i=new Map(r.remote.map(u=>[u.identity,u])),s=new Map,o=new Map(r.local.map(u=>[u.object.path,u]));for(let u of r.local)!u.stable_identity||u.object.identity===""||(s.set(u.object.identity,u.object),o.delete(u.object.path));for(let[u,d]of n){let f=o.get(d.path);f&&(s.set(u,{...f.object,identity:u}),o.delete(d.path))}for(let[u,d]of i){if(s.has(u))continue;let f=o.get(d.path);f&&f.object.entity===d.entity&&(s.set(u,{...f.object,identity:u}),o.delete(d.path))}for(let[u,d]of n){if(s.has(u))continue;let f=[...o.values()].filter(m=>m.object.entity===d.entity&&m.object.payload_revision===d.payload_revision);if(f.length!==1)continue;let p=f[0];s.set(u,{...p.object,identity:u,revision:p.object.payload_revision===d.payload_revision?d.revision:p.object.revision}),o.delete(p.object.path)}for(let u of o.values()){let d=u.stable_identity?u.object.identity:MO(e,u.object,t);s.set(d,{...u.object,identity:d})}let a=new Set([...n.keys(),...s.keys(),...i.keys()]),c=new Map([...s.values()].map(u=>[u.path,u])),l=new Map([...i.values()].map(u=>[u.path,u]));return[...a].sort().map(u=>{let d=n.get(u),f=s.get(u),p=i.get(u),m=p?.path??f?.path??d.path,h=f?.path??p?.path??d.path;return{entity:(f??p??d).entity,identity:u,base:ho(d),local:ho(f),remote:ho(p),local_target_owner:ho(c.get(m)),remote_target_owner:ho(l.get(h))}})}function Jw(r,e){let t=[];for(let l of[...r.objects].sort(IO))kO(r,l,t);if(t=$O(t,r.objects,e),t=wO(t,r.objects),t.length>0||r.kind!=="incremental"||r.boundary.checkpoint.cursor!==r.boundary.authority_cursor){let l=t.map(u=>u.key);t.push({key:"checkpoint",depends_on_keys:l,command:"advance_checkpoint",reason:r.kind==="incremental"?"remote_change":r.kind,expected:r.boundary.checkpoint,next:{generation:r.boundary.checkpoint.generation+1,cursor:r.boundary.authority_cursor}})}let i=new Map;for(let l of t){let{key:u,depends_on_keys:d,...f}=l;i.set(u,zn({action_scope:{replica_id:r.boundary.replica_id,scope_epoch:r.boundary.scope_epoch,generation:r.boundary.checkpoint.generation},key:u,...f},e))}let s=t.map(l=>{let{key:u,depends_on_keys:d,...f}=l,p={...f,action_id:i.get(u),depends_on:d.map(m=>i.get(m))};if((p.command==="put_remote"||p.command==="move_remote"||p.command==="delete_remote")&&(p.idempotency_key=p.action_id),p.command==="move_remote"){let m=d.find(h=>h===`${p.source.identity}:put-remote`);m&&(p.revision_from_dependency=i.get(m))}return p}),o=[...r.issues].sort(RO),a={uploads:s.filter(OO).length,downloads:s.filter(NO).length,conflicts:s.filter(l=>l.command==="record_conflict").length,blocking_issues:o.filter(l=>l.blocking).length},c={plan_version:1,engine_profile:Vc,protocol_profile:"exact_document_v1",planner_policy:zc,projection_policy:Hc,replica_id:r.boundary.replica_id,mode:r.mode,kind:r.kind,base_cursor:r.boundary.checkpoint.cursor,authority_cursor:r.boundary.authority_cursor,scope_epoch:r.boundary.scope_epoch,checkpoint_generation:r.boundary.checkpoint.generation,selective_sync:r.selective_sync,actions:s,issues:o,summary:a};return{...c,fingerprint:zn(c,e)}}function wO(r,e){if(!r.some(c=>c.command==="move_remote"))return r;let t=[...r],n=new Set;for(let c of SO(t))for(let l of c){let u=t.find(d=>d.key===l);u?.command==="move_remote"&&n.add(u.source.identity)}let i=$p(t),s=new Map(t.map(c=>[c.key,c])),o=!0;for(;o;){o=!1;for(let c of t){if(c.command!=="move_remote")continue;let l=c.expected_target_owner;if(l.state!=="exact"||l.object.identity===c.source.identity)continue;let u=s.get(i.get(gr(l.object))??""),d=u&&zw(u);(!u||d&&n.has(d))&&!n.has(c.source.identity)&&(n.add(c.source.identity),o=!0)}}if(n.size>0){t=t.filter(l=>{let u=zw(l);return!u||!n.has(u)||l.command!=="put_remote"&&l.command!=="move_remote"});let c=new Map(e.map(l=>[l.identity,l]));for(let l of[...n].sort()){let u=c.get(l);!u||u.entity==="resource"||t.push({key:`${l}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"local_change",identity:l,entity:u.entity,local:u.local,remote:u.remote,conflict_kind:"path_occupied"})}}let a=$p(t);for(let c of t){if(c.command!=="move_remote")continue;let l=c.expected_target_owner;if(l.state!=="exact"||l.object.identity===c.source.identity)continue;let u=a.get(gr(l.object));!u||u===c.key||(c.depends_on_keys.includes(u)||c.depends_on_keys.push(u),c.expected_target_owner={state:"absent"})}return Yw(t)}function SO(r){let e=r.filter(s=>s.command==="move_remote"),t=new Map(e.map(s=>[s.key,s])),n=$p(r),i=new Map;for(let s of e){let o=[],a=new Map,c=s;for(;c;){let l=a.get(c.key);if(l!==void 0){let d=o.slice(l);i.set([...d].sort().join("\0"),d);break}a.set(c.key,o.length),o.push(c.key);let u=c.expected_target_owner;c=u.state==="exact"?t.get(n.get(gr(u.object))??""):void 0}}return[...i.values()]}function $p(r){let e=new Map;for(let t of r)t.command==="move_remote"?e.set(gr(t.source),t.key):t.command==="delete_remote"&&e.set(gr(t.target),t.key);return e}function zw(r){if(r.command==="move_remote")return r.source.identity;if(r.command==="put_remote"||r.command==="delete_remote")return r.target.identity}function $O(r,e,t){if(!r.some(d=>d.command==="move_local"||d.command==="write_local"))return r;let n=[...r],i=new Set;for(let d of e)d.base.state==="exact"&&i.add(d.base.object.path),d.local.state==="exact"&&i.add(d.local.object.path),d.remote.state==="exact"&&i.add(d.remote.object.path);for(;;){let d=EO(n);if(!d)break;let f=[...d].sort()[0],p=n.findIndex(v=>v.key===f),m=n[p];if(!m||m.command!=="move_local")throw new Error("Planner invariant: local path cycle contains a non-move action.");let h=xO(m.source,m.target_path,i,t);i.add(h);let y={...m.source,path:h},g={key:`${m.source.identity}:stage-local`,depends_on_keys:[...m.depends_on_keys],command:"move_local",reason:m.reason,source:m.source,target_path:h,expected_source_owner:m.expected_source_owner,expected_target_owner:{state:"absent"}};m.source=y,m.expected_source_owner={state:"exact",object:y},m.depends_on_keys=[g.key],n.splice(p,0,g)}let s=Ep(n),o=new Map(e.map(d=>[d.identity,d])),a=new Set,c=new Map(n.map(d=>[d.key,d])),l=!0;for(;l;){l=!1;for(let d of n){let f=Hw(d),p=Wc(d);if(f?.state!=="exact"||f.object.identity===p)continue;let m=c.get(s.get(gr(f.object))??""),h=m&&Wc(m);(!m||h&&a.has(h))&&!a.has(p)&&(a.add(p),l=!0)}}if(a.size>0){n=n.filter(d=>!a.has(Wc(d))||d.command!=="move_local"&&d.command!=="write_local");for(let d of[...a].sort()){let f=o.get(d);!f||f.entity==="resource"||n.push({key:`${d}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"remote_change",identity:d,entity:f.entity,local:f.local,remote:f.remote,conflict_kind:"path_occupied"})}}let u=Ep(n);for(let d of n){let f=Hw(d),p=Wc(d);if(f?.state!=="exact"||f.object.identity===p)continue;let m=u.get(gr(f.object));!m||m===d.key||(d.depends_on_keys.includes(m)||d.depends_on_keys.push(m),AO(d,{state:"absent"}))}return Yw(n)}function EO(r){let e=r.filter(i=>i.command==="move_local"),t=new Map(e.map(i=>[i.key,i])),n=Ep(r);for(let i of e){let s=[],o=new Map,a=i;for(;a;){let c=o.get(a.key);if(c!==void 0)return s.slice(c);o.set(a.key,s.length),s.push(a.key);let l=a.expected_target_owner;a=l.state==="exact"?t.get(n.get(gr(l.object))??""):void 0}}}function Ep(r){let e=new Map;for(let t of r)t.command==="move_local"?e.set(gr(t.source),t.key):t.command==="delete_local"&&e.set(gr(t.target),t.key);return e}function Hw(r){if(r.command==="move_local")return r.expected_target_owner;if(r.command==="write_local")return r.expected_path_owner}function AO(r,e){r.command==="move_local"?r.expected_target_owner=e:r.command==="write_local"&&(r.expected_path_owner=e)}function Wc(r){return r.command==="move_local"?r.source.identity:r.command==="write_local"||r.command==="delete_local"?r.target.identity:""}function gr(r){return`${r.entity}\0${r.identity}\0${r.path}`}function xO(r,e,t,n){let i=r.path.lastIndexOf("/"),s=i<0?"":r.path.slice(0,i+1),o=i<0?r.path:r.path.slice(i+1),a=o.lastIndexOf("."),c=a>0?o.slice(a):"";for(let l=0;;l+=1){let u=n(`${r.entity}\0${r.identity}\0${r.path}\0${e}\0${l}`),d=`${s}.mdbase-sync-stage-${u.slice(0,16)}${c}`;if(!t.has(d))return d}}function Yw(r){let e=[...r],t=new Set,n=[];for(;e.length>0;){let i=e.findIndex(o=>o.depends_on_keys.every(a=>t.has(a)));if(i<0)throw new Error("Planner invariant: action dependency graph contains a cycle.");let[s]=e.splice(i,1);n.push(s),t.add(s.key)}return n}function kO(r,e,t){if(e.frozen_conflict){t.push(TO(e.frozen_conflict.local,e.frozen_conflict.remote)?{key:`${e.identity}:clear-conflict`,depends_on_keys:[],command:"clear_conflict",reason:"pending",identity:e.identity,entity:e.entity,expected_local:e.frozen_conflict.local,expected_remote:e.frozen_conflict.remote}:{key:`${e.identity}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"pending",identity:e.identity,entity:e.entity,...e.frozen_conflict});return}let n=!Sp(e.local,e.base),i=!Sp(e.remote,e.base);if(!(!n&&!i)){if(e.entity==="resource"){if(n)return;wp(e,t);return}if(r.mode==="read_only"){n||wp(e,t);return}if(n&&i){if(Sp(e.local,e.remote))return;t.push(CO(e));return}n?PO(e,t):wp(e,t)}}function wp(r,e){if(r.remote.state==="absent"){r.local.state==="exact"&&e.push({key:`${r.identity}:delete-local`,depends_on_keys:[],command:"delete_local",reason:"remote_change",target:r.local.object,expected_local:r.local,expected_path_owner:r.local_target_owner});return}let t=r.remote.object;if(r.local.state==="absent"){e.push(Kw(r,t,[]));return}let n=r.local.object,i;if(n.path!==t.path){let s=`${r.identity}:move-local`;e.push({key:s,depends_on_keys:[],command:"move_local",reason:"remote_change",source:n,target_path:t.path,expected_source_owner:r.local,expected_target_owner:r.local_target_owner}),i=s}n.revision!==t.revision&&e.push(Kw(r,t,i?[i]:[]))}function Kw(r,e,t){return{key:`${r.identity}:write-local`,depends_on_keys:t,command:"write_local",reason:"remote_change",target:e,payload_revision:e.payload_revision,expected_local:t.length>0?{state:"exact",object:{...e,revision:qr(r.local).revision,payload_revision:qr(r.local).payload_revision,...qr(r.local).size===void 0?{}:{size:qr(r.local).size}}}:r.local,expected_path_owner:t.length>0?{state:"exact",object:{...e,revision:qr(r.local).revision,payload_revision:qr(r.local).payload_revision,...qr(r.local).size===void 0?{}:{size:qr(r.local).size}}}:r.local_target_owner}}function PO(r,e){if(r.local.state==="absent"){r.remote.state==="exact"&&e.push({key:`${r.identity}:delete-remote`,depends_on_keys:[],command:"delete_remote",reason:"local_change",target:r.remote.object,expected_remote:r.remote,expected_local:r.local,idempotency_key:""});return}let t=r.local.object;if(r.remote.state==="absent"){e.push(Ww(r,t,[]));return}let n=r.remote.object,i;if(t.revision!==n.revision){let s=Ww(r,{...t,path:n.path},[]);e.push(s),i=s.key}t.path!==n.path&&e.push({key:`${r.identity}:move-remote`,depends_on_keys:i?[i]:[],command:"move_remote",reason:"local_change",source:i?{...n,revision:t.revision}:n,target_path:t.path,expected_source_owner:i?{state:"exact",object:{...n,revision:t.revision}}:r.remote,expected_target_owner:r.remote_target_owner,expected_local:r.local,idempotency_key:""})}function Ww(r,e,t){return{key:`${r.identity}:put-remote`,depends_on_keys:t,command:"put_remote",reason:"local_change",target:e,payload_revision:qr(r.local).payload_revision,expected_remote:r.remote,expected_local:r.local,idempotency_key:""}}function CO(r){return{key:`${r.identity}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"remote_change",identity:r.identity,entity:r.entity,local:r.local,remote:r.remote,conflict_kind:r.local.state==="absent"||r.remote.state==="absent"?"delete_vs_change":"both_changed"}}function qr(r){if(r.state!=="exact")throw new Error("Planner invariant: expected exact object state.");return r.object}function ho(r){return r?{state:"exact",object:r}:{state:"absent"}}function MO(r,e,t){let n=t(`${r}\0${e.entity}\0${e.path}\0${e.revision}`);return`${n.slice(0,8)}-${n.slice(8,12)}-5${n.slice(13,16)}-8${n.slice(17,20)}-${n.slice(20,32)}`}function Sp(r,e){return Kc(r)===Kc(e)}function TO(r,e){return r.state==="absent"||e.state==="absent"?r.state===e.state:r.object.entity===e.object.entity&&r.object.identity===e.object.identity&&r.object.path===e.object.path&&r.object.payload_revision===e.object.payload_revision&&r.object.size===e.object.size}function IO(r,e){return`${r.entity}\0${r.identity}`.localeCompare(`${e.entity}\0${e.identity}`)}function RO(r,e){return`${r.path??""}\0${r.code}\0${r.message}`.localeCompare(`${e.path??""}\0${e.code}\0${e.message}`)}function OO(r){return r.command==="put_remote"||r.command==="move_remote"||r.command==="delete_remote"}function NO(r){return r.command==="write_local"||r.command==="move_local"||r.command==="delete_local"}var Gc=class{replicaId;transport;mode;fileSystem;blobStore;selectiveSync;runtime;readState;currentRecordPathPolicy;constructor(e,t,n,i,s,o,a,c,l){this.replicaId=e,this.transport=t,this.mode=n,this.fileSystem=i,this.blobStore=s,this.selectiveSync=o,this.runtime=a,this.readState=c,this.currentRecordPathPolicy=l}async inspect(e){let t=e===void 0?await this.readState():e;if(!t)return this.inspectSnapshot("initial",null);if(t.batch)throw new b("mirror_recovery_required","The prepared sync batch must recover before a new inspection can be planned.");return JSON.stringify(t.selective_sync)!==JSON.stringify(this.selectiveSync)?this.inspectSnapshot("rebuild",t):this.inspectIncremental(t)}async inspectSnapshot(e,t){let n=await Bc(this.replicaId,this.transport,this.mode,this.selectiveSync,this.runtime),i=Fc(n.resources),s=await this.inspectLocal(t,n.resources,i),o=new Map(n.records.map(({record:c})=>[c.record_id,c])),a=new Map(n.files.map(c=>[c.file_id,c]));return this.finish({kind:e,prior:t,authorityCursor:n.session.head,scopeEpoch:n.session.scope_epoch,local:s,remoteRecords:o,remoteResources:n.resources,remoteFiles:a,snapshot:n})}async inspectIncremental(e){let t=new Map;for(let[l,u]of Object.entries(e.records))u.record&&t.set(l,u.record);let n=new Map(Object.entries(e.files??{}).map(([l,u])=>[l,u.file])),i=new Map(Xw(e).map(l=>[jO(l),l])),s=e.cursor,o=e.cursor;for(;;){let l=s,u=await this.transport.changes(l,200);if(u.scope_epoch!==e.scope_epoch||u.cursoru.head||u.has_more&&u.cursor===l)throw new b("invalid_change_page","Authority returned an invalid change boundary.");if(u.reset_required)return this.inspectSnapshot("rebuild",e);for(let d of u.events){if(d.sequence<=o||d.sequence>u.cursor)throw new b("invalid_change_page","Authority change events are not strictly ordered.");o=d.sequence,this.applyRemoteObservation(i,t,n,d)}if(s=u.cursor,!u.has_more)break}let a=Object.values(e.resources??{}).map(l=>({path:l.path,kind:FO(l.path),revision:l.revision,document:""})),c=await this.inspectLocal(e,a,await this.currentRecordPathPolicy(e));return this.finish({kind:"incremental",prior:e,authorityCursor:s,scopeEpoch:e.scope_epoch,local:c,remoteRecords:t,remoteResources:[],remoteFiles:n,remoteRefs:[...i.values()]})}applyRemoteObservation(e,t,n,i){if(i.type==="put"){Zv(i);let s=i.record.record_id;Un(this.selectiveSync,i.record.path)?(e.set(`record:${s}`,Qw(i.record)),t.set(s,i.record)):(e.delete(`record:${s}`),t.delete(s));return}if(i.type==="remove"){e.delete(`record:${i.record_id}`),t.delete(i.record_id);return}if(i.type==="file_put"){ht(i.file);let s=i.file.file_id;Nc(this.selectiveSync,i.file)?(e.set(`file:${s}`,xp(i.file)),n.set(s,i.file)):(e.delete(`file:${s}`),n.delete(s));return}e.delete(`file:${i.file_id}`),n.delete(i.file_id)}async inspectLocal(e,t,n){let i=[],s=new Map,o=new Map,a=[],c=new Map(Object.entries(e?.records??{}).map(([m,h])=>[h.path,[m,h]])),l=new Map(Object.entries(e?.planned_conflicts??{}).filter(([,m])=>m.entity==="record"&&m.local.state==="exact").map(([m,h])=>[h.local.state==="exact"?h.local.object.path:"",m])),u=new Map(Object.entries(e?.local_bindings??{}).filter(([,m])=>m.entity==="record").map(([m,h])=>[h.path,m])),d=new Set([...Object.keys(e?.resources??{}),...t.map(m=>m.path)]);for(let m of d){let h=await this.fileSystem.read(m),y=e?.resources?.[m];if(h===null)continue;let g=`sha256:${this.runtime.digest(h)}`;i.push({stable_identity:!0,object:Hi("resource",m,m,g)}),s.set(m,h);let v=t.find(_=>_.path===m);!y&&v&&v.revision!==g?a.push({code:"local_collision",message:`${m} differs locally from the exact authority document.`,path:m,blocking:!0}):y&&y.revision!==g&&a.push({code:"mirror_diverged",message:`Authority-owned resource ${m} changed locally.`,path:m,blocking:!0})}let f=new Set(Object.values(e?.records??{}).map(m=>m.path)),p=Dw(await this.fileSystem.listMarkdown(d),n).filter(m=>Un(this.selectiveSync,m)||f.has(m));for(let m of p){let h=await this.fileSystem.read(m);if(h===null)continue;let y=`sha256:${this.runtime.digest(h)}`,g=l.get(m),v=u.get(m),_=c.get(m)?.[0],w=g??v??_??"";i.push({stable_identity:w!=="",object:Hi("record",w,m,y)}),s.set(m,h)}if(this.selectiveSync.file_classes.length>0){if(!this.fileSystem.listBinary)throw new b("file_storage_unavailable","Selected files require binary enumeration.");let m=new Set(Object.values(e?.files??{}).map(_=>_.file.path)),h=new Map(Object.entries(e?.files??{}).map(([_,w])=>[w.file.path,[_,w]])),y=new Map(Object.entries(e?.planned_conflicts??{}).filter(([,_])=>_.entity==="file"&&_.local.state==="exact").map(([_,w])=>[w.local.state==="exact"?w.local.object.path:"",_])),g=new Map(Object.entries(e?.local_bindings??{}).filter(([,_])=>_.entity==="file").map(([_,w])=>[w.path,_])),v=(await this.fileSystem.listBinary(d)).filter(_=>hw(this.selectiveSync,_)||m.has(_));for(let _ of v){let w=await this.fileSystem.inspectBinary(_);if(!w)continue;let A=y.get(_),x=g.get(_),M=h.get(_),S=A??x??M?.[0]??"";i.push({stable_identity:S!=="",object:{entity:"file",identity:S,path:_,revision:M&&M[1].file.content_digest===w.content_digest?M[1].file.revision:w.content_digest,payload_revision:w.content_digest,size:w.size}}),o.set(_,w)}}try{po([...d,...p,...o.keys()])}catch(m){let h=m instanceof Error?m:new Error(String(m));a.push({code:e0(m),message:h.message,blocking:!0})}return{observations:i,documents:s,binary:o,issues:a}}async finish(e){let{prior:t,local:n}=e,i=e.remoteRefs??[...e.remoteResources.map(LO),...[...e.remoteRecords.values()].map(Qw),...[...e.remoteFiles.values()].map(xp)],s=Gw({base:t?Xw(t):[],local:n.observations,remote:i},`${this.replicaId}\0${e.scopeEpoch}\0${t?.generation??0}`,this.runtime.digest);for(let d of s){let f=t?.planned_conflicts?.[d.identity];!f||f.entity!==d.entity||(d.frozen_conflict={local:d.local,remote:d.remote,conflict_kind:f.conflict_kind})}let o=[...n.issues];for(let d of s)(e.kind==="initial"||e.kind==="rebuild")&&d.base.state==="absent"&&d.local.state==="exact"&&d.remote.state==="exact"&&!Zw(d.local,d.remote)&&o.push({code:"local_collision",message:`${d.remote.object.path} differs locally from the exact authority object.`,path:d.remote.object.path,blocking:this.mode!=="read_write"||d.entity==="resource"}),d.remote.state==="exact"&&d.local_target_owner.state==="exact"&&d.remote.object.identity!==d.local_target_owner.object.identity&&o.push({code:"local_collision",message:`${d.remote.object.path} is owned by different local bytes.`,path:d.remote.object.path,blocking:!0});try{po([...i.map(d=>d.path),...n.observations.map(({object:d})=>d.path)])}catch(d){let f=d instanceof Error?d:new Error(String(d));o.push({code:e0(d),message:f.message,blocking:!0})}if(this.mode==="read_only"){for(let d of s)if(d.entity!=="resource"&&!Zw(d.local,d.base)){let f=qO(d.local,d.base);if(o.some(p=>p.blocking&&p.path===f))continue;o.push({code:"mirror_diverged",message:`${f} changed in a receive-only mirror.`,path:f,blocking:!0})}}let a=zn(Fn(this.selectiveSync),this.runtime.digest),c={boundary:{engine_profile:Vc,protocol_profile:"exact_document_v1",planner_policy:zc,projection_policy:Hc,replica_id:this.replicaId,scope_epoch:e.scopeEpoch,authority_cursor:e.authorityCursor,checkpoint:{generation:t?.generation??0,cursor:t?.cursor??null},selective_sync_fingerprint:a},mode:this.mode,kind:e.kind,selective_sync:Fn(this.selectiveSync),objects:s,issues:DO(o)},l=Jw(c,this.runtime.digest),u=await this.bindPayloads(l,n,e.remoteRecords,e.remoteResources,e.remoteFiles);return{summary:c,plan:l,durable_payloads:u,prior:t,snapshot:e.snapshot,remote_records:e.remoteRecords,remote_files:e.remoteFiles}}async bindPayloads(e,t,n,i,s){let o={documents:{},records:{},resources:{},files:{},local_files:{},mutations:{}},a=new Map(i.map(c=>[c.path,c]));for(let c of e.actions)if(c.command==="put_remote"){let l=c.expected_local.state==="exact"?c.expected_local.object.path:c.target.path;if(c.target.entity==="file"){let u=t.binary.get(l);if(!u)throw Hn(c.action_id);await this.stageLocalBinary(l,u),o.local_files[c.action_id]={path:l,...u}}else{let u=t.documents.get(l);if(u===void 0||`sha256:${this.runtime.digest(u)}`!==c.payload_revision)throw Hn(c.action_id);o.documents[c.action_id]=u}c.target.entity==="record"&&(o.mutations[c.action_id]={operation:"put",mutation_id:Ap(c.action_id),replica_id:this.replicaId,scope_epoch:e.scope_epoch,record_id:c.target.identity,...c.expected_remote.state==="exact"?{base_revision:c.expected_remote.object.revision}:{},path:c.target.path,document:o.documents[c.action_id],created_at:this.runtime.now()})}else if(c.command==="write_local")if(c.target.entity==="record"){let l=n.get(c.target.identity);if(!l||l.revision!==c.target.revision)throw Hn(c.action_id);o.records[c.action_id]=l}else if(c.target.entity==="resource"){let l=a.get(c.target.path);if(!l||l.revision!==c.target.revision)throw Hn(c.action_id);o.resources[c.action_id]=l}else{let l=s.get(c.target.identity);if(!l||l.revision!==c.target.revision||!this.blobStore)throw Hn(c.action_id);await Dc(this.transport,this.blobStore,l),o.files[c.action_id]=l}else if(c.command==="record_conflict"&&c.remote.state==="exact")if(c.entity==="record"){let l=n.get(c.identity);if(!l||l.revision!==c.remote.object.revision)throw Hn(c.action_id);o.records[c.action_id]=l}else{let l=s.get(c.identity);if(!l||l.revision!==c.remote.object.revision)throw Hn(c.action_id);o.files[c.action_id]=l}else c.command==="move_remote"&&c.source.entity==="record"?o.mutations[c.action_id]={operation:"move",mutation_id:Ap(c.action_id),replica_id:this.replicaId,scope_epoch:e.scope_epoch,record_id:c.source.identity,base_revision:c.expected_source_owner.state==="exact"?c.expected_source_owner.object.revision:c.source.revision,path:c.target_path,created_at:this.runtime.now()}:c.command==="delete_remote"&&c.target.entity==="record"&&(o.mutations[c.action_id]={operation:"delete",mutation_id:Ap(c.action_id),replica_id:this.replicaId,scope_epoch:e.scope_epoch,record_id:c.target.identity,base_revision:c.expected_remote.state==="exact"?c.expected_remote.object.revision:c.target.revision,created_at:this.runtime.now()});return o}async stageLocalBinary(e,t){if(!this.blobStore||!this.fileSystem.readBinary)throw new b("writable_file_storage_unavailable","Writable files require streaming filesystem and blob-store adapters.");if(await this.blobStore.has(t.content_digest))return;let n=await this.fileSystem.readBinary(e);if(!n)throw new b("sync_plan_stale",`${e} disappeared during inspection.`);await this.blobStore.write(t.content_digest,gw(n,t,e))}};function DO(r){let e=new Map;for(let t of r)e.set(`${t.code}\0${t.path??""}\0${t.message}\0${t.blocking}`,t);return[...e.values()]}function Xw(r){return[...Object.entries(r.resources??{}).map(([e,t])=>Hi("resource",e,t.path,t.revision)),...Object.entries(r.records).map(([e,t])=>Hi("record",e,t.path,t.revision)),...Object.entries(r.files??{}).map(([e,t])=>xp({...t.file,file_id:e}))]}function Qw(r){return Hi("record",r.record_id,r.path,r.revision)}function LO(r){return Hi("resource",r.path,r.path,r.revision)}function Hi(r,e,t,n){return{entity:r,identity:e,path:t,revision:n,payload_revision:n}}function xp(r){return{entity:"file",identity:r.file_id,path:r.path,revision:r.revision,payload_revision:r.content_digest,size:r.size}}function jO(r){return`${r.entity}:${r.identity}`}function Zw(r,e){return JSON.stringify(r)===JSON.stringify(e)}function qO(r,e){return r.state==="exact"?r.object.path:e.state==="exact"?e.object.path:"mirror"}function Hn(r){return new b("sync_payload_incomplete",`Inspected action ${r} has no revision-bound payload.`)}function e0(r){return r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:"sync_inspection_failed"}function FO(r){return r==="mdbase.yaml"?"configuration":r.endsWith("lock.yaml")?"lock":r.startsWith("_types/")?"type":r.startsWith("_contracts/")?"contract":r.startsWith("_views/")?"view":"schema"}function Ap(r){let e=r.replace(/^sha256:/u,"");return`${e.slice(0,8)}-${e.slice(8,12)}-4${e.slice(13,16)}-8${e.slice(17,20)}-${e.slice(20,32)}`}async function t0(r,e,t,n){if(r?.batch){if(r.batch.plan.fingerprint!==e.fingerprint)throw new b("mirror_recovery_required","A different prepared sync batch must recover before this plan can apply.");return r}let i=r?structuredClone(r):BO(e.replica_id,e.scope_epoch,e.mode,e.selective_sync);return i.scope_epoch=e.scope_epoch,i.selective_sync=e.selective_sync,i.batch={phase:"prepared",plan:e,next_action:0,receipts:[],payloads:t,checkpoint_before:{generation:e.checkpoint_generation,cursor:e.base_cursor},checkpoint_after:{generation:e.checkpoint_generation+1,cursor:e.authority_cursor}},await n.write(i),i}async function r0(r,e){let t=rt(r);t.phase!=="effects_complete"&&(t.phase="applying",delete t.failure,await Yc(r,{type:"phase",plan_fingerprint:t.plan.fingerprint,phase:"applying"},e))}async function n0(r,e,t){let n=rt(r),i=n.plan.actions[n.next_action];if(!i||i.action_id!==e.action_id)throw new b("invalid_mirror_state","The durable sync receipt does not match the next prepared action.");let s={type:"receipt",plan_fingerprint:n.plan.fingerprint,receipt:structuredClone(e),delta:UO(r,i)};n.receipts.push(structuredClone(e)),n.next_action+=1,await Yc(r,s,t)}async function i0(r,e){let t=rt(r),n=t.plan.actions[t.next_action];if(!n||n.command!=="advance_checkpoint")throw new b("invalid_mirror_state","Sync effects cannot complete before the checkpoint action is next.");t.phase="effects_complete",await Yc(r,{type:"effects_complete",plan_fingerprint:t.plan.fingerprint},e)}async function Jc(r,e,t,n){let i=rt(r);i.phase=e,i.failure=t,await Yc(r,{type:"phase",plan_fingerprint:i.plan.fingerprint,phase:e,failure:t},n)}async function Yc(r,e,t){t.appendJournal?await t.appendJournal(e):await t.write(r)}function UO(r,e){let t="identity"in e?e.identity:"target"in e?e.target.identity:"source"in e?e.source.identity:null;if(t===null)return{};let n="entity"in e?e.entity:"target"in e?e.target.entity:"source"in e?e.source.entity:null;if(n===null)return{};let i={planned_conflicts:{[t]:mo(r.planned_conflicts?.[t])},local_bindings:{[t]:mo(r.local_bindings?.[t])}};return n==="record"?i.records={[t]:mo(r.records[t])}:n==="resource"?i.resources={[t]:mo(r.resources?.[t])}:i.files={[t]:mo(r.files?.[t])},i}function mo(r){return r===void 0?null:structuredClone(r)}function rt(r){if(!r.batch)throw new b("invalid_mirror_state","The mirror has no prepared sync batch.");return r.batch}async function s0(r,e){let t=rt(r);if(t.phase!=="blocked"||t.failure?.code!=="sync_plan_stale")throw new b("mirror_recovery_required","Only a stale batch at a durable action boundary can be abandoned.");delete r.batch,await e.write(r)}function BO(r,e,t,n){return{protocol_version:1,engine_version:3,generation:0,replica_id:r,scope_epoch:e,cursor:0,records:{},resources:{},files:{},selective_sync:n,mode:t,planned_conflicts:{}}}var Qc=class{ports;materializer;ownersByPath=new Map;pathsByOwner=new Map;constructor(e){this.ports=e,this.materializer=new zi(e.fileSystem,e.runtime,e.mode,e.blobStore)}async execute(e,t){let n=rt(e);this.indexPathOwners(e);let i=new Set(n.receipts.map(s=>s.action_id));for(await r0(e,this.ports.store);n.next_action!i.has(a));if(o){let a={code:"invalid_mirror_state",message:`Action ${s.action_id} is missing dependency ${o}.`,action_id:s.action_id};return await Jc(e,"blocked",a,this.ports.store),{status:"blocked",completed:n.next_action,failure:a}}try{let a=await this.dispatch(e,s);await n0(e,a,this.ports.store),i.add(a.action_id),this.ports.onProgress?.(n.next_action,n.plan.actions.length-1)}catch(a){let c=HO(a,s.action_id);return await Jc(e,"blocked",c,this.ports.store),{status:c.code==="sync_plan_stale"?"stale":"blocked",completed:n.next_action,failure:c}}}throw new b("invalid_mirror_state","Prepared plan has no checkpoint action.")}async dispatch(e,t){switch(t.command){case"write_local":return this.writeLocal(e,t);case"move_local":return this.moveLocal(e,t);case"delete_local":return this.deleteLocal(e,t);case"put_remote":return this.putRemote(e,t);case"move_remote":return this.moveRemote(e,t);case"delete_remote":return this.deleteRemote(e,t);case"record_conflict":return e.planned_conflicts??={},e.planned_conflicts[t.identity]={decision_id:o0(t.entity,t.identity,t.local,t.remote,t.conflict_kind,this.ports.runtime.digest),entity:t.entity,local:t.local,remote:t.remote,conflict_kind:t.conflict_kind},e.local_bindings??={},t.local.state==="exact"?e.local_bindings[t.identity]={entity:t.entity,path:t.local.object.path}:delete e.local_bindings[t.identity],this.rebaseConflict(e,t),{action_id:t.action_id,status:"conflicted"};case"clear_conflict":return delete e.planned_conflicts?.[t.identity],delete e.local_bindings?.[t.identity],{action_id:t.action_id,status:"completed"};case"advance_checkpoint":throw new b("invalid_mirror_state","The executor cannot dispatch checkpoint actions.")}}rebaseConflict(e,t){let n=rt(e).payloads;if(t.entity==="record"){if(t.remote.state==="absent"){delete e.records[t.identity];return}let s=n.records[t.action_id];if(!s||s.revision!==t.remote.object.revision)throw br(t);Xc(s,this.ports.runtime,s.revision),e.records[t.identity]={path:s.path,revision:s.revision,hash:t.local.state==="exact"?t.local.object.payload_revision.replace(/^sha256:/u,""):this.ports.runtime.digest(s.document),...this.ports.mode==="read_write"?{record:s}:{}};return}if(e.files??={},t.remote.state==="absent"){delete e.files[t.identity];return}let i=n.files[t.action_id];if(!i||i.revision!==t.remote.object.revision)throw br(t);ht(i),e.files[t.identity]={file:i}}async writeLocal(e,t){let n=await this.ports.fileSystem.exists(t.target.path);(!n||!await this.matchesRef(t.target))&&(await this.assertLocal(t.expected_local),await this.assertPathOwner(t.target.path,t.expected_path_owner,n));let i=rt(e).payloads;if(t.target.entity==="record"){let o=i.records[t.action_id];if(!o||o.revision!==t.payload_revision)throw br(t);return Xc(o,this.ports.runtime,t.payload_revision),await this.materializer.put(e,o,{inspectionPreflighted:!0}),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}if(t.target.entity==="resource"){let o=i.resources[t.action_id];if(!o||o.revision!==t.payload_revision||`sha256:${this.ports.runtime.digest(o.document)}`!==o.revision)throw br(t);return await this.materializer.putResource(e,o,e),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}let s=i.files[t.action_id];if(!s||s.content_digest!==t.payload_revision)throw br(t);return await this.materializer.putFile(e,s,e),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}async moveLocal(e,t){return await this.matchesRef({...t.source,path:t.target_path})||(await this.assertLocal(t.expected_source_owner),await this.assertPathOwner(t.target_path,t.expected_target_owner),await this.ports.fileSystem.move(t.source.path,t.target_path)),VO(e,t.source,t.target_path),this.installPathOwner({...t.source,path:t.target_path}),{action_id:t.action_id,status:"completed"}}async deleteLocal(e,t){if(await this.matchesRef(t.target))if(await this.assertLocal(t.expected_local),t.target.entity==="record")await this.materializer.remove(e,t.target.identity,t.target.path,{inspectionPreflighted:!0});else if(t.target.entity==="resource"){let i=e.resources?.[t.target.identity];i?await this.materializer.removeResource(e,t.target.path,i):await this.ports.fileSystem.remove(t.target.path)}else await this.materializer.removeFile(e,t.target.identity);else zO(e,t.target);return this.removePathOwner(t.target),{action_id:t.action_id,status:"completed"}}async putRemote(e,t){let n=rt(e).payloads;if(t.target.entity==="record"){let a=n.mutations[t.action_id],c=n.documents[t.action_id];if(!a||a.operation!=="put"||c===void 0)throw br(t);if(`sha256:${this.ports.runtime.digest(c)}`!==t.payload_revision)throw new b("sync_plan_stale","Prepared local document payload no longer matches its revision.");let l=await this.ports.transport.mutate(a);return this.acceptRecordReceipt(e,t,l,c),kp(t.action_id,l)}if(t.target.entity==="resource")throw new b("invalid_sync_plan","Authority resources are not writable mirror objects.");let i=n.local_files[t.action_id];if(!i||!this.ports.blobStore||!this.ports.transport.uploadFile)throw br(t);let s={protocol_version:1,type:"open_file_upload",transfer_id:Cp(t.action_id),path:t.target.path,size:i.size,content_digest:i.content_digest,...i.media_type?{media_type:i.media_type}:{},...t.expected_remote.state==="exact"?{if_revision:t.expected_remote.object.revision}:{}},o=await this.ports.transport.uploadFile(s,this.ports.blobStore.read(i.content_digest));if(ht(o.file),o.transfer_id!==s.transfer_id||o.file.path!==t.target.path||o.file.content_digest!==i.content_digest||o.file.size!==i.size)throw Pp(t);return e.files??={},e.files[o.file.file_id]={file:o.file},delete e.local_bindings?.[t.target.identity],{action_id:t.action_id,status:"completed",file:o.file}}async moveRemote(e,t){if(t.source.entity==="record"){let s=rt(e).payloads.mutations[t.action_id];if(!s||s.operation!=="move")throw br(t);let o=await this.ports.transport.mutate(s);return this.acceptRecordReceipt(e,t,o),kp(t.action_id,o)}if(t.source.entity==="resource"||!this.ports.transport.moveFile)throw new b("invalid_sync_plan","This remote move command is unsupported.");let n={protocol_version:1,type:"move_file",mutation_id:Cp(t.action_id),file_id:t.source.identity,if_revision:this.dependencyFileRevision(e,t)??(t.expected_source_owner.state==="exact"?t.expected_source_owner.object.revision:t.source.revision),from_path:t.source.path,path:t.target_path,update_references:!1},i=await this.ports.transport.moveFile(n);if(ht(i.file),i.mutation_id!==n.mutation_id||i.file.file_id!==t.source.identity||i.file.path!==t.target_path)throw Pp(t);return e.files??={},e.files[t.source.identity]={file:i.file},delete e.local_bindings?.[t.source.identity],{action_id:t.action_id,status:"completed",file:i.file}}dependencyFileRevision(e,t){if(!t.revision_from_dependency)return;let n=rt(e).receipts.find(({action_id:i})=>i===t.revision_from_dependency);if(!n?.file||n.file.file_id!==t.source.identity)throw new b("invalid_mirror_state",`Move ${t.action_id} is missing its dependency file receipt.`);return n.file.revision}async deleteRemote(e,t){if(t.target.entity==="record"){let s=rt(e).payloads.mutations[t.action_id];if(!s||s.operation!=="delete")throw br(t);let o=await this.ports.transport.mutate(s);return this.acceptRecordReceipt(e,t,o),kp(t.action_id,o)}if(t.target.entity==="resource"||!this.ports.transport.deleteFile)throw new b("invalid_sync_plan","This remote delete command is unsupported.");let n={protocol_version:1,type:"delete_file",mutation_id:Cp(t.action_id),file_id:t.target.identity,if_revision:t.expected_remote.state==="exact"?t.expected_remote.object.revision:t.target.revision,path:t.target.path},i=await this.ports.transport.deleteFile(n);if(i.mutation_id!==n.mutation_id||i.file_id!==t.target.identity||i.previous_path!==t.target.path)throw Pp(t);return delete e.files?.[t.target.identity],delete e.local_bindings?.[t.target.identity],{action_id:t.action_id,status:"completed"}}acceptRecordReceipt(e,t,n,i){let o=("target"in t?t.target:t.source).identity;if(n.status==="applied"||n.status==="previously_applied"){if(n.record){Xc(n.record,this.ports.runtime,n.record.revision);let u=e.records[o];e.records[o]={path:n.record.path,revision:n.record.revision,hash:i===void 0?u?.hash??this.ports.runtime.digest(n.record.document):this.ports.runtime.digest(i),...this.ports.mode==="read_write"?{record:n.record}:{}}}else delete e.records[o];delete e.local_bindings?.[o];return}let a=n.status==="conflicted"?n.conflict.current:void 0;a&&Xc(a,this.ports.runtime,a.revision);let c=a?{state:"exact",object:{entity:"record",identity:o,path:a.path,revision:a.revision,payload_revision:a.revision}}:t.command==="move_remote"?t.expected_source_owner:t.expected_remote;e.planned_conflicts??={};let l=n.status==="rejected"?"rejected":"both_changed";e.planned_conflicts[o]={decision_id:o0("record",o,t.expected_local,c,l,this.ports.runtime.digest),entity:"record",local:t.expected_local,remote:c,conflict_kind:l},e.local_bindings??={},t.expected_local.state==="exact"&&(e.local_bindings[o]={entity:"record",path:t.expected_local.object.path}),a&&(e.records[o]={path:a.path,revision:a.revision,hash:t.expected_local.state==="exact"?t.expected_local.object.payload_revision.replace(/^sha256:/u,""):this.ports.runtime.digest(a.document),...this.ports.mode==="read_write"?{record:a}:{}})}async assertLocal(e){if(e.state!=="absent"&&!await this.matchesRef(e.object))throw new b("sync_plan_stale",`${e.object.path} no longer matches the inspected revision.`)}async assertPathOwner(e,t,n){let i=this.ownersByPath.get(e);if(t.state==="absent"){if(i||(n??await this.pathExists(e)))throw new b("sync_plan_stale",`${e} is no longer vacant.`);return}if(!i||i.entity!==t.object.entity||i.identity!==t.object.identity)throw new b("sync_plan_stale",`${e} has a different path owner.`)}async matchesRef(e){if(e.entity==="file"){let n=await this.ports.fileSystem.inspectBinary(e.path);return n!==null&&n.content_digest===e.payload_revision&&(e.size===void 0||n.size===e.size)}let t=await this.ports.fileSystem.read(e.path);return t!==null&&`sha256:${this.ports.runtime.digest(t)}`===e.payload_revision}async pathExists(e){return this.ports.fileSystem.exists(e)}indexPathOwners(e){this.ownersByPath.clear(),this.pathsByOwner.clear();for(let[t,n]of Object.entries(e.records))this.installPathOwner({entity:"record",identity:t,path:n.path,revision:n.revision,payload_revision:`sha256:${n.hash}`});for(let[t,n]of Object.entries(e.resources??{}))this.installPathOwner({entity:"resource",identity:t,path:n.path,revision:n.revision,payload_revision:`sha256:${n.hash}`});for(let[t,n]of Object.entries(e.files??{}))this.installPathOwner({entity:"file",identity:t,path:n.file.path,revision:n.file.revision,payload_revision:n.file.content_digest,size:n.file.size})}installPathOwner(e){let t=`${e.entity}:${e.identity}`,n=this.pathsByOwner.get(t);n!==void 0&&this.ownersByPath.delete(n),this.ownersByPath.set(e.path,e),this.pathsByOwner.set(t,e.path)}removePathOwner(e){let t=`${e.entity}:${e.identity}`,n=this.pathsByOwner.get(t)??e.path;this.ownersByPath.delete(n),this.pathsByOwner.delete(t)}};function o0(r,e,t,n,i,s){return zn({entity:r,identity:e,local:t,remote:n,conflict_kind:i},s)}function VO(r,e,t){if(e.entity==="record"){let n=r.records[e.identity];n&&(n.path=t,n.record&&(n.record.path=t))}else if(e.entity==="resource"){let n=r.resources?.[e.identity];n&&(n.path=t)}else{let n=r.files?.[e.identity];n&&(n.file.path=t)}}function zO(r,e){e.entity==="record"?delete r.records[e.identity]:e.entity==="resource"?delete r.resources?.[e.identity]:delete r.files?.[e.identity]}function Xc(r,e,t){let n=kc(r);if(r.revision!==t||`sha256:${e.digest(n)}`!==t)throw new b("invalid_sync_response","Record receipt does not match its exact document revision.")}function kp(r,e){return e.status==="applied"||e.status==="previously_applied"?{action_id:r,status:"completed",...e.record?{record:e.record}:{}}:{action_id:r,status:e.status}}function br(r){return new b("sync_payload_incomplete",`Prepared action ${r.action_id} has no exact payload capability.`)}function Pp(r){return new b("invalid_sync_response",`Authority receipt does not match prepared action ${r.action_id}.`)}function HO(r,e){let t=r instanceof Error?r:new Error(String(r));return{code:r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:"sync_action_failed",message:t.message,action_id:e}}function Cp(r){let e=r.replace(/^sha256:/u,"");return`${e.slice(0,8)}-${e.slice(8,12)}-4${e.slice(13,16)}-8${e.slice(17,20)}-${e.slice(20,32)}`}var yo=class{fileSystem;runtime;constructor(e,t){this.fileSystem=e,this.runtime=t}async validate(e,t){if((t?.generation??0)!==e.checkpoint_generation||(t?.cursor??null)!==e.base_cursor||(t?.scope_epoch??e.scope_epoch)!==e.scope_epoch)throw Zc("The durable checkpoint changed after inspection.");for(let n of e.actions)n.depends_on.length===0&&await this.validateAction(n)}async validateAction(e){switch(e.command){case"write_local":await this.validateExpected(e.expected_local),await this.validateExpectedAt(e.target.path,e.expected_path_owner);return;case"delete_local":await this.validateExpected(e.expected_local),await this.validateExpectedAt(e.target.path,e.expected_path_owner);return;case"move_local":await this.validateExpectedAt(e.source.path,e.expected_source_owner),await this.validateExpectedAt(e.target_path,e.expected_target_owner);return;case"put_remote":case"move_remote":await this.validateExpected(e.expected_local);return;case"delete_remote":await this.validateExpectedAt(e.target.path,e.expected_local);return;case"record_conflict":await this.validateExpected(e.local);return;case"clear_conflict":await this.validateExpected(e.expected_local);return;case"advance_checkpoint":return}}async validateExpectedAt(e,t){if(t.state==="absent"){if(await this.pathExists(e))throw Zc(`${e} is no longer vacant.`);return}if(t.object.path!==e||!await this.matches(t.object))throw Zc(`${e} no longer has the inspected owner and bytes.`)}async validateExpected(e){if(e.state!=="absent"&&!await this.matches(e.object))throw Zc(`${e.object.path} no longer matches the inspected bytes.`)}async matches(e){if(e.entity==="file"){let n=await this.fileSystem.inspectBinary(e.path);return n!==null&&n.content_digest===e.payload_revision&&(e.size===void 0||n.size===e.size)}let t=await this.fileSystem.read(e.path);return t!==null&&`sha256:${this.runtime.digest(t)}`===e.payload_revision}async pathExists(e){return this.fileSystem.exists(e)}};function Zc(r){return new b("sync_plan_stale",r)}async function a0(r,e,t){let n=rt(r);if(n.phase!=="effects_complete")throw new b("invalid_mirror_state","A checkpoint cannot advance before every prepared effect is durable.");let i=n.plan.actions[n.next_action];if(!i||i.command!=="advance_checkpoint")throw new b("invalid_mirror_state","Prepared checkpoint action is missing.");if(i.expected.generation!==n.checkpoint_before.generation||i.expected.cursor!==n.checkpoint_before.cursor||i.next.generation!==n.checkpoint_after.generation||i.next.cursor!==n.checkpoint_after.cursor)throw new b("invalid_mirror_state","Prepared checkpoint boundary is inconsistent.");let s=n.plan.fingerprint;return r.generation=i.next.generation,r.cursor=i.next.cursor??0,r.last_completed_plan=s,r.last_synced_at=e.now(),delete r.batch,await t.write(r),s}async function c0(r,e,t,n){let[i]=e.actions;if(e.actions.length!==1||!i||i.command!=="advance_checkpoint"||i.expected.generation!==(r.generation??0)||i.expected.cursor!==r.cursor||i.next.generation!==(r.generation??0)+1||i.next.cursor!==e.authority_cursor||r.batch!==void 0)throw new b("invalid_mirror_state","Empty checkpoint plan is inconsistent.");return r.generation=i.next.generation,r.cursor=i.next.cursor??0,r.last_completed_plan=e.fingerprint,r.last_synced_at=t.now(),await n.write(r),e.fingerprint}var Kn=class{replicaId;transport;mode;stateStore;fileSystem;blobStore;selectiveSync;lease;runtime;materializer;onProgress;constructor(e,t,n,i="read_only"){this.replicaId=e,this.transport=t,this.mode=i,this.stateStore=n.stateStore,this.fileSystem=n.fileSystem,this.blobStore=n.blobStore,this.selectiveSync=Fn(n.selectiveSync),this.lease=n.lease??new uo,this.runtime=n.runtime??fo,this.materializer=new zi(this.fileSystem,this.runtime,this.mode,this.blobStore),this.onProgress=n.onProgress}async sync(e={}){return this.lease.runExclusive(async()=>{let t=await this.readState();if(t?.batch?.phase==="blocked"&&t.batch.failure?.code==="sync_plan_stale"&&(await s0(t,this.journalStore()),t=await this.readState()),t?.batch)return this.executePrepared(t,e.signal);let n=await this.inspectDetailed(t);return this.applyInspection(n,e.signal)})}async inspect(){return this.lease.runExclusive(async()=>{let e=await this.readState();return e?.batch?.plan??(await this.inspectDetailed(e)).plan})}async apply(e,t={}){return this.lease.runExclusive(async()=>{let n=await this.readState();if(n?.batch){if(n.batch.plan.fingerprint!==e.fingerprint)throw new b("mirror_recovery_required","A different prepared plan must recover before this plan can apply.");return this.executePrepared(n,t.signal)}let i=await this.inspectDetailed(n);return i.plan.fingerprint!==e.fingerprint?jr("stale",e,yr(i.prior,this.mode),0,{code:"sync_plan_stale",message:"The local folder or authority changed. Inspect the sync plan again."}):this.applyInspection(i,t.signal)})}async applyInspection(e,t){let n=e.plan;if(n.issues.some(s=>s.blocking))return jr("attention",n,yr(e.prior,this.mode),0);if(t?.aborted)return jr("cancelled",n,yr(e.prior,this.mode),0,{code:"sync_cancelled",message:"Sync cancelled before preparation."});try{await new yo(this.fileSystem,this.runtime).validate(n,e.prior)}catch(s){let o=s instanceof Error?s:new Error(String(s)),a=s&&typeof s=="object"&&"code"in s&&typeof s.code=="string"?s.code:"sync_revalidation_failed";return jr(a==="sync_plan_stale"?"stale":"failed",n,yr(e.prior,this.mode),0,{code:a,message:o.message})}if(n.actions.length===0)return jr("applied",n,yr(e.prior,this.mode),0);if(e.prior&&n.actions.length===1&&n.actions[0]?.command==="advance_checkpoint")return await c0(e.prior,n,this.runtime,this.journalStore()),jr("applied",n,yr(e.prior,this.mode),0);let i=await t0(e.prior??this.initialUnchangedState(e),n,e.durable_payloads,this.journalStore());return this.executePrepared(i,t)}async executePrepared(e,t){let n=e.batch,i=await new Qc({transport:this.transport,fileSystem:this.fileSystem,blobStore:this.blobStore,runtime:this.runtime,mode:this.mode,store:this.journalStore(),onProgress:(c,l)=>this.onProgress?.({phase:"applying",completed:c,total:l,done:c===l})}).execute(e,t);if(i.status!=="effects_complete"){let c=yr(e,this.mode);return jr(i.status==="blocked"?"failed":i.status,n.plan,c,i.completed,i.failure)}let s=n.plan;await a0(e,this.runtime,this.journalStore()),await this.pruneFileBlobs();let o=yr(e,this.mode),a=o.conflicts.length>0||o.local_issues.length>0||s.summary.conflicts>0;return jr(a?"attention":"applied",s,o,i.completed)}inspectDetailed(e){return new Gc(this.replicaId,this.transport,this.mode,this.fileSystem,this.blobStore,this.selectiveSync,this.runtime,()=>this.readState(),t=>this.currentRecordPathPolicy(t)).inspect(e)}initialUnchangedState(e){if(e.plan.kind!=="initial"||!e.snapshot)return null;let t=new Set(e.summary.objects.filter(o=>o.local.state==="exact"&&o.remote.state==="exact"&&JSON.stringify(o.local)===JSON.stringify(o.remote)).map(o=>`${o.entity}:${o.identity}`)),n={};for(let{record:o,hash:a}of e.snapshot.records)t.has(`record:${o.record_id}`)&&(n[o.record_id]={path:o.path,revision:o.revision,hash:a,...this.mode==="read_write"?{record:o}:{}});let i={};for(let o of e.snapshot.resources)t.has(`resource:${o.path}`)&&(i[o.path]={path:o.path,revision:o.revision,hash:this.runtime.digest(o.document)});let s={};for(let o of e.snapshot.files)t.has(`file:${o.file_id}`)&&(s[o.file_id]={file:o});return{protocol_version:1,engine_version:3,generation:0,replica_id:e.plan.replica_id,scope_epoch:e.plan.scope_epoch,cursor:0,records:n,resources:i,files:s,selective_sync:e.plan.selective_sync,mode:e.plan.mode,planned_conflicts:{}}}async status(){let e=await this.checkpointStatus();return e.state==="not_initialized"?e:Vw(e,await this.inspect())}async checkpointStatus(){return this.lease.runExclusive(()=>this.checkpointStatusUnlocked())}async checkpointStatusUnlocked(){return yr(await this.readState(),this.mode)}async authorityPromotionManifest(){return this.lease.runExclusive(async()=>{if(this.mode!=="read_write")throw new b("promotion_requires_writable_mirror","Only a read-write mirror can prove an authority promotion source.");let e=await this.readState();if(!e)throw new b("mirror_not_initialized","Synchronize this mirror first.");if(e.batch||Object.keys(e.planned_conflicts??{}).length>0)throw new b("promotion_mirror_not_clean","Finish the prepared batch and resolve conflicts before promotion.");let t=await Bw({state:e,selectiveSync:this.selectiveSync,fileSystem:this.fileSystem,pathPolicy:await this.currentRecordPathPolicy(e),digest:this.runtime.digest});if((await this.inspectDetailed(e)).plan.actions.some(i=>i.command!=="advance_checkpoint"))throw new b("promotion_mirror_not_clean","Synchronize this mirror immediately before promotion.");return t})}async previewInitialization(){let e=await this.inspect(),t=e.actions.filter(i=>i.command==="put_remote"||i.command==="move_remote"||i.command==="delete_remote"),n=e.actions.filter(i=>i.command==="write_local"||i.command==="move_local"||i.command==="delete_local");return{already_initialized:e.kind==="incremental",download_documents:n.filter(i=>"target"in i&&i.target.entity!=="file"||"source"in i&&i.source.entity!=="file").length,upload_documents:t.filter(i=>"target"in i&&i.target.entity==="record"||"source"in i&&i.source.entity==="record").length,unchanged_documents:0,download_files:n.filter(i=>"target"in i&&i.target.entity==="file"||"source"in i&&i.source.entity==="file").length,upload_files:t.filter(i=>"target"in i&&i.target.entity==="file"||"source"in i&&i.source.entity==="file").length,unchanged_files:0,collisions:e.issues.filter(i=>i.code==="local_collision"&&i.path).map(i=>i.path),local_issues:e.issues.filter(i=>i.code==="invalid_frontmatter"&&i.path!==void 0).map(i=>({code:"invalid_frontmatter",message:i.message,path:i.path}))}}async resolveConflict(e,t,n){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,t,n))}async resolveConflictUnlocked(e,t,n){if(this.mode!=="read_write")throw new b("mirror_read_only","Receive-only mirrors have no writable conflicts.");let i=await this.readState();if(!i||i.batch)throw new b("mirror_recovery_required","Finish sync recovery before resolving conflicts.");let s=i.planned_conflicts?.[e];if(!s)throw new b("mirror_conflict_not_found","Writable mirror conflict was not found.");if((s.decision_id??"")!==t)throw l0();let o=new yo(this.fileSystem,this.runtime);s.local.state==="exact"?await o.validateExpected(s.local):s.remote.state==="exact"&&await o.validateExpectedAt(s.remote.object.path,s.local);let a=await Bc(this.replicaId,this.transport,this.mode,this.selectiveSync,this.runtime),c=s.entity==="record"?a.records.find(({record:d})=>d.record_id===e)?.record:void 0,l=s.entity==="file"?a.files.find(d=>d.file_id===e):void 0;if(!(s.entity==="record"?KO(s.remote,c):WO(s.remote,l)))throw l0();n==="remote"&&(s.entity==="record"?await this.installRemoteRecord(i,e,c):await this.installRemoteFile(i,e,l)),delete i.planned_conflicts?.[e],n==="remote"&&delete i.local_bindings?.[e],await this.writeState(i)}async installRemoteRecord(e,t,n){if(n){let o=e.planned_conflicts?.[t],a=await this.fileSystem.read(n.path),c=e.records[t]?.path===n.path||o?.local.state==="exact"&&o.local.object.path===n.path;await this.materializer.put(e,n,{inspectionPreflighted:!1,...c&&a!==null?{acceptedHash:this.runtime.digest(a)}:{}});return}let i=e.planned_conflicts?.[t],s=i?.local.state==="exact"?i.local.object.path:e.records[t]?.path;s&&await this.fileSystem.read(s)!==null&&await this.fileSystem.remove(s),delete e.records[t]}async installRemoteFile(e,t,n){if(n){if(!this.blobStore)throw new b("file_storage_unavailable","File resolution needs a blob store.");await Dc(this.transport,this.blobStore,n);let o=e.planned_conflicts?.[t],a=o?.local.state==="exact"?{content_digest:o.local.object.payload_revision,size:o.local.object.size??0}:void 0,c=e.local_bindings?.[t]?.path;await this.materializer.putFile(e,n,e,a),c&&c!==n.path&&await this.fileSystem.remove(c);return}let i=e.planned_conflicts?.[t],s=i?.local.state==="exact"?i.local.object.path:e.files?.[t]?.file.path;s&&await this.fileSystem.inspectBinary(s)!==null&&await this.fileSystem.remove(s),delete e.files?.[t]}async readState(){let e=await this.stateStore.read();if(e===null)return null;try{return Tw(e,this.replicaId,this.mode)}catch(t){throw t instanceof b?t:new b("invalid_mirror_state","Mirror metadata is corrupt or belongs to another replica.")}}writeState(e){return this.stateStore.write(e)}journalStore(){let e=this.stateStore;return{write:t=>this.writeState(t),...e.appendJournal?{appendJournal:t=>e.appendJournal(t)}:{}}}async pruneFileBlobs(){if(!this.blobStore)return;let e=await this.readState();if(!e)return;let t=new Set;for(let n of Object.values(e.files??{}))t.add(n.file.content_digest);for(let n of Object.values(e.batch?.payloads.files??{}))t.add(n.content_digest);for(let n of Object.values(e.batch?.payloads.local_files??{}))t.add(n.content_digest);await this.blobStore.prune(t)}currentRecordPathPolicy(e){return this.materializer.recordPathPolicy(e)}};function KO(r,e){return r.state==="absent"?e===void 0:e!==void 0&&r.object.entity==="record"&&r.object.identity===e.record_id&&r.object.path===e.path&&r.object.revision===e.revision&&r.object.payload_revision===e.revision&&r.object.size===void 0}function WO(r,e){return r.state==="absent"?e===void 0:e!==void 0&&r.object.entity==="file"&&r.object.identity===e.file_id&&r.object.path===e.path&&r.object.revision===e.revision&&r.object.payload_revision===e.content_digest&&r.object.size===e.size}function l0(){return new b("mirror_conflict_stale","Local or hosted content changed after this conflict was recorded. Synchronize again before choosing a version.")}var go=class extends Kn{constructor(e,t,n){super(e,t,n,"read_write")}};function d0(r){let e=[...r.actions.flatMap(t=>t.command==="advance_checkpoint"?[]:[GO(t)]),...r.issues.map(t=>({kind:"document",path:t.path??"Sync engine",direction:"attention",action:"fix",detail:t.message}))];return{plan:r,phase:r.kind,entries:e,cursor:r.base_cursor,remoteHead:r.authority_cursor,already_initialized:r.kind==="incremental",download_documents:r.actions.filter(t=>["write_local","move_local","delete_local"].includes(t.command)&&("target"in t?t.target.entity!=="file":"source"in t&&t.source.entity!=="file")).length,upload_documents:r.actions.filter(t=>["put_remote","move_remote","delete_remote"].includes(t.command)&&("target"in t?t.target.entity==="record":"source"in t&&t.source.entity==="record")).length,unchanged_documents:0,download_files:r.actions.filter(t=>["write_local","move_local","delete_local"].includes(t.command)&&("target"in t?t.target.entity==="file":"source"in t&&t.source.entity==="file")).length,upload_files:r.actions.filter(t=>["put_remote","move_remote","delete_remote"].includes(t.command)&&("target"in t?t.target.entity==="file":"source"in t&&t.source.entity==="file")).length,unchanged_files:0,collisions:r.issues.filter(t=>t.blocking&&t.code==="local_collision"&&t.path!==void 0).map(t=>t.path),local_issues:r.issues.filter(t=>t.code==="invalid_frontmatter"&&t.path!==void 0).map(t=>({code:"invalid_frontmatter",message:t.message,path:t.path}))}}function GO(r){if(r.command==="advance_checkpoint")throw new Error("Checkpoint actions are not preview entries.");if(r.command==="record_conflict"){let c=r.local.state==="exact"?r.local.object:r.remote.state==="exact"?r.remote.object:void 0;return{kind:r.entity==="file"?"file":"document",path:c?.path??r.identity,direction:"attention",action:"fix",detail:`Local and hosted ${r.entity} changes conflict (${r.conflict_kind.replace(/_/g," ")}).`,...c?.entity==="file"&&c.size!==void 0?{estimatedBytes:c.size}:{},...r.entity==="record"?{recordId:r.identity}:{fileId:r.identity}}}if(r.command==="clear_conflict"){let c=r.expected_local.state==="exact"?r.expected_local.object:r.expected_remote.state==="exact"?r.expected_remote.object:void 0;return{kind:r.entity==="file"?"file":"document",path:c?.path??r.identity,direction:"attention",action:"fix",detail:`Local and hosted ${r.entity} content now matches; clear the resolved conflict.`,...c?.entity==="file"&&c.size!==void 0?{estimatedBytes:c.size}:{},...r.entity==="record"?{recordId:r.identity}:{fileId:r.identity}}}let e=r.command.endsWith("_local"),t="target"in r?r.target:r.source,n=r.command==="move_local"||r.command==="move_remote"?r.target_path:t.path,i=r.command==="write_local"&&r.expected_local.state==="absent"||r.command==="put_remote"&&r.expected_remote.state==="absent",s=r.command.startsWith("move_")?"rename":r.command.startsWith("delete_")?"delete":i?"create":"update",o=r.command.split("_")[0],a=r.command.startsWith("move_")?` from ${t.path}`:"";return{kind:t.entity==="file"?"file":"document",path:n,direction:e?"download":"upload",action:s,detail:`${e?"Hosted":"Local"} ${t.entity} will ${o}${a}.`,...t.entity==="file"&&t.size!==void 0?{estimatedBytes:t.size}:{},...t.entity==="record"?{recordId:t.identity}:{},...t.entity==="file"?{fileId:t.identity}:{}}}var Ki=".mdbase/connect-role.json",bo=".mdbase/authority-adoption.json",_o=".mdbase/authority-adoption-snapshot.json",JO="mdbase-obsidian-connect",yn="mirrors",YO="mdbase-obsidian-connect-blobs",gn="manifests",bn="chunks",el=1024*1024,XO="mdbase-connect-access-",QO="mdbase-connect-refresh-",ZO="mdbase-connect-adoption-",eN=300*1e3,tN=[".git",".trash",".mdbase"],rN=new Set([".git",".mdbase",".trash","node_modules","_contracts","_schemas","_types","_views"]),Mp=["image","audio","video","pdf","other"],wo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function nt(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function _r(r){let e=r?.file_classes??[];if(e.some(s=>!Mp.includes(s))||new Set(e).size!==e.length)throw new b("invalid_file_materialization","Selected file media classes must be valid and unique.");let t=[...e].sort((s,o)=>Mp.indexOf(s)-Mp.indexOf(o)),n=r?.excluded_folders??[];if(n.some(s=>typeof s!="string"||!s.trim()))throw new b("invalid_file_materialization","Excluded folders cannot be empty.");let i=n.map(s=>Rn(s.trim())).sort((s,o)=>s.toLocaleLowerCase().localeCompare(o.toLocaleLowerCase()));if(i.length>100)throw new b("invalid_file_materialization","File sync supports at most 100 excluded folders.");if(new Set(i.map(s=>s.toLocaleLowerCase())).size!==i.length)throw new b("invalid_file_materialization","Excluded folders must be unique on portable filesystems.");for(let s of i)vo(s,!0);return{file_classes:t,excluded_folders:i}}function y0(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 nN(r,e,t=y0(e)){if(!r.file_classes.includes(t))return!1;let n=(0,te.normalizePath)(e);return!r.excluded_folders.some(i=>n===i||n.startsWith(`${i}/`))}function vo(r,e=!1){let t=Rn(r),n=t.split("/");if(t.length>1024||!e&&/\.md$/i.test(t)||n.some(i=>i.startsWith(".")||rN.has(i.toLowerCase())||/[<>"|?*]/u.test(i)||/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu.test(i)))throw new b("invalid_file_path",`Collection file path ${t} is hidden, reserved, or non-portable.`);return t}async function g0(r){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",r));return{size:r.byteLength,content_digest:`sha256:${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`}}async function Ip(r){let e=[],t=0;for await(let s of r){if(!(s instanceof Uint8Array))throw new b("file_integrity_failed","A binary stream returned an invalid chunk.");if(s.byteLength){if(t+=s.byteLength,!Number.isSafeInteger(t))throw new b("file_too_large","The binary file is too large for this device.");e.push(Uint8Array.from(s))}}let n=new Uint8Array(t),i=0;for(let s of e)n.set(s,i),i+=s.byteLength;return n.buffer}function u0(r){let e=r.includes(".")?r.slice(r.lastIndexOf(".")+1).toLowerCase():"";return{avif:"image/avif",gif:"image/gif",jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",svg:"image/svg+xml",webp:"image/webp",flac:"audio/flac",m4a:"audio/mp4",mp3:"audio/mpeg",ogg:"audio/ogg",opus:"audio/opus",wav:"audio/wav",mov:"video/quicktime",mp4:"video/mp4",webm:"video/webm",pdf:"application/pdf"}[e]}async function iN(r,e){if(r!==void 0){if(!e)return JSON.stringify(r);if(r instanceof ArrayBuffer)return r;if(ArrayBuffer.isView(r))return Uint8Array.from(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).buffer;if(r instanceof Blob)return r.arrayBuffer();throw new b("invalid_file_upload","The adoption upload body was not binary data.")}}function tl(r,e){if(e!=null)return e;if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}function b0(r){let e=r["retry-after"]??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())}async function il(r,e=i=>(0,te.requestUrl)(i),t=(i,s)=>window.fetch(i,s),n=sN()){if(n)try{return await f0(r,n)}catch{}try{return await e(r)}catch(i){try{return await f0(r,t)}catch{throw i}}}function sN(){try{if(typeof require!="function")return null;let r=require("electron").remote?.net;return r?.fetch?r.fetch.bind(r):null}catch{return null}}async function f0(r,e){let t=new Headers(r.headers);r.contentType&&!t.has("content-type")&&t.set("content-type",r.contentType);let n=await e(r.url,{method:r.method,headers:t,body:r.body}),i=await n.arrayBuffer(),s=new TextDecoder().decode(i),o=null;if(s.trim())try{o=JSON.parse(s)}catch{o=null}if(r.throw!==!1&&n.status>=400)throw new Error(`Request failed with status ${n.status}`);let a={};return n.headers.forEach((c,l)=>{a[l]=c}),{status:n.status,headers:a,arrayBuffer:i,json:o,text:s}}function oN(){return async r=>{if(r.signal?.aborted)throw new DOMException("Enrollment cancelled.","AbortError");let e=await il({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(r.signal?.aborted)throw new DOMException("Enrollment cancelled.","AbortError");return{status:e.status,body:tl(e.text,e.json),retryAfterMs:b0(e.headers)}}}function aN(){return async r=>{if(r.signal?.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await iN(r.body,r.rawBody),t=await il({url:r.url,method:r.method,headers:r.headers,body:e,contentType:e===void 0||r.rawBody?void 0:"application/json",throw:!1});if(r.signal?.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");return{status:t.status,body:tl(t.text,t.json),retryAfterMs:b0(t.headers),headers:t.headers}}}var Rp=class{constructor(e,t,n=il,i){this.accessToken=t;this.send=n;this.onFileProgress=i;let s;try{s=new URL(e)}catch{throw new b("invalid_sync_url","Sync URL must be an absolute authority endpoint.")}if(!(s.protocol==="https:"||s.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(s.hostname))||s.username||s.password||s.search||s.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(s.pathname))throw new b("invalid_sync_url","Sync URL must identify one authority sync endpoint.");this.syncUrl=s.href.replace(/\/$/,""),this.filesUrl=this.syncUrl.replace(/\/sync$/u,"/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=0;this.onFileProgress?.({direction:"download",path:e.path,transferredBytes:n,totalBytes:e.size});let i=await this.fileRequest("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:t,file_id:e.file_id,revision:e.revision});if(i.protocol_version!==1||i.type!=="file_transfer"||i.transfer_id!==t||i.direction!=="download"||i.protection!=="transport_tls"||i.total_size!==e.size||i.strategy.kind!=="object_ranges"||!Number.isSafeInteger(i.strategy.part_size)||i.strategy.part_size<=0)throw new b("invalid_sync_response","The authority returned an incompatible file download session.");let s=Math.ceil(e.size/i.strategy.part_size);for(let o=0;o=300)throw this.responseError(c,"file_download_failed");let l=p0(c.headers,"content-length");if(l!==void 0&&Number(l)!==a||c.arrayBuffer.byteLength!==a)throw new b("file_integrity_failed","Hosted authority returned a file part with the wrong length.");n+=a,this.onFileProgress?.({direction:"download",path:e.path,transferredBytes:n,totalBytes:e.size}),a&&(yield new Uint8Array(c.arrayBuffer))}}finally{await this.fileRequest("DELETE",`transfers/${encodeURIComponent(t)}`).catch(()=>{})}}async uploadFile(e,t){let n=await this.fileRequest("POST","uploads",e);if(n.protocol_version!==1||n.type!=="file_transfer"||n.transfer_id!==e.transfer_id||n.direction!=="upload"||n.protection!=="transport_tls"||n.total_size!==e.size||!["object_put","object_multipart"].includes(n.strategy.kind))throw new b("invalid_sync_response","Authority returned an incompatible file upload session.");let i=n.strategy.kind==="object_multipart"?n.strategy.part_size:Math.max(1,e.size);if(!Number.isSafeInteger(i)||i<=0)throw new b("invalid_sync_response","Authority returned an invalid upload part size.");let s=new Op(t),o=Math.max(1,Math.ceil(e.size/i));if(n.received.some(d=>!Number.isSafeInteger(d)||d<0||d>=o)||new Set(n.received).size!==n.received.length)throw new b("invalid_sync_response","Authority returned invalid upload progress.");let a=n.uploaded_parts??[];if(a.some((d,f)=>!Number.isSafeInteger(d.part_number)||d.part_number<1||d.part_number>o||!d.etag||d.etag.length>255||f>0&&a[f-1].part_number>=d.part_number)||(n.strategy.kind==="object_multipart"?a.length!==n.received.length||a.some((d,f)=>d.part_number-1!==n.received[f]):a.length!==0))throw new b("invalid_sync_response","Authority returned invalid uploaded part receipts.");let c=n.received.reduce((d,f)=>{let p=f*i;return d+Math.min(i,Math.max(0,e.size-p))},0);if(this.onFileProgress?.({direction:"upload",path:e.path,transferredBytes:c,totalBytes:e.size}),n.received.length===o)return this.commitUpload(e.transfer_id,a);let l=new Set(n.received),u=Array.from({length:o},()=>{});for(let d of a)u[d.part_number-1]=d;for(let d=0;d=300)throw new b("file_upload_failed",`Object storage returned HTTP ${y.status}.`);if(c+=p,this.onFileProgress?.({direction:"upload",path:e.path,transferredBytes:c,totalBytes:e.size}),n.strategy.kind==="object_multipart"){let g=p0(y.headers,"etag");if(!g)throw new b("invalid_sync_response","Object storage omitted a multipart ETag.");u[d]={part_number:d+1,etag:g}}}return await s.expectEnd(),this.commitUpload(e.transfer_id,u.filter(d=>d!==void 0))}async commitUpload(e,t){let n=await this.fileRequest("POST",`uploads/${encodeURIComponent(e)}/commit`,{protocol_version:1,type:"commit_file_upload",transfer_id:e,parts:t});if(n.protocol_version!==1||n.type!=="file_upload_committed"||n.transfer_id!==e)throw new b("invalid_sync_response","Authority returned an invalid file upload receipt.");return n}async moveFile(e){let t=await this.fileRequest("POST",`${encodeURIComponent(e.file_id)}/move`,e);if(t.protocol_version!==1||t.type!=="file_moved"||t.mutation_id!==e.mutation_id)throw new b("invalid_sync_response","Authority returned an invalid file move receipt.");return t}async deleteFile(e){let t=await this.fileRequest("POST",`${encodeURIComponent(e.file_id)}/delete`,e);if(t.protocol_version!==1||t.type!=="file_deleted"||t.mutation_id!==e.mutation_id||t.file_id!==e.file_id)throw new b("invalid_sync_response","Authority returned an invalid file delete receipt.");return t}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){return this.requestAt(this.syncUrl,e,t,n)}async fileRequest(e,t,n){return this.requestAt(this.filesUrl,e,t,n)}async requestAt(e,t,n,i){let s=await this.send({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=tl(s.text,s.json);if(s.status<200||s.status>=300)throw this.responseError(s,"sync_failed");return o}responseError(e,t){let n=tl(e.text,e.json),i=nt(n)&&nt(n.error)?n.error:{};return new b(typeof i.code=="string"?i.code:t,typeof i.message=="string"?i.message:`Sync request failed (${e.status}).`)}},Op=class{constructor(e){this.remainder=new Uint8Array;this.iterator=e[Symbol.asyncIterator]()}async read(e){let t=new Uint8Array(new ArrayBuffer(e)),n=0;for(;n!["authorization","cookie","host","proxy-authorization","content-length"].includes(e.toLowerCase())))}function p0(r,e){return Object.entries(r).find(([n])=>n.toLowerCase()===e.toLowerCase())?.[1]}function _0(r){return[r.configDir||".obsidian",...tN].map(t=>(0,te.normalizePath)(t).replace(/\/+$/,""))}function Wn(r,e){let t=Rn(e);if(_0(r).some(n=>t===n||t.startsWith(`${n}/`)))throw new b("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${t}`);return t}function Ee(r){if(r?.aborted)throw new DOMException("Synchronization cancelled.","AbortError")}function yt(r,e){return r??new Error(`IndexedDB ${e} failed without an error detail.`)}function uN(r,e){let t=async a=>{Ee(e);let c=await a();return Ee(e),c},n=async function*(a){for await(let c of a)Ee(e),yield c;Ee(e)},i=r.uploadFile?.bind(r),s=r.moveFile?.bind(r),o=r.deleteFile?.bind(r);return{openSession:()=>t(()=>r.openSession()),snapshot:(a,c)=>t(()=>r.snapshot(a,c)),fileSnapshot:(a,c)=>t(()=>r.fileSnapshot(a,c)),downloadFile:a=>n(r.downloadFile(a)),...i?{uploadFile:(a,c)=>t(()=>i(a,n(c)))}:{},...s?{moveFile:a=>t(()=>s(a))}:{},...o?{deleteFile:a=>t(()=>o(a))}:{},changes:(a,c)=>t(()=>r.changes(a,c)),mutate:a=>t(()=>r.mutate(a))}}async function Wi(r,e){let t=(0,te.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 te.TFolder)){if(s)throw new b("mirror_path_collision",`A file blocks the mirror folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}var Np=class{constructor(e,t=n=>e.delete(n,!0)){this.vault=e;this.trashFile=t}async exists(e){let t=Wn(this.vault,e);return this.vault.getAbstractFileByPath(t)!==null||await this.vault.adapter.exists(t)}async read(e){let t=Wn(this.vault,e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof te.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);return this.vault.cachedRead(n)}async write(e,t){let n=Wn(this.vault,e),i=n.lastIndexOf("/");i>=0&&await Wi(this.vault,n.slice(0,i));let s=this.vault.getAbstractFileByPath(n);if(s instanceof te.TFolder)throw new b("mirror_path_collision",`A folder blocks the mirror file ${n}.`);s instanceof te.TFile?await this.vault.modify(s,t):await this.vault.create(n,t)}async move(e,t){let n=Wn(this.vault,e),i=Wn(this.vault,t),s=this.vault.getAbstractFileByPath(n);if(!(s instanceof te.TFile))throw new b("mirror_path_collision",`Expected a file at ${n}.`);if(this.vault.getAbstractFileByPath(i)!==null||await this.vault.adapter.exists(i))throw new b("mirror_path_collision",`A file or folder blocks the mirror path ${i}.`);let o=i.lastIndexOf("/");o>=0&&await Wi(this.vault,i.slice(0,o)),await this.vault.rename(s,i)}async remove(e){let t=Wn(this.vault,e),n=this.vault.getAbstractFileByPath(t);if(n!=null){if(!(n instanceof te.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);await this.trashFile(n)}}async listMarkdown(e){return this.vault.getMarkdownFiles().map(t=>(0,te.normalizePath)(t.path)).filter(t=>!e.has(t)).filter(t=>!_0(this.vault).some(n=>t===n||t.startsWith(`${n}/`))).sort()}async inspectBinary(e){let t=vo(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof te.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);return g0(await this.vault.readBinary(n))}async writeBinary(e,t){let n=vo(e),i=await Ip(t),s=n.lastIndexOf("/");s>=0&&await Wi(this.vault,n.slice(0,s));let o=this.vault.getAbstractFileByPath(n);if(o instanceof te.TFolder)throw new b("mirror_path_collision",`A folder blocks the mirror file ${n}.`);o instanceof te.TFile?await this.vault.modifyBinary(o,i):await this.vault.createBinary(n,i)}async listBinary(e){return v0(this.vault).map(t=>(0,te.normalizePath)(t.path)).filter(t=>!/\.md$/i.test(t)&&!e.has(t)).filter(t=>{try{return vo(t),!0}catch{return!1}}).sort()}async readBinary(e){let t=vo(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof te.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);let i=new Uint8Array(await this.vault.readBinary(n));return(async function*(){for(let s=0;s{}),a}}async remove(e){let t=await this.manifest(e);await this.delete(gn,this.manifestKey(e)),t&&await this.removeStage(t.stage,t.chunks)}async prune(e){let t=await this.open(),n=await new Promise((o,a)=>{let c=[],l=t.transaction(gn,"readonly").objectStore(gn).openCursor();l.onsuccess=()=>{let u=l.result;if(!u)return o(c);c.push([u.key,u.value]),u.continue()},l.onerror=()=>a(yt(l.error,"manifest cursor"))}),i=new Set;for(let[o,a]of n)!Array.isArray(o)||o[0]!==this.namespace||typeof o[1]=="string"&&e.has(o[1])||(await this.delete(gn,o),await this.removeStage(a.stage,a.chunks));for(let[o,a]of n)Array.isArray(o)&&o[0]===this.namespace&&typeof o[1]=="string"&&e.has(o[1])&&i.add(a.stage);let s=await new Promise((o,a)=>{let c=[],l=t.transaction(bn,"readonly").objectStore(bn).openKeyCursor();l.onsuccess=()=>{let u=l.result;if(!u)return o(c);let d=u.key,f=Array.isArray(d)&&typeof d[1]=="string"?d[1]:null;Array.isArray(d)&&d[0]===this.namespace&&(f===null||!i.has(f))&&c.push(d),u.continue()},l.onerror=()=>a(yt(l.error,"chunk cursor"))});for(let o of s)await this.delete(bn,o)}manifest(e){return this.get(gn,this.manifestKey(e))}manifestKey(e){return[this.namespace,e]}chunkKey(e,t){return[this.namespace,e,t]}async removeStage(e,t){for(let n=0;n{let o=n.transaction(e,"readonly").objectStore(e).get(t);o.onsuccess=()=>i(o.result??null),o.onerror=()=>s(yt(o.error,`read from ${e}`))})}async put(e,t,n){let i=await this.open();await new Promise((s,o)=>{let a=i.transaction(e,"readwrite");a.objectStore(e).put(n,t),a.oncomplete=()=>s(),a.onerror=()=>o(yt(a.error,`write to ${e}`)),a.onabort=()=>o(yt(a.error,`write to ${e}`))})}async delete(e,t){let n=await this.open();await new Promise((i,s)=>{let o=n.transaction(e,"readwrite");o.objectStore(e).delete(t),o.oncomplete=()=>i(),o.onerror=()=>s(yt(o.error,`delete from ${e}`)),o.onabort=()=>s(yt(o.error,`delete from ${e}`))})}open(){if(typeof indexedDB>"u")throw new b("storage_unavailable","IndexedDB is required for binary file sync.");return this.database??=new Promise((e,t)=>{let n=indexedDB.open(YO,1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(gn)||n.result.createObjectStore(gn),n.result.objectStoreNames.contains(bn)||n.result.createObjectStore(bn)},n.onerror=()=>t(yt(n.error,"binary store open")),n.onsuccess=()=>e(n.result)}),this.database}},Dp=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(yn,"readonly").objectStore(yn).get(this.key);i.onsuccess=()=>t(i.result??null),i.onerror=()=>n(yt(i.error,"mirror state read"))})}async write(e){let t=await this.open();await new Promise((n,i)=>{let s=t.transaction(yn,"readwrite");s.objectStore(yn).put(e,this.key),s.oncomplete=()=>n(),s.onerror=()=>i(yt(s.error,"mirror state write")),s.onabort=()=>i(yt(s.error,"mirror state write"))})}async clear(){let e=await this.open();await new Promise((t,n)=>{let i=e.transaction(yn,"readwrite");i.objectStore(yn).delete(this.key),i.oncomplete=()=>t(),i.onerror=()=>n(yt(i.error,"mirror state clear")),i.onabort=()=>n(yt(i.error,"mirror state clear"))})}open(){if(typeof indexedDB>"u")throw new b("storage_unavailable","IndexedDB is required for persistent mirror state.");return this.database??=new Promise((e,t)=>{let n=indexedDB.open(JO,1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(yn)||n.result.createObjectStore(yn)},n.onerror=()=>t(yt(n.error,"mirror state store open")),n.onsuccess=()=>e(n.result)}),this.database}},Lp=class r{constructor(e){this.key=e}static{this.active=new Set}async runExclusive(e){if(r.active.has(this.key))throw new b("mirror_busy","A mirror operation is already running for this vault.");r.active.add(this.key);try{return await e()}finally{r.active.delete(this.key)}}},nl=class{constructor(e,t,n={}){this.app=e;this.settingsHost=t;this.options=n;this.progress=null;this.fileProgress=null;this.syncAbort=null;this.statusRequest=null;this.mirrorOperationTail=Promise.resolve();this.adoptionMarker=null;this.fileSystem=n.fileSystem??new Np(e.vault,i=>e.fileManager.trashFile(i)),this.enrollmentClient=n.enrollmentClient??new Rc({request:oN()}),this.adoptionClient=n.adoptionClient??new qc({request:aN()})}async initialize(){if(this.adoptionMarker=await this.readAdoptionMarker(),this.adoptionMarker&&this.settingsHost.getMirrorProfile())throw new b("authority_adoption_state_conflict","This vault contains both an authority-adoption checkpoint and a mirror profile.")}getProgress(){return this.progress?{...this.progress}:null}getFileProgress(){return this.fileProgress?{...this.fileProgress}:null}getAdoptionMarker(){return this.adoptionMarker?JSON.parse(JSON.stringify(this.adoptionMarker)):null}getSelectiveSync(){return _r(this.settingsHost.getMirrorProfile()?.selectiveSync??this.adoptionMarker?.selective_sync)}async configureSelectiveSync(e){let t=this.requireProfile();await this.settingsHost.saveMirrorProfile({...t,selectiveSync:_r(e)})}assertLocalAuthorityWritable(){if(this.adoptionMarker&&["fenced","activating","adopted"].includes(this.adoptionMarker.phase))throw new b("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 b("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:Tp(i),selective_sync:_r(e.selectiveSync),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(Tp(i)),this.runAdoptionWithRecovery(i,t)}async resumeAdoption(e={}){let t=this.adoptionMarker??await this.readAdoptionMarker();if(!t)throw new b("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 b("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 e.onVerification?.(Tp(i)),this.runAdoptionWithRecovery(i,{...e,onVerification:s=>e.onVerification?.(s)})}async cancelAdoption(e){let t=this.adoptionMarker??await this.readAdoptionMarker();if(!t)return;if(["activating","adopted"].includes(t.phase))throw new b("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 b("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({controlUrl:e.controlUrl,mirrorName:e.mirrorName,mode:e.mode,...n?{collectionId:n}:{}},t),s=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i,e.selectiveSync)}catch(o){if(s)try{await this.app.vault.adapter.remove(Ki)}catch{throw new b("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 this.withMirrorOperation(async()=>{let e=this.requireProfile();await this.assertMirror(e.collectionId);let t=await this.createMirror();return d0(await t.inspect())})}async status(){if(this.statusRequest)return this.statusRequest;let e=this.readStatus();this.statusRequest=e;try{return await e}finally{this.statusRequest===e&&(this.statusRequest=null)}}async readStatus(){return this.withMirrorOperation(async()=>{let e=this.settingsHost.getMirrorProfile();return e?(await this.assertMirror(e.collectionId),(await this.createMirror()).status()):null})}async reconnect(){let e=this.requireProfile(),t=this.app.secretStorage.getSecret(this.refreshSecretId(e.collectionId));if(!t)throw new b("mirror_credentials_missing","The mirror refresh credential is missing. Approve this vault again.");let n=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:this.app.secretStorage.getSecret(this.accessSecretId(e.collectionId))??"",refreshCredential:t,accessTokenExpiresAt:e.accessTokenExpiresAt});await this.persistEnrollment(n,e.selectiveSync);let i=await this.status();if(!i)throw new b("mirror_not_configured","The renewed mirror profile could not be loaded.");return i}async reauthorize(e){let t=this.requireProfile(),n=this.stateStoreFor(t),i=await n.read();if(i?.batch)throw new b("mirror_recovery_required","Resume the durable synchronization checkpoint before approving this vault again.");let s=await this.enrollmentClient.enroll({controlUrl:t.controlUrl,mirrorName:t.name,mode:t.mode,collectionId:t.collectionId},e);if(s.collectionId!==t.collectionId)throw new b("mirror_identity_conflict","Connect approved a different collection. The existing mirror was not changed.");let o=h0(s,t.selectiveSync);i&&s.replicaId!==t.replicaId&&await this.stateStoreFor(o).write({...i,replica_id:s.replicaId}),await this.persistEnrollment(s,t.selectiveSync),s.replicaId!==t.replicaId&&"clear"in n&&typeof n.clear=="function"&&await n.clear();let a=await this.status();if(!a)throw new b("mirror_not_configured","The reauthorized mirror profile could not be loaded.");return a}async conflictComparison(e){let t=this.requireProfile(),n=await this.transportFor(t),i=await n.openSession(),s={state:"absent"};if(e.entity==="record"){let l;do{let u=await n.snapshot(i.snapshot_id,l),d=u.records.find(f=>f.record_id===e.object_id);if(d){s={state:"exact",path:d.path,revision:d.revision,size:new TextEncoder().encode(d.document).byteLength,document:d.document};break}l=u.next_page}while(l)}else{let l;do{let u=await n.fileSnapshot(i.snapshot_id,l),d=u.files.find(f=>f.file_id===e.object_id);if(d){s={state:"exact",path:d.path,revision:d.content_digest,size:d.size,modifiedAt:d.modified_at};break}l=u.next_page}while(l)}let o=e.path??s.path,a={state:"absent"};if(o){let l=this.app.vault.getAbstractFileByPath(o);if(l instanceof te.TFile)if(e.entity==="record"){let u=await this.app.vault.cachedRead(l);a={state:"exact",path:o,size:new TextEncoder().encode(u).byteLength,modifiedAt:l.stat?.mtime?new Date(l.stat.mtime).toISOString():void 0,document:u}}else{let u=await this.fileSystem.inspectBinary(o);u&&(a={state:"exact",path:o,revision:u.content_digest,size:u.size,modifiedAt:l.stat?.mtime?new Date(l.stat.mtime).toISOString():void 0,resourceUrl:this.app.vault.getResourcePath(l)})}}if(!(await this.status())?.conflicts.some(l=>l.object_id===e.object_id&&l.decision_id===e.decision_id))throw new b("conflict_decision_stale","This file changed again while its versions were loading.");return{entity:e.entity,objectId:e.object_id,decisionId:e.decision_id,local:a,remote:s}}async preserveConflictCopy(e){let t=Wn(this.app.vault,e),n=this.app.vault.getAbstractFileByPath(t);if(!(n instanceof te.TFile))throw new b("mirror_conflict_copy_missing",`No local file exists at ${t}.`);let i=n.extension?`.${n.extension}`:"",s=i?t.slice(0,-i.length):t,o=`${s} (local conflict copy)${i}`,a=2;for(;this.app.vault.getAbstractFileByPath(o)||await this.app.vault.adapter.exists(o);)o=`${s} (local conflict copy ${a})${i}`,a+=1;return await this.app.vault.adapter.copy(t,o),o}async disconnect(e){if(this.isSyncing())throw new b("mirror_busy","Stop the current synchronization before disconnecting.");let t=this.requireProfile(),n=this.stateStoreFor(t),i=await n.read();if(i?.batch)throw new b("mirror_recovery_required","Resume the durable synchronization checkpoint before disconnecting.");let s={removed:[],preserved:[]},o=await this.readMarker();o&&await this.app.vault.adapter.remove(Ki);try{await this.settingsHost.saveMirrorProfile(null)}catch(a){throw o&&await this.markMirror(t.collectionId),a}return this.app.secretStorage.setSecret(this.accessSecretId(t.collectionId),""),this.app.secretStorage.setSecret(this.refreshSecretId(t.collectionId),""),"clear"in n&&typeof n.clear=="function"&&await n.clear(),await this.blobStoreFor(t).prune(new Set),e&&i&&await this.removeExactMirrorFiles(i,s),s}async sync(e,t,n){if(this.syncAbort)throw new b("mirror_busy","Synchronization is already running for this vault.");let i=new AbortController;this.syncAbort=i;try{return await this.withMirrorOperation(async()=>{let o=await(await this.createMirror(a=>{Ee(i.signal),this.progress=a,t?.({...a})},i.signal,a=>{Ee(i.signal),this.fileProgress=a,n?.({...a})})).apply(e.plan,{signal:i.signal});return Ee(i.signal),o})}finally{this.progress=null,this.fileProgress=null,this.syncAbort=null}}cancelSync(){this.syncAbort?.abort()}isSyncing(){return this.syncAbort!==null}async resolveConflict(e,t,n){return this.withMirrorOperation(async()=>{let i=await this.createMirror();return await i.resolveConflict(e,t,n),i.status()})}async withMirrorOperation(e){let t=this.mirrorOperationTail,n;this.mirrorOperationTail=new Promise(i=>{n=i}),await t;try{return await e()}finally{n()}}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 b("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,this.adoptionUploadOptions(e,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,t.signal);await this.updateAdoptionPhase("uploading"),await this.adoptionClient.uploadSnapshot(e,s,o,this.adoptionUploadOptions(e,t));let a=await this.captureAuthoritySnapshot(e.requested.collectionId,t.signal);await this.writeAdoptionSnapshot(a),await this.updateAdoptionPhase("fenced",a);let c=await this.requirePreparedAdoption(e,t);await this.adoptionClient.uploadSnapshot(e,c,a,this.adoptionUploadOptions(e,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 fN(n)?(await this.adoptionClient.cancel(e,{signal:t.signal}).catch(()=>{}),await this.clearAdoptionCheckpoint(e.adoptionId),new b(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 Rr("Hosted authority activation has already started. Resume using the saved fenced snapshot."):new b("authority_adoption_already_completed","Hosted authority has already adopted this collection.")}async finishRetainedMirror(e,t,n){let i,s=this.adoptionClient.mirrorEnrollmentSession(e,t);if(!s)throw new b("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:a=>n.onStatus?.({...a,state:a.state})})}catch(a){if(n.signal?.aborted)throw a;i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,collectionId:e.requested.collectionId,mirrorName:e.requested.mirrorName??e.requested.sourceName,mode:"read_write"},{signal:n.signal,onVerification:c=>n.onVerification(c)})}let o=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i,this.adoptionMarker?.selective_sync)}catch(a){throw o&&await this.app.vault.adapter.remove(Ki),a}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async captureAuthoritySnapshot(e,t){Ee(t);let n=await Ei(this.app.vault);if(Ee(t),!n)throw new b("invalid_collection_configuration","A valid mdbase.yaml is required.");let i=await this.app.vault.adapter.read("mdbase.yaml");Ee(t);let s=(0,te.parseYaml)(i),o=[{path:"mdbase.yaml",kind:"configuration",document:i}],a=`${(0,te.normalizePath)(n.settings.types_folder)}/`,c=this.app.vault.getMarkdownFiles().filter(p=>(0,te.normalizePath)(p.path).startsWith(a)).sort((p,m)=>p.path.localeCompare(m.path));for(let p of c)Ee(t),o.push({path:(0,te.normalizePath)(p.path),kind:"type",document:await this.app.vault.cachedRead(p)}),Ee(t);let l=pN(s);if(l.length){let p=l.map(h=>(0,m0.default)(h,{dot:!0})),m=v0(this.app.vault).filter(h=>h.extension==="base").filter(h=>p.some(y=>y((0,te.normalizePath)(h.path)))).sort((h,y)=>h.path.localeCompare(y.path));for(let h of m)Ee(t),o.push({path:(0,te.normalizePath)(h.path),kind:"view",document:await this.app.vault.cachedRead(h)}),Ee(t)}let u=[];for(let p of this.app.vault.getMarkdownFiles().sort((m,h)=>m.path.localeCompare(h.path))){Ee(t);let m=(0,te.normalizePath)(p.path);if(Ai(m,n))continue;let h=await this.app.vault.cachedRead(p);Ee(t),u.push({path:m,document:h})}let d=[],f=_r(this.adoptionMarker?.selective_sync);if(f.file_classes.length){let p=this.adoptionBlobStore(e),m=(await this.fileSystem.listBinary?.(new Set(o.map(h=>h.path)))??[]).filter(h=>nN(f,h)).filter(h=>!Ai(h,n));for(let h of m){Ee(t);let y=await this.fileSystem.readBinary?.(h);if(Ee(t),!y)continue;let g=await Ip(y);Ee(t);let v=await g0(g);Ee(t),await p.write(v.content_digest,(async function*(){yield new Uint8Array(g)})()),Ee(t);let _=this.app.vault.getAbstractFileByPath(h);d.push({file_id:jc(e,`file:${h}`),path:h,revision:v.content_digest,...v,...u0(h)?{media_type:u0(h)}:{},media_class:y0(h),modified_at:new Date(_ instanceof te.TFile&&_.stat?.mtime?_.stat.mtime:Date.now()).toISOString()})}}return Ee(t),pp({collectionId:e,sourceHead:0,specVersion:n.spec_version,resources:o,records:u,files:d})}adoptionBlobStore(e){return this.options.adoptionBlobStoreFactory?.(e)??new rl(`adoption:${e}`)}adoptionUploadOptions(e,t){let n=this.adoptionBlobStore(e.requested.collectionId);return{signal:t.signal,fileSource:async i=>Ip(n.read(i.content_digest)),onFileProgress:({file:i,transferredBytes:s,totalBytes:o})=>t.onFileProgress?.(i.path,s,o)}}async ensurePortableCollectionIdentity(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))throw new b("collection_not_initialized","Initialize an mdbase collection before hosting it.");let e=await this.app.vault.adapter.read("mdbase.yaml"),t;try{t=(0,te.parseYaml)(e)}catch{throw new b("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!nt(t))throw new b("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let n=nt(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,i;if(n===void 0){i=crypto.randomUUID();let o=nt(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,te.stringifyYaml)(t))}else if(typeof n=="string"&&wo.test(n))i=n;else throw new b("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}}stateStoreFor(e){return this.options.stateStoreFactory?.(e)??new Dp(`${e.collectionId}:${e.replicaId}`)}blobStoreFor(e){return this.options.blobStoreFactory?.(e)??new rl(`${e.collectionId}:${e.replicaId}`)}async transportFor(e,t,n){let i=await this.freshAccessToken(e),s=this.options.transportFactory?.(e,i)??new Rp(e.syncUrl,i,il,n);return uN(s,t)}async createMirror(e,t,n){let i=this.requireProfile();await this.assertMirror(i.collectionId);let s=await this.transportFor(i,t,n),o={stateStore:this.stateStoreFor(i),fileSystem:this.fileSystem,blobStore:this.blobStoreFor(i),selectiveSync:_r(i.selectiveSync),lease:this.options.leaseFactory?.(i)??new Lp(`${i.collectionId}:${i.replicaId}`),onProgress:e};return i.mode==="read_write"?new go(i.replicaId,s,o):new Kn(i.replicaId,s,o)}requireProfile(){let e=this.settingsHost.getMirrorProfile();if(!e)throw new b("mirror_not_configured","This vault is not connected to a collection authority.");return e}accessSecretId(e){return`${XO}${e.toLowerCase()}`}refreshSecretId(e){return`${QO}${e.toLowerCase()}`}adoptionSecretId(e){return`${ZO}${e.toLowerCase()}`}async storeAdoptionSecret(e){this.app.secretStorage.setSecret(this.adoptionSecretId(e.adoptionId),e.credential)}async persistEnrollment(e,t){this.app.secretStorage.setSecret(this.accessSecretId(e.collectionId),e.accessToken),this.app.secretStorage.setSecret(this.refreshSecretId(e.collectionId),e.refreshCredential),await this.settingsHost.saveMirrorProfile(h0(e,t??this.settingsHost.getMirrorProfile()?.selectiveSync))}async removeExactMirrorFiles(e,t){let n=new Map;for(let[i,s]of Object.entries(e.records)){let o=e.local_bindings?.[i]?.path??s.path;n.set(o,{entity:"document",document:s.record?.document,revision:s.revision})}for(let[i,s]of Object.entries(e.resources??{})){let o=e.local_bindings?.[i]?.path??s.path;n.set(o,{entity:"document",document:s.record?.document,revision:s.revision})}for(let[i,s]of Object.entries(e.files??{})){let o=e.local_bindings?.[i]?.path??s.file.path;n.set(o,{entity:"file",digest:s.file.content_digest,size:s.file.size})}for(let[i,s]of[...n.entries()].sort(([o],[a])=>a.localeCompare(o))){let o=!1;if(s.entity==="document"){let a=await this.fileSystem.read(i);o=a!==null&&(s.document!==void 0?a===s.document:await yN(a,s.revision))}else if(s.entity==="file"){let a=await this.fileSystem.inspectBinary(i);o=a!==null&&a.content_digest===s.digest&&a.size===s.size}if(!o){await this.fileSystem.exists(i)&&t.preserved.push(i);continue}try{await this.fileSystem.remove(i),t.removed.push(i)}catch{t.preserved.push(i)}}}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()>eN)return n;let s=this.app.secretStorage.getSecret(this.refreshSecretId(e.collectionId));if(!s)throw new b("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??"",refreshCredential:s,accessTokenExpiresAt:e.accessTokenExpiresAt});return await this.persistEnrollment(o,e.selectiveSync),o.accessToken}async assertCanBecomeMirror(e){let t=await this.readMarker(),n=await this.readPortableCollectionId();if(n&&!t)throw new b("local_authority_requires_transfer","This vault has a local Connect identity. Transfer authority explicitly before using it as a mirror.");if(n&&t?.collection_id!==n)throw new b("mirror_identity_conflict","The vault identity and mirror role marker identify different collections.");let i=this.settingsHost.getMirrorProfile(),s=i?.collectionId??e;if(t&&s&&t.collection_id!==s)throw new b("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 b("existing_collection_requires_transfer","This vault already contains an mdbase collection. Connect an empty vault, or transfer collection authority explicitly.");return s??t?.collection_id}async readPortableCollectionId(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))return null;let e;try{e=(0,te.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch{throw new b("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!nt(e))throw new b("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let t=e["x-mdbase-connect"];if(t===void 0)return null;if(!nt(t))throw new b("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"||!wo.test(n))throw new b("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 b("mirror_identity_conflict","This vault already mirrors a different collection authority.");return!1}return await Wi(this.app.vault,".mdbase"),await this.app.vault.adapter.write(Ki,`${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 b("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(Ki))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(Ki))}catch{throw new b("invalid_mirror_marker","The mirror role marker is corrupt.")}if(!nt(e)||e.version!==1||e.role!=="mirror"||typeof e.collection_id!="string"||!wo.test(e.collection_id))throw new b("invalid_mirror_marker","The mirror role marker is invalid.");return e}requireAdoptionMarker(e){if(!this.adoptionMarker||this.adoptionMarker.session.adoptionId!==e)throw new b("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 b("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 Wi(this.app.vault,".mdbase"),await this.app.vault.adapter.write(bo,`${JSON.stringify(e,null,2)} -`),this.adoptionMarker=e}async readAdoptionMarker(){if(!await this.app.vault.adapter.exists(bo))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(bo))}catch{throw new b("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is corrupt.")}if(!hN(e))throw new b("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is invalid.");return e}async writeAdoptionSnapshot(e){await Wi(this.app.vault,".mdbase"),await this.app.vault.adapter.write(_o,JSON.stringify(e))}async readAdoptionSnapshot(e){if(!await this.app.vault.adapter.exists(_o))throw new b("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(_o))}catch{throw new b("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 b("authority_adoption_snapshot_mismatch","The fenced authority snapshot does not match its durable checkpoint.");return t}async clearAdoptionCheckpoint(e){let t=this.adoptionMarker?.session.requested.collectionId;await this.app.vault.adapter.exists(bo)&&await this.app.vault.adapter.remove(bo),await this.app.vault.adapter.exists(_o)&&await this.app.vault.adapter.remove(_o),this.app.secretStorage.setSecret(this.adoptionSecretId(e),""),this.adoptionMarker=null,t&&await this.adoptionBlobStore(t).prune(new Set).catch(()=>{})}};function Tp(r){let{credential:e,...t}=r;return t}function fN(r){return r instanceof W&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function pN(r){if(!nt(r))return[];let e=r["x-obsidian"];return!nt(e)||!nt(e.bases)||!Array.isArray(e.bases.include)?[]:e.bases.include.filter(t=>typeof t=="string")}function v0(r){let e=r.getFiles?.();if(e)return e;let t=[],n=i=>{for(let s of i.children)s instanceof te.TFile?t.push(s):s instanceof te.TFolder&&n(s)};return n(r.getRoot()),t}function hN(r){if(!nt(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!nt(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&wo.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&nt(e.requested)&&typeof e.requested.collectionId=="string"&&wo.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.selective_sync===void 0||mN(r.selective_sync))&&(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))}function mN(r){if(!nt(r)||!Array.isArray(r.file_classes)||!Array.isArray(r.excluded_folders))return!1;try{let e=_r(r);return e.file_classes.length===r.file_classes.length&&e.excluded_folders.length===r.excluded_folders.length}catch{return!1}}function h0(r,e){return{version:1,syncUrl:r.syncUrl,controlUrl:r.controlUrl,collectionId:r.collectionId,replicaId:r.replicaId,mode:r.mode,name:r.name,enrollmentId:r.enrollmentId,accessTokenExpiresAt:r.accessTokenExpiresAt,selectiveSync:_r(e)}}async function yN(r,e){if(!e?.startsWith("sha256:"))return!1;let t=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)));return`sha256:${Array.from(t,i=>i.toString(16).padStart(2,"0")).join("")}`===e}var it=require("obsidian");var Ao="0.3.0",gN=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),bN=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 ve(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Pe(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function Fr(r){return fo.digest(r)}function Gn(r){return Array.isArray(r)?`[${r.map(Gn).join(",")}]`:ve(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${Gn(r[e])}`).join(",")}}`:JSON.stringify(r)}function jp(r){if(Array.isArray(r))return r.map(jp);if(!ve(r))return r;let e={};for(let[t,n]of Object.entries(r)){let i=jp(n);i!=null&&(Array.isArray(i)&&i.length===0||ve(i)&&Object.keys(i).length===0||(e[t]=i))}return e}function Gi(r){return[...new Set(r)]}function _N(r){return ve(r.fields)?Object.values(r.fields).some(e=>ve(e)&&(typeof e.tn_role=="string"||Array.isArray(e.tn_completed_values))):!1}function qp(r,e,t){let n=ve(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)?Pe(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=qp(`${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(ve(n.fields)?n.fields:{})){let f=qp(`${r}.${u}`,d,t);c[u]=f.schema,Object.assign(i,f.links),Object.assign(s,f.legacy),o.push(...f.unsupported),ve(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:Gi(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"&&(n.type==="list"?a.minItems=n.min_length:a.minLength=n.min_length),typeof n.max_length=="number"&&(n.type==="list"?a.maxItems=n.max_length: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=Pe(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");(!bN.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!u)&&(s[`${r}.${c}`]=Pe(l))}return{schema:a,links:i,legacy:s,unsupported:o}}function So(r,e,t,n){let i=ve(r[e])?r[e]:{},s=ve(i.set)?i.set:{};s[t]=n,i.set=s,r[e]=i}function vN(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(ve(t)&&t.transform==="slugify"&&typeof t.from=="string")So(r,"on_create",e,{slugify:t.from});else return!1;return!0}function wN(r){let e=r.match(/^(.*\/)?\{title\}\.md$/);return e?{runtime:"tasknotes",template:"{{title}}",folder:(e[1]??"").replace(/\/$/,""),generated_by:"tasknotes.filename.create"}:{runtime:"tasknotes",template:r,generated_by:"tasknotes.filename.create"}}function SN(r,e,t){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"||!ve(t.fields))throw new Error(`${r} is not a v0.2 type with a name and fields.`);let n=_N(t),i=t.name.trim().toLowerCase(),s={type:{const:i}},o=[],a={},c={},l=[],u={},d={},f=[],p=[],m={},h={},y={};for(let[x,M]of Object.entries(t.fields)){let S=ve(M)?M:{},C=qp(x,S,n);s[x]=C.schema,Object.assign(c,C.links),Object.assign(d,C.legacy),f.push(...C.unsupported),S.required===!0&&o.push(x),S.default!==void 0&&(a[x]=Pe(S.default)),S.unique===!0&&l.push({field:x,scope:"collection"}),S.generated!==void 0&&(vN(u,x,S.generated)?p.push(x):(d[`${x}.generated`]=Pe(S.generated),f.push(`${x}.generated`))),typeof S.tn_role=="string"&&(m[S.tn_role]=x),Array.isArray(S.tn_completed_values)&&(h.completed_values=Pe(S.tn_completed_values))}a.status!==void 0&&(h.default=Pe(a.status)),a.priority!==void 0&&(y.default=Pe(a.priority));let g=typeof t.display_name_key=="string"&&Object.prototype.hasOwnProperty.call(t.fields,t.display_name_key)?t.display_name_key:void 0,v={...g?{display:{name_field:g}}:{},read_defaults:a,links:c,unique:l};typeof t.path_pattern=="string"&&(v.path=n?wN(t.path_pattern):{pattern:t.path_pattern});let _={};for(let[x,M]of Object.entries(t))gN.has(x)||(_[x]=Pe(M));Object.keys(d).length&&(_.fields=d);let w=jp({kind:"mdbase.type",name:i,version:1,description:typeof t.description=="string"?t.description:void 0,match:ve(t.match)?Pe(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:Gi(o)}:{}}},collection:v,lifecycle:u,...n?{"x-tasknotes":{contract:"tasknotes.task",version:1,field_roles:m,status:h,priority:y,archive:{tags_field:m.tags??"tags",archived_tag:"archived"}}}:{},...Object.keys(_).length?{"x-legacy-v0.2":_}:{}}),A=[];t.extends!==void 0&&f.push("extends");for(let x of Gi(f).sort())A.push({path:r,code:"migration_lossy",message:`${x} cannot be expressed as canonical v0.3 write behavior and was retained as legacy metadata where possible.`,severity:"lossy"});return n&&A.push({path:r,code:"path_policy_runtime_owned",message:"TaskNotes filename behavior is recorded as TaskNotes runtime metadata.",severity:"warning"}),t.strict!==!0&&A.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"&&!g&&A.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:w,summary:{path:r,name:i,fieldsConverted:Object.keys(t.fields).length,requiredFields:Gi(o),defaultsMoved:Object.keys(a),generatedFieldsMoved:Gi(p),linksMoved:Object.keys(c),taskNotes:n},diagnostics:A}}function $N(r){let e=Pe(r);e.spec_version=Ao;let t=ve(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=Gi(["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 w0(r,e){let t=ve(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 EN(r,e){let t={};for(let[n,i]of Object.entries(ve(e.fields)?e.fields:{}))ve(i)&&(t[n]=Pe(i));return{name:typeof e.name=="string"?e.name:r.split("/").pop()?.replace(/\.md$/,"")??"type",fields:t,match:ve(e.match)?Pe(e.match):void 0,filePath:r,specProfile:"v0.2"}}function AN(r,e){let t=ve(e.schema)?e.schema:{},n=ve(t.value)?t.value:{};return{name:typeof e.name=="string"?e.name:r.split("/").pop()?.replace(/\.md$/,"")??"type",fields:On(n),match:ve(e.match)?Pe(e.match):void 0,collection:ve(e.collection)?Pe(e.collection):void 0,schema:Pe(n),filePath:r,specProfile:"v0.3"}}function xN(r,e,t){let n=Pe(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]=Pe(a.default))}return n}function kN(r,e,t){let n=Pe(r);for(let i of e){let s=t.get(i);if(s)for(let[o,a]of Object.entries(s.collection?.read_defaults??{}))o in n||(n[o]=Pe(a))}return n}async function PN(r,e){let t=(0,it.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 it.TFolder)){if(s)throw new Error(`A file blocks folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}async function sl(r,e,t){let n=(0,it.normalizePath)(e),i=n.lastIndexOf("/");if(i>=0&&await PN(r,n.slice(0,i)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let s=r.getAbstractFileByPath(n);if(s instanceof it.TFolder)throw new Error(`A folder blocks file ${n}.`);s instanceof it.TFile?await r.modify(s,t):await r.create(n,t)}async function Eo(r,e){let t=(0,it.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof it.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 S0(r){let e=await Eo(r,"mdbase.yaml"),t=(0,it.parseYaml)(e);if(!ve(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===Ao?"This collection is already mdbase v0.3.":`Expected an mdbase v0.2.x collection, found ${JSON.stringify(n)}.`);let i=ve(t.settings)?t.settings:{},s=typeof i.types_folder=="string"?(0,it.normalizePath)(i.types_folder):"_types",o=`${s}/`,a=[],c=[],l=[],u=$N(t),d=`${(0,it.stringifyYaml)(u).trimEnd()} -`;a.push({path:"mdbase.yaml",sourceDigest:Fr(e),targetDigest:Fr(d),source:e,target:d});let f=new Map,p=new Map;for(let w of r.getMarkdownFiles().filter(A=>A.path.startsWith(o)).sort((A,x)=>A.path.localeCompare(x.path))){let A=await r.cachedRead(w),x=dt(A);if(!x.hasFrontmatter||x.error)throw new Error(`Cannot migrate ${w.path}: ${x.error??"frontmatter is missing"}.`);let M=SN(w.path,n,x.frontmatter),S=EN(w.path,x.frontmatter),C=AN(w.path,M.target);f.set(S.name,S),p.set(C.name,C);let $=`${bt(M.target,x.body)} -`;a.push({path:w.path,sourceDigest:Fr(A),targetDigest:Fr($),source:A,target:$}),c.push(M.summary),l.push(...M.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${s}.`);let m=0,h=0,y=w0(t,n),g=w0(u,Ao),v=r.getMarkdownFiles().filter(w=>!w.path.startsWith(o)).filter(w=>!w.path.startsWith(".mdbase/")).sort((w,A)=>w.path.localeCompare(A.path));for(let[w,A]of v.entries()){let x=dt(await r.cachedRead(A));if(x.error){h+=1;continue}let M=rn(A.path,x.frontmatter,y,f),S=rn(A.path,x.frontmatter,g,p),C=xN(x.frontmatter,M,f),$=kN(x.frontmatter,S,p);(Gn(M.slice().sort())!==Gn(S.slice().sort())||Gn(C)!==Gn($))&&l.push({path:A.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,w>0&&w%250===0&&await new Promise(V=>window.setTimeout(V,0))}let _=Fr(Gn({sourceVersion:n,operations:a.map(({path:w,sourceDigest:A,targetDigest:x})=>({path:w,sourceDigest:A,targetDigest:x})),diagnostics:l}));return{planVersion:1,analysisId:_,sourceVersion:n,targetVersion:Ao,createdAt:new Date().toISOString(),backupLocation:`.mdbase/migrations/v02-to-v03-${_.slice(0,12)}`,operations:a,typeSummaries:c,diagnostics:l,applicable:!l.some(w=>w.severity==="lossy"),recordFilesRewritten:0,recordsVerified:m,recordsSkipped:h}}async function $o(r,e,t){await sl(r,e,`${JSON.stringify(t,null,2)} -`)}async function $0(r,e,t={}){if(e.planVersion!==1||e.targetVersion!==Ao)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 Eo(r,s.path);if(Fr(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 sl(r,`${e.backupLocation}/files/${s.path}`,s.source);await $o(r,n,i),i.status="applying",await $o(r,n,i);try{for(let s of e.operations){let o=await Eo(r,s.path);if(Fr(o)!==s.sourceDigest)throw new Error(`${s.path} changed during migration.`);i.written.push(s.path),await $o(r,n,i),await sl(r,s.path,s.target);let a=await Eo(r,s.path);if(Fr(a)!==s.targetDigest)throw new Error(`${s.path} did not verify after write.`)}return i.status="applied",i.completed_at=new Date().toISOString(),await $o(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 sl(r,a,c.source),Fr(await Eo(r,a))!==c.sourceDigest&&o.push(a)}catch{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 $o(r,n,i)}catch{}return{applied:!1,restored:o.length===0,manifestPath:n,written:[...i.written],error:i.error}}}var ol=require("obsidian");function Se(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function $t(r){return JSON.parse(JSON.stringify(r))}var CN=new Set(["file","formula","this"]);function MN(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(CN.has(e.toLowerCase()))throw new Error(`Type name '${e}' is reserved.`);return e}function Fp(){return{specProfile:"v0.3",originalFrontmatter:{},name:"",description:"",extendsType:"",displayNameKey:"",strictMode:!1,pathPattern:"",filenamePattern:"",matchPathGlob:"",matchFieldsPresent:"",matchWhere:"",fields:[{name:"title",definition:{type:"string",required:!0}}],implementations:[],body:`# Type +`)&&e.slice(1)===r}function Tp(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)=>Tp(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)&&Tp(s,n[i]))}var es=class{fileSystem;runtime;mode;blobStore;constructor(e,t,n,i){this.fileSystem=e,this.runtime=t,this.mode=n,this.blobStore=i}async recordPathPolicy(e){return p0(Object.keys(e.resources??{}),()=>this.fileSystem.read("mdbase.yaml"))}async put(e,t,n={}){let{managedState:i=e,acceptedHash:s,materialized:o,inspectionPreflighted:a}=n;a||_n(t.path,await this.recordPathPolicy(e)),o===void 0&&!a&&y0(t.path,t.record_id,Object.keys(e.resources??{}),Object.entries(e.records),Object.entries(e.files??{}));let c=o?.document??Dc(t),l=a===1?null:await this.fileSystem.read(t.path),u=i?.records[t.record_id],d=l===null?null:this.runtime.digest(l);if(d!==null&&l!==c&&!(u!==void 0&&u.path===t.path&&d===u.hash)&&(!s||d!==s))throw new bt(t.record_id,t.path);u&&u.path!==t.path&&await this.remove(i,t.record_id,u.path);let f=this.runtime.digest(c);s===f&&d===f||await this.fileSystem.write(t.path,c),e.records[t.record_id]={path:t.path,revision:t.revision,hash:o?.hash??f,...this.mode==="read_write"?{record:t}:{}}}async putFile(e,t,n=e,i){if(gt(t),!this.blobStore)throw new b("file_storage_unavailable","Selected collection files require a content-addressed blob store adapter.");g0(t.path,t.file_id,e),e.files??={};let s=n.files?.[t.file_id],o=await this.fileSystem.inspectBinary(t.path),a=Et(t.path),c=Object.values(n.files??{}).find(m=>Et(m.file.path)===a),l=[...Object.values(n.resources??{}),...Object.values(n.records)].find(m=>Et(m.path)===a),u=l?await this.fileSystem.read(t.path):null,d=s?.file.path===t.path&&Br(o,s.file),f=c!==void 0&&Br(o,c.file),p=l!==void 0&&u!==null&&this.runtime.digest(u)===l.hash;if(o!==null&&!Br(o,t)&&!d&&!f&&!p&&!(i!==void 0&&o?.size===i.size&&o.content_digest===i.content_digest))throw new bt(t.file_id,t.path);if(s&&s.file.path!==t.path){let m=await this.fileSystem.inspectBinary(s.file.path);if(m!==null&&!Br(m,s.file))throw new bt(t.file_id,s.file.path)}Br(o,t)||await this.fileSystem.writeBinary(t.path,Vc(this.blobStore.read(t.content_digest),t)),s&&s.file.path!==t.path&&await this.fileSystem.remove(s.file.path),e.files[t.file_id]={file:t}}async removeFile(e,t){let n=e.files?.[t];if(!n)return;let i=await this.fileSystem.inspectBinary(n.file.path);if(i!==null&&!Br(i,n.file))throw new bt(t,n.file.path);i!==null&&await this.fileSystem.remove(n.file.path),delete e.files[t]}async remove(e,t,n,i={}){let s=e.records[t],o=s?.path??n;i.inspectionPreflighted||_n(o,await this.recordPathPolicy(e));let a=await this.fileSystem.read(o);if(a!==null&&s&&this.runtime.digest(a)!==s.hash)throw new bt(t,s.path);a!==null&&await this.fileSystem.remove(o),delete e.records[t]}async putResource(e,t,n){let i=await this.fileSystem.read(t.path),s=n?.resources?.[t.path];if(i!==null&&i!==t.document&&(!s||this.runtime.digest(i)!==s.hash))throw new bt(`resource:${t.path}`,t.path);await this.fileSystem.write(t.path,t.document),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 bt(`resource:${t}`,t);i!==null&&await this.fileSystem.remove(t),e.resources&&delete e.resources[t]}};async function v0(r,e,t,n){for(let i in r.records){if(!Object.hasOwn(r.records,i))continue;let s=r.records[i];_n(s.path,e);let o=await t.read(s.path);if(o===null||n(o)!==s.hash)throw new bt(i,s.path)}for(let[i,s]of Object.entries(r.resources??{})){let o=await t.read(s.path);if(o===null||n(o)!==s.hash)throw new bt(`resource:${i}`,s.path)}for(let[i,s]of Object.entries(r.files??{})){let o=await t.inspectBinary(s.file.path);if(!Br(o,s.file))throw new bt(i,s.file.path)}}async function _0(r){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 b("promotion_incomplete_file_projection","Moving the source of truth requires every collection file class with no excluded folders.");if(Object.keys(e.planned_conflicts??{}).length>0||e.batch!==void 0)throw new b("promotion_not_converged","Upload or resolve every local change before moving the source of truth.");await v0(e,i,n,s);let o=new Set(Object.keys(e.resources??{})),a=new Set(Object.values(e.records).map(d=>d.path)),c=(await n.listMarkdown(o)).filter(d=>!a.has(d));if(c.length>0)throw new b("promotion_unmanaged_files",`Synchronize unmanaged Markdown before promotion: ${c.join(", ")}.`);if(!n.listBinary)throw new b("promotion_file_scan_unavailable","Moving the source of truth requires binary file enumeration.");let l=new Set(Object.values(e.files??{}).map(d=>d.file.path)),u=(await n.listBinary(new Set([...o,...a]))).filter(d=>!l.has(d));if(u.length>0)throw new b("promotion_unmanaged_files",`Synchronize unmanaged files before moving the source of truth: ${u.join(", ")}.`);return{cursor:e.cursor,digest:jc([...Object.entries(e.resources??{}).map(([d,f])=>({kind:"resource",path:d,identity:"",document_hash:gp(f.hash)})),...Object.entries(e.records).map(([d,f])=>({kind:"record",path:f.path,identity:d,document_hash:gp(f.hash)})),...Object.values(e.files??{}).map(({file:d})=>({kind:"file",path:d.path,identity:d.file_id,document_hash:qc(d)}))])}}function wr(r,e,t,n,i){return{status:r,plan_fingerprint:e.fingerprint,applied:n,pending:t.pending,checkpoint_cursor:t.cursor,conflicts:t.conflicts.length,issues:e.issues,...i?{failure:i}:{}}}function w0(r,e){if(["planned","applying","cancelled","stale","blocked","failed"].includes(r.state))return r;let t=[...r.local_issues];for(let n of e.issues)n.path&&(n.code==="invalid_frontmatter"||n.code==="file_read_failed")&&!t.some(({path:i,code:s,message:o})=>i===n.path&&s===n.code&&o===n.message)&&t.push({path:n.path,code:n.code,message:n.message});return r.conflicts.length>0||t.length>0||e.summary.blocking_issues>0||e.summary.conflicts>0?{...r,state:"attention",local_issues:t}:{...r,state:e.actions.some(n=>n.command!=="advance_checkpoint")?"changes_waiting":"up_to_date"}}function rr(r,e){if(!r)return{state:"not_initialized",mode:e,pending:0,pending_files:0,conflicts:[],local_issues:[],cursor:null,last_synced_at:null};let t=[];for(let[o,a]of Object.entries(r.planned_conflicts??{})){let c=t.findIndex(({entity:u,object_id:d})=>u===a.entity&&d===o);c!==-1&&t.splice(c,1);let l=a.local.state==="exact"?a.local.object.path:a.remote.state==="exact"?a.remote.object.path:null;t.push({entity:a.entity,object_id:o,decision_id:a.decision_id??"",path:l,kind:a.conflict_kind==="rejected"?"rejected":"conflicted",message:a.conflict_kind==="rejected"?"The authority rejected this local change.":"Local and authority changes need a decision."})}let n=[],i=r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(o=>o.command!=="advance_checkpoint").length:0;return{state:(r.batch?r.batch.phase==="prepared"?"planned":r.batch.phase==="applying"||r.batch.phase==="effects_complete"?"applying":r.batch.phase==="cancelled"?"cancelled":r.batch.failure?.code==="sync_plan_stale"?"stale":"blocked":null)??(t.length?"attention":"up_to_date"),mode:e,pending:i,pending_files:r.batch?r.batch.plan.actions.slice(r.batch.next_action).filter(o=>o.command!=="advance_checkpoint"&&("target"in o&&o.target.entity==="file"||"source"in o&&o.source.entity==="file"||"entity"in o&&o.entity==="file")).length:0,conflicts:t,local_issues:n,cursor:r.batch?.checkpoint_before.cursor??r.cursor,last_synced_at:r.last_synced_at??null,generation:r.generation??0,pending_checkpoint:r.batch?.checkpoint_after.cursor??null,...r.batch?{plan_fingerprint:r.batch.plan.fingerprint}:{},...r.last_completed_plan?{last_completed_plan:r.last_completed_plan}:{},recovery_required:r.batch!==void 0,...r.batch?.failure?{failure:r.batch.failure}:{}}}async function sN(r,e,t){let n=await e.openSession();if(n.protocol_version!==1||n.protocol_profile!=="exact_document_v1"||n.replica_id!==r||n.mode!==t)throw new b("sync_protocol_incompatible",`Filesystem mirror requires exact-document v1 and its own ${t.replace("_","-")} replica.`);return n}async function Xc(r,e,t,n,i){let s=await sN(r,e,t),o=s.resources.documents??[],a=Jc(o),c=new Yc(a,o,i.digest),l=[];await b0(e,s,async f=>{for(let p of f){let m=c.validate(p);Xn(n,m.record.path)&&l.push(m)}});let u=[],d=new Set;return await Gw(e,s,async f=>{for(let p of f)if(zc(n,p)){if(d.has(p.file_id))throw new b("invalid_snapshot",`Hosted snapshot repeats file identity ${p.file_id}.`);d.add(p.file_id),u.push(p)}}),$o([...o.map(f=>f.path),...l.map(({record:f})=>f.path),...u.map(f=>f.path)]),{session:s,resources:o,records:l,files:u}}var Qc="exact_document_plan_only_v1",Zc="three_way_exact_document_v1",el="portable_mirror_projection_v1";function tl(r){return JSON.stringify(Rp(r))}function ei(r,e){return`sha256:${e(tl(r))}`}function Rp(r){if(r===null||typeof r=="string"||typeof r=="boolean")return r;if(typeof r=="number"){if(!Number.isSafeInteger(r))throw new b("invalid_sync_plan","Sync plans contain only safe integer numeric values.");return r}if(Array.isArray(r))return r.map(Rp);if(typeof r=="object"){let e={};for(let t of Object.keys(r).sort()){let n=r[t];if(n===void 0)throw new b("invalid_sync_plan",`Sync plan field ${t} is undefined rather than an explicit state.`);e[t]=Rp(n)}return e}throw new b("invalid_sync_plan","Sync plans contain only canonical I-JSON values.")}function A0(r,e,t){let n=new Map(r.base.map(u=>[u.identity,u])),i=new Map(r.remote.map(u=>[u.identity,u])),s=new Map,o=new Map(r.local.map(u=>[u.object.path,u]));for(let u of r.local)!u.stable_identity||u.object.identity===""||(s.set(u.object.identity,u.object),o.delete(u.object.path));for(let[u,d]of n){let f=o.get(d.path);f&&(s.set(u,{...f.object,identity:u}),o.delete(d.path))}for(let[u,d]of i){if(s.has(u))continue;let f=o.get(d.path);f&&f.object.entity===d.entity&&(s.set(u,{...f.object,identity:u}),o.delete(d.path))}for(let[u,d]of n){if(s.has(u))continue;let f=[...o.values()].filter(m=>m.object.entity===d.entity&&m.object.payload_revision===d.payload_revision);if(f.length!==1)continue;let p=f[0];s.set(u,{...p.object,identity:u,revision:p.object.payload_revision===d.payload_revision?d.revision:p.object.revision}),o.delete(p.object.path)}for(let u of o.values()){let d=u.stable_identity?u.object.identity:mN(e,u.object,t);s.set(d,{...u.object,identity:d})}let a=new Set([...n.keys(),...s.keys(),...i.keys()]),c=new Map([...s.values()].map(u=>[u.path,u])),l=new Map([...i.values()].map(u=>[u.path,u]));return[...a].sort().map(u=>{let d=n.get(u),f=s.get(u),p=i.get(u),m=p?.path??f?.path??d.path,h=f?.path??p?.path??d.path;return{entity:(f??p??d).entity,identity:u,base:Eo(d),local:Eo(f),remote:Eo(p),local_target_owner:Eo(c.get(m)),remote_target_owner:Eo(l.get(h))}})}function k0(r,e){let t=r.issues.some(d=>d.blocking),n=[],i=t&&r.mode==="read_only"&&r.issues.every(d=>!d.blocking||d.code==="invalid_frontmatter");if(!t||i){for(let d of[...r.objects].sort(gN)){let{local:f,remote:p}=d,m=i&&f.state==="exact"&&r.issues.some(h=>h.blocking&&h.path===f.object.path)&&p.state==="exact"&&p.object.path===f.object.path;(!t||m)&&fN(r,d,n,m)}i&&n.length!==r.issues.filter(d=>d.blocking).length&&(n=[]),n=cN(n,r.objects,e),n=oN(n,r.objects)}if(n.length>0||!t&&(r.kind!=="incremental"||r.boundary.checkpoint.cursor!==r.boundary.authority_cursor)){let d=n.map(f=>f.key);n.push({key:"checkpoint",depends_on_keys:d,command:"advance_checkpoint",reason:r.kind==="incremental"?"remote_change":r.kind,expected:r.boundary.checkpoint,next:t?r.boundary.checkpoint:{generation:r.boundary.checkpoint.generation+1,cursor:r.boundary.authority_cursor}})}let o=new Map;for(let d of n){let{key:f,depends_on_keys:p,...m}=d;o.set(f,ei({action_scope:{replica_id:r.boundary.replica_id,scope_epoch:r.boundary.scope_epoch,generation:r.boundary.checkpoint.generation},key:f,...m},e))}let a=n.map(d=>{let{key:f,depends_on_keys:p,...m}=d,h={...m,action_id:o.get(f),depends_on:p.map(y=>o.get(y))};if((h.command==="put_remote"||h.command==="move_remote"||h.command==="delete_remote")&&(h.idempotency_key=h.action_id),h.command==="move_remote"){let y=p.find(g=>g===`${h.source.identity}:put-remote`);y&&(h.revision_from_dependency=o.get(y))}return h}),c=[...r.issues].sort(bN),l={uploads:a.filter(_N).length,downloads:a.filter(wN).length,conflicts:a.filter(d=>d.command==="record_conflict").length,blocking_issues:c.filter(d=>d.blocking).length},u={plan_version:1,engine_profile:Qc,protocol_profile:"exact_document_v1",planner_policy:Zc,projection_policy:el,replica_id:r.boundary.replica_id,mode:r.mode,kind:r.kind,base_cursor:r.boundary.checkpoint.cursor,authority_cursor:r.boundary.authority_cursor,scope_epoch:r.boundary.scope_epoch,checkpoint_generation:r.boundary.checkpoint.generation,selective_sync:r.selective_sync,actions:a,issues:c,summary:l};return{...u,fingerprint:ei(u,e)}}function oN(r,e){if(!r.some(c=>c.command==="move_remote"))return r;let t=[...r],n=new Set;for(let c of aN(t))for(let l of c){let u=t.find(d=>d.key===l);u?.command==="move_remote"&&n.add(u.source.identity)}let i=Dp(t),s=new Map(t.map(c=>[c.key,c])),o=!0;for(;o;){o=!1;for(let c of t){if(c.command!=="move_remote")continue;let l=c.expected_target_owner;if(l.state!=="exact"||l.object.identity===c.source.identity)continue;let u=s.get(i.get(Sr(l.object))??""),d=u&&S0(u);(!u||d&&n.has(d))&&!n.has(c.source.identity)&&(n.add(c.source.identity),o=!0)}}if(n.size>0){t=t.filter(l=>{let u=S0(l);return!u||!n.has(u)||l.command!=="put_remote"&&l.command!=="move_remote"});let c=new Map(e.map(l=>[l.identity,l]));for(let l of[...n].sort()){let u=c.get(l);!u||u.entity==="resource"||t.push({key:`${l}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"local_change",identity:l,entity:u.entity,local:u.local,remote:u.remote,conflict_kind:"path_occupied"})}}let a=Dp(t);for(let c of t){if(c.command!=="move_remote")continue;let l=c.expected_target_owner;if(l.state!=="exact"||l.object.identity===c.source.identity)continue;let u=a.get(Sr(l.object));!u||u===c.key||(c.depends_on_keys.includes(u)||c.depends_on_keys.push(u),c.expected_target_owner={state:"absent"})}return P0(t)}function aN(r){let e=r.filter(s=>s.command==="move_remote"),t=new Map(e.map(s=>[s.key,s])),n=Dp(r),i=new Map;for(let s of e){let o=[],a=new Map,c=s;for(;c;){let l=a.get(c.key);if(l!==void 0){let d=o.slice(l);i.set([...d].sort().join("\0"),d);break}a.set(c.key,o.length),o.push(c.key);let u=c.expected_target_owner;c=u.state==="exact"?t.get(n.get(Sr(u.object))??""):void 0}}return[...i.values()]}function Dp(r){let e=new Map;for(let t of r)t.command==="move_remote"?e.set(Sr(t.source),t.key):t.command==="delete_remote"&&e.set(Sr(t.target),t.key);return e}function S0(r){if(r.command==="move_remote")return r.source.identity;if(r.command==="put_remote"||r.command==="delete_remote")return r.target.identity}function cN(r,e,t){if(!r.some(d=>d.command==="move_local"||d.command==="write_local"))return r;let n=[...r],i=new Set;for(let d of e)d.base.state==="exact"&&i.add(d.base.object.path),d.local.state==="exact"&&i.add(d.local.object.path),d.remote.state==="exact"&&i.add(d.remote.object.path);for(;;){let d=lN(n);if(!d)break;let f=[...d].sort()[0],p=n.findIndex(_=>_.key===f),m=n[p];if(!m||m.command!=="move_local")throw new Error("Planner invariant: local path cycle contains a non-move action.");let h=uN(m.source,m.target_path,i,t);i.add(h);let y={...m.source,path:h},g={key:`${m.source.identity}:stage-local`,depends_on_keys:[...m.depends_on_keys],command:"move_local",reason:m.reason,source:m.source,target_path:h,expected_source_owner:m.expected_source_owner,expected_target_owner:{state:"absent"}};m.source=y,m.expected_source_owner={state:"exact",object:y},m.depends_on_keys=[g.key],n.splice(p,0,g)}let s=Lp(n),o=new Map(e.map(d=>[d.identity,d])),a=new Set,c=new Map(n.map(d=>[d.key,d])),l=!0;for(;l;){l=!1;for(let d of n){let f=$0(d),p=rl(d);if(f?.state!=="exact"||f.object.identity===p)continue;let m=c.get(s.get(Sr(f.object))??""),h=m&&rl(m);(!m||h&&a.has(h))&&!a.has(p)&&(a.add(p),l=!0)}}if(a.size>0){n=n.filter(d=>!a.has(rl(d))||d.command!=="move_local"&&d.command!=="write_local");for(let d of[...a].sort()){let f=o.get(d);!f||f.entity==="resource"||n.push({key:`${d}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"remote_change",identity:d,entity:f.entity,local:f.local,remote:f.remote,conflict_kind:"path_occupied"})}}let u=Lp(n);for(let d of n){let f=$0(d),p=rl(d);if(f?.state!=="exact"||f.object.identity===p)continue;let m=u.get(Sr(f.object));!m||m===d.key||(d.depends_on_keys.includes(m)||d.depends_on_keys.push(m),dN(d,{state:"absent"}))}return P0(n)}function lN(r){let e=r.filter(i=>i.command==="move_local"),t=new Map(e.map(i=>[i.key,i])),n=Lp(r);for(let i of e){let s=[],o=new Map,a=i;for(;a;){let c=o.get(a.key);if(c!==void 0)return s.slice(c);o.set(a.key,s.length),s.push(a.key);let l=a.expected_target_owner;a=l.state==="exact"?t.get(n.get(Sr(l.object))??""):void 0}}}function Lp(r){let e=new Map;for(let t of r)t.command==="move_local"?e.set(Sr(t.source),t.key):t.command==="delete_local"&&e.set(Sr(t.target),t.key);return e}function $0(r){if(r.command==="move_local")return r.expected_target_owner;if(r.command==="write_local")return r.expected_path_owner}function dN(r,e){r.command==="move_local"?r.expected_target_owner=e:r.command==="write_local"&&(r.expected_path_owner=e)}function rl(r){return r.command==="move_local"?r.source.identity:r.command==="write_local"||r.command==="delete_local"?r.target.identity:""}function Sr(r){return`${r.entity}\0${r.identity}\0${r.path}`}function uN(r,e,t,n){let i=r.path.lastIndexOf("/"),s=i<0?"":r.path.slice(0,i+1),o=i<0?r.path:r.path.slice(i+1),a=o.lastIndexOf("."),c=a>0?o.slice(a):"";for(let l=0;;l+=1){let u=n(`${r.entity}\0${r.identity}\0${r.path}\0${e}\0${l}`),d=`${s}.mdbase-sync-stage-${u.slice(0,16)}${c}`;if(!t.has(d))return d}}function P0(r){let e=[...r],t=new Set,n=[];for(;e.length>0;){let i=e.findIndex(o=>o.depends_on_keys.every(a=>t.has(a)));if(i<0)throw new Error("Planner invariant: action dependency graph contains a cycle.");let[s]=e.splice(i,1);n.push(s),t.add(s.key)}return n}function fN(r,e,t,n){if(e.frozen_conflict){t.push(yN(e.frozen_conflict.local,e.frozen_conflict.remote)?{key:`${e.identity}:clear-conflict`,depends_on_keys:[],command:"clear_conflict",reason:"pending",identity:e.identity,entity:e.entity,expected_local:e.frozen_conflict.local,expected_remote:e.frozen_conflict.remote}:{key:`${e.identity}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"pending",identity:e.identity,entity:e.entity,...e.frozen_conflict});return}let i=!Np(e.local,e.base),s=!Np(e.remote,e.base);if(!(!i&&!s)){if(e.entity==="resource"){if(i)return;Op(e,t);return}if(r.mode==="read_only"){(!i||n)&&Op(e,t);return}if(i&&s){if(Np(e.local,e.remote))return;t.push(hN(e));return}i?pN(e,t):Op(e,t)}}function Op(r,e){if(r.remote.state==="absent"){r.local.state==="exact"&&e.push({key:`${r.identity}:delete-local`,depends_on_keys:[],command:"delete_local",reason:"remote_change",target:r.local.object,expected_local:r.local,expected_path_owner:r.local_target_owner});return}let t=r.remote.object;if(r.local.state==="absent"){e.push(E0(r,t,[]));return}let n=r.local.object,i;if(n.path!==t.path){let s=`${r.identity}:move-local`;e.push({key:s,depends_on_keys:[],command:"move_local",reason:"remote_change",source:n,target_path:t.path,expected_source_owner:r.local,expected_target_owner:r.local_target_owner}),i=s}n.revision!==t.revision&&e.push(E0(r,t,i?[i]:[]))}function E0(r,e,t){return{key:`${r.identity}:write-local`,depends_on_keys:t,command:"write_local",reason:"remote_change",target:e,payload_revision:e.payload_revision,expected_local:t.length>0?{state:"exact",object:{...e,revision:zr(r.local).revision,payload_revision:zr(r.local).payload_revision,...zr(r.local).size===void 0?{}:{size:zr(r.local).size}}}:r.local,expected_path_owner:t.length>0?{state:"exact",object:{...e,revision:zr(r.local).revision,payload_revision:zr(r.local).payload_revision,...zr(r.local).size===void 0?{}:{size:zr(r.local).size}}}:r.local_target_owner}}function pN(r,e){if(r.local.state==="absent"){r.remote.state==="exact"&&e.push({key:`${r.identity}:delete-remote`,depends_on_keys:[],command:"delete_remote",reason:"local_change",target:r.remote.object,expected_remote:r.remote,expected_local:r.local,idempotency_key:""});return}let t=r.local.object;if(r.remote.state==="absent"){e.push(x0(r,t,[]));return}let n=r.remote.object,i;if(t.revision!==n.revision){let s=x0(r,{...t,path:n.path},[]);e.push(s),i=s.key}t.path!==n.path&&e.push({key:`${r.identity}:move-remote`,depends_on_keys:i?[i]:[],command:"move_remote",reason:"local_change",source:i?{...n,revision:t.revision}:n,target_path:t.path,expected_source_owner:i?{state:"exact",object:{...n,revision:t.revision}}:r.remote,expected_target_owner:r.remote_target_owner,expected_local:r.local,idempotency_key:""})}function x0(r,e,t){return{key:`${r.identity}:put-remote`,depends_on_keys:t,command:"put_remote",reason:"local_change",target:e,payload_revision:zr(r.local).payload_revision,expected_remote:r.remote,expected_local:r.local,idempotency_key:""}}function hN(r){return{key:`${r.identity}:conflict`,depends_on_keys:[],command:"record_conflict",reason:"remote_change",identity:r.identity,entity:r.entity,local:r.local,remote:r.remote,conflict_kind:r.local.state==="absent"||r.remote.state==="absent"?"delete_vs_change":"both_changed"}}function zr(r){if(r.state!=="exact")throw new Error("Planner invariant: expected exact object state.");return r.object}function Eo(r){return r?{state:"exact",object:r}:{state:"absent"}}function mN(r,e,t){let n=t(`${r}\0${e.entity}\0${e.path}\0${e.revision}`);return`${n.slice(0,8)}-${n.slice(8,12)}-5${n.slice(13,16)}-8${n.slice(17,20)}-${n.slice(20,32)}`}function Np(r,e){return tl(r)===tl(e)}function yN(r,e){return r.state==="absent"||e.state==="absent"?r.state===e.state:r.object.entity===e.object.entity&&r.object.identity===e.object.identity&&r.object.path===e.object.path&&r.object.payload_revision===e.object.payload_revision&&r.object.size===e.object.size}function gN(r,e){return`${r.entity}\0${r.identity}`.localeCompare(`${e.entity}\0${e.identity}`)}function bN(r,e){return vN(`${r.path??""}\0${r.code}\0${r.message}`,`${e.path??""}\0${e.code}\0${e.message}`)}function vN(r,e){let t=new TextEncoder,n=t.encode(r),i=t.encode(e),s=Math.min(n.length,i.length);for(let o=0;o[c.record_id,c])),a=new Map(n.files.map(c=>[c.file_id,c]));return this.finish({kind:e,prior:t,authorityCursor:n.session.head,scopeEpoch:n.session.scope_epoch,local:s,remoteRecords:o,remoteResources:n.resources,remoteFiles:a,snapshot:n})}async inspectIncremental(e){let t=new Map;for(let[l,u]of Object.entries(e.records))u.record&&t.set(l,u.record);let n=new Map(Object.entries(e.files??{}).map(([l,u])=>[l,u.file])),i=new Map(C0(e).map(l=>[EN(l),l])),s=e.cursor,o=e.cursor;for(;;){let l=s,u=await this.transport.changes(l,200);if(u.scope_epoch!==e.scope_epoch||u.cursoru.head||u.has_more&&u.cursor===l)throw new b("invalid_change_page","Authority returned an invalid change boundary.");if(u.reset_required)return this.inspectSnapshot("rebuild",e);for(let d of u.events){if(d.sequence<=o||d.sequence>u.cursor)throw new b("invalid_change_page","Authority change events are not strictly ordered.");o=d.sequence,this.applyRemoteObservation(i,t,n,d)}if(s=u.cursor,!u.has_more)break}let a=Object.values(e.resources??{}).map(l=>({path:l.path,kind:AN(l.path),revision:l.revision,document:""})),c=await this.inspectLocal(e,a,await this.currentRecordPathPolicy(e));return this.mode==="read_only"&&c.issues.some(l=>l.code==="invalid_frontmatter")?this.inspectSnapshot("rebuild",e):this.finish({kind:"incremental",prior:e,authorityCursor:s,scopeEpoch:e.scope_epoch,local:c,remoteRecords:t,remoteResources:[],remoteFiles:n,remoteRefs:[...i.values()]})}applyRemoteObservation(e,t,n,i){if(i.type==="put"){Iw(i);let s=i.record.record_id;Xn(this.selectiveSync,i.record.path)?(e.set(`record:${s}`,M0(i.record)),t.set(s,i.record)):(e.delete(`record:${s}`),t.delete(s));return}if(i.type==="remove"){e.delete(`record:${i.record_id}`),t.delete(i.record_id);return}if(i.type==="file_put"){gt(i.file);let s=i.file.file_id;zc(this.selectiveSync,i.file)?(e.set(`file:${s}`,qp(i.file)),n.set(s,i.file)):(e.delete(`file:${s}`),n.delete(s));return}e.delete(`file:${i.file_id}`),n.delete(i.file_id)}async inspectLocal(e,t,n){let i=[],s=new Map,o=new Map,a=[],c=new Map(Object.entries(e?.records??{}).map(([m,h])=>[h.path,[m,h]])),l=new Map(Object.entries(e?.planned_conflicts??{}).filter(([,m])=>m.entity==="record"&&m.local.state==="exact").map(([m,h])=>[h.local.state==="exact"?h.local.object.path:"",m])),u=new Map(Object.entries(e?.local_bindings??{}).filter(([,m])=>m.entity==="record").map(([m,h])=>[h.path,m])),d=new Set([...Object.keys(e?.resources??{}),...t.map(m=>m.path)]);for(let m of d){let h=e?.resources?.[m],y;try{y=await this.fileSystem.read(m)}catch{a.push(T0(m)),h&&i.push({stable_identity:!0,object:wn("resource",m,m,h.revision)});continue}if(y===null)continue;let g=y,_=_r(g,this.runtime);i.push({stable_identity:!0,object:wn("resource",m,m,_)}),s.set(m,g);let v=t.find(w=>w.path===m);!h&&v&&v.revision!==_?a.push({code:"local_collision",message:`${m} differs locally from the exact authority document.`,path:m,blocking:!0}):h&&h.revision!==_&&a.push({code:"mirror_diverged",message:`Authority-owned resource ${m} changed locally.`,path:m,blocking:!0})}let f=new Set(Object.values(e?.records??{}).map(m=>m.path)),p=h0(await this.fileSystem.listMarkdown(d),n).filter(m=>Xn(this.selectiveSync,m)||f.has(m));for(let m of p){let h=l.get(m),y=u.get(m),g=c.get(m),_=g?.[0],v=h??y??_??"",w;try{w=await this.fileSystem.readText(m)}catch{w=null}if(typeof w!="string"){a.push(w===null?T0(m):{code:"invalid_frontmatter",message:`Invalid frontmatter (${w.code}).`,path:m,blocking:!0});let $=w?.revision??g?.[1].revision;$&&i.push({stable_identity:v!=="",object:wn("record",v,m,$)});continue}let S=w,x=_r(S,this.runtime);i.push({stable_identity:v!=="",object:wn("record",v,m,x)}),s.set(m,S);let C=Pw(S);C.outcome!=="parsed"&&a.push({code:"invalid_frontmatter",message:`Invalid frontmatter (${C.outcome}).`,path:m,blocking:!0})}if(this.selectiveSync.file_classes.length>0){if(!this.fileSystem.listBinary)throw new b("file_storage_unavailable","Selected files require binary enumeration.");let m=new Set(Object.values(e?.files??{}).map(v=>v.file.path)),h=new Map(Object.entries(e?.files??{}).map(([v,w])=>[w.file.path,[v,w]])),y=new Map(Object.entries(e?.planned_conflicts??{}).filter(([,v])=>v.entity==="file"&&v.local.state==="exact").map(([v,w])=>[w.local.state==="exact"?w.local.object.path:"",v])),g=new Map(Object.entries(e?.local_bindings??{}).filter(([,v])=>v.entity==="file").map(([v,w])=>[w.path,v])),_=(await this.fileSystem.listBinary(d)).filter(v=>Kw(this.selectiveSync,v)||m.has(v));for(let v of _){let w=await this.fileSystem.inspectBinary(v);if(!w)continue;let S=y.get(v),x=g.get(v),C=h.get(v),$=S??x??C?.[0]??"";i.push({stable_identity:$!=="",object:{entity:"file",identity:$,path:v,revision:C&&C[1].file.content_digest===w.content_digest?C[1].file.revision:w.content_digest,payload_revision:w.content_digest,size:w.size}}),o.set(v,w)}}try{$o([...d,...p,...o.keys()])}catch(m){let h=Kn(m);a.push({code:Wn(m,"sync_inspection_failed"),message:h.message,blocking:!0})}return{observations:i,documents:s,binary:o,issues:a}}async finish(e){let{prior:t,local:n}=e,i=e.remoteRefs??[...e.remoteResources.map($N),...[...e.remoteRecords.values()].map(M0),...[...e.remoteFiles.values()].map(qp)],s=A0({base:t?C0(t):[],local:n.observations,remote:i},`${this.replicaId}\0${e.scopeEpoch}\0${t?.generation??0}`,this.runtime.digest);for(let d of s){let f=t?.planned_conflicts?.[d.identity];!f||f.entity!==d.entity||(d.frozen_conflict={local:d.local,remote:d.remote,conflict_kind:f.conflict_kind})}let o=[...n.issues];for(let d of s)(e.kind==="initial"||e.kind==="rebuild")&&d.base.state==="absent"&&d.local.state==="exact"&&d.remote.state==="exact"&&!I0(d.local,d.remote)&&o.push({code:"local_collision",message:`${d.remote.object.path} differs locally from the exact authority object.`,path:d.remote.object.path,blocking:this.mode!=="read_write"||d.entity==="resource"}),d.remote.state==="exact"&&d.local_target_owner.state==="exact"&&d.remote.object.identity!==d.local_target_owner.object.identity&&o.push({code:"local_collision",message:`${d.remote.object.path} is owned by different local bytes.`,path:d.remote.object.path,blocking:!0});try{$o([...i.map(d=>d.path),...n.observations.map(({object:d})=>d.path)])}catch(d){let f=Kn(d);o.push({code:Wn(d,"sync_inspection_failed"),message:f.message,blocking:!0})}if(this.mode==="read_only"){for(let d of s)if(d.entity!=="resource"&&!I0(d.local,d.base)){let f=xN(d.local,d.base);if(o.some(p=>p.blocking&&p.path===f))continue;o.push({code:"mirror_diverged",message:`${f} changed in a receive-only mirror.`,path:f,blocking:!0})}}let a=ei(Yn(this.selectiveSync),this.runtime.digest),c={boundary:{engine_profile:Qc,protocol_profile:"exact_document_v1",planner_policy:Zc,projection_policy:el,replica_id:this.replicaId,scope_epoch:e.scopeEpoch,authority_cursor:e.authorityCursor,checkpoint:{generation:t?.generation??0,cursor:t?.cursor??null},selective_sync_fingerprint:a},mode:this.mode,kind:e.kind,selective_sync:Yn(this.selectiveSync),objects:s,issues:SN(o)},l=k0(c,this.runtime.digest),u=await this.bindPayloads(l,n,e.remoteRecords,e.remoteResources,e.remoteFiles);return{summary:c,plan:l,durable_payloads:u,prior:t,snapshot:e.snapshot,remote_records:e.remoteRecords,remote_files:e.remoteFiles}}async bindPayloads(e,t,n,i,s){let o={documents:{},records:{},resources:{},files:{},local_files:{},mutations:{}},a=new Map(i.map(c=>[c.path,c]));for(let c of e.actions)if(c.command==="put_remote"){let l=c.expected_local.state==="exact"?c.expected_local.object.path:c.target.path;if(c.target.entity==="file"){let u=t.binary.get(l);if(!u)throw ti(c.action_id);await this.stageLocalBinary(l,u),o.local_files[c.action_id]={path:l,...u}}else{let u=t.documents.get(l);if(u===void 0||_r(u,this.runtime)!==c.payload_revision)throw ti(c.action_id);o.documents[c.action_id]=u}c.target.entity==="record"&&(o.mutations[c.action_id]={operation:"put",mutation_id:jp(c.action_id),replica_id:this.replicaId,scope_epoch:e.scope_epoch,record_id:c.target.identity,...c.expected_remote.state==="exact"?{base_revision:c.expected_remote.object.revision}:{},path:c.target.path,document:o.documents[c.action_id],created_at:this.runtime.now()})}else if(c.command==="write_local")if(c.target.entity==="record"){let l=n.get(c.target.identity);if(!l||l.revision!==c.target.revision)throw ti(c.action_id);o.records[c.action_id]=l}else if(c.target.entity==="resource"){let l=a.get(c.target.path);if(!l||l.revision!==c.target.revision)throw ti(c.action_id);o.resources[c.action_id]=l}else{let l=s.get(c.target.identity);if(!l||l.revision!==c.target.revision||!this.blobStore)throw ti(c.action_id);await Hc(this.transport,this.blobStore,l),o.files[c.action_id]=l}else if(c.command==="record_conflict"&&c.remote.state==="exact")if(c.entity==="record"){let l=n.get(c.identity);if(!l||l.revision!==c.remote.object.revision)throw ti(c.action_id);o.records[c.action_id]=l}else{let l=s.get(c.identity);if(!l||l.revision!==c.remote.object.revision)throw ti(c.action_id);o.files[c.action_id]=l}else c.command==="move_remote"&&c.source.entity==="record"?o.mutations[c.action_id]={operation:"move",mutation_id:jp(c.action_id),replica_id:this.replicaId,scope_epoch:e.scope_epoch,record_id:c.source.identity,base_revision:c.expected_source_owner.state==="exact"?c.expected_source_owner.object.revision:c.source.revision,path:c.target_path,created_at:this.runtime.now()}:c.command==="delete_remote"&&c.target.entity==="record"&&(o.mutations[c.action_id]={operation:"delete",mutation_id:jp(c.action_id),replica_id:this.replicaId,scope_epoch:e.scope_epoch,record_id:c.target.identity,base_revision:c.expected_remote.state==="exact"?c.expected_remote.object.revision:c.target.revision,created_at:this.runtime.now()});return o}async stageLocalBinary(e,t){if(!this.blobStore||!this.fileSystem.readBinary)throw new b("writable_file_storage_unavailable","Writable files require streaming filesystem and blob-store adapters.");if(await this.blobStore.has(t.content_digest))return;let n=await this.fileSystem.readBinary(e);if(!n)throw new b("sync_plan_stale",`${e} disappeared during inspection.`);await this.blobStore.write(t.content_digest,Jw(n,t,e))}};function SN(r){let e=new Map;for(let t of r)e.set(`${t.code}\0${t.path??""}\0${t.message}\0${t.blocking}`,t);return[...e.values()]}function C0(r){return[...Object.entries(r.resources??{}).map(([e,t])=>wn("resource",e,t.path,t.revision)),...Object.entries(r.records).map(([e,t])=>wn("record",e,t.path,t.revision)),...Object.entries(r.files??{}).map(([e,t])=>qp({...t.file,file_id:e}))]}function M0(r){return wn("record",r.record_id,r.path,r.revision)}function $N(r){return wn("resource",r.path,r.path,r.revision)}function wn(r,e,t,n){return{entity:r,identity:e,path:t,revision:n,payload_revision:n}}function qp(r){return{entity:"file",identity:r.file_id,path:r.path,revision:r.revision,payload_revision:r.content_digest,size:r.size}}function EN(r){return`${r.entity}:${r.identity}`}function I0(r,e){return JSON.stringify(r)===JSON.stringify(e)}function xN(r,e){return r.state==="exact"?r.object.path:e.state==="exact"?e.object.path:"mirror"}function ti(r){return new b("sync_payload_incomplete",`Inspected action ${r} has no revision-bound payload.`)}function T0(r){return{code:"file_read_failed",message:"Could not read local file.",path:r,blocking:!0}}function AN(r){return r==="mdbase.yaml"?"configuration":r.endsWith("lock.yaml")?"lock":r.startsWith("_types/")?"type":r.startsWith("_contracts/")?"contract":r.startsWith("_views/")?"view":"schema"}function jp(r){let e=r.replace(/^sha256:/u,"");return`${e.slice(0,8)}-${e.slice(8,12)}-4${e.slice(13,16)}-8${e.slice(17,20)}-${e.slice(20,32)}`}var xo=class{fileSystem;runtime;constructor(e,t){this.fileSystem=e,this.runtime=t}async validate(e,t){if((t?.generation??0)!==e.checkpoint_generation||(t?.cursor??null)!==e.base_cursor||(t?.scope_epoch??e.scope_epoch)!==e.scope_epoch)throw $r("The durable checkpoint changed after inspection.");for(let n of e.actions)n.depends_on.length===0&&await this.validateAction(n)}async validateAction(e){switch(e.command){case"write_local":await this.validateExpected(e.expected_local),await this.validateExpectedAt(e.target.path,e.expected_path_owner);return;case"delete_local":await this.validateExpected(e.expected_local),await this.validateExpectedAt(e.target.path,e.expected_path_owner);return;case"move_local":await this.validateExpectedAt(e.source.path,e.expected_source_owner),await this.validateExpectedAt(e.target_path,e.expected_target_owner);return;case"put_remote":case"move_remote":await this.validateExpected(e.expected_local);return;case"delete_remote":await this.validateExpectedAt(e.target.path,e.expected_local);return;case"record_conflict":await this.validateExpected(e.local);return;case"clear_conflict":await this.validateExpected(e.expected_local);return;case"advance_checkpoint":return}}async validateExpectedAt(e,t){if(t.state==="absent"){if(await this.fileSystem.exists(e))throw $r(`${e} is no longer vacant.`);return}if(t.object.path!==e||!await il(this.fileSystem,this.runtime,t.object,!0))throw $r(`${e} no longer has the inspected owner and bytes.`)}async validateExpected(e){if(e.state!=="absent"&&!await il(this.fileSystem,this.runtime,e.object,!0))throw $r(`${e.object.path} no longer matches the inspected bytes.`)}};async function il(r,e,t,n){if(t.entity==="file"){let s=await r.inspectBinary(t.path);return!!s&&s.content_digest===t.payload_revision&&(t.size===void 0||s.size===t.size)}let i;try{i=await r.readText(t.path)}catch(s){throw s instanceof b&&s.code==="file_read_failed"&&n?$r(s.message):s}return(typeof i=="string"?_r(i,e):i?.revision)===t.payload_revision}function $r(r){return new b("sync_plan_stale",r)}async function R0(r,e,t,n){if(r?.batch){if(r.batch.plan.fingerprint!==e.fingerprint)throw new b("mirror_recovery_required","A different prepared sync batch must recover before this plan can apply.");return r}let i=r?structuredClone(r):PN(e.replica_id,e.scope_epoch,e.mode,e.selective_sync);i.scope_epoch=e.scope_epoch,i.selective_sync=e.selective_sync;let s=e.actions.at(-1);if(s?.command!=="advance_checkpoint")throw new b("invalid_sync_plan","Prepared plan has no checkpoint action.");return i.batch={phase:"prepared",plan:e,next_action:0,receipts:[],payloads:t,checkpoint_before:{generation:e.checkpoint_generation,cursor:e.base_cursor},checkpoint_after:s.next},await n.write(i),i}async function O0(r,e){let t=st(r);t.phase!=="effects_complete"&&(t.phase="applying",delete t.failure,await ol(r,{type:"phase",plan_fingerprint:t.plan.fingerprint,phase:"applying"},e))}async function N0(r,e,t){let n=st(r),i=n.plan.actions[n.next_action];if(!i||i.action_id!==e.action_id)throw Re("The durable sync receipt does not match the next prepared action.");let s={type:"receipt",plan_fingerprint:n.plan.fingerprint,receipt:structuredClone(e),delta:kN(r,i)};n.receipts.push(structuredClone(e)),n.next_action+=1,await ol(r,s,t)}async function D0(r,e){let t=st(r),n=t.plan.actions[t.next_action];if(!n||n.command!=="advance_checkpoint")throw Re("Sync effects cannot complete before the checkpoint action is next.");t.phase="effects_complete",await ol(r,{type:"effects_complete",plan_fingerprint:t.plan.fingerprint},e)}async function sl(r,e,t,n){let i=st(r);i.phase=e,i.failure=t,await ol(r,{type:"phase",plan_fingerprint:i.plan.fingerprint,phase:e,failure:t},n)}async function ol(r,e,t){t.appendJournal?await t.appendJournal(e):await t.write(r)}function kN(r,e){let t="identity"in e?e.identity:"target"in e?e.target.identity:"source"in e?e.source.identity:null;if(t===null)return{};let n="entity"in e?e.entity:"target"in e?e.target.entity:"source"in e?e.source.entity:null;if(n===null)return{};let i={planned_conflicts:{[t]:Ao(r.planned_conflicts?.[t])},local_bindings:{[t]:Ao(r.local_bindings?.[t])}};return n==="record"?i.records={[t]:Ao(r.records[t])}:n==="resource"?i.resources={[t]:Ao(r.resources?.[t])}:i.files={[t]:Ao(r.files?.[t])},i}function Ao(r){return r===void 0?null:structuredClone(r)}function st(r){if(!r.batch)throw Re("The mirror has no prepared sync batch.");return r.batch}async function L0(r,e){let t=st(r);if(t.phase!=="blocked"||t.failure?.code!=="sync_plan_stale")throw new b("mirror_recovery_required","Only a stale batch at a durable action boundary can be abandoned.");delete r.batch,await e.write(r)}function PN(r,e,t,n){return{protocol_version:1,engine_version:3,generation:0,replica_id:r,scope_epoch:e,cursor:0,records:{},resources:{},files:{},selective_sync:n,mode:t,planned_conflicts:{}}}var cl=class{ports;materializer;ownersByPath=new Map;pathsByOwner=new Map;constructor(e){this.ports=e,this.materializer=new es(e.fileSystem,e.runtime,e.mode,e.blobStore)}async execute(e,t){let n=st(e);this.indexPathOwners(e);let i=new Set(n.receipts.map(s=>s.action_id));for(await O0(e,this.ports.store);n.next_action!i.has(a));if(o){let a={code:"invalid_mirror_state",message:`Action ${s.action_id} is missing dependency ${o}.`,action_id:s.action_id};return await sl(e,"blocked",a,this.ports.store),{status:"blocked",completed:n.next_action,failure:a}}try{let a=await this.dispatch(e,s);await N0(e,a,this.ports.store),i.add(a.action_id),this.ports.onProgress?.(n.next_action,n.plan.actions.length-1)}catch(a){let c=IN(a,s.action_id);return await sl(e,"blocked",c,this.ports.store),{status:c.code==="sync_plan_stale"?"stale":"blocked",completed:n.next_action,failure:c}}}throw Re("Prepared plan has no checkpoint action.")}async dispatch(e,t){switch(t.command){case"write_local":return this.writeLocal(e,t);case"move_local":return this.moveLocal(e,t);case"delete_local":return this.deleteLocal(e,t);case"put_remote":return this.putRemote(e,t);case"move_remote":return this.moveRemote(e,t);case"delete_remote":return this.deleteRemote(e,t);case"record_conflict":return e.planned_conflicts??={},e.planned_conflicts[t.identity]={decision_id:j0(t.entity,t.identity,t.local,t.remote,t.conflict_kind,this.ports.runtime.digest),entity:t.entity,local:t.local,remote:t.remote,conflict_kind:t.conflict_kind},e.local_bindings??={},t.local.state==="exact"?e.local_bindings[t.identity]={entity:t.entity,path:t.local.object.path}:delete e.local_bindings[t.identity],this.rebaseConflict(e,t),{action_id:t.action_id,status:"conflicted"};case"clear_conflict":return delete e.planned_conflicts?.[t.identity],delete e.local_bindings?.[t.identity],{action_id:t.action_id,status:"completed"};case"advance_checkpoint":throw Re("The executor cannot dispatch checkpoint actions.")}}rebaseConflict(e,t){let n=st(e).payloads;if(t.entity==="record"){if(t.remote.state==="absent"){delete e.records[t.identity];return}let s=n.records[t.action_id];if(!s||s.revision!==t.remote.object.revision)throw Er(t);al(s,this.ports.runtime,s.revision),e.records[t.identity]={path:s.path,revision:s.revision,hash:t.local.state==="exact"?t.local.object.payload_revision.replace(/^sha256:/u,""):this.ports.runtime.digest(s.document),...this.ports.mode==="read_write"?{record:s}:{}};return}if(e.files??={},t.remote.state==="absent"){delete e.files[t.identity];return}let i=n.files[t.action_id];if(!i||i.revision!==t.remote.object.revision)throw Er(t);gt(i),e.files[t.identity]={file:i}}async writeLocal(e,t){let n=st(e),i=await this.ports.fileSystem.exists(t.target.path);(!i||!await this.matchesRef(t.target))&&(await this.assertLocal(t.expected_local),await this.assertPathOwner(t.target.path,t.expected_path_owner,i));let s=n.payloads;if(t.target.entity==="record"){let a=s.records[t.action_id];if(!a||a.revision!==t.payload_revision)throw Er(t);return al(a,this.ports.runtime,t.payload_revision),await this.materializer.put(e,a,{inspectionPreflighted:n.plan.summary.blocking_issues?1:!0}),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}if(t.target.entity==="resource"){let a=s.resources[t.action_id];if(!a||a.revision!==t.payload_revision||_r(a.document,this.ports.runtime)!==a.revision)throw Er(t);return await this.materializer.putResource(e,a,e),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}let o=s.files[t.action_id];if(!o||o.content_digest!==t.payload_revision)throw Er(t);return await this.materializer.putFile(e,o,e),this.installPathOwner(t.target),{action_id:t.action_id,status:"completed"}}async moveLocal(e,t){return await this.matchesRef({...t.source,path:t.target_path})||(await this.assertLocal(t.expected_source_owner),await this.assertPathOwner(t.target_path,t.expected_target_owner),await this.ports.fileSystem.move(t.source.path,t.target_path)),CN(e,t.source,t.target_path),this.installPathOwner({...t.source,path:t.target_path}),{action_id:t.action_id,status:"completed"}}async deleteLocal(e,t){if(await this.matchesRef(t.target))if(await this.assertLocal(t.expected_local),t.target.entity==="record")await this.materializer.remove(e,t.target.identity,t.target.path,{inspectionPreflighted:!0});else if(t.target.entity==="resource"){let i=e.resources?.[t.target.identity];i?await this.materializer.removeResource(e,t.target.path,i):await this.ports.fileSystem.remove(t.target.path)}else await this.materializer.removeFile(e,t.target.identity);else MN(e,t.target);return this.removePathOwner(t.target),{action_id:t.action_id,status:"completed"}}async putRemote(e,t){let n=st(e).payloads;if(t.target.entity==="record"){let a=n.mutations[t.action_id],c=n.documents[t.action_id];if(!a||a.operation!=="put"||c===void 0)throw Er(t);if(_r(c,this.ports.runtime)!==t.payload_revision)throw $r("Prepared local document payload no longer matches its revision.");let l=await this.ports.transport.mutate(a);return this.acceptRecordReceipt(e,t,l,c),Fp(t.action_id,l)}if(t.target.entity==="resource")throw new b("invalid_sync_plan","Authority resources are not writable mirror objects.");let i=n.local_files[t.action_id];if(!i||!this.ports.blobStore||!this.ports.transport.uploadFile)throw Er(t);let s={protocol_version:1,type:"open_file_upload",transfer_id:Bp(t.action_id),path:t.target.path,size:i.size,content_digest:i.content_digest,...i.media_type?{media_type:i.media_type}:{},...t.expected_remote.state==="exact"?{if_revision:t.expected_remote.object.revision}:{}},o=await this.ports.transport.uploadFile(s,this.ports.blobStore.read(i.content_digest));if(gt(o.file),o.transfer_id!==s.transfer_id||o.file.path!==t.target.path||o.file.content_digest!==i.content_digest||o.file.size!==i.size)throw Up(t);return e.files??={},e.files[o.file.file_id]={file:o.file},delete e.local_bindings?.[t.target.identity],{action_id:t.action_id,status:"completed",file:o.file}}async moveRemote(e,t){if(t.source.entity==="record"){let s=st(e).payloads.mutations[t.action_id];if(!s||s.operation!=="move")throw Er(t);let o=await this.ports.transport.mutate(s);return this.acceptRecordReceipt(e,t,o),Fp(t.action_id,o)}if(t.source.entity==="resource"||!this.ports.transport.moveFile)throw new b("invalid_sync_plan","This remote move command is unsupported.");let n={protocol_version:1,type:"move_file",mutation_id:Bp(t.action_id),file_id:t.source.identity,if_revision:this.dependencyFileRevision(e,t)??(t.expected_source_owner.state==="exact"?t.expected_source_owner.object.revision:t.source.revision),from_path:t.source.path,path:t.target_path,update_references:!1},i=await this.ports.transport.moveFile(n);if(gt(i.file),i.mutation_id!==n.mutation_id||i.file.file_id!==t.source.identity||i.file.path!==t.target_path)throw Up(t);return e.files??={},e.files[t.source.identity]={file:i.file},delete e.local_bindings?.[t.source.identity],{action_id:t.action_id,status:"completed",file:i.file}}dependencyFileRevision(e,t){if(!t.revision_from_dependency)return;let n=st(e).receipts.find(({action_id:i})=>i===t.revision_from_dependency);if(!n?.file||n.file.file_id!==t.source.identity)throw Re(`Move ${t.action_id} is missing its dependency file receipt.`);return n.file.revision}async deleteRemote(e,t){if(t.target.entity==="record"){let s=st(e).payloads.mutations[t.action_id];if(!s||s.operation!=="delete")throw Er(t);let o=await this.ports.transport.mutate(s);return this.acceptRecordReceipt(e,t,o),Fp(t.action_id,o)}if(t.target.entity==="resource"||!this.ports.transport.deleteFile)throw new b("invalid_sync_plan","This remote delete command is unsupported.");let n={protocol_version:1,type:"delete_file",mutation_id:Bp(t.action_id),file_id:t.target.identity,if_revision:t.expected_remote.state==="exact"?t.expected_remote.object.revision:t.target.revision,path:t.target.path},i=await this.ports.transport.deleteFile(n);if(i.mutation_id!==n.mutation_id||i.file_id!==t.target.identity||i.previous_path!==t.target.path)throw Up(t);return delete e.files?.[t.target.identity],delete e.local_bindings?.[t.target.identity],{action_id:t.action_id,status:"completed"}}acceptRecordReceipt(e,t,n,i){let o=("target"in t?t.target:t.source).identity;if(n.status==="applied"||n.status==="previously_applied"){if(n.record){al(n.record,this.ports.runtime,n.record.revision);let u=e.records[o];e.records[o]={path:n.record.path,revision:n.record.revision,hash:i===void 0?u?.hash??this.ports.runtime.digest(n.record.document):this.ports.runtime.digest(i),...this.ports.mode==="read_write"?{record:n.record}:{}}}else delete e.records[o];delete e.local_bindings?.[o];return}let a=n.status==="conflicted"?n.conflict.current:void 0;a&&al(a,this.ports.runtime,a.revision);let c=a?{state:"exact",object:{entity:"record",identity:o,path:a.path,revision:a.revision,payload_revision:a.revision}}:t.command==="move_remote"?t.expected_source_owner:t.expected_remote;e.planned_conflicts??={};let l=n.status==="rejected"?"rejected":"both_changed";e.planned_conflicts[o]={decision_id:j0("record",o,t.expected_local,c,l,this.ports.runtime.digest),entity:"record",local:t.expected_local,remote:c,conflict_kind:l},e.local_bindings??={},t.expected_local.state==="exact"&&(e.local_bindings[o]={entity:"record",path:t.expected_local.object.path}),a&&(e.records[o]={path:a.path,revision:a.revision,hash:t.expected_local.state==="exact"?t.expected_local.object.payload_revision.replace(/^sha256:/u,""):this.ports.runtime.digest(a.document),...this.ports.mode==="read_write"?{record:a}:{}})}async assertLocal(e){if(e.state!=="absent"&&!await this.matchesRef(e.object))throw $r(`${e.object.path} no longer matches the inspected revision.`)}async assertPathOwner(e,t,n){let i=this.ownersByPath.get(e);if(t.state==="absent"){if(i||(n??await this.ports.fileSystem.exists(e)))throw $r(`${e} is no longer vacant.`);return}if(!i||i.entity!==t.object.entity||i.identity!==t.object.identity)throw $r(`${e} has a different path owner.`)}matchesRef(e){return il(this.ports.fileSystem,this.ports.runtime,e,!1)}indexPathOwners(e){this.ownersByPath.clear(),this.pathsByOwner.clear();for(let[t,n]of Object.entries(e.records))this.installPathOwner({entity:"record",identity:t,path:n.path,revision:n.revision,payload_revision:`sha256:${n.hash}`});for(let[t,n]of Object.entries(e.resources??{}))this.installPathOwner({entity:"resource",identity:t,path:n.path,revision:n.revision,payload_revision:`sha256:${n.hash}`});for(let[t,n]of Object.entries(e.files??{}))this.installPathOwner({entity:"file",identity:t,path:n.file.path,revision:n.file.revision,payload_revision:n.file.content_digest,size:n.file.size})}installPathOwner(e){let t=`${e.entity}:${e.identity}`,n=this.pathsByOwner.get(t);n!==void 0&&this.ownersByPath.delete(n),this.ownersByPath.set(e.path,e),this.pathsByOwner.set(t,e.path)}removePathOwner(e){let t=`${e.entity}:${e.identity}`,n=this.pathsByOwner.get(t)??e.path;this.ownersByPath.delete(n),this.pathsByOwner.delete(t)}};function j0(r,e,t,n,i,s){return ei({entity:r,identity:e,local:t,remote:n,conflict_kind:i},s)}function CN(r,e,t){if(e.entity==="record"){let n=r.records[e.identity];n&&(n.path=t,n.record&&(n.record.path=t))}else if(e.entity==="resource"){let n=r.resources?.[e.identity];n&&(n.path=t)}else{let n=r.files?.[e.identity];n&&(n.file.path=t)}}function MN(r,e){e.entity==="record"?delete r.records[e.identity]:e.entity==="resource"?delete r.resources?.[e.identity]:delete r.files?.[e.identity]}function al(r,e,t){let n=Dc(r);if(r.revision!==t||_r(n,e)!==t)throw new b("invalid_sync_response","Record receipt does not match its exact document revision.")}function Fp(r,e){return e.status==="applied"||e.status==="previously_applied"?{action_id:r,status:"completed",...e.record?{record:e.record}:{}}:{action_id:r,status:e.status}}function Er(r){return new b("sync_payload_incomplete",`Prepared action ${r.action_id} has no exact payload capability.`)}function Up(r){return new b("invalid_sync_response",`Authority receipt does not match prepared action ${r.action_id}.`)}function IN(r,e){let t=Kn(r);return{code:Wn(r,"sync_action_failed"),message:t.message,action_id:e}}function Bp(r){let e=r.replace(/^sha256:/u,"");return`${e.slice(0,8)}-${e.slice(8,12)}-4${e.slice(13,16)}-8${e.slice(17,20)}-${e.slice(20,32)}`}async function q0(r,e,t){let n=st(r);if(n.phase!=="effects_complete")throw Re("A checkpoint cannot advance before every prepared effect is durable.");let i=n.plan.actions[n.next_action];if(!i||i.command!=="advance_checkpoint")throw Re("Prepared checkpoint action is missing.");if(i.expected.generation!==n.checkpoint_before.generation||i.expected.cursor!==n.checkpoint_before.cursor||i.next.generation!==n.checkpoint_after.generation||i.next.cursor!==n.checkpoint_after.cursor)throw Re("Prepared checkpoint boundary is inconsistent.");let s=n.plan.fingerprint;return r.generation=i.next.generation,r.cursor=i.next.cursor??0,r.last_completed_plan=s,r.last_synced_at=e.now(),delete r.batch,await t.write(r),s}async function F0(r,e,t,n){let[i]=e.actions;if(e.actions.length!==1||!i||i.command!=="advance_checkpoint"||i.expected.generation!==(r.generation??0)||i.expected.cursor!==r.cursor||i.next.generation!==(r.generation??0)+1||i.next.cursor!==e.authority_cursor||r.batch!==void 0)throw Re("Empty checkpoint plan is inconsistent.");return r.generation=i.next.generation,r.cursor=i.next.cursor??0,r.last_completed_plan=e.fingerprint,r.last_synced_at=t.now(),await n.write(r),e.fingerprint}var ri=class{replicaId;transport;mode;stateStore;fileSystem;blobStore;selectiveSync;lease;runtime;materializer;onProgress;constructor(e,t,n,i="read_only"){this.replicaId=e,this.transport=t,this.mode=i,this.stateStore=n.stateStore,this.fileSystem=n.fileSystem,this.blobStore=n.blobStore,this.selectiveSync=Yn(n.selectiveSync),this.lease=n.lease??new wo,this.runtime=n.runtime??So,this.materializer=new es(this.fileSystem,this.runtime,this.mode,this.blobStore),this.onProgress=n.onProgress}async sync(e={}){return this.lease.runExclusive(async()=>{let t=await this.readState();if(t?.batch?.phase==="blocked"&&t.batch.failure?.code==="sync_plan_stale"&&(await L0(t,this.journalStore()),t=await this.readState()),t?.batch)return this.executePrepared(t,e.signal);let n=await this.inspectDetailed(t);return this.applyInspection(n,e.signal)})}async inspect(){return this.lease.runExclusive(async()=>{let e=await this.readState();return e?.batch?.plan??(await this.inspectDetailed(e)).plan})}async apply(e,t={}){return this.lease.runExclusive(async()=>{let n=await this.readState();if(n?.batch){if(n.batch.plan.fingerprint!==e.fingerprint)throw new b("mirror_recovery_required","A different prepared plan must recover before this plan can apply.");return this.executePrepared(n,t.signal)}if(n?.last_completed_plan===e.fingerprint){let s=rr(n,this.mode);return wr(s.state==="attention"?"attention":"applied",{...e,issues:[]},s,0)}let i=await this.inspectDetailed(n);return i.plan.fingerprint!==e.fingerprint?wr("stale",e,rr(i.prior,this.mode),0,{code:"sync_plan_stale",message:"The local folder or authority changed. Inspect the sync plan again."}):this.applyInspection(i,t.signal)})}async applyInspection(e,t){let n=e.plan;if(n.issues.some(s=>s.blocking)&&n.actions.length===0)return wr("attention",n,rr(e.prior,this.mode),0);if(t?.aborted)return wr("cancelled",n,rr(e.prior,this.mode),0,{code:"sync_cancelled",message:"Sync cancelled before preparation."});try{await new xo(this.fileSystem,this.runtime).validate(n,e.prior)}catch(s){let o=Kn(s),a=Wn(s,"sync_revalidation_failed");return wr(a==="sync_plan_stale"?"stale":"failed",n,rr(e.prior,this.mode),0,{code:a,message:o.message})}if(n.actions.length===0)return wr("applied",n,rr(e.prior,this.mode),0);if(e.prior&&n.actions.length===1&&n.actions[0]?.command==="advance_checkpoint")return await F0(e.prior,n,this.runtime,this.journalStore()),wr("applied",n,rr(e.prior,this.mode),0);let i=await R0(e.prior??this.initialUnchangedState(e),n,e.durable_payloads,this.journalStore());return this.executePrepared(i,t)}async executePrepared(e,t){let n=e.batch,i=await new cl({transport:this.transport,fileSystem:this.fileSystem,blobStore:this.blobStore,runtime:this.runtime,mode:this.mode,store:this.journalStore(),onProgress:(c,l)=>this.onProgress?.({phase:"applying",completed:c,total:l,done:c===l})}).execute(e,t);if(i.status!=="effects_complete"){let c=rr(e,this.mode);return wr(i.status==="blocked"?"failed":i.status,n.plan,c,i.completed,i.failure)}let s=n.plan;await q0(e,this.runtime,this.journalStore()),await this.pruneFileBlobs();let o=rr(e,this.mode),a=o.conflicts.length>0||o.local_issues.length>0||s.summary.conflicts>0;return wr(a?"attention":"applied",s,o,i.completed)}inspectDetailed(e){return new nl(this.replicaId,this.transport,this.mode,this.fileSystem,this.blobStore,this.selectiveSync,this.runtime,()=>this.readState(),t=>this.currentRecordPathPolicy(t)).inspect(e)}initialUnchangedState(e){if(e.plan.kind!=="initial"||!e.snapshot)return null;let t=new Set(e.summary.objects.filter(o=>o.local.state==="exact"&&o.remote.state==="exact"&&JSON.stringify(o.local)===JSON.stringify(o.remote)).map(o=>`${o.entity}:${o.identity}`)),n={};for(let{record:o,hash:a}of e.snapshot.records)t.has(`record:${o.record_id}`)&&(n[o.record_id]={path:o.path,revision:o.revision,hash:a,...this.mode==="read_write"?{record:o}:{}});let i={};for(let o of e.snapshot.resources)t.has(`resource:${o.path}`)&&(i[o.path]={path:o.path,revision:o.revision,hash:this.runtime.digest(o.document)});let s={};for(let o of e.snapshot.files)t.has(`file:${o.file_id}`)&&(s[o.file_id]={file:o});return{protocol_version:1,engine_version:3,generation:0,replica_id:e.plan.replica_id,scope_epoch:e.plan.scope_epoch,cursor:0,records:n,resources:i,files:s,selective_sync:e.plan.selective_sync,mode:e.plan.mode,planned_conflicts:{}}}async status(){let e=await this.checkpointStatus(),t=await this.inspect();return e.state==="not_initialized"&&!t.issues.some(n=>n.code==="invalid_frontmatter"||n.code==="file_read_failed")?e:w0(e,t)}async checkpointStatus(){return this.lease.runExclusive(()=>this.checkpointStatusUnlocked())}async checkpointStatusUnlocked(){return rr(await this.readState(),this.mode)}async authorityPromotionManifest(){return this.lease.runExclusive(async()=>{if(this.mode!=="read_write")throw new b("promotion_requires_writable_mirror","Only a read-write mirror can prove an authority promotion source.");let e=await this.readState();if(!e)throw new b("mirror_not_initialized","Synchronize this mirror first.");if(e.batch||Object.keys(e.planned_conflicts??{}).length>0)throw new b("promotion_mirror_not_clean","Finish the prepared batch and resolve conflicts before promotion.");let t=await _0({state:e,selectiveSync:this.selectiveSync,fileSystem:this.fileSystem,pathPolicy:await this.currentRecordPathPolicy(e),digest:this.runtime.digest});if((await this.inspectDetailed(e)).plan.actions.some(i=>i.command!=="advance_checkpoint"))throw new b("promotion_mirror_not_clean","Synchronize this mirror immediately before promotion.");return t})}async previewInitialization(){let e=await this.inspect(),t=e.actions.filter(i=>i.command==="put_remote"||i.command==="move_remote"||i.command==="delete_remote"),n=e.actions.filter(i=>i.command==="write_local"||i.command==="move_local"||i.command==="delete_local");return{already_initialized:e.kind==="incremental",download_documents:n.filter(i=>"target"in i&&i.target.entity!=="file"||"source"in i&&i.source.entity!=="file").length,upload_documents:t.filter(i=>"target"in i&&i.target.entity==="record"||"source"in i&&i.source.entity==="record").length,unchanged_documents:0,download_files:n.filter(i=>"target"in i&&i.target.entity==="file"||"source"in i&&i.source.entity==="file").length,upload_files:t.filter(i=>"target"in i&&i.target.entity==="file"||"source"in i&&i.source.entity==="file").length,unchanged_files:0,collisions:e.issues.filter(i=>i.code==="local_collision"&&i.path).map(i=>i.path),local_issues:e.issues.filter(i=>i.code==="invalid_frontmatter"&&i.path!==void 0).map(i=>({code:"invalid_frontmatter",message:i.message,path:i.path}))}}async resolveConflict(e,t,n){await this.lease.runExclusive(()=>this.resolveConflictUnlocked(e,t,n))}async resolveConflictUnlocked(e,t,n){if(this.mode!=="read_write")throw new b("mirror_read_only","Receive-only mirrors have no writable conflicts.");let i=await this.readState();if(!i||i.batch)throw new b("mirror_recovery_required","Finish sync recovery before resolving conflicts.");let s=i.planned_conflicts?.[e];if(!s)throw new b("mirror_conflict_not_found","Writable mirror conflict was not found.");if((s.decision_id??"")!==t)throw U0();let o=new xo(this.fileSystem,this.runtime);s.local.state==="exact"?await o.validateExpected(s.local):s.remote.state==="exact"&&await o.validateExpectedAt(s.remote.object.path,s.local);let a=await Xc(this.replicaId,this.transport,this.mode,this.selectiveSync,this.runtime),c=s.entity==="record"?a.records.find(({record:d})=>d.record_id===e)?.record:void 0,l=s.entity==="file"?a.files.find(d=>d.file_id===e):void 0;if(!(s.entity==="record"?TN(s.remote,c):RN(s.remote,l)))throw U0();n==="remote"&&(s.entity==="record"?await this.installRemoteRecord(i,e,c):await this.installRemoteFile(i,e,l)),delete i.planned_conflicts?.[e],n==="remote"&&delete i.local_bindings?.[e],await this.writeState(i)}async installRemoteRecord(e,t,n){if(n){let o=e.planned_conflicts?.[t],a=await this.fileSystem.read(n.path),c=e.records[t]?.path===n.path||o?.local.state==="exact"&&o.local.object.path===n.path;await this.materializer.put(e,n,{inspectionPreflighted:!1,...c&&a!==null?{acceptedHash:this.runtime.digest(a)}:{}});return}let i=e.planned_conflicts?.[t],s=i?.local.state==="exact"?i.local.object.path:e.records[t]?.path;s&&await this.fileSystem.read(s)!==null&&await this.fileSystem.remove(s),delete e.records[t]}async installRemoteFile(e,t,n){if(n){if(!this.blobStore)throw new b("file_storage_unavailable","File resolution needs a blob store.");await Hc(this.transport,this.blobStore,n);let o=e.planned_conflicts?.[t],a=o?.local.state==="exact"?{content_digest:o.local.object.payload_revision,size:o.local.object.size??0}:void 0,c=e.local_bindings?.[t]?.path;await this.materializer.putFile(e,n,e,a),c&&c!==n.path&&await this.fileSystem.remove(c);return}let i=e.planned_conflicts?.[t],s=i?.local.state==="exact"?i.local.object.path:e.files?.[t]?.file.path;s&&await this.fileSystem.inspectBinary(s)!==null&&await this.fileSystem.remove(s),delete e.files?.[t]}async readState(){let e=await this.stateStore.read();if(e===null)return null;try{return l0(e,this.replicaId,this.mode)}catch(t){throw t instanceof b?t:Re("Mirror metadata is corrupt or belongs to another replica.")}}writeState(e){return this.stateStore.write(e)}journalStore(){let e=this.stateStore;return{write:t=>this.writeState(t),...e.appendJournal?{appendJournal:t=>e.appendJournal(t)}:{}}}async pruneFileBlobs(){if(!this.blobStore)return;let e=await this.readState();if(!e)return;let t=new Set;for(let n of Object.values(e.files??{}))t.add(n.file.content_digest);for(let n of Object.values(e.batch?.payloads.files??{}))t.add(n.content_digest);for(let n of Object.values(e.batch?.payloads.local_files??{}))t.add(n.content_digest);await this.blobStore.prune(t)}currentRecordPathPolicy(e){return this.materializer.recordPathPolicy(e)}};function TN(r,e){return r.state==="absent"?e===void 0:e!==void 0&&r.object.entity==="record"&&r.object.identity===e.record_id&&r.object.path===e.path&&r.object.revision===e.revision&&r.object.payload_revision===e.revision&&r.object.size===void 0}function RN(r,e){return r.state==="absent"?e===void 0:e!==void 0&&r.object.entity==="file"&&r.object.identity===e.file_id&&r.object.path===e.path&&r.object.revision===e.revision&&r.object.payload_revision===e.content_digest&&r.object.size===e.size}function U0(){return new b("mirror_conflict_stale","Local or hosted content changed after this conflict was recorded. Synchronize again before choosing a version.")}var ko=class extends ri{constructor(e,t,n){super(e,t,n,"read_write")}};function B0(r){let e=[...r.actions.flatMap(t=>t.command==="advance_checkpoint"?[]:[ON(t)]),...r.issues.map(t=>({kind:"document",path:t.path??"Sync engine",direction:"attention",action:"fix",detail:t.message}))];return{plan:r,phase:r.kind,entries:e,cursor:r.base_cursor,remoteHead:r.authority_cursor,already_initialized:r.kind==="incremental",download_documents:r.actions.filter(t=>["write_local","move_local","delete_local"].includes(t.command)&&("target"in t?t.target.entity!=="file":"source"in t&&t.source.entity!=="file")).length,upload_documents:r.actions.filter(t=>["put_remote","move_remote","delete_remote"].includes(t.command)&&("target"in t?t.target.entity==="record":"source"in t&&t.source.entity==="record")).length,unchanged_documents:0,download_files:r.actions.filter(t=>["write_local","move_local","delete_local"].includes(t.command)&&("target"in t?t.target.entity==="file":"source"in t&&t.source.entity==="file")).length,upload_files:r.actions.filter(t=>["put_remote","move_remote","delete_remote"].includes(t.command)&&("target"in t?t.target.entity==="file":"source"in t&&t.source.entity==="file")).length,unchanged_files:0,collisions:r.issues.filter(t=>t.blocking&&t.code==="local_collision"&&t.path!==void 0).map(t=>t.path),local_issues:r.issues.filter(t=>["invalid_frontmatter","file_read_failed"].includes(t.code)&&t.path!==void 0).map(t=>({code:t.code,message:t.message,path:t.path}))}}function ON(r){if(r.command==="advance_checkpoint")throw new Error("Checkpoint actions are not preview entries.");if(r.command==="record_conflict"){let c=r.local.state==="exact"?r.local.object:r.remote.state==="exact"?r.remote.object:void 0;return{kind:r.entity==="file"?"file":"document",path:c?.path??r.identity,direction:"attention",action:"fix",detail:`Local and hosted ${r.entity} changes conflict (${r.conflict_kind.replace(/_/g," ")}).`,...c?.entity==="file"&&c.size!==void 0?{estimatedBytes:c.size}:{},...r.entity==="record"?{recordId:r.identity}:{fileId:r.identity}}}if(r.command==="clear_conflict"){let c=r.expected_local.state==="exact"?r.expected_local.object:r.expected_remote.state==="exact"?r.expected_remote.object:void 0;return{kind:r.entity==="file"?"file":"document",path:c?.path??r.identity,direction:"attention",action:"fix",detail:`Local and hosted ${r.entity} content now matches; clear the resolved conflict.`,...c?.entity==="file"&&c.size!==void 0?{estimatedBytes:c.size}:{},...r.entity==="record"?{recordId:r.identity}:{fileId:r.identity}}}let e=r.command.endsWith("_local"),t="target"in r?r.target:r.source,n=r.command==="move_local"||r.command==="move_remote"?r.target_path:t.path,i=r.command==="write_local"&&r.expected_local.state==="absent"||r.command==="put_remote"&&r.expected_remote.state==="absent",s=r.command.startsWith("move_")?"rename":r.command.startsWith("delete_")?"delete":i?"create":"update",o=r.command.split("_")[0],a=r.command.startsWith("move_")?` from ${t.path}`:"";return{kind:t.entity==="file"?"file":"document",path:n,direction:e?"download":"upload",action:s,detail:`${e?"Hosted":"Local"} ${t.entity} will ${o}${a}.`,...t.entity==="file"&&t.size!==void 0?{estimatedBytes:t.size}:{},...t.entity==="record"?{recordId:t.identity}:{},...t.entity==="file"?{fileId:t.identity}:{}}}var ts=".mdbase/connect-role.json",Po=".mdbase/authority-adoption.json",Co=".mdbase/authority-adoption-snapshot.json",NN="mdbase-obsidian-connect",Sn="mirrors",DN="mdbase-obsidian-connect-blobs",$n="manifests",En="chunks",ll=1024*1024,LN=32*1024*1024;function ii(r){if(!Number.isSafeInteger(r)||r<0||r>LN)throw new b("file_too_large","Binary sync supports files up to 32 MiB on this device. Exclude this file's folder to continue.")}var jN="mdbase-connect-access-",qN="mdbase-connect-refresh-",FN="mdbase-connect-adoption-",UN=300*1e3,BN=[".git",".trash",".mdbase"],VN=new Set([".git",".mdbase",".trash","node_modules","_contracts","_schemas","_types","_views"]),Vp=["image","audio","video","pdf","other"],Io=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ot(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function xr(r){let e=r?.file_classes??[];if(e.some(s=>!Vp.includes(s))||new Set(e).size!==e.length)throw new b("invalid_file_materialization","Selected file media classes must be valid and unique.");let t=[...e].sort((s,o)=>Vp.indexOf(s)-Vp.indexOf(o)),n=r?.excluded_folders??[];if(n.some(s=>typeof s!="string"||!s.trim()))throw new b("invalid_file_materialization","Excluded folders cannot be empty.");let i=n.map(s=>Fn(s.trim())).sort((s,o)=>s.toLocaleLowerCase().localeCompare(o.toLocaleLowerCase()));if(i.length>100)throw new b("invalid_file_materialization","File sync supports at most 100 excluded folders.");if(new Set(i.map(s=>s.toLocaleLowerCase())).size!==i.length)throw new b("invalid_file_materialization","Excluded folders must be unique on portable filesystems.");for(let s of i)Mo(s,!0);return{file_classes:t,excluded_folders:i}}function G0(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 zN(r,e,t=G0(e)){if(!r.file_classes.includes(t))return!1;let n=(0,te.normalizePath)(e);return!r.excluded_folders.some(i=>n===i||n.startsWith(`${i}/`))}function Mo(r,e=!1){let t=Fn(r),n=t.split("/");if(t.length>1024||!e&&/\.md$/i.test(t)||n.some(i=>i.startsWith(".")||VN.has(i.toLowerCase())||/[<>"|?*]/u.test(i)||/^(?:CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu.test(i)))throw new b("invalid_file_path",`Collection file path ${t} is hidden, reserved, or non-portable.`);return t}async function Hp(r){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",r));return{size:r.byteLength,content_digest:`sha256:${Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}`}}async function Kp(r){let e=[],t=0;for await(let s of r){if(!(s instanceof Uint8Array))throw new b("file_integrity_failed","A binary stream returned an invalid chunk.");s.byteLength&&(t+=s.byteLength,ii(t),e.push(Uint8Array.from(s)))}let n=new Uint8Array(t),i=0;for(let s of e)n.set(s,i),i+=s.byteLength;return n.buffer}function V0(r){let e=r.includes(".")?r.slice(r.lastIndexOf(".")+1).toLowerCase():"";return{avif:"image/avif",gif:"image/gif",jpeg:"image/jpeg",jpg:"image/jpeg",png:"image/png",svg:"image/svg+xml",webp:"image/webp",flac:"audio/flac",m4a:"audio/mp4",mp3:"audio/mpeg",ogg:"audio/ogg",opus:"audio/opus",wav:"audio/wav",mov:"video/quicktime",mp4:"video/mp4",webm:"video/webm",pdf:"application/pdf"}[e]}async function HN(r,e){if(r!==void 0){if(!e)return JSON.stringify(r);if(r instanceof ArrayBuffer)return r;if(ArrayBuffer.isView(r))return Uint8Array.from(new Uint8Array(r.buffer,r.byteOffset,r.byteLength)).buffer;if(r instanceof Blob)return r.arrayBuffer();throw new b("invalid_file_upload","The adoption upload body was not binary data.")}}function dl(r,e){if(e!=null)return e;if(!r.trim())return{};try{return JSON.parse(r)}catch{return{}}}function J0(r){let e=r["retry-after"]??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())}async function fl(r,e=i=>(0,te.requestUrl)(i),t=(i,s)=>window.fetch(i,s),n=KN()){if(n)try{return await z0(r,n)}catch{}try{return await e(r)}catch(i){try{return await z0(r,t)}catch{throw i}}}function KN(){try{if(typeof require!="function")return null;let r=require("electron").remote?.net;return r?.fetch?r.fetch.bind(r):null}catch{return null}}async function z0(r,e){let t=new Headers(r.headers);r.contentType&&!t.has("content-type")&&t.set("content-type",r.contentType);let n=await e(r.url,{method:r.method,headers:t,body:r.body}),i=await n.arrayBuffer(),s=new TextDecoder().decode(i),o=null;if(s.trim())try{o=JSON.parse(s)}catch{o=null}if(r.throw!==!1&&n.status>=400)throw new Error(`Request failed with status ${n.status}`);let a={};return n.headers.forEach((c,l)=>{a[l]=c}),{status:n.status,headers:a,arrayBuffer:i,json:o,text:s}}function WN(){return async r=>{if(r.signal?.aborted)throw new DOMException("Enrollment cancelled.","AbortError");let e=await fl({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(r.signal?.aborted)throw new DOMException("Enrollment cancelled.","AbortError");return{status:e.status,body:dl(e.text,e.json),retryAfterMs:J0(e.headers)}}}function GN(){return async r=>{if(r.signal?.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");let e=await HN(r.body,r.rawBody),t=await fl({url:r.url,method:r.method,headers:r.headers,body:e,contentType:e===void 0||r.rawBody?void 0:"application/json",throw:!1});if(r.signal?.aborted)throw new DOMException("Collection adoption cancelled.","AbortError");return{status:t.status,body:dl(t.text,t.json),retryAfterMs:J0(t.headers),headers:t.headers}}}var Wp=class{constructor(e,t,n=fl,i){this.accessToken=t;this.send=n;this.onFileProgress=i;let s;try{s=new URL(e)}catch{throw new b("invalid_sync_url","Sync URL must be an absolute authority endpoint.")}if(!(s.protocol==="https:"||s.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(s.hostname))||s.username||s.password||s.search||s.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(s.pathname))throw new b("invalid_sync_url","Sync URL must identify one authority sync endpoint.");this.syncUrl=s.href.replace(/\/$/,""),this.filesUrl=this.syncUrl.replace(/\/sync$/u,"/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){ii(e.size);let t=crypto.randomUUID();try{let n=0;this.onFileProgress?.({direction:"download",path:e.path,transferredBytes:n,totalBytes:e.size});let i=await this.fileRequest("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:t,file_id:e.file_id,revision:e.revision});if(i.protocol_version!==1||i.type!=="file_transfer"||i.transfer_id!==t||i.direction!=="download"||i.protection!=="transport_tls"||i.total_size!==e.size||i.strategy.kind!=="object_ranges"||!Number.isSafeInteger(i.strategy.part_size)||i.strategy.part_size<=0)throw new b("invalid_sync_response","The authority returned an incompatible file download session.");let s=Math.ceil(e.size/i.strategy.part_size);for(let o=0;o=300)throw this.responseError(c,"file_download_failed");let l=H0(c.headers,"content-length");if(l!==void 0&&Number(l)!==a||c.arrayBuffer.byteLength!==a)throw new b("file_integrity_failed","Hosted authority returned a file part with the wrong length.");n+=a,this.onFileProgress?.({direction:"download",path:e.path,transferredBytes:n,totalBytes:e.size}),a&&(yield new Uint8Array(c.arrayBuffer))}}finally{await this.fileRequest("DELETE",`transfers/${encodeURIComponent(t)}`).catch(()=>{})}}async uploadFile(e,t){ii(e.size);let n=await this.fileRequest("POST","uploads",e);if(n.protocol_version!==1||n.type!=="file_transfer"||n.transfer_id!==e.transfer_id||n.direction!=="upload"||n.protection!=="transport_tls"||n.total_size!==e.size||!["object_put","object_multipart"].includes(n.strategy.kind))throw new b("invalid_sync_response","Authority returned an incompatible file upload session.");let i=n.strategy.kind==="object_multipart"?n.strategy.part_size:Math.max(1,e.size);if(!Number.isSafeInteger(i)||i<=0)throw new b("invalid_sync_response","Authority returned an invalid upload part size.");let s=new Gp(t),o=Math.max(1,Math.ceil(e.size/i));if(n.received.some(d=>!Number.isSafeInteger(d)||d<0||d>=o)||new Set(n.received).size!==n.received.length)throw new b("invalid_sync_response","Authority returned invalid upload progress.");let a=n.uploaded_parts??[];if(a.some((d,f)=>!Number.isSafeInteger(d.part_number)||d.part_number<1||d.part_number>o||!d.etag||d.etag.length>255||f>0&&a[f-1].part_number>=d.part_number)||(n.strategy.kind==="object_multipart"?a.length!==n.received.length||a.some((d,f)=>d.part_number-1!==n.received[f]):a.length!==0))throw new b("invalid_sync_response","Authority returned invalid uploaded part receipts.");let c=n.received.reduce((d,f)=>{let p=f*i;return d+Math.min(i,Math.max(0,e.size-p))},0);if(this.onFileProgress?.({direction:"upload",path:e.path,transferredBytes:c,totalBytes:e.size}),n.received.length===o)return this.commitUpload(e.transfer_id,a);let l=new Set(n.received),u=Array.from({length:o},()=>{});for(let d of a)u[d.part_number-1]=d;for(let d=0;d=300)throw new b("file_upload_failed",`Object storage returned HTTP ${y.status}.`);if(c+=p,this.onFileProgress?.({direction:"upload",path:e.path,transferredBytes:c,totalBytes:e.size}),n.strategy.kind==="object_multipart"){let g=H0(y.headers,"etag");if(!g)throw new b("invalid_sync_response","Object storage omitted a multipart ETag.");u[d]={part_number:d+1,etag:g}}}return await s.expectEnd(),this.commitUpload(e.transfer_id,u.filter(d=>d!==void 0))}async commitUpload(e,t){let n=await this.fileRequest("POST",`uploads/${encodeURIComponent(e)}/commit`,{protocol_version:1,type:"commit_file_upload",transfer_id:e,parts:t});if(n.protocol_version!==1||n.type!=="file_upload_committed"||n.transfer_id!==e)throw new b("invalid_sync_response","Authority returned an invalid file upload receipt.");return n}async moveFile(e){let t=await this.fileRequest("POST",`${encodeURIComponent(e.file_id)}/move`,e);if(t.protocol_version!==1||t.type!=="file_moved"||t.mutation_id!==e.mutation_id)throw new b("invalid_sync_response","Authority returned an invalid file move receipt.");return t}async deleteFile(e){let t=await this.fileRequest("POST",`${encodeURIComponent(e.file_id)}/delete`,e);if(t.protocol_version!==1||t.type!=="file_deleted"||t.mutation_id!==e.mutation_id||t.file_id!==e.file_id)throw new b("invalid_sync_response","Authority returned an invalid file delete receipt.");return t}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){return this.requestAt(this.syncUrl,e,t,n)}async fileRequest(e,t,n){return this.requestAt(this.filesUrl,e,t,n)}async requestAt(e,t,n,i){let s=await this.send({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=dl(s.text,s.json);if(s.status<200||s.status>=300)throw this.responseError(s,"sync_failed");return o}responseError(e,t){let n=dl(e.text,e.json),i=ot(n)&&ot(n.error)?n.error:{};return new b(typeof i.code=="string"?i.code:t,typeof i.message=="string"?i.message:`Sync request failed (${e.status}).`)}},Gp=class{constructor(e){this.remainder=new Uint8Array;this.iterator=e[Symbol.asyncIterator]()}async read(e){let t=new Uint8Array(new ArrayBuffer(e)),n=0;for(;n!["authorization","cookie","host","proxy-authorization","content-length"].includes(e.toLowerCase())))}function H0(r,e){return Object.entries(r).find(([n])=>n.toLowerCase()===e.toLowerCase())?.[1]}function Y0(r){return[r.configDir||".obsidian",...BN].map(t=>(0,te.normalizePath)(t).replace(/\/+$/,""))}function ni(r,e){let t=Fn(e);if(Y0(r).some(n=>t===n||t.startsWith(`${n}/`)))throw new b("unsafe_mirror_path",`The collection authority attempted to write a reserved path: ${t}`);return t}function Se(r){if(r?.aborted)throw new DOMException("Synchronization cancelled.","AbortError")}function vt(r,e){return r??new Error(`IndexedDB ${e} failed without an error detail.`)}function QN(r,e){let t=async a=>{Se(e);let c=await a();return Se(e),c},n=async function*(a){for await(let c of a)Se(e),yield c;Se(e)},i=r.uploadFile?.bind(r),s=r.moveFile?.bind(r),o=r.deleteFile?.bind(r);return{openSession:()=>t(()=>r.openSession()),snapshot:(a,c)=>t(()=>r.snapshot(a,c)),fileSnapshot:(a,c)=>t(()=>r.fileSnapshot(a,c)),downloadFile:a=>n(r.downloadFile(a)),...i?{uploadFile:(a,c)=>t(()=>i(a,n(c)))}:{},...s?{moveFile:a=>t(()=>s(a))}:{},...o?{deleteFile:a=>t(()=>o(a))}:{},changes:(a,c)=>t(()=>r.changes(a,c)),mutate:a=>t(()=>r.mutate(a))}}async function rs(r,e){let t=(0,te.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 te.TFolder)){if(s)throw new b("mirror_path_collision",`A file blocks the mirror folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}var Jp=class{constructor(e,t=i=>e.delete(i,!0),n=()=>{}){this.vault=e;this.trashFile=t;this.assertActive=n}async exists(e){let t=ni(this.vault,e);return this.vault.getAbstractFileByPath(t)!==null||await this.vault.adapter.exists(t)}async read(e){let t=await this.readText(e);if(t===null||typeof t=="string")return t;throw new b(t.code,t.reason)}async readText(e){let t=ni(this.vault,e);if(this.vault.getAbstractFileByPath(t)instanceof te.TFolder)throw new b("mirror_path_collision",`Expected a file at ${t}.`);let i;try{i=await this.vault.adapter.readBinary(t)}catch{try{if(!await this.vault.adapter.exists(t))return null}catch{}throw new b("file_read_failed",`Could not read ${t}.`)}try{return new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{return{kind:"invalid",code:"invalid_utf8",reason:"File is not valid UTF-8.",revision:(await Hp(i)).content_digest}}}async write(e,t){let n=ni(this.vault,e),i=n.lastIndexOf("/");i>=0&&await rs(this.vault,n.slice(0,i));let s=this.vault.getAbstractFileByPath(n);if(s instanceof te.TFolder)throw new b("mirror_path_collision",`A folder blocks the mirror file ${n}.`);this.assertActive(),s instanceof te.TFile?await this.vault.modify(s,t):await this.vault.create(n,t)}async move(e,t){let n=ni(this.vault,e),i=ni(this.vault,t),s=this.vault.getAbstractFileByPath(n);if(!(s instanceof te.TFile))throw new b("mirror_path_collision",`Expected a file at ${n}.`);if(this.vault.getAbstractFileByPath(i)!==null||await this.vault.adapter.exists(i))throw new b("mirror_path_collision",`A file or folder blocks the mirror path ${i}.`);let o=i.lastIndexOf("/");o>=0&&await rs(this.vault,i.slice(0,o)),this.assertActive(),await this.vault.rename(s,i)}async remove(e){let t=ni(this.vault,e),n=this.vault.getAbstractFileByPath(t);if(n!=null){if(!(n instanceof te.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);this.assertActive(),await this.trashFile(n)}}async listMarkdown(e){return this.vault.getMarkdownFiles().map(t=>(0,te.normalizePath)(t.path)).filter(t=>!e.has(t)).filter(t=>!Y0(this.vault).some(n=>t===n||t.startsWith(`${n}/`))).sort()}async inspectBinary(e){let t=Mo(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof te.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);ii(n.stat.size);let i=await this.vault.readBinary(n);return ii(i.byteLength),Hp(i)}async writeBinary(e,t){let n=Mo(e),i=await Kp(t),s=n.lastIndexOf("/");s>=0&&await rs(this.vault,n.slice(0,s));let o=this.vault.getAbstractFileByPath(n);if(o instanceof te.TFolder)throw new b("mirror_path_collision",`A folder blocks the mirror file ${n}.`);this.assertActive(),o instanceof te.TFile?await this.vault.modifyBinary(o,i):await this.vault.createBinary(n,i)}async listBinary(e){return X0(this.vault).map(t=>(0,te.normalizePath)(t.path)).filter(t=>!/\.md$/i.test(t)&&!e.has(t)).filter(t=>{try{return Mo(t),!0}catch{return!1}}).sort()}async readBinary(e){let t=Mo(e),n=this.vault.getAbstractFileByPath(t);if(n==null)return null;if(!(n instanceof te.TFile))throw new b("mirror_path_collision",`Expected a file at ${t}.`);ii(n.stat.size);let i=new Uint8Array(await this.vault.readBinary(n));return ii(i.byteLength),(async function*(){for(let s=0;s{}),a}n&&n.stage!==i&&await this.removeStage(n.stage,n.chunks).catch(()=>{})}async remove(e){let t=await this.manifest(e);await this.delete($n,this.manifestKey(e)),t&&await this.removeStage(t.stage,t.chunks)}async prune(e){let t=await this.open(),n=await new Promise((o,a)=>{let c=[],l=t.transaction($n,"readonly").objectStore($n).openCursor();l.onsuccess=()=>{let u=l.result;if(!u)return o(c);c.push([u.key,u.value]),u.continue()},l.onerror=()=>a(vt(l.error,"manifest cursor"))}),i=new Set;for(let[o,a]of n)!Array.isArray(o)||o[0]!==this.namespace||typeof o[1]=="string"&&e.has(o[1])||(await this.delete($n,o),await this.removeStage(a.stage,a.chunks));for(let[o,a]of n)Array.isArray(o)&&o[0]===this.namespace&&typeof o[1]=="string"&&e.has(o[1])&&i.add(a.stage);let s=await new Promise((o,a)=>{let c=[],l=t.transaction(En,"readonly").objectStore(En).openKeyCursor();l.onsuccess=()=>{let u=l.result;if(!u)return o(c);let d=u.key,f=Array.isArray(d)&&typeof d[1]=="string"?d[1]:null;Array.isArray(d)&&d[0]===this.namespace&&(f===null||!i.has(f))&&c.push(d),u.continue()},l.onerror=()=>a(vt(l.error,"chunk cursor"))});for(let o of s)await this.delete(En,o)}manifest(e){return this.get($n,this.manifestKey(e))}manifestKey(e){return[this.namespace,e]}chunkKey(e,t){return[this.namespace,e,t]}async removeStage(e,t){for(let n=0;n{let o=n.transaction(e,"readonly").objectStore(e).get(t);o.onsuccess=()=>i(o.result??null),o.onerror=()=>s(vt(o.error,`read from ${e}`))})}async put(e,t,n){let i=await this.open();await new Promise((s,o)=>{let a=i.transaction(e,"readwrite");a.objectStore(e).put(n,t),a.oncomplete=()=>s(),a.onerror=()=>o(vt(a.error,`write to ${e}`)),a.onabort=()=>o(vt(a.error,`write to ${e}`))})}async delete(e,t){let n=await this.open();await new Promise((i,s)=>{let o=n.transaction(e,"readwrite");o.objectStore(e).delete(t),o.oncomplete=()=>i(),o.onerror=()=>s(vt(o.error,`delete from ${e}`)),o.onabort=()=>s(vt(o.error,`delete from ${e}`))})}close(){this.database?.then(e=>e.close(),()=>{}),this.database=null}open(){if(typeof indexedDB>"u")throw new b("storage_unavailable","IndexedDB is required for binary file sync.");return this.database??=new Promise((e,t)=>{let n=indexedDB.open(DN,1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains($n)||n.result.createObjectStore($n),n.result.objectStoreNames.contains(En)||n.result.createObjectStore(En)},n.onerror=()=>t(vt(n.error,"binary store open")),n.onsuccess=()=>e(n.result)}),this.database}},Xp=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(Sn,"readonly").objectStore(Sn).get(this.key);i.onsuccess=()=>t(i.result??null),i.onerror=()=>n(vt(i.error,"mirror state read"))})}async write(e){let t=await this.open();await new Promise((n,i)=>{let s=t.transaction(Sn,"readwrite");s.objectStore(Sn).put(e,this.key),s.oncomplete=()=>n(),s.onerror=()=>i(vt(s.error,"mirror state write")),s.onabort=()=>i(vt(s.error,"mirror state write"))})}async clear(){let e=await this.open();await new Promise((t,n)=>{let i=e.transaction(Sn,"readwrite");i.objectStore(Sn).delete(this.key),i.oncomplete=()=>t(),i.onerror=()=>n(vt(i.error,"mirror state clear")),i.onabort=()=>n(vt(i.error,"mirror state clear"))})}close(){this.database?.then(e=>e.close(),()=>{}),this.database=null}open(){if(typeof indexedDB>"u")throw new b("storage_unavailable","IndexedDB is required for persistent mirror state.");return this.database??=new Promise((e,t)=>{let n=indexedDB.open(NN,1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(Sn)||n.result.createObjectStore(Sn)},n.onerror=()=>t(vt(n.error,"mirror state store open")),n.onsuccess=()=>e(n.result)}),this.database}},Qp=class r{constructor(e){this.key=e}static{this.active=new Set}async runExclusive(e){if(r.active.has(this.key))throw new b("mirror_busy","A mirror operation is already running for this vault.");r.active.add(this.key);try{return await e()}finally{r.active.delete(this.key)}}},ul=class{constructor(e,t,n={}){this.app=e;this.settingsHost=t;this.options=n;this.disposed=!1;this.lifetime=new AbortController;this.stateStores=new Map;this.blobStores=new Map;this.progress=null;this.fileProgress=null;this.syncAbort=null;this.statusRequest=null;this.mirrorOperationTail=Promise.resolve();this.adoptionMarker=null;this.fileSystem=n.fileSystem??new Jp(e.vault,i=>e.fileManager.trashFile(i),()=>this.assertActive()),this.enrollmentClient=n.enrollmentClient??new Bc({request:WN()}),this.adoptionClient=n.adoptionClient??new Gc({request:GN()})}dispose(){this.disposed=!0,this.lifetime.abort(),this.cancelSync();for(let e of this.stateStores.values())e.close();for(let e of this.blobStores.values())e.close();this.stateStores.clear(),this.blobStores.clear()}async withLifetime(e,t){this.assertActive();let n=new AbortController,i=()=>n.abort();this.lifetime.signal.addEventListener("abort",i,{once:!0}),e?.addEventListener("abort",i,{once:!0}),e?.aborted&&n.abort();try{return Se(n.signal),await t(n.signal)}finally{this.lifetime.signal.removeEventListener("abort",i),e?.removeEventListener("abort",i)}}assertActive(){if(this.disposed)throw new DOMException("Plugin unloaded.","AbortError")}async initialize(){this.adoptionMarker=await this.readAdoptionMarker();let e=this.settingsHost.getMirrorProfile();if(this.adoptionMarker&&e){if(this.adoptionMarker.phase==="adopted"&&this.adoptionMarker.session.requested.collectionId===e.collectionId){await this.assertMirror(e.collectionId),await this.clearAdoptionCheckpoint(this.adoptionMarker.session.adoptionId);return}throw new b("authority_adoption_state_conflict","This vault contains both an authority-adoption checkpoint and a mirror profile.")}}getProgress(){return this.progress?{...this.progress}:null}getFileProgress(){return this.fileProgress?{...this.fileProgress}:null}getAdoptionMarker(){return this.adoptionMarker?JSON.parse(JSON.stringify(this.adoptionMarker)):null}getSelectiveSync(){return xr(this.settingsHost.getMirrorProfile()?.selectiveSync??this.adoptionMarker?.selective_sync)}async configureSelectiveSync(e){let t=this.requireProfile();await this.settingsHost.saveMirrorProfile({...t,selectiveSync:xr(e)})}assertLocalAuthorityWritable(){if(this.assertActive(),this.adoptionMarker&&["fenced","activating","adopted"].includes(this.adoptionMarker.phase))throw new b("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){return this.withLifetime(t.signal,n=>this.adoptLocalCollectionActive(e,{...t,signal:n}))}async adoptLocalCollectionActive(e,t){if(this.settingsHost.getMirrorProfile())throw new b("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:zp(i),selective_sync:xr(e.selectiveSync),manifest_digest:null,source_revision:null,source_head:null}),await t.onVerification(zp(i)),this.runAdoptionWithRecovery(i,t)}async resumeAdoption(e={}){let t=this.adoptionMarker??await this.readAdoptionMarker();if(!t)throw new b("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 b("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 e.onVerification?.(zp(i)),this.withLifetime(e.signal,s=>this.runAdoptionWithRecovery(i,{...e,signal:s,onVerification:o=>e.onVerification?.(o)}))}async cancelAdoption(e){return this.withLifetime(e,t=>this.cancelAdoptionActive(t))}async cancelAdoptionActive(e){let t=this.adoptionMarker??await this.readAdoptionMarker();if(!t)return;if(["activating","adopted"].includes(t.phase))throw new b("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 b("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){return this.withLifetime(t.signal,n=>this.enrollActive(e,{...t,signal:n}))}async enrollActive(e,t){let n=await this.assertCanBecomeMirror(e.collectionId),i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,mirrorName:e.mirrorName,mode:e.mode,...n?{collectionId:n}:{}},t),s=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i,e.selectiveSync)}catch(o){if(s)try{await this.app.vault.adapter.remove(ts)}catch{throw new b("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 this.withMirrorOperation(async()=>{let e=this.requireProfile();await this.assertMirror(e.collectionId);let t=await this.createMirror();return B0(await t.inspect())})}async status(){if(this.statusRequest)return this.statusRequest;let e=this.readStatus();this.statusRequest=e;try{return await e}finally{this.statusRequest===e&&(this.statusRequest=null)}}async readStatus(){return this.withMirrorOperation(async()=>{let e=this.settingsHost.getMirrorProfile();return e?(await this.assertMirror(e.collectionId),(await this.createMirror()).status()):null})}async reconnect(){let e=this.requireProfile(),t=this.app.secretStorage.getSecret(this.refreshSecretId(e.collectionId));if(!t)throw new b("mirror_credentials_missing","The mirror refresh credential is missing. Approve this vault again.");let n=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:this.app.secretStorage.getSecret(this.accessSecretId(e.collectionId))??"",refreshCredential:t,accessTokenExpiresAt:e.accessTokenExpiresAt});await this.persistEnrollment(n,e.selectiveSync);let i=await this.status();if(!i)throw new b("mirror_not_configured","The renewed mirror profile could not be loaded.");return i}async reauthorize(e){return this.withLifetime(e.signal,t=>this.reauthorizeActive({...e,signal:t}))}async reauthorizeActive(e){let t=this.requireProfile(),n=this.stateStoreFor(t),i=await n.read();if(i?.batch)throw new b("mirror_recovery_required","Resume the durable synchronization checkpoint before approving this vault again.");let s=await this.enrollmentClient.enroll({controlUrl:t.controlUrl,mirrorName:t.name,mode:t.mode,collectionId:t.collectionId},e);if(s.collectionId!==t.collectionId)throw new b("mirror_identity_conflict","Connect approved a different collection. The existing mirror was not changed.");let o=K0(s,t.selectiveSync);i&&s.replicaId!==t.replicaId&&await this.stateStoreFor(o).write({...i,replica_id:s.replicaId}),await this.persistEnrollment(s,t.selectiveSync),s.replicaId!==t.replicaId&&"clear"in n&&typeof n.clear=="function"&&await n.clear();let a=await this.status();if(!a)throw new b("mirror_not_configured","The reauthorized mirror profile could not be loaded.");return a}async conflictComparison(e){let t=this.requireProfile(),n=await this.transportFor(t),i=await n.openSession(),s={state:"absent"};if(e.entity==="record"){let l;do{let u=await n.snapshot(i.snapshot_id,l),d=u.records.find(f=>f.record_id===e.object_id);if(d){s={state:"exact",path:d.path,revision:d.revision,size:new TextEncoder().encode(d.document).byteLength,document:d.document};break}l=u.next_page}while(l)}else{let l;do{let u=await n.fileSnapshot(i.snapshot_id,l),d=u.files.find(f=>f.file_id===e.object_id);if(d){s={state:"exact",path:d.path,revision:d.content_digest,size:d.size,modifiedAt:d.modified_at};break}l=u.next_page}while(l)}let o=e.path??s.path,a={state:"absent"};if(o){let l=this.app.vault.getAbstractFileByPath(o);if(l instanceof te.TFile)if(e.entity==="record"){let u=await this.app.vault.cachedRead(l);a={state:"exact",path:o,size:new TextEncoder().encode(u).byteLength,modifiedAt:l.stat?.mtime?new Date(l.stat.mtime).toISOString():void 0,document:u}}else{let u=await this.fileSystem.inspectBinary(o);u&&(a={state:"exact",path:o,revision:u.content_digest,size:u.size,modifiedAt:l.stat?.mtime?new Date(l.stat.mtime).toISOString():void 0,resourceUrl:this.app.vault.getResourcePath(l)})}}if(!(await this.status())?.conflicts.some(l=>l.object_id===e.object_id&&l.decision_id===e.decision_id))throw new b("conflict_decision_stale","This file changed again while its versions were loading.");return{entity:e.entity,objectId:e.object_id,decisionId:e.decision_id,local:a,remote:s}}async preserveConflictCopy(e){let t=ni(this.app.vault,e),n=this.app.vault.getAbstractFileByPath(t);if(!(n instanceof te.TFile))throw new b("mirror_conflict_copy_missing",`No local file exists at ${t}.`);let i=n.extension?`.${n.extension}`:"",s=i?t.slice(0,-i.length):t,o=`${s} (local conflict copy)${i}`,a=2;for(;this.app.vault.getAbstractFileByPath(o)||await this.app.vault.adapter.exists(o);)o=`${s} (local conflict copy ${a})${i}`,a+=1;return await this.app.vault.adapter.copy(t,o),o}async disconnect(e){if(this.isSyncing())throw new b("mirror_busy","Stop the current synchronization before disconnecting.");let t=this.requireProfile(),n=this.stateStoreFor(t),i=await n.read();if(i?.batch)throw new b("mirror_recovery_required","Resume the durable synchronization checkpoint before disconnecting.");let s={removed:[],preserved:[]},o=await this.readMarker();o&&await this.app.vault.adapter.remove(ts);try{await this.settingsHost.saveMirrorProfile(null)}catch(a){throw o&&await this.markMirror(t.collectionId),a}return this.app.secretStorage.setSecret(this.accessSecretId(t.collectionId),""),this.app.secretStorage.setSecret(this.refreshSecretId(t.collectionId),""),"clear"in n&&typeof n.clear=="function"&&await n.clear(),await this.blobStoreFor(t).prune(new Set),e&&i&&await this.removeExactMirrorFiles(i,s),s}async sync(e,t,n){if(this.syncAbort)throw new b("mirror_busy","Synchronization is already running for this vault.");let i=new AbortController;this.syncAbort=i;try{return await this.withMirrorOperation(async()=>{let o=await(await this.createMirror(a=>{Se(i.signal),this.progress=a,t?.({...a})},i.signal,a=>{Se(i.signal),this.fileProgress=a,n?.({...a})})).apply(e.plan,{signal:i.signal});return Se(i.signal),o})}finally{this.progress=null,this.fileProgress=null,this.syncAbort=null}}cancelSync(){this.syncAbort?.abort()}isSyncing(){return this.syncAbort!==null}async resolveConflict(e,t,n){return this.withMirrorOperation(async()=>{let i=await this.createMirror();return await i.resolveConflict(e,t,n),i.status()})}async withMirrorOperation(e){let t=this.mirrorOperationTail,n;this.mirrorOperationTail=new Promise(i=>{n=i}),await t;try{return this.assertActive(),await e()}finally{n()}}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 b("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,this.adoptionUploadOptions(e,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,t.signal);await this.updateAdoptionPhase("uploading"),await this.adoptionClient.uploadSnapshot(e,s,o,this.adoptionUploadOptions(e,t));let a=await this.captureAuthoritySnapshot(e.requested.collectionId,t.signal);await this.writeAdoptionSnapshot(a),await this.updateAdoptionPhase("fenced",a);let c=await this.requirePreparedAdoption(e,t);await this.adoptionClient.uploadSnapshot(e,c,a,this.adoptionUploadOptions(e,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 ZN(n)?(await this.adoptionClient.cancel(e,{signal:t.signal}).catch(()=>{}),await this.clearAdoptionCheckpoint(e.adoptionId),new b(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 qr("Hosted authority activation has already started. Resume using the saved fenced snapshot."):new b("authority_adoption_already_completed","Hosted authority has already adopted this collection.")}async finishRetainedMirror(e,t,n){let i,s=this.adoptionClient.mirrorEnrollmentSession(e,t);if(!s)throw new b("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:a=>n.onStatus?.({...a,state:a.state})})}catch(a){if(n.signal?.aborted)throw a;i=await this.enrollmentClient.enroll({controlUrl:e.controlUrl,collectionId:e.requested.collectionId,mirrorName:e.requested.mirrorName??e.requested.sourceName,mode:"read_write"},{signal:n.signal,onVerification:c=>n.onVerification(c)})}let o=await this.markMirror(i.collectionId);try{await this.persistEnrollment(i,this.adoptionMarker?.selective_sync)}catch(a){throw o&&await this.app.vault.adapter.remove(ts),a}return await this.clearAdoptionCheckpoint(e.adoptionId),this.requireProfile()}async captureAuthoritySnapshot(e,t){Se(t);let n=await Ii(this.app.vault);if(Se(t),!n)throw new b("invalid_collection_configuration","A valid mdbase.yaml is required.");let i=await this.app.vault.adapter.read("mdbase.yaml");Se(t);let s=(0,te.parseYaml)(i),o=[{path:"mdbase.yaml",kind:"configuration",document:i}],a=`${(0,te.normalizePath)(n.settings.types_folder)}/`,c=this.app.vault.getMarkdownFiles().filter(p=>(0,te.normalizePath)(p.path).startsWith(a)).sort((p,m)=>p.path.localeCompare(m.path));for(let p of c)Se(t),o.push({path:(0,te.normalizePath)(p.path),kind:"type",document:await this.app.vault.cachedRead(p)}),Se(t);let l=eD(s);if(l.length){let p=l.map(h=>(0,W0.default)(h,{dot:!0})),m=X0(this.app.vault).filter(h=>h.extension==="base").filter(h=>p.some(y=>y((0,te.normalizePath)(h.path)))).sort((h,y)=>h.path.localeCompare(y.path));for(let h of m)Se(t),o.push({path:(0,te.normalizePath)(h.path),kind:"view",document:await this.app.vault.cachedRead(h)}),Se(t)}let u=[];for(let p of this.app.vault.getMarkdownFiles().sort((m,h)=>m.path.localeCompare(h.path))){Se(t);let m=(0,te.normalizePath)(p.path);if(Ti(m,n))continue;let h=await this.app.vault.cachedRead(p);Se(t),u.push({path:m,document:h})}let d=[],f=xr(this.adoptionMarker?.selective_sync);if(f.file_classes.length){let p=this.adoptionBlobStore(e),m=(await this.fileSystem.listBinary?.(new Set(o.map(h=>h.path)))??[]).filter(h=>zN(f,h)).filter(h=>!Ti(h,n));for(let h of m){Se(t);let y=await this.fileSystem.readBinary?.(h);if(Se(t),!y)continue;let g=await Kp(y);Se(t);let _=await Hp(g);Se(t),await p.write(_.content_digest,(async function*(){yield new Uint8Array(g)})()),Se(t);let v=this.app.vault.getAbstractFileByPath(h);d.push({file_id:Wc(e,`file:${h}`),path:h,revision:_.content_digest,..._,...V0(h)?{media_type:V0(h)}:{},media_class:G0(h),modified_at:new Date(v instanceof te.TFile&&v.stat?.mtime?v.stat.mtime:Date.now()).toISOString()})}}return Se(t),Ap({collectionId:e,sourceHead:0,specVersion:n.spec_version,resources:o,records:u,files:d})}adoptionBlobStore(e){return this.options.adoptionBlobStoreFactory?.(e)??this.cachedBlobStore(`adoption:${e}`)}adoptionUploadOptions(e,t){let n=this.adoptionBlobStore(e.requested.collectionId);return{signal:t.signal,fileSource:async i=>Kp(n.read(i.content_digest)),onFileProgress:({file:i,transferredBytes:s,totalBytes:o})=>t.onFileProgress?.(i.path,s,o)}}async ensurePortableCollectionIdentity(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))throw new b("collection_not_initialized","Initialize an mdbase collection before hosting it.");let e=await this.app.vault.adapter.read("mdbase.yaml"),t;try{t=(0,te.parseYaml)(e)}catch{throw new b("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!ot(t))throw new b("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let n=ot(t["x-mdbase-connect"])?t["x-mdbase-connect"].collection_id:void 0,i;if(n===void 0){i=crypto.randomUUID();let o=ot(t["x-mdbase-connect"])?t["x-mdbase-connect"]:{};t["x-mdbase-connect"]={...o,collection_id:i},this.assertActive(),await this.app.vault.adapter.write("mdbase.yaml",(0,te.stringifyYaml)(t))}else if(typeof n=="string"&&Io.test(n))i=n;else throw new b("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}}stateStoreFor(e){if(this.assertActive(),this.options.stateStoreFactory)return this.options.stateStoreFactory(e);let t=`${e.collectionId}:${e.replicaId}`,n=this.stateStores.get(t);return n||(n=new Xp(t),this.stateStores.set(t,n)),n}cachedBlobStore(e){this.assertActive();let t=this.blobStores.get(e);return t||(t=new Yp(e),this.blobStores.set(e,t)),t}blobStoreFor(e){return this.options.blobStoreFactory?.(e)??this.cachedBlobStore(`${e.collectionId}:${e.replicaId}`)}async transportFor(e,t,n){this.assertActive();let i=await this.freshAccessToken(e);this.assertActive();let s=this.options.transportFactory?.(e,i)??new Wp(e.syncUrl,i,fl,n);return QN(s,t)}async createMirror(e,t,n){let i=this.requireProfile();await this.assertMirror(i.collectionId);let s=await this.transportFor(i,t,n),o={stateStore:this.stateStoreFor(i),fileSystem:this.fileSystem,blobStore:this.blobStoreFor(i),selectiveSync:xr(i.selectiveSync),lease:this.options.leaseFactory?.(i)??new Qp(`${i.collectionId}:${i.replicaId}`),onProgress:e};return i.mode==="read_write"?new ko(i.replicaId,s,o):new ri(i.replicaId,s,o)}requireProfile(){this.assertActive();let e=this.settingsHost.getMirrorProfile();if(!e)throw new b("mirror_not_configured","This vault is not connected to a collection authority.");return e}accessSecretId(e){return`${jN}${e.toLowerCase()}`}refreshSecretId(e){return`${qN}${e.toLowerCase()}`}adoptionSecretId(e){return`${FN}${e.toLowerCase()}`}async storeAdoptionSecret(e){this.app.secretStorage.setSecret(this.adoptionSecretId(e.adoptionId),e.credential)}async persistEnrollment(e,t){this.assertActive(),this.app.secretStorage.setSecret(this.accessSecretId(e.collectionId),e.accessToken),this.app.secretStorage.setSecret(this.refreshSecretId(e.collectionId),e.refreshCredential),await this.settingsHost.saveMirrorProfile(K0(e,t??this.settingsHost.getMirrorProfile()?.selectiveSync))}async removeExactMirrorFiles(e,t){let n=new Map;for(let[i,s]of Object.entries(e.records)){let o=e.local_bindings?.[i]?.path??s.path;n.set(o,{entity:"document",document:s.record?.document,revision:s.revision})}for(let[i,s]of Object.entries(e.resources??{})){let o=e.local_bindings?.[i]?.path??s.path;n.set(o,{entity:"document",document:s.record?.document,revision:s.revision})}for(let[i,s]of Object.entries(e.files??{})){let o=e.local_bindings?.[i]?.path??s.file.path;n.set(o,{entity:"file",digest:s.file.content_digest,size:s.file.size})}for(let[i,s]of[...n.entries()].sort(([o],[a])=>a.localeCompare(o))){let o=!1;if(s.entity==="document"){let a=await this.fileSystem.read(i);o=a!==null&&(s.document!==void 0?a===s.document:await nD(a,s.revision))}else if(s.entity==="file"){let a=await this.fileSystem.inspectBinary(i);o=a!==null&&a.content_digest===s.digest&&a.size===s.size}if(!o){await this.fileSystem.exists(i)&&t.preserved.push(i);continue}try{await this.fileSystem.remove(i),t.removed.push(i)}catch{t.preserved.push(i)}}}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()>UN)return n;let s=this.app.secretStorage.getSecret(this.refreshSecretId(e.collectionId));if(!s)throw new b("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??"",refreshCredential:s,accessTokenExpiresAt:e.accessTokenExpiresAt});return await this.persistEnrollment(o,e.selectiveSync),o.accessToken}async assertCanBecomeMirror(e){let t=await this.readMarker(),n=await this.readPortableCollectionId();if(n&&!t)throw new b("local_authority_requires_transfer","This vault has a local Connect identity. Transfer authority explicitly before using it as a mirror.");if(n&&t?.collection_id!==n)throw new b("mirror_identity_conflict","The vault identity and mirror role marker identify different collections.");let i=this.settingsHost.getMirrorProfile(),s=i?.collectionId??e;if(t&&s&&t.collection_id!==s)throw new b("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 b("existing_collection_requires_transfer","This vault already contains an mdbase collection. Connect an empty vault, or transfer collection authority explicitly.");return s??t?.collection_id}async readPortableCollectionId(){if(!await this.app.vault.adapter.exists("mdbase.yaml"))return null;let e;try{e=(0,te.parseYaml)(await this.app.vault.adapter.read("mdbase.yaml"))}catch{throw new b("invalid_collection_configuration","mdbase.yaml must contain valid YAML.")}if(!ot(e))throw new b("invalid_collection_configuration","mdbase.yaml must contain a YAML mapping.");let t=e["x-mdbase-connect"];if(t===void 0)return null;if(!ot(t))throw new b("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"||!Io.test(n))throw new b("invalid_collection_configuration","x-mdbase-connect.collection_id must be a UUID string.");return n}async markMirror(e){this.assertActive();let t=await this.readMarker();if(t){if(t.collection_id!==e)throw new b("mirror_identity_conflict","This vault already mirrors a different collection authority.");return!1}return await rs(this.app.vault,".mdbase"),this.assertActive(),await this.app.vault.adapter.write(ts,`${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 b("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(ts))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(ts))}catch{throw new b("invalid_mirror_marker","The mirror role marker is corrupt.")}if(!ot(e)||e.version!==1||e.role!=="mirror"||typeof e.collection_id!="string"||!Io.test(e.collection_id))throw new b("invalid_mirror_marker","The mirror role marker is invalid.");return e}requireAdoptionMarker(e){if(!this.adoptionMarker||this.adoptionMarker.session.adoptionId!==e)throw new b("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 b("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 rs(this.app.vault,".mdbase"),this.assertActive(),await this.app.vault.adapter.write(Po,`${JSON.stringify(e,null,2)} +`),this.adoptionMarker=e}async readAdoptionMarker(){if(!await this.app.vault.adapter.exists(Po))return null;let e;try{e=JSON.parse(await this.app.vault.adapter.read(Po))}catch{throw new b("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is corrupt.")}if(!tD(e))throw new b("invalid_authority_adoption_checkpoint","The collection-adoption checkpoint is invalid.");return e}async writeAdoptionSnapshot(e){this.assertActive(),await rs(this.app.vault,".mdbase"),this.assertActive(),await this.app.vault.adapter.write(Co,JSON.stringify(e))}async readAdoptionSnapshot(e){if(!await this.app.vault.adapter.exists(Co))throw new b("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(Co))}catch{throw new b("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 b("authority_adoption_snapshot_mismatch","The fenced authority snapshot does not match its durable checkpoint.");return t}async clearAdoptionCheckpoint(e){let t=this.adoptionMarker?.session.requested.collectionId;await this.app.vault.adapter.exists(Co)&&await this.app.vault.adapter.remove(Co),await this.app.vault.adapter.exists(Po)&&await this.app.vault.adapter.remove(Po),this.app.secretStorage.setSecret(this.adoptionSecretId(e),""),this.adoptionMarker=null,t&&await this.adoptionBlobStore(t).prune(new Set).catch(()=>{})}};function zp(r){let{credential:e,...t}=r;return t}function ZN(r){return r instanceof K&&["authority_adoption_expired","authority_adoption_cancelled"].includes(r.code)}function eD(r){if(!ot(r))return[];let e=r["x-obsidian"];return!ot(e)||!ot(e.bases)||!Array.isArray(e.bases.include)?[]:e.bases.include.filter(t=>typeof t=="string")}function X0(r){let e=r.getFiles?.();if(e)return e;let t=[],n=i=>{for(let s of i.children)s instanceof te.TFile?t.push(s):s instanceof te.TFolder&&n(s)};return n(r.getRoot()),t}function tD(r){if(!ot(r)||r.version!==1||!["waiting_for_approval","uploading","fenced","activating","adopted"].includes(String(r.phase))||!ot(r.session))return!1;let e=r.session;return typeof e.controlUrl=="string"&&typeof e.adoptionId=="string"&&Io.test(e.adoptionId)&&typeof e.verificationUri=="string"&&typeof e.expiresAt=="string"&&ot(e.requested)&&typeof e.requested.collectionId=="string"&&Io.test(e.requested.collectionId)&&typeof e.requested.displayName=="string"&&typeof e.requested.sourceName=="string"&&e.requested.retainMirror===!0&&(r.selective_sync===void 0||rD(r.selective_sync))&&(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))}function rD(r){if(!ot(r)||!Array.isArray(r.file_classes)||!Array.isArray(r.excluded_folders))return!1;try{let e=xr(r);return e.file_classes.length===r.file_classes.length&&e.excluded_folders.length===r.excluded_folders.length}catch{return!1}}function K0(r,e){return{version:1,syncUrl:r.syncUrl,controlUrl:r.controlUrl,collectionId:r.collectionId,replicaId:r.replicaId,mode:r.mode,name:r.name,enrollmentId:r.enrollmentId,accessTokenExpiresAt:r.accessTokenExpiresAt,selectiveSync:xr(e)}}async function nD(r,e){if(!e?.startsWith("sha256:"))return!1;let t=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r)));return`sha256:${Array.from(t,i=>i.toString(16).padStart(2,"0")).join("")}`===e}var at=require("obsidian");var No="0.3.0",iD=new Set(["name","description","display_name_key","strict","path_pattern","filename_pattern","match","fields","extends"]),sD=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 _e(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Pe(r){return r===void 0?r:JSON.parse(JSON.stringify(r))}function Hr(r){return So.digest(r)}function si(r){return Array.isArray(r)?`[${r.map(si).join(",")}]`:_e(r)?`{${Object.keys(r).sort().map(e=>`${JSON.stringify(e)}:${si(r[e])}`).join(",")}}`:JSON.stringify(r)}function Zp(r){if(Array.isArray(r))return r.map(Zp);if(!_e(r))return r;let e={};for(let[t,n]of Object.entries(r)){let i=Zp(n);i!=null&&(Array.isArray(i)&&i.length===0||_e(i)&&Object.keys(i).length===0||(e[t]=i))}return e}function ns(r){return[...new Set(r)]}function oD(r){return _e(r.fields)?Object.values(r.fields).some(e=>_e(e)&&(typeof e.tn_role=="string"||Array.isArray(e.tn_completed_values))):!1}function eh(r,e,t){let n=_e(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)?Pe(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=eh(`${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(_e(n.fields)?n.fields:{})){let f=eh(`${r}.${u}`,d,t);c[u]=f.schema,Object.assign(i,f.links),Object.assign(s,f.legacy),o.push(...f.unsupported),_e(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:ns(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"&&(n.type==="list"?a.minItems=n.min_length:a.minLength=n.min_length),typeof n.max_length=="number"&&(n.type==="list"?a.maxItems=n.max_length: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=Pe(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");(!sD.has(c)||(c==="tn_role"||c==="tn_completed_values")&&!u)&&(s[`${r}.${c}`]=Pe(l))}return{schema:a,links:i,legacy:s,unsupported:o}}function To(r,e,t,n){let i=_e(r[e])?r[e]:{},s=_e(i.set)?i.set:{};s[t]=n,i.set=s,r[e]=i}function aD(r,e,t){if(t==="now")To(r,"on_create",e,{now:!0});else if(t==="now_on_write")To(r,"on_update",e,{now:!0});else if(t==="uuid")To(r,"on_create",e,{uuid:!0});else if(t==="ulid")To(r,"on_create",e,{ulid:!0});else if(_e(t)&&t.transform==="slugify"&&typeof t.from=="string")To(r,"on_create",e,{slugify:t.from});else return!1;return!0}function cD(r){let e=r.match(/^(.*\/)?\{title\}\.md$/);return e?{runtime:"tasknotes",template:"{{title}}",folder:(e[1]??"").replace(/\/$/,""),generated_by:"tasknotes.filename.create"}:{runtime:"tasknotes",template:r,generated_by:"tasknotes.filename.create"}}function lD(r,e,t){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"||!_e(t.fields))throw new Error(`${r} is not a v0.2 type with a name and fields.`);let n=oD(t),i=t.name.trim().toLowerCase(),s={type:{const:i}},o=[],a={},c={},l=[],u={},d={},f=[],p=[],m={},h={},y={};for(let[x,C]of Object.entries(t.fields)){let $=_e(C)?C:{},M=eh(x,$,n);s[x]=M.schema,Object.assign(c,M.links),Object.assign(d,M.legacy),f.push(...M.unsupported),$.required===!0&&o.push(x),$.default!==void 0&&(a[x]=Pe($.default)),$.unique===!0&&l.push({field:x,scope:"collection"}),$.generated!==void 0&&(aD(u,x,$.generated)?p.push(x):(d[`${x}.generated`]=Pe($.generated),f.push(`${x}.generated`))),typeof $.tn_role=="string"&&(m[$.tn_role]=x),Array.isArray($.tn_completed_values)&&(h.completed_values=Pe($.tn_completed_values))}a.status!==void 0&&(h.default=Pe(a.status)),a.priority!==void 0&&(y.default=Pe(a.priority));let g=typeof t.display_name_key=="string"&&Object.prototype.hasOwnProperty.call(t.fields,t.display_name_key)?t.display_name_key:void 0,_={...g?{display:{name_field:g}}:{},read_defaults:a,links:c,unique:l};typeof t.path_pattern=="string"&&(_.path=n?cD(t.path_pattern):{pattern:t.path_pattern});let v={};for(let[x,C]of Object.entries(t))iD.has(x)||(v[x]=Pe(C));Object.keys(d).length&&(v.fields=d);let w=Zp({kind:"mdbase.type",name:i,version:1,description:typeof t.description=="string"?t.description:void 0,match:_e(t.match)?Pe(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:ns(o)}:{}}},collection:_,lifecycle:u,...n?{"x-tasknotes":{contract:"tasknotes.task",version:1,field_roles:m,status:h,priority:y,archive:{tags_field:m.tags??"tags",archived_tag:"archived"}}}:{},...Object.keys(v).length?{"x-legacy-v0.2":v}:{}}),S=[];t.extends!==void 0&&f.push("extends");for(let x of ns(f).sort())S.push({path:r,code:"migration_lossy",message:`${x} cannot be expressed as canonical v0.3 write behavior and was retained as legacy metadata where possible.`,severity:"lossy"});return n&&S.push({path:r,code:"path_policy_runtime_owned",message:"TaskNotes filename behavior is recorded as TaskNotes runtime metadata.",severity:"warning"}),t.strict!==!0&&S.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"&&!g&&S.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:w,summary:{path:r,name:i,fieldsConverted:Object.keys(t.fields).length,requiredFields:ns(o),defaultsMoved:Object.keys(a),generatedFieldsMoved:ns(p),linksMoved:Object.keys(c),taskNotes:n},diagnostics:S}}function dD(r){let e=Pe(r);e.spec_version=No;let t=_e(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=ns(["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 Q0(r,e){let t=_e(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 uD(r,e){let t={};for(let[n,i]of Object.entries(_e(e.fields)?e.fields:{}))_e(i)&&(t[n]=Pe(i));return{name:typeof e.name=="string"?e.name:r.split("/").pop()?.replace(/\.md$/,"")??"type",fields:t,match:_e(e.match)?Pe(e.match):void 0,filePath:r,specProfile:"v0.2"}}function fD(r,e){let t=_e(e.schema)?e.schema:{},n=_e(t.value)?t.value:{};return{name:typeof e.name=="string"?e.name:r.split("/").pop()?.replace(/\.md$/,"")??"type",fields:Un(n),match:_e(e.match)?Pe(e.match):void 0,collection:_e(e.collection)?Pe(e.collection):void 0,schema:Pe(n),filePath:r,specProfile:"v0.3"}}function pD(r,e,t){let n=Pe(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]=Pe(a.default))}return n}function hD(r,e,t){let n=Pe(r);for(let i of e){let s=t.get(i);if(s)for(let[o,a]of Object.entries(s.collection?.read_defaults??{}))o in n||(n[o]=Pe(a))}return n}async function mD(r,e){let t=(0,at.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 at.TFolder)){if(s)throw new Error(`A file blocks folder ${n}.`);await r.adapter.exists(n)||await r.createFolder(n)}}}async function pl(r,e,t){let n=(0,at.normalizePath)(e),i=n.lastIndexOf("/");if(i>=0&&await mD(r,n.slice(0,i)),n.startsWith(".mdbase/")){await r.adapter.write(n,t);return}let s=r.getAbstractFileByPath(n);if(s instanceof at.TFolder)throw new Error(`A folder blocks file ${n}.`);s instanceof at.TFile?await r.modify(s,t):await r.create(n,t)}async function Oo(r,e){let t=(0,at.normalizePath)(e),n=r.getAbstractFileByPath(t);if(n instanceof at.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 Z0(r){let e=await Oo(r,"mdbase.yaml"),t=(0,at.parseYaml)(e);if(!_e(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===No?"This collection is already mdbase v0.3.":`Expected an mdbase v0.2.x collection, found ${JSON.stringify(n)}.`);let i=_e(t.settings)?t.settings:{},s=typeof i.types_folder=="string"?(0,at.normalizePath)(i.types_folder):"_types",o=`${s}/`,a=[],c=[],l=[],u=dD(t),d=`${(0,at.stringifyYaml)(u).trimEnd()} +`;a.push({path:"mdbase.yaml",sourceDigest:Hr(e),targetDigest:Hr(d),source:e,target:d});let f=new Map,p=new Map;for(let w of r.getMarkdownFiles().filter(S=>S.path.startsWith(o)).sort((S,x)=>S.path.localeCompare(x.path))){let S=await r.cachedRead(w),x=et(S);if(!x.hasFrontmatter||x.error)throw new Error(`Cannot migrate ${w.path}: ${x.error??"frontmatter is missing"}.`);let C=lD(w.path,n,x.frontmatter),$=uD(w.path,x.frontmatter),M=fD(w.path,C.target);f.set($.name,$),p.set(M.name,M);let A=`${Vt(C.target,x.body)} +`;a.push({path:w.path,sourceDigest:Hr(S),targetDigest:Hr(A),source:S,target:A}),c.push(C.summary),l.push(...C.diagnostics)}if(!c.length)throw new Error(`No v0.2 type files were found in ${s}.`);let m=0,h=0,y=Q0(t,n),g=Q0(u,No),_=r.getMarkdownFiles().filter(w=>!w.path.startsWith(o)).filter(w=>!w.path.startsWith(".mdbase/")).sort((w,S)=>w.path.localeCompare(S.path));for(let[w,S]of _.entries()){let x=et(await r.cachedRead(S));if(x.error){h+=1;continue}let C=sn(S.path,x.frontmatter,y,f),$=sn(S.path,x.frontmatter,g,p),M=pD(x.frontmatter,C,f),A=hD(x.frontmatter,$,p);(si(C.slice().sort())!==si($.slice().sort())||si(M)!==si(A))&&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,w>0&&w%250===0&&await new Promise(W=>window.setTimeout(W,0))}let v=Hr(si({sourceVersion:n,operations:a.map(({path:w,sourceDigest:S,targetDigest:x})=>({path:w,sourceDigest:S,targetDigest:x})),diagnostics:l}));return{planVersion:1,analysisId:v,sourceVersion:n,targetVersion:No,createdAt:new Date().toISOString(),backupLocation:`.mdbase/migrations/v02-to-v03-${v.slice(0,12)}`,operations:a,typeSummaries:c,diagnostics:l,applicable:!l.some(w=>w.severity==="lossy"),recordFilesRewritten:0,recordsVerified:m,recordsSkipped:h}}async function Ro(r,e,t){await pl(r,e,`${JSON.stringify(t,null,2)} +`)}async function eS(r,e,t={}){if(e.planVersion!==1||e.targetVersion!==No)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 Oo(r,s.path);if(Hr(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 pl(r,`${e.backupLocation}/files/${s.path}`,s.source);await Ro(r,n,i),i.status="applying",await Ro(r,n,i);try{for(let s of e.operations){let o=await Oo(r,s.path);if(Hr(o)!==s.sourceDigest)throw new Error(`${s.path} changed during migration.`);i.written.push(s.path),await Ro(r,n,i),await pl(r,s.path,s.target);let a=await Oo(r,s.path);if(Hr(a)!==s.targetDigest)throw new Error(`${s.path} did not verify after write.`)}return i.status="applied",i.completed_at=new Date().toISOString(),await Ro(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 pl(r,a,c.source),Hr(await Oo(r,a))!==c.sourceDigest&&o.push(a)}catch{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 Ro(r,n,i)}catch{}return{applied:!1,restored:o.length===0,manifestPath:n,written:[...i.written],error:i.error}}}var hl=require("obsidian");function $e(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function xt(r){return JSON.parse(JSON.stringify(r))}var yD=new Set(["file","formula","this"]);function gD(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(yD.has(e.toLowerCase()))throw new Error(`Type name '${e}' is reserved.`);return e}function th(){return{specProfile:"v0.3",originalFrontmatter:{},name:"",description:"",extendsType:"",displayNameKey:"",strictMode:!1,pathPattern:"",filenamePattern:"",matchPathGlob:"",matchFieldsPresent:"",matchWhere:"",fields:[{name:"title",definition:{type:"string",required:!0}}],implementations:[],body:`# Type -Describe the type and intended usage.`,extraFrontmatter:{}}}function TN(r){return Se(r)?Object.entries(r).filter(e=>Se(e[1])).map(([e,t])=>({name:e,definition:$t(t)})):[]}function IN(r){return Array.isArray(r)?r.flatMap(e=>{if(!Se(e)||typeof e.contract!="string"||typeof e.version!="string")return[];let t=Se(e.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,i])=>typeof i=="string")):{},n=Se(e.binding)?$t(e.binding):void 0;return[{contract:e.contract,version:e.version,fields:t,...n?{binding:n}:{}}]}):[]}function RN(r){return Object.fromEntries(r.map(e=>[e.name,e.definition]))}function ON(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 al(r,e,t){let n=r.kind==="mdbase.type",i=n&&Se(r.schema)?r.schema:{},s=Se(i.value)?i.value:{},o=typeof i.ref=="string"?i.ref:"",a=n&&Se(r.collection)?r.collection:{},c=Se(a.display)?a.display:{},l=Se(a.path)?a.path:{},u=TN(n?On(s):r.fields);n&&NN(u,a.links);let d=Se(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,g]of Object.entries(r))p.has(y)||(m[y]=$t(g));let h="";if(d.where!==void 0)try{h=(0,ol.stringifyYaml)(d.where).trim()}catch{h=""}return{specProfile:n?"v0.3":"v0.2",originalFrontmatter:$t(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:Fp().fields,implementations:IN(r.implements),body:e.trim()||`# ${t} +Describe the type and intended usage.`,extraFrontmatter:{}}}function bD(r){return $e(r)?Object.entries(r).filter(e=>$e(e[1])).map(([e,t])=>({name:e,definition:xt(t)})):[]}function vD(r){return Array.isArray(r)?r.flatMap(e=>{if(!$e(e)||typeof e.contract!="string"||typeof e.version!="string")return[];let t=$e(e.fields)?Object.fromEntries(Object.entries(e.fields).filter(([,i])=>typeof i=="string")):{},n=$e(e.binding)?xt(e.binding):void 0;return[{contract:e.contract,version:e.version,fields:t,...n?{binding:n}:{}}]}):[]}function _D(r){return Object.fromEntries(r.map(e=>[e.name,e.definition]))}function wD(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 ml(r,e,t){let n=r.kind==="mdbase.type",i=n&&$e(r.schema)?r.schema:{},s=$e(i.value)?i.value:{},o=typeof i.ref=="string"?i.ref:"",a=n&&$e(r.collection)?r.collection:{},c=$e(a.display)?a.display:{},l=$e(a.path)?a.path:{},u=bD(n?Un(s):r.fields);n&&SD(u,a.links);let d=$e(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,g]of Object.entries(r))p.has(y)||(m[y]=xt(g));let h="";if(d.where!==void 0)try{h=(0,hl.stringifyYaml)(d.where).trim()}catch{h=""}return{specProfile:n?"v0.3":"v0.2",originalFrontmatter:xt(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:th().fields,implementations:vD(r.implements),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 Ji(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?$t(r.originalFrontmatter):{},t=Se(e.schema)?e.schema:{},n=Se(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]=$t(h.definition)}let s=MN(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:Bs(i,n,r.strictMode===!0)}};delete o.schema.ref,r.description.trim()?o.description=r.description.trim():delete o.description;let a=Se(o.match)?$t(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,ol.parseYaml)(r.matchWhere);if(!Se(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=Se(o.collection)?$t(o.collection):{},u=Se(l.display)?$t(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=Se(l.path)?l.path:{};l.path={...h,pattern:r.pathPattern.trim()}}else if(Se(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=Se(l.links)?$t(l.links):{},f=$t(d),p=E0(i),m=E0(On(n));for(let h of new Set([...m.selectors,...p.selectors]))delete f[h];for(let[h,y]of p.links)f[h]={...Se(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,r.implementations.length?o.implements=r.implementations.map(h=>({contract:h.contract,version:h.version,fields:$t(h.fields),...h.binding&&Object.keys(h.binding).length?{binding:$t(h.binding)}:{}})):delete o.implements;for(let h of["fields","strict","extends","display_name_key","path_pattern","filename_pattern"])delete o[h];return o}function Ur(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function A0(r){return JSON.parse(JSON.stringify(r))}function Yi(r){return`${r.id}@${r.version}`}function xo(r){let e=Ur(r.schema)?r.schema:{},t=Ur(e.properties)?e.properties:{},n=new Set(Array.isArray(e.required)?e.required.map(String):[]);return Object.entries(t).filter(i=>Ur(i[1])).map(([i,s])=>({name:i,reference:i,required:n.has(i),schema:s,...typeof s.description=="string"?{description:s.description}:{}}))}function ko(r){let e=Object.fromEntries(r.fields.map(s=>[s.name,s.definition])),t=Bs(e),n=Ur(t.properties)?t.properties:{},i=new Set(Array.isArray(t.required)?t.required.map(String):[]);return Object.entries(n).filter(s=>Ur(s[1])).map(([s,o])=>({label:s,reference:s,required:i.has(s),type:_n(o),schema:o}))}function Xi(r,e){return r.fields[e.reference]??r.fields[e.name]??""}function Po(r,e){if(!e)return r.required?{level:"error",label:"Required",message:`Map required contract field ${r.reference}.`}:{level:"unmapped",label:"Not exposed",message:"This optional contract field is not exposed."};let t=_n(r.schema);return M0(t,e.type)?r.required&&!e.required?{level:"warning",label:"Review",message:`${e.reference} is optional in this type, so the contract value may be absent.`}:{level:"valid",label:"Ready",message:"This field satisfies the contract shape."}:{level:"error",label:"Incompatible",message:`${e.reference} is ${e.type}, but the contract expects ${t}.`}}function x0(r,e){if(r.implementations.some(i=>i.contract===e.id&&i.version===e.version))throw new Error(`${e.id} ${e.version} is already implemented.`);let t=ko(r),n=Object.fromEntries(xo(e).flatMap(i=>{let s=t.find(o=>o.reference.toLowerCase()===i.reference.toLowerCase()&&M0(_n(i.schema),o.type));return s?[[i.reference,s.reference]]:[]}));r.implementations.push({contract:e.id,version:e.version,fields:n})}function k0(r,e,t){r.implementations=r.implementations.filter(n=>n.contract!==e||n.version!==t)}function P0(r,e,t){t?r.fields[e]=t:delete r.fields[e]}function Up(r,e){r.binding=Object.keys(e).length?A0(e):void 0}function Co(r){if(!r)return"";if(Array.isArray(r.enum)&&r.enum.length)return A0(r.enum[0]);let e=_n(r);if(e==="object"){let t={},n=Ur(r.properties)?r.properties:{},i=new Set(Array.isArray(r.required)?r.required.map(String):[]);for(let[s,o]of Object.entries(n))i.has(s)&&Ur(o)&&(t[s]=Co(o));return t}return e==="array"?[]:e==="boolean"?!1:e==="number"||e==="integer"?0:""}function _n(r){return"const"in r?typeof r.const:Array.isArray(r.type)?String(r.type.find(e=>e!=="null")??r.type[0]??"string"):typeof r.type=="string"?r.type:Array.isArray(r.enum)?"string":Ur(r.properties)||Ur(r.additionalProperties)?"object":"any"}function C0(r){let e=_n(r);return e==="array"?"List":e==="boolean"?"Boolean":e==="integer"?"Integer":e==="number"?"Number":e==="object"?"Object":e==="any"?"Any value":"Text"}function M0(r,e){return r==="any"||e==="any"||r===e?!0:r==="number"&&e==="integer"}function Bp(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function DN(r){return JSON.parse(JSON.stringify(r))}function Hp(r){let e=2166136261,t=2654435769;for(let n=0;n>>0).toString(36)}-${(t>>>0).toString(36)}`}function T0(r){let e=DN(r);return delete e.sourceRevision,e}function cl(r,e){return r===null||e===null?r===e:JSON.stringify(T0(r))===JSON.stringify(T0(e))}function I0(r){return new Map(r.fields.map(e=>[e.name,e]))}function Vp(r){return typeof r.type=="string"?r.type:"any"}function zp(r,e,t,n){let i=Vp(r);if(i==="enum"&&(!Array.isArray(r.values)||r.values.length===0)&&t.push({code:"enum_without_values",severity:"warning",path:e,message:"Add at least one allowed value, or use String for an unrestricted value."}),i==="link"){let s=typeof r.target=="string"?r.target.trim():"";s&&s!=="any"&&n.size&&!n.has(s)&&t.push({code:"unknown_link_target",severity:"error",path:e,message:`The target type '${s}' is not installed in this collection.`})}if(i==="list"&&(Bp(r.items)?zp(r.items,`${e}[]`,t,n):t.push({code:"list_items_missing",severity:"error",path:e,message:"Choose the shape of each list item."})),i==="object"){if(!Bp(r.fields)){t.push({code:"object_fields_missing",severity:"error",path:e,message:"Add an object field or change this field's type."});return}let s=new Set;for(let[o,a]of Object.entries(r.fields)){let c=`${e}.${o||"unnamed"}`;o.trim()?s.has(o)&&t.push({code:"duplicate_field_name",severity:"error",path:c,message:`The nested field '${o}' is declared more than once.`}):t.push({code:"field_name_required",severity:"error",path:c,message:"Every nested field needs a name."}),s.add(o),Bp(a)&&zp(a,c,t,n)}}}function ll(r,e={}){let t=[],n=new Set(e.knownTypes??[]);try{Ji(r)}catch(a){t.push({code:"invalid_type_document",severity:"error",path:"type",message:a instanceof Error?a.message:String(a)})}let i=new Set;for(let a of r.fields){let c=a.name.trim(),l=`fields.${c||"unnamed"}`;c?i.has(c)&&t.push({code:"duplicate_field_name",severity:"error",path:l,message:`The field '${c}' is declared more than once.`}):t.push({code:"field_name_required",severity:"error",path:l,message:"Every field needs a name."}),i.add(c),zp(a.definition,l,t,n)}r.displayNameKey.trim()&&!i.has(r.displayNameKey.trim())&&t.push({code:"display_field_missing",severity:"error",path:"identity.displayNameKey",message:`The display field '${r.displayNameKey.trim()}' is not declared.`});let s=new Map([...e.contracts??[]].map(a=>[Yi(a),a])),o=ko(r);for(let a of r.implementations){let c=`${a.contract}@${a.version}`,l=s.get(c);if(!l){t.push({code:"contract_unavailable",severity:"error",path:`applications.${c}`,message:"This exact application contract is not installed."});continue}for(let u of xo(l)){let d=Xi(a,u),f=o.find(m=>m.reference===d),p=Po(u,f);p.level!=="valid"&&t.push({code:p.level==="error"?"invalid_contract_mapping":"review_contract_mapping",severity:p.level==="error"?"error":"warning",path:`applications.${c}.${u.reference}`,message:p.message})}}return t.filter((a,c,l)=>l.findIndex(u=>u.code===a.code&&u.path===a.path&&u.message===a.message)===c)}function dl(r,e){if(!r)return[{code:"create_type",risk:"safe",summary:`Create the type '${e.name||"Untitled type"}'.`}];let t=[];r.name!==e.name&&t.push({code:"rename_type",risk:"high",summary:`Rename the type from '${r.name}' to '${e.name}'. Existing type references may need review.`}),(r.description!==e.description||r.displayNameKey!==e.displayNameKey)&&t.push({code:"identity",risk:"safe",summary:"Update the type's identity and display metadata."}),(r.matchPathGlob!==e.matchPathGlob||r.matchFieldsPresent!==e.matchFieldsPresent||r.matchWhere!==e.matchWhere)&&t.push({code:"membership",risk:"high",summary:"Change which records belong to this type."}),r.pathPattern!==e.pathPattern&&t.push({code:"placement",risk:"review",summary:"Change the suggested path for new records."}),r.strictMode!==e.strictMode&&t.push({code:"strictness",risk:e.strictMode===!0?"high":"review",summary:e.strictMode===!0?"Reject fields that are not declared by this type.":"Allow fields that are not declared by this type."});let n=I0(r),i=I0(e),s=[...i.keys()].filter(a=>!n.has(a)),o=[...n.keys()].filter(a=>!i.has(a));s.length&&t.push({code:"add_fields",risk:s.some(a=>i.get(a)?.definition.required===!0)?"high":"safe",summary:`Add ${s.length===1?"field":"fields"}: ${s.join(", ")}.`}),o.length&&t.push({code:"remove_fields",risk:"high",summary:`Remove ${o.length===1?"field":"fields"}: ${o.join(", ")}.`});for(let[a,c]of i){let l=n.get(a);if(!l)continue;let u=Vp(l.definition),d=Vp(c.definition);u!==d&&t.push({code:"change_field_type",risk:"high",summary:`Change '${a}' from ${u} to ${d}.`}),l.definition.required!==!0&&c.definition.required===!0&&t.push({code:"require_field",risk:"high",summary:`Make '${a}' required. Existing records may become invalid.`}),u===d&&JSON.stringify(l.definition)!==JSON.stringify(c.definition)&&l.definition.required===c.definition.required&&t.push({code:"field_rules",risk:"review",summary:`Update validation or documentation for '${a}'.`})}return JSON.stringify(r.implementations)!==JSON.stringify(e.implementations)&&t.push({code:"application_compatibility",risk:"review",summary:"Update application contract mappings or settings."}),!t.length&&!cl(r,e)&&t.push({code:"type_document",risk:"review",summary:"Update advanced type metadata or documentation."}),t}var ce=require("obsidian");var Qi="mdbase-frontmatter",R0=` +Type definition for ${t}.`,extraFrontmatter:m,...o?{readOnlyReason:`This type uses schema.ref (${o}). Edit the referenced JSON Schema file directly.`}:{}}}function is(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?xt(r.originalFrontmatter):{},t=$e(e.schema)?e.schema:{},n=$e(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]=xt(h.definition)}let s=gD(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:Hs(i,n,r.strictMode===!0)}};delete o.schema.ref,r.description.trim()?o.description=r.description.trim():delete o.description;let a=$e(o.match)?xt(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,hl.parseYaml)(r.matchWhere);if(!$e(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=$e(o.collection)?xt(o.collection):{},u=$e(l.display)?xt(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=$e(l.path)?l.path:{};l.path={...h,pattern:r.pathPattern.trim()}}else if($e(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=$e(l.links)?xt(l.links):{},f=xt(d),p=tS(i),m=tS(Un(n));for(let h of new Set([...m.selectors,...p.selectors]))delete f[h];for(let[h,y]of p.links)f[h]={...$e(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,r.implementations.length?o.implements=r.implementations.map(h=>({contract:h.contract,version:h.version,fields:xt(h.fields),...h.binding&&Object.keys(h.binding).length?{binding:xt(h.binding)}:{}})):delete o.implements;for(let h of["fields","strict","extends","display_name_key","path_pattern","filename_pattern"])delete o[h];return o}function Kr(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function rS(r){return JSON.parse(JSON.stringify(r))}function ss(r){return`${r.id}@${r.version}`}function Do(r){let e=Kr(r.schema)?r.schema:{},t=Kr(e.properties)?e.properties:{},n=new Set(Array.isArray(e.required)?e.required.map(String):[]);return Object.entries(t).filter(i=>Kr(i[1])).map(([i,s])=>({name:i,reference:i,required:n.has(i),schema:s,...typeof s.description=="string"?{description:s.description}:{}}))}function Lo(r){let e=Object.fromEntries(r.fields.map(s=>[s.name,s.definition])),t=Hs(e),n=Kr(t.properties)?t.properties:{},i=new Set(Array.isArray(t.required)?t.required.map(String):[]);return Object.entries(n).filter(s=>Kr(s[1])).map(([s,o])=>({label:s,reference:s,required:i.has(s),type:xn(o),schema:o}))}function os(r,e){return r.fields[e.reference]??r.fields[e.name]??""}function jo(r,e){if(!e)return r.required?{level:"error",label:"Required",message:`Map required contract field ${r.reference}.`}:{level:"unmapped",label:"Not exposed",message:"This optional contract field is not exposed."};let t=xn(r.schema);return aS(t,e.type)?r.required&&!e.required?{level:"warning",label:"Review",message:`${e.reference} is optional in this type, so the contract value may be absent.`}:{level:"valid",label:"Ready",message:"This field satisfies the contract shape."}:{level:"error",label:"Incompatible",message:`${e.reference} is ${e.type}, but the contract expects ${t}.`}}function nS(r,e){if(r.implementations.some(i=>i.contract===e.id&&i.version===e.version))throw new Error(`${e.id} ${e.version} is already implemented.`);let t=Lo(r),n=Object.fromEntries(Do(e).flatMap(i=>{let s=t.find(o=>o.reference.toLowerCase()===i.reference.toLowerCase()&&aS(xn(i.schema),o.type));return s?[[i.reference,s.reference]]:[]}));r.implementations.push({contract:e.id,version:e.version,fields:n})}function iS(r,e,t){r.implementations=r.implementations.filter(n=>n.contract!==e||n.version!==t)}function sS(r,e,t){t?r.fields[e]=t:delete r.fields[e]}function rh(r,e){r.binding=Object.keys(e).length?rS(e):void 0}function qo(r){if(!r)return"";if(Array.isArray(r.enum)&&r.enum.length)return rS(r.enum[0]);let e=xn(r);if(e==="object"){let t={},n=Kr(r.properties)?r.properties:{},i=new Set(Array.isArray(r.required)?r.required.map(String):[]);for(let[s,o]of Object.entries(n))i.has(s)&&Kr(o)&&(t[s]=qo(o));return t}return e==="array"?[]:e==="boolean"?!1:e==="number"||e==="integer"?0:""}function xn(r){return"const"in r?typeof r.const:Array.isArray(r.type)?String(r.type.find(e=>e!=="null")??r.type[0]??"string"):typeof r.type=="string"?r.type:Array.isArray(r.enum)?"string":Kr(r.properties)||Kr(r.additionalProperties)?"object":"any"}function oS(r){let e=xn(r);return e==="array"?"List":e==="boolean"?"Boolean":e==="integer"?"Integer":e==="number"?"Number":e==="object"?"Object":e==="any"?"Any value":"Text"}function aS(r,e){return r==="any"||e==="any"||r===e?!0:r==="number"&&e==="integer"}function nh(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function $D(r){return JSON.parse(JSON.stringify(r))}function oh(r){let e=2166136261,t=2654435769;for(let n=0;n>>0).toString(36)}-${(t>>>0).toString(36)}`}function cS(r){let e=$D(r);return delete e.sourceRevision,e}function yl(r,e){return r===null||e===null?r===e:JSON.stringify(cS(r))===JSON.stringify(cS(e))}function lS(r){return new Map(r.fields.map(e=>[e.name,e]))}function ih(r){return typeof r.type=="string"?r.type:"any"}function sh(r,e,t,n){let i=ih(r);if(i==="enum"&&(!Array.isArray(r.values)||r.values.length===0)&&t.push({code:"enum_without_values",severity:"warning",path:e,message:"Add at least one allowed value, or use String for an unrestricted value."}),i==="link"){let s=typeof r.target=="string"?r.target.trim():"";s&&s!=="any"&&n.size&&!n.has(s)&&t.push({code:"unknown_link_target",severity:"error",path:e,message:`The target type '${s}' is not installed in this collection.`})}if(i==="list"&&(nh(r.items)?sh(r.items,`${e}[]`,t,n):t.push({code:"list_items_missing",severity:"error",path:e,message:"Choose the shape of each list item."})),i==="object"){if(!nh(r.fields)){t.push({code:"object_fields_missing",severity:"error",path:e,message:"Add an object field or change this field's type."});return}let s=new Set;for(let[o,a]of Object.entries(r.fields)){let c=`${e}.${o||"unnamed"}`;o.trim()?s.has(o)&&t.push({code:"duplicate_field_name",severity:"error",path:c,message:`The nested field '${o}' is declared more than once.`}):t.push({code:"field_name_required",severity:"error",path:c,message:"Every nested field needs a name."}),s.add(o),nh(a)&&sh(a,c,t,n)}}}function gl(r,e={}){let t=[],n=new Set(e.knownTypes??[]);try{is(r)}catch(a){t.push({code:"invalid_type_document",severity:"error",path:"type",message:a instanceof Error?a.message:String(a)})}let i=new Set;for(let a of r.fields){let c=a.name.trim(),l=`fields.${c||"unnamed"}`;c?i.has(c)&&t.push({code:"duplicate_field_name",severity:"error",path:l,message:`The field '${c}' is declared more than once.`}):t.push({code:"field_name_required",severity:"error",path:l,message:"Every field needs a name."}),i.add(c),sh(a.definition,l,t,n)}r.displayNameKey.trim()&&!i.has(r.displayNameKey.trim())&&t.push({code:"display_field_missing",severity:"error",path:"identity.displayNameKey",message:`The display field '${r.displayNameKey.trim()}' is not declared.`});let s=new Map([...e.contracts??[]].map(a=>[ss(a),a])),o=Lo(r);for(let a of r.implementations){let c=`${a.contract}@${a.version}`,l=s.get(c);if(!l){t.push({code:"contract_unavailable",severity:"error",path:`applications.${c}`,message:"This exact application contract is not installed."});continue}for(let u of Do(l)){let d=os(a,u),f=o.find(m=>m.reference===d),p=jo(u,f);p.level!=="valid"&&t.push({code:p.level==="error"?"invalid_contract_mapping":"review_contract_mapping",severity:p.level==="error"?"error":"warning",path:`applications.${c}.${u.reference}`,message:p.message})}}return t.filter((a,c,l)=>l.findIndex(u=>u.code===a.code&&u.path===a.path&&u.message===a.message)===c)}function bl(r,e){if(!r)return[{code:"create_type",risk:"safe",summary:`Create the type '${e.name||"Untitled type"}'.`}];let t=[];r.name!==e.name&&t.push({code:"rename_type",risk:"high",summary:`Rename the type from '${r.name}' to '${e.name}'. Existing type references may need review.`}),(r.description!==e.description||r.displayNameKey!==e.displayNameKey)&&t.push({code:"identity",risk:"safe",summary:"Update the type's identity and display metadata."}),(r.matchPathGlob!==e.matchPathGlob||r.matchFieldsPresent!==e.matchFieldsPresent||r.matchWhere!==e.matchWhere)&&t.push({code:"membership",risk:"high",summary:"Change which records belong to this type."}),r.pathPattern!==e.pathPattern&&t.push({code:"placement",risk:"review",summary:"Change the suggested path for new records."}),r.strictMode!==e.strictMode&&t.push({code:"strictness",risk:e.strictMode===!0?"high":"review",summary:e.strictMode===!0?"Reject fields that are not declared by this type.":"Allow fields that are not declared by this type."});let n=lS(r),i=lS(e),s=[...i.keys()].filter(a=>!n.has(a)),o=[...n.keys()].filter(a=>!i.has(a));s.length&&t.push({code:"add_fields",risk:s.some(a=>i.get(a)?.definition.required===!0)?"high":"safe",summary:`Add ${s.length===1?"field":"fields"}: ${s.join(", ")}.`}),o.length&&t.push({code:"remove_fields",risk:"high",summary:`Remove ${o.length===1?"field":"fields"}: ${o.join(", ")}.`});for(let[a,c]of i){let l=n.get(a);if(!l)continue;let u=ih(l.definition),d=ih(c.definition);u!==d&&t.push({code:"change_field_type",risk:"high",summary:`Change '${a}' from ${u} to ${d}.`}),l.definition.required!==!0&&c.definition.required===!0&&t.push({code:"require_field",risk:"high",summary:`Make '${a}' required. Existing records may become invalid.`}),u===d&&JSON.stringify(l.definition)!==JSON.stringify(c.definition)&&l.definition.required===c.definition.required&&t.push({code:"field_rules",risk:"review",summary:`Update validation or documentation for '${a}'.`})}return JSON.stringify(r.implementations)!==JSON.stringify(e.implementations)&&t.push({code:"application_compatibility",risk:"review",summary:"Update application contract mappings or settings."}),!t.length&&!yl(r,e)&&t.push({code:"type_document",risk:"review",summary:"Update advanced type metadata or documentation."}),t}var ce=require("obsidian");var as="mdbase-frontmatter",dS=` @@ -185,15 +190,13 @@ Type definition for ${t}.`,extraFrontmatter:m,...o?{readOnlyReason:`This type us -`;async function O0(r,e,t,n){let i=await r.resolveConflict(e,t,n),s=await r.preview();return{status:i,preview:s}}function N0(r,e){let t=r.split(` +`;async function uS(r,e,t,n){let i=await r.resolveConflict(e,t,n),s=await r.preview();return{status:i,preview:s}}function fS(r,e){let t=r.split(` `),n=e.split(` -`),i=t.length>200||n.length>200,s=t.slice(0,200),o=n.slice(0,200),a=Array.from({length:s.length+1},()=>new Uint16Array(o.length+1));for(let d=s.length-1;d>=0;d-=1)for(let f=o.length-1;f>=0;f-=1)a[d][f]=s[d]===o[f]?a[d+1][f+1]+1:Math.max(a[d+1][f],a[d][f+1]);let c=[],l=0,u=0;for(;(l=300);)l=o.length||l=a[l][u+1]?(c.push({kind:"local",value:s[l]}),l+=1):(c.push({kind:"remote",value:o[u]}),u+=1);return{lines:c,truncated:i||l0?Math.min(100,Math.round(i.transferredBytes/i.totalBytes*100)):100;return{state:"syncing",label:`mdbase: ${i.direction==="upload"?"Uploading":"Downloading"} ${l}%`,detail:`${i.path} \xB7 ${Et(i.transferredBytes)} of ${Et(i.totalBytes)}`,destination:"sync"}}if(n)return{state:"syncing",label:`mdbase: Syncing${n.total==null?"":` ${n.completed}/${n.total}`}`,detail:"Open synchronization progress",destination:"sync"};if(s)return{state:s.action==="resume"?"paused":s.action==="retry"?"offline":"attention",label:s.action==="resume"?"mdbase: Paused":s.action==="retry"?"mdbase: Offline":"mdbase: Needs attention",detail:s.title,destination:"sync"};if(t?.recovery_required||t?.conflicts.length||t?.local_issues.length||["attention","blocked","failed","stale"].includes(t?.state??""))return{state:"attention",label:"mdbase: Needs attention",detail:"Review synchronization",destination:"sync"};if(t?.state==="cancelled")return{state:"paused",label:"mdbase: Paused",detail:"Review and resume synchronization",destination:"sync"};let c=t?.pending??0;return a||c>0||t?.state==="changes_waiting"||t?.state==="planned"?{state:"waiting",label:c>0?`mdbase: ${c} ${c===1?"change":"changes"}`:"mdbase: Changes waiting",detail:"Review local and hosted changes",destination:"sync"}:t?.state==="up_to_date"?{state:"synced",label:"mdbase: Synced",detail:"Local and hosted collections are aligned",destination:"sync"}:{state:"waiting",label:"mdbase: Ready to sync",detail:"Review the first synchronization",destination:"sync"}}function Zt(r){let e=jN(r);return e==="mirror_busy"?{code:e,title:"Synchronization is already running",message:"The active transfer is still using this vault. Its progress is shown below.",action:"resume",actionLabel:"Show progress"}:["mirror_credentials_missing","invalid_mirror_enrollment","mirror_enrollment_expired"].includes(e)?{code:e,title:"Connect approval is required again",message:"Your local files and mirror checkpoint are safe. Approve this vault again to restore access.",action:"reauthorize",actionLabel:"Sign in again"}:["operation_cancelled","cancelled","AbortError"].includes(e)?{code:e,title:"Synchronization paused safely",message:"Completed changes remain checkpointed. Review the current plan before resuming.",action:"resume",actionLabel:"Review and resume"}:["stale","stale_mirror_plan","mirror_plan_stale","conflict_decision_stale"].includes(e)?{code:e,title:"The collection changed again",message:"No stale decision was applied. Review the newest local and hosted versions.",action:"review",actionLabel:"Review newest changes"}:["enrollment_recovery_required","mirror_recovery_required","pending_mirror_recovery"].includes(e)?{code:e,title:"Synchronization needs recovery",message:"Your original files are safe. Resume from the durable checkpoint before disconnecting this vault.",action:"resume",actionLabel:"Resume recovery"}:{code:e,title:"Connect could not be reached",message:qN(r,"Your local files are safe. Check the connection and try again."),action:"retry",actionLabel:"Retry connection"}}function D0(r){return Array.isArray(r)?r.filter(LN).slice(-30):[]}function L0(r,e){return[...r.filter(t=>t.id!==e.id),e].slice(-30)}function j0(r){return{...r,id:crypto.randomUUID(),occurredAt:new Date().toISOString()}}function LN(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return typeof e.id=="string"&&typeof e.occurredAt=="string"&&typeof e.summary=="string"&&(e.detail===void 0||typeof e.detail=="string")&&(e.path===void 0||typeof e.path=="string")&&["success","info","attention","error"].includes(e.tone??"")&&typeof e.requiresAcknowledgement=="boolean"}function jN(r){return r instanceof DOMException?r.name:r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:r instanceof Error&&r.name?r.name:"sync_failed"}function qN(r,e){return r instanceof Error&&r.message?r.message:e}var Wp="https://connect.mdbase.dev",Yn="mdbase-workspace-view",FN=["string","integer","number","boolean","date","datetime","time","enum","link","list","object","any"];function je(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function Jn(r){return JSON.parse(JSON.stringify(r))}function ul(r){return typeof r.type=="string"?r.type:"any"}function UN(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 q0(r,e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,writable:!0,value:t})}function Nt(r,e,t,n,i={}){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.setAttr("data-focus-key",`form-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`),c.value=t,c.placeholder=i.placeholder??"",c.addEventListener("input",()=>n(c.value)),c}function qe(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 BN(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}function Gp(r){if(!r)return"Never synced";let e=Date.parse(r);if(!Number.isFinite(e))return r;let t=Math.round((e-Date.now())/1e3),n=Math.abs(t),i=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});if(n<60)return i.format(t,"second");let s=Math.round(t/60);if(Math.abs(s)<60)return i.format(s,"minute");let o=Math.round(s/60);return Math.abs(o)<24?i.format(o,"hour"):i.format(Math.round(o/24),"day")}function VN(r){return r?r.state==="up_to_date"?"Up to date":r.state==="changes_waiting"?"Local changes waiting":["attention","blocked","failed","stale"].includes(r.state)||r.recovery_required?"Needs attention":r.state==="cancelled"?"Paused safely":r.state==="applying"?"Synchronizing":r.state==="planned"?"Review ready":"Ready for first sync":"Checking connection"}function Jp(r){return r instanceof Error&&r.name==="AbortError"}var Xp=class extends ce.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}confirm(t){return new Promise(n=>{this.resolve=n,this.titleEl.setText("Confirm high-impact type changes"),this.contentEl.createEl("p",{text:"These schema changes can change membership or invalidate existing records. The plugin will save only the type definition; it will not rewrite records."});let i=this.contentEl.createEl("ul",{cls:"mdbase-confirm-change-list"});for(let c of t)i.createEl("li",{text:c.summary});let s=this.contentEl.createDiv({cls:"modal-button-container"}),o=s.createEl("button",{text:"Keep reviewing"});o.onclick=()=>this.finish(!1);let a=s.createEl("button",{text:"Save high-impact changes"});a.addClass("mod-warning"),a.onclick=()=>this.finish(!0),this.open()})}onClose(){this.settled||this.finish(!1,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}},Qp=class extends ce.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}choose(t){return new Promise(n=>{this.resolve=n,this.titleEl.setText("Disconnect this vault?"),this.contentEl.createEl("p",{text:`This stops synchronization with ${t}. It does not delete the hosted collection.`});let i=this.contentEl.createEl("ul");i.createEl("li",{text:"Keep local files leaves the current vault contents in place as an unsynced local copy."}),i.createEl("li",{text:"Remove synced files deletes only files that still exactly match the last checkpoint. Local edits are preserved."});let s=this.contentEl.createDiv({cls:"modal-button-container"}),o=s.createEl("button",{text:"Cancel"});o.onclick=()=>this.finish(null);let a=s.createEl("button",{text:"Disconnect and keep files"});a.onclick=()=>this.finish("keep");let c=s.createEl("button",{text:"Remove unchanged synced files"});c.addClass("mod-warning"),c.onclick=()=>this.finish("remove"),this.open()})}onClose(){this.settled||this.finish(null,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}},fl=class extends ce.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.fileProgress=null;this.syncProblem=null;this.conflictComparisons=new Map;this.loadingConflictComparisons=new Set;this.pendingSyncFocus=null;this.transientMessage="";this.issueQuery="";this.issueSeverity="all";this.issueLimit=250;this.enrollmentVerification="";this.enrollmentAbort=null;this.enrollmentControlUrl=Wp;this.enrollmentMirrorName="Obsidian";this.enrollmentCollectionId="";this.enrollmentMode="read_write";this.filePolicyDraft=null;this.adoptionFileProgress="";this.draftSaveTimer=null;this.fieldQuery="";this.expandedFields=new Set;this.fieldIds=new WeakMap;this.nextFieldId=1;this.refreshVersion=0;this.typeSelectionVersion=0}getViewType(){return Yn}getDisplayText(){return"mdbase"}getIcon(){return Qi}async onOpen(){this.containerEl.addClass("mdbase-workspace"),this.registerDomEvent(this.containerEl,"keydown",t=>{(t.metaKey||t.ctrlKey)&&t.key.toLowerCase()==="s"&&this.dirty&&(t.preventDefault(),this.saveCurrentType())}),await this.refresh(!0)}async onClose(){await this.flushTypeDraft(),this.enrollmentAbort?.abort(),this.enrollmentAbort=null}async refresh(t=!1){let n=++this.refreshVersion;try{let i=await this.host.loadWorkspaceSchema(t);if(n!==this.refreshVersion||(this.schema=i,this.selectedPath&&!this.typeEntries().some(s=>s.filePath===this.selectedPath)&&(this.selectedPath=null,this.model=null,this.originalModel=null),!this.selectedPath&&this.typeEntries().length&&!ce.Platform.isMobile&&(this.selectedPath=this.typeEntries()[0].filePath),this.selectedPath&&(!this.model||t)&&(await this.selectType(this.selectedPath,!1),n!==this.refreshVersion))||(this.destination==="sync"&&await this.refreshMirrorStatus(),n!==this.refreshVersion))return;this.render()}catch(i){if(n!==this.refreshVersion)return;this.transientMessage=i instanceof Error?i.message:String(i),this.render()}}showDestination(t){this.destination=t,t==="sync"?this.refreshMirrorStatus().then(()=>this.render()):this.render()}createNewType(){this.destination="types",this.createType()}async editType(t){this.destination="types",await this.selectType(t)}async reviewSyncChanges(){this.host.getMirrorProfile()&&await this.perform(()=>this.loadMirrorPreview())}async syncNow(){if(this.host.getMirrorProfile()){if(!this.mirrorPreview){await this.reviewSyncChanges(),this.mirrorPreview?.plan.actions.length&&new ce.Notice("The current transfer review is open. Run sync now again or confirm it in the mdbase view.");return}await this.perform(()=>this.applyReviewedSync())}}focusSyncSection(t){this.destination="sync",this.pendingSyncFocus=t,this.render(),window.setTimeout(()=>this.focusPendingSyncSection(),0)}async reconnectCollection(){await this.perform(async()=>{try{this.mirrorStatus=await this.host.connectSync.reconnect(),this.syncProblem=null,this.host.setSyncStatus(this.mirrorStatus),await this.host.recordSyncActivity({summary:"Collection reconnected",detail:"Connect credentials were renewed and the mirror checkpoint was preserved.",tone:"success",requiresAcknowledgement:!1}),this.transientMessage="Connection restored. Your mirror checkpoint was preserved."}catch(t){if(Zt(t).action!=="reauthorize")throw t;await this.reauthorizeCollection()}})}typeEntries(){return this.schema?[...this.schema.types.values()].sort((t,n)=>t.name.localeCompare(n.name)):[]}render(){let t=this.containerEl,n=this.captureRenderSnapshot(t);t.empty(),t.addClass("mdbase-workspace");let i=t.createDiv({cls:"mdbase-shell"});this.renderTopbar(i),this.transientMessage&&i.createDiv({cls:"mdbase-inline-message",text:this.transientMessage}).setAttr("role","status");let s=i.createDiv({cls:"mdbase-workspace-content"});s.setAttr("data-scroll-key","workspace"),this.destination==="types"?this.renderTypes(s):this.destination==="sync"?this.renderSync(s):this.renderIssues(s),this.restoreRenderSnapshot(t,n)}captureRenderSnapshot(t){let n=t.ownerDocument,i=t.contains(n.activeElement)?n.activeElement:null,s=i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement?i:null,o=new Map;for(let a of Array.from(t.querySelectorAll("[data-scroll-key]"))){let c=a.getAttr("data-scroll-key");c&&o.set(c,{top:a.scrollTop,left:a.scrollLeft})}return{focusKey:i?.getAttr("data-focus-key")??null,selectionStart:s?.selectionStart??null,selectionEnd:s?.selectionEnd??null,scroll:o}}restoreRenderSnapshot(t,n){for(let[s,o]of n.scroll){let a=t.querySelector(`[data-scroll-key="${s}"]`);a&&(a.scrollTop=o.top,a.scrollLeft=o.left)}if(!n.focusKey)return;let i=t.querySelector(`[data-focus-key="${n.focusKey}"]`);i?.focus({preventScroll:!0}),(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement)&&n.selectionStart!==null&&n.selectionEnd!==null&&i.setSelectionRange(n.selectionStart,n.selectionEnd)}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,ce.setIcon)(s,Qi),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:BN(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){let n=t.createDiv({cls:"mdbase-legacy-banner"}),i=n.createDiv();i.createEl("strong",{text:`mdbase ${this.schema?.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"});qe(o,"Files replaced",String(n.operations.length)),qe(o,"Type definitions",String(n.typeSummaries.length)),qe(o,"Record reads verified",String(n.recordsVerified)),n.recordsSkipped&&qe(o,"Records skipped",String(n.recordsSkipped)),qe(o,"Record files rewritten","0"),qe(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){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,ce.setIcon)(s,"plus"),s.disabled=(this.schema?.config.spec_version.startsWith("0.2.")??!0)||this.host.getMirrorProfile()?.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.setAttr("data-focus-key","type-search"),o.value=this.query,o.oninput=()=>{this.query=o.value,this.render();let u=this.containerEl.querySelector(".mdbase-type-search");u?.focus(),u?.setSelectionRange(u.value.length,u.value.length)};let a=n.createDiv({cls:"mdbase-type-list"});a.setAttr("data-scroll-key","type-list");let c=this.query.trim().toLowerCase(),l=this.typeEntries().filter(u=>`${u.name} ${u.description??""} ${u.filePath}`.toLowerCase().includes(c));if(!l.length){a.createDiv({cls:"mdbase-empty-list",text:c?"No matching types.":"No type definitions."});return}for(let u of l){let d=a.createEl("button",{cls:"mdbase-type-row"});u.filePath===this.selectedPath&&d.addClass("is-active"),d.setAttr("aria-current",u.filePath===this.selectedPath?"true":"false"),d.createSpan({cls:"mdbase-type-name",text:u.name}),d.createSpan({cls:"mdbase-type-meta",text:`${Object.keys(u.fields).length} fields \xB7 ${u.specProfile??"v0.2"}`}),d.onclick=()=>void this.selectType(u.filePath)}}renderTypeEditor(t){let n=t.createDiv({cls:"mdbase-type-editor-pane"});if(n.setAttr("data-scroll-key","type-editor"),!this.model){let h=n.createDiv({cls:"mdbase-empty-state"});h.createEl("h2",{text:"Choose a type"}),h.createEl("p",{text:"Select a type definition from the list to inspect or edit it."});return}let i=this.host.getMirrorProfile()?.mode==="read_only",s=this.model.specProfile==="v0.2"||i||!!this.model.readOnlyReason,o=this.model.readOnlyReason??(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,ce.setIcon)(c,"arrow-left"),c.onclick=()=>{if(this.dirty){new ce.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:this.model.specProfile??"v0.2"}),this.dirty&&u.createSpan({cls:"mdbase-dirty",text:"Unsaved"}),l.createDiv({cls:"mdbase-editor-path",text:this.selectedPath??"New type"});let d=a.createDiv({cls:"mdbase-editor-actions"});if(this.selectedPath){let h=this.selectedPath,y=d.createEl("button",{text:"Open source"});y.onclick=()=>void this.host.openFileByPath(h)}let f=d.createEl("button",{text:"Save"});if(f.addClass("mod-cta"),f.disabled=s||!this.dirty||this.busy,f.onclick=()=>void this.saveCurrentType(),this.dirty){let h=d.createEl("button",{text:"Discard"});h.onclick=()=>void this.discardCurrentType()}s&&n.createDiv({cls:"mdbase-readonly-note",text:o});let p=n.createDiv({cls:"mdbase-mode-switch"});p.setAttr("role","tablist");for(let[h,y]of[["design","Design"],["yaml","YAML"]]){let g=p.createEl("button",{text:y});g.setAttr("role","tab"),g.setAttr("aria-selected",String(this.editorMode===h)),this.editorMode===h&&g.addClass("is-active"),g.onclick=()=>this.switchEditorMode(h)}let m=n.createDiv({cls:"mdbase-editor-document"});m.setAttr("data-scroll-key","type-document"),this.editorMode==="design"?this.renderDesignEditor(m,this.model,s):this.renderYamlEditor(m,s),this.dirty&&!s&&this.renderDraftBar(n,this.model)}renderDraftBar(t,n){let i=dl(this.originalModel,n),o=ll(n,{knownTypes:this.typeEntries().map(p=>p.name),contracts:this.schema?.contracts.values()}).filter(p=>p.severity==="error").length,a=i.filter(p=>p.risk==="high").length,c=t.createDiv({cls:"mdbase-draft-bar"}),l=c.createDiv({cls:"mdbase-draft-summary"});l.createEl("strong",{text:`${i.length} pending ${i.length===1?"change":"changes"}`}),l.createSpan({text:o?`${o} ${o===1?"error":"errors"} to fix`:a?`${a} high-impact ${a===1?"change":"changes"}`:"Ready to save"});let u=c.createDiv({cls:"mdbase-actions"});if(this.editorMode==="design"){let p=u.createEl("button",{text:"Review"});p.onclick=()=>this.containerEl.querySelector("#mdbase-section-review")?.scrollIntoView({behavior:"smooth",block:"start"})}let d=u.createEl("button",{text:"Discard"});d.onclick=()=>void this.discardCurrentType();let f=u.createEl("button",{text:"Save changes"});f.addClass("mod-cta"),f.disabled=o>0||this.busy,f.onclick=()=>void this.saveCurrentType()}renderDesignEditor(t,n,i){let s=ll(n,{knownTypes:this.typeEntries().map(F=>F.name),contracts:this.schema?.contracts.values()});this.renderSectionNavigation(t,s);let o=t.createEl("section",{cls:"mdbase-editor-section"});o.id="mdbase-section-identity",o.createEl("h3",{text:"Identity"});let a=Nt(o,"Name",n.name,F=>{n.name=F,this.markDirty()},{description:"Stable type name used by collection records."});a.disabled=i;let c=Nt(o,"Description",n.description,F=>{n.description=F,this.markDirty()},{multiline:!0});c.disabled=i;let l=o.createDiv({cls:"mdbase-form-row"}),u=l.createEl("label",{text:"Display field"}),d=l.createEl("select");u.htmlFor=d.id="mdbase-display-field",d.createEl("option",{value:"",text:"Use the file name"});for(let F of n.fields)d.createEl("option",{value:F.name,text:F.name||"Unnamed field"});n.displayNameKey&&!n.fields.some(F=>F.name===n.displayNameKey)&&d.createEl("option",{value:n.displayNameKey,text:`${n.displayNameKey} \xB7 missing`}),d.value=n.displayNameKey,d.onchange=()=>{n.displayNameKey=d.value,this.markDirty()},d.disabled=i;let f=o.createEl("label",{cls:"mdbase-checkbox-row"}),p=f.createEl("input",{type:"checkbox"});p.checked=n.strictMode===!0,p.disabled=i,p.onchange=()=>{n.strictMode=p.checked,this.markDirty()},f.createSpan({text:"Reject undeclared fields"});let m=t.createEl("section",{cls:"mdbase-editor-section"});m.id="mdbase-section-membership",m.createEl("h3",{text:"Membership"});let h=Nt(m,"Path glob",n.matchPathGlob,F=>{n.matchPathGlob=F,this.markDirty()},{placeholder:"Projects/**/*.md"});h.disabled=i;let y=Nt(m,"Fields present",n.matchFieldsPresent,F=>{n.matchFieldsPresent=F,this.markDirty()},{description:"Comma-separated frontmatter keys."});y.disabled=i;let g=Nt(m,"Where",n.matchWhere,F=>{n.matchWhere=F,this.markDirty()},{multiline:!0,description:"YAML predicate, including contains and nested equality conditions.",placeholder:`tags: - contains: task`});g.disabled=i;let v=t.createEl("section",{cls:"mdbase-editor-section"});v.id="mdbase-section-fields";let _=v.createDiv({cls:"mdbase-section-header"});_.createEl("h3",{text:"Fields"});let w=_.createEl("button",{text:"Add field"});w.disabled=i,w.onclick=()=>{let F={type:"string"};n.fields.push({name:"",definition:F}),this.expandedFields.add(this.fieldId(F)),this.markDirty(!0)};let A=v.createDiv({cls:"mdbase-field-toolbar"}),x=n.fields.filter(F=>F.definition.required===!0).length;A.createDiv({cls:"mdbase-field-count",text:`${n.fields.length} ${n.fields.length===1?"field":"fields"} \xB7 ${x} required`});let M=A.createDiv({cls:"mdbase-field-toolbar-actions"}),S=M.createEl("input",{type:"search"});S.placeholder="Filter fields",S.setAttr("aria-label","Filter fields"),S.setAttr("data-focus-key","field-search"),S.value=this.fieldQuery,S.oninput=()=>{this.fieldQuery=S.value,this.render()};let C=M.createEl("button",{text:"Collapse all"});C.disabled=this.expandedFields.size===0,C.onclick=()=>{this.expandedFields.clear(),this.render()};let $=v.createDiv({cls:"mdbase-fields"}),V=this.fieldQuery.trim().toLowerCase(),q=n.fields.filter(F=>!V||this.fieldMatches(F.name,F.definition,V));for(let F of q){let Q=n.fields.indexOf(F);this.renderFieldRow($,F,Q,i)}q.length||$.createDiv({cls:"mdbase-empty-list",text:n.fields.length?"No fields match this filter.":"No fields declared."});let oe=t.createEl("section",{cls:"mdbase-editor-section"});oe.id="mdbase-section-placement",oe.createEl("h3",{text:"Placement"});let P=Nt(oe,"Path pattern",n.pathPattern,F=>{n.pathPattern=F,this.markDirty()},{placeholder:"Notes/{title}.md"});P.disabled=i,this.renderContractEditor(t,n,i);let k=t.createEl("section",{cls:"mdbase-editor-section mdbase-change-review"});if(k.id="mdbase-section-review",k.createEl("h3",{text:"Change review"}),s.length){let F=k.createDiv({cls:"mdbase-diagnostic-summary"}),Q=s.filter(Je=>Je.severity==="error").length,fe=s.length-Q;F.createEl("strong",{text:`${Q} ${Q===1?"error":"errors"} \xB7 ${fe} ${fe===1?"warning":"warnings"}`});for(let Je of s.slice(0,12)){let Fe=F.createDiv({cls:"mdbase-diagnostic-item"});Fe.setAttr("data-severity",Je.severity),Fe.createEl("code",{text:Je.path}),Fe.createSpan({text:Je.message})}}if(!this.dirty)k.createEl("p",{text:"No pending changes."});else{let F=k.createEl("ul");for(let Q of dl(this.originalModel,n))F.createEl("li",{text:Q.summary}).setAttr("data-risk",Q.risk)}}renderSectionNavigation(t,n){let i=t.createDiv({cls:"mdbase-section-nav"});i.setAttr("aria-label","Type sections"),i.setAttr("data-scroll-key","section-nav");let s=[["identity","Overview"],["membership","Membership"],["fields","Fields"],["applications","Applications"],["review",n.some(o=>o.severity==="error")?"Review \xB7 errors":"Review"]];for(let[o,a]of s){let c=i.createEl("button",{text:a});c.onclick=()=>{this.containerEl.querySelector(`#mdbase-section-${o}`)?.scrollIntoView({behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth",block:"start"})}}}renderContractEditor(t,n,i){let s=t.createEl("section",{cls:"mdbase-editor-section mdbase-contracts-section"});s.id="mdbase-section-applications";let a=s.createDiv({cls:"mdbase-section-header"}).createDiv();a.createEl("h3",{text:"Works with applications"}),a.createDiv({cls:"mdbase-form-description",text:"Tell compatible applications what this type's fields mean."});let c=[...this.schema?.contracts.values()??[]],l=new Set(n.implementations.map(d=>`${d.contract}@${d.version}`)),u=c.filter(d=>!l.has(Yi(d)));c.length||s.createDiv({cls:"mdbase-contract-empty",text:"No record contracts are installed in this collection. Add contract files under the configured contracts folder to connect this type to an application."});for(let d of n.implementations){let f=c.find(p=>p.id===d.contract&&p.version===d.version);this.renderContractImplementation(s,n,d,f,i)}if(u.length){let d=s.createDiv({cls:"mdbase-contract-add"}),f=d.createEl("label",{text:"Installed contract"}),p=d.createEl("select");f.htmlFor=p.id=`mdbase-contract-${Math.random().toString(36).slice(2)}`;for(let h of u)p.createEl("option",{value:Yi(h),text:`${h.id} \xB7 ${h.version}`});let m=d.createEl("button",{text:"Connect application contract"});m.disabled=i,m.onclick=()=>{let h=u.find(y=>Yi(y)===p.value);if(h)try{x0(n,h),this.markDirty(!0)}catch(y){new ce.Notice(y instanceof Error?y.message:String(y))}}}}renderContractImplementation(t,n,i,s,o){let a=t.createEl("article",{cls:"mdbase-contract-implementation"}),c=a.createDiv({cls:"mdbase-contract-header"}),l=c.createDiv();l.createEl("strong",{text:i.contract}),l.createSpan({cls:"mdbase-contract-version",text:i.version});let u=c.createEl("button",{text:"Remove"});if(u.disabled=o,u.onclick=()=>{k0(n,i.contract,i.version),this.markDirty(!0)},!s){a.createDiv({cls:"mdbase-contract-unavailable",text:"This exact contract is not installed in the collection. Restore it or remove this implementation before saving."});return}let d=xo(s),f=ko(n),p=d.filter(_=>Xi(i,_)),m=d.filter(_=>_.required),h=m.filter(_=>Xi(i,_)).length,y=a.createEl("details");y.open=hV.reference===w),x=Po(_,A),M=v.createDiv({cls:`mdbase-contract-mapping-row ${x.level}`}),S=M.createDiv({cls:"mdbase-contract-field-definition"});S.createEl("code",{text:_.reference}),S.createSpan({cls:_.required?"mdbase-contract-required":"mdbase-contract-optional",text:_.required?"Required":"Optional"}),S.createEl("small",{text:_.description||C0(_.schema)});let C=M.createEl("select");C.setAttr("aria-label",`${i.contract} ${_.reference} source field`),C.setAttr("aria-invalid",x.level==="error"?"true":"false"),C.disabled=o,C.createEl("option",{value:"",text:_.required?"Choose a source field":"Not exposed"});for(let V of f){let q=Po(_,V),oe=C.createEl("option",{value:V.reference,text:`${V.reference} \xB7 ${V.type}${q.level==="warning"?" \xB7 review":""}`});oe.disabled=q.level==="error"}C.value=w,C.onchange=()=>{P0(i,_.reference,C.value||void 0),this.markDirty(!0)};let $=M.createDiv({cls:"mdbase-contract-mapping-status"});$.createEl("strong",{text:x.label}),$.createEl("small",{text:x.message})}if(s.binding_schema){let _=a.createEl("details",{cls:"mdbase-contract-settings"});_.open=!!i.binding;let w=_.createEl("summary");w.createSpan({text:"Contract settings"}),w.createSpan({cls:"mdbase-contract-summary",text:i.binding?"Configured":"Optional"});let A=_.createDiv({cls:"mdbase-contract-settings-body"});if(A.createEl("p",{cls:"mdbase-form-description",text:"Control how compatible applications interpret this type. Values follow the contract's schema."}),i.binding)this.renderContractSchemaValue(A,s.binding_schema,i.binding,x=>{je(x)&&(Up(i,x),this.markDirty())},"Settings",o);else{let x=A.createEl("button",{text:"Configure settings"});x.disabled=o,x.onclick=()=>{let M=Co(s.binding_schema);je(M)&&(Up(i,M),this.markDirty(!0))}}}}renderContractSchemaValue(t,n,i,s,o,a){if(_n(n)==="object"){let l=je(i)?i:{},u=t.createEl("fieldset",{cls:"mdbase-contract-schema-object"});u.createEl("legend",{text:o});let d=je(n.properties)?n.properties:{},f=new Set(Array.isArray(n.required)?n.required.map(String):[]),p=[...new Set([...f,...Object.keys(l).filter(h=>h in d)])];for(let h of p){let y=d[h];if(!je(y))continue;let g=u.createDiv({cls:"mdbase-contract-schema-field"}),v=typeof y.description=="string"?y.description:void 0;g.createEl("label",{text:`${h}${f.has(h)?" \xB7 required":""}`}),v&&g.createEl("small",{text:v}),this.renderContractSchemaControl(g,y,l[h],_=>{s({...l,[h]:_})},h,a)}p.length||u.createDiv({cls:"mdbase-empty-list",text:"No settings declared."});let m=Object.keys(d).filter(h=>!p.includes(h));if(m.length){let h=u.createDiv({cls:"mdbase-contract-schema-add"}),y=h.createEl("select");for(let v of m)y.createEl("option",{value:v,text:v});let g=h.createEl("button",{text:"Add optional setting"});g.disabled=a,g.onclick=()=>{let v=y.value,_=d[v];je(_)&&s({...l,[v]:Co(_)})}}return}this.renderContractSchemaControl(t,n,i,s,o,a)}renderContractSchemaControl(t,n,i,s,o,a){let c=_n(n);if(Array.isArray(n.enum)){let u=t.createEl("select");u.setAttr("aria-label",o);for(let d of n.enum)u.createEl("option",{value:JSON.stringify(d),text:String(d)});u.value=JSON.stringify(i),u.disabled=a,u.onchange=()=>s(JSON.parse(u.value));return}if(c==="array"){let u=je(n.items)?n.items:{type:"string"},d=Array.isArray(i)?i:[],f=t.createDiv({cls:"mdbase-contract-schema-array"});for(let[m,h]of d.entries()){let y=f.createDiv({cls:"mdbase-contract-schema-array-item"});y.createSpan({text:`${m+1}.`}),this.renderContractSchemaControl(y,u,h,v=>{s(d.map((_,w)=>w===m?v:_))},`${o} item ${m+1}`,a);let g=y.createEl("button",{text:"Remove"});g.disabled=a||d.length<=(typeof n.minItems=="number"?n.minItems:0),g.onclick=()=>s(d.filter((v,_)=>_!==m))}let p=t.createEl("button",{text:`Add ${o.toLowerCase()} item`});p.disabled=a||typeof n.maxItems=="number"&&d.length>=n.maxItems,p.onclick=()=>s([...d,Co(u)]);return}if(c==="object"){this.renderContractSchemaValue(t,n,i,s,o,a);return}if(c==="boolean"){let u=t.createEl("input",{type:"checkbox"});u.checked=i===!0,u.disabled=a,u.setAttr("aria-label",o),u.onchange=()=>s(u.checked);return}let l=t.createEl("input",{type:c==="number"||c==="integer"?"number":"text"});l.setAttr("aria-label",o),l.value=i==null?"":typeof i=="string"?i:typeof i=="number"||typeof i=="boolean"?String(i):"",l.disabled=a,l.oninput=()=>s(c==="number"||c==="integer"?Number(l.value):l.value)}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:()=>{this.model?.fields.splice(i,1),this.markDirty(!0)},readOnly:s,depth:0})}renderFieldDefinition(t,n,i){let s=t.createEl("details",{cls:"mdbase-field-node"});s.setAttr("data-depth",String(i.depth));let o=this.fieldId(n),a=!!this.fieldQuery.trim()&&this.fieldMatches(i.name??i.staticLabel??"",n,this.fieldQuery.trim().toLowerCase());s.open=this.expandedFields.has(o)||a,s.ontoggle=()=>{s.open?this.expandedFields.add(o):this.expandedFields.delete(o)};let c=s.createEl("summary",{cls:"mdbase-field-summary"});c.createSpan({cls:"mdbase-field-summary-name",text:i.name||i.staticLabel||"Unnamed field"}),c.createSpan({cls:"mdbase-field-summary-type",text:ul(n)}),c.createSpan({cls:"mdbase-field-summary-rule",text:i.required?"Required":i.staticLabel?"Item shape":"Optional"});let l=s.createDiv({cls:"mdbase-field-row"});if(i.staticLabel)l.createDiv({cls:"mdbase-field-role",text:i.staticLabel});else{let p=l.createEl("input",{type:"text",cls:"mdbase-field-name-control"});p.setAttr("data-focus-key",`field-${o}-name`),p.setAttr("aria-label",i.nameLabel),p.placeholder="fieldName",p.value=i.name??"",p.disabled=i.readOnly,i.onNameInput&&(p.oninput=()=>i.onNameInput?.(p.value)),i.onNameCommit&&(p.onchange=()=>i.onNameCommit?.(p.value,p))}let u=l.createEl("select",{cls:"mdbase-field-type-control"});u.setAttr("data-focus-key",`field-${o}-type`),u.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} type`);for(let p of FN){let m=p==="any"?"Any value":p[0].toUpperCase()+p.slice(1);u.createEl("option",{value:p,text:m})}u.value=ul(n),u.disabled=i.readOnly,u.onchange=()=>{n.type=u.value,u.value==="list"&&!je(n.items)&&(n.items={type:"string"}),u.value==="object"&&!je(n.fields)&&(n.fields={}),u.value==="enum"&&!Array.isArray(n.values)&&(n.values=[]),this.markDirty(!0)};let d=l.createEl("input",{type:"text",cls:"mdbase-field-description-control"});if(d.setAttr("data-focus-key",`field-${o}-description`),d.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} description`),d.placeholder="Description",d.value=typeof n.description=="string"?n.description:"",d.disabled=i.readOnly,d.oninput=()=>{d.value?n.description=d.value:delete n.description,this.markDirty()},i.onRequiredChange){let p=l.createEl("label",{cls:"mdbase-field-required"}),m=p.createEl("input",{type:"checkbox"});m.setAttr("data-focus-key",`field-${o}-required`),m.checked=i.required===!0,m.disabled=i.readOnly,m.onchange=()=>i.onRequiredChange?.(m.checked),p.createSpan({text:"Required"})}if(i.onRemove){let p=l.createEl("button",{cls:"mdbase-field-remove"});p.setAttr("aria-label",`Remove ${i.name||i.staticLabel||"field"}`),(0,ce.setIcon)(p,"trash-2"),p.disabled=i.readOnly,p.onclick=i.onRemove}let f=ul(n);f==="enum"&&this.renderEnumFieldDetails(s,n,i),f==="link"&&this.renderLinkFieldDetails(s,n,i),f==="list"&&this.renderListFieldDetails(s,n,i),f==="object"&&this.renderObjectFieldDetails(s,n,i)}fieldId(t){let n=this.fieldIds.get(t);if(n)return n;let i=`field-${this.nextFieldId}`;return this.nextFieldId+=1,this.fieldIds.set(t,i),i}fieldMatches(t,n,i){return`${t} ${ul(n)} ${typeof n.description=="string"?n.description:""}`.toLowerCase().includes(i)||je(n.items)&&this.fieldMatches("item",n.items,i)?!0:je(n.fields)?Object.entries(n.fields).some(([o,a])=>je(a)&&this.fieldMatches(o,a,i)):!1}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("select");a.setAttr("aria-label",`${i.name||i.staticLabel||"Link"} target type`),a.createEl("option",{value:"",text:"Any type"});let c=typeof n.target=="string"?n.target:"";for(let d of this.typeEntries())a.createEl("option",{value:d.name,text:d.name});c&&!this.typeEntries().some(d=>d.name===c)&&a.createEl("option",{value:c,text:`${c} \xB7 missing`}),a.value=c,a.disabled=i.readOnly,a.onchange=()=>{a.value?n.target=a.value:delete n.target,this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`;let l=s.createEl("label",{cls:"mdbase-field-required"}),u=l.createEl("input",{type:"checkbox"});u.checked=n.validate_exists===!0,u.disabled=i.readOnly,u.onchange=()=>{n.validate_exists=u.checked,this.markDirty()},l.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=je(n.items)?n.items:{type:"any"};!je(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=je(n.fields)?n.fields:{};!je(n.fields)&&!i.readOnly&&(n.fields=c),a.onclick=()=>{let d=UN(c);q0(c,d,{type:"string"}),this.markDirty(!0)};let l=s.createDiv({cls:"mdbase-nested-fields"}),u=Object.entries(c).filter(d=>je(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 ce.Notice("Nested field name is required."),h.value=p;return}if(y!==p&&Object.prototype.hasOwnProperty.call(c,y)){new ce.Notice(`Nested field already exists: ${y}`),h.value=p;return}y!==p&&(delete c[p],q0(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.setAttr("data-focus-key","yaml-editor"),s.value=this.yamlDraft,s.disabled=n,s.spellcheck=!1,s.oninput=()=>{this.yamlDraft=s.value,this.markDirty(!1)}}renderSync(t){let n=t.createDiv({cls:"mdbase-sync-document"}),i=n.createDiv({cls:"mdbase-document-header"});i.createEl("h2",{text:"Sync"}),i.createEl("p",{text:"A clear handoff between this vault and its hosted collection authority."});let s=this.host.getMirrorProfile();if(!s){this.renderEnrollment(n);return}this.syncProblem=this.host.getCurrentSyncProblem()??this.syncProblem;let o=n.createEl("section",{cls:"mdbase-sync-hero"});o.setAttr("data-state",this.mirrorStatus?.state??"checking");let a=o.createDiv({cls:"mdbase-sync-route"}),c=a.createDiv({cls:"mdbase-sync-endpoint"});(0,ce.setIcon)(c.createSpan({cls:"mdbase-sync-endpoint-icon"}),"vault");let l=c.createDiv();l.createEl("strong",{text:this.app.vault.getName()});let u=s.selectiveSync??{file_classes:[],excluded_folders:[]},d=u.file_classes.length?`Markdown + ${u.file_classes.join(", ")}`:"Markdown only";l.createSpan({text:`${s.mode==="read_write"?"Upload and download":"Downloads only"} \xB7 ${d}`});let f=a.createDiv({cls:"mdbase-sync-connection"});(0,ce.setIcon)(f.createSpan(),s.mode==="read_write"?"arrow-left-right":"arrow-left"),f.createSpan({text:VN(this.mirrorStatus)});let p=a.createDiv({cls:"mdbase-sync-endpoint"});(0,ce.setIcon)(p.createSpan({cls:"mdbase-sync-endpoint-icon"}),"cloud");let m=p.createDiv();m.createEl("strong",{text:s.name}),m.createSpan({text:"Hosted authority"});let h=o.createDiv({cls:"mdbase-sync-meta"}),y=this.mirrorStatus?.pending_files??0;if(h.createSpan({text:`${s.mode==="read_write"?"Read\u2013write mirror":"Read-only mirror"} \xB7 ${Gp(this.mirrorStatus?.last_synced_at)}${y?` \xB7 ${y} queued ${y===1?"file":"files"}`:""}`}),h.createEl("code",{text:s.collectionId}).setAttr("title","Collection ID"),this.fileProgress||this.mirrorProgress){let S=o.createDiv({cls:"mdbase-sync-progress",attr:{"aria-live":"polite"}}),C=this.fileProgress?.totalBytes??this.mirrorProgress?.total??null,$=this.fileProgress?.transferredBytes??this.mirrorProgress?.completed??0,V=S.createEl("progress");V.max=C??1,V.value=C==null?0:$,C==null&&V.removeAttribute("value"),S.createDiv({cls:"mdbase-progress-label",text:this.fileProgress?`${this.fileProgress.direction==="upload"?"Uploading":"Downloading"} ${this.fileProgress.path} \xB7 ${Et($)} of ${Et(C??0)}`:`${this.mirrorProgress?.phase==="uploading"?"Uploading local changes":this.mirrorProgress?.phase==="downloading"?"Downloading collection files":"Applying changes"} \xB7 ${$}${C==null?"":` of ${C}`}`});let q=S.createEl("button",{text:"Stop safely"});q.onclick=()=>{this.host.connectSync.cancelSync(),this.transientMessage="Stopping after the current network request\u2026",this.render()}}(this.syncProblem||this.mirrorStatus?.recovery_required)&&this.renderRecoveryCard(o,this.syncProblem??{code:"mirror_recovery_required",title:"Synchronization needs recovery",message:"Your original files are safe. Resume from the durable checkpoint before disconnecting this vault.",action:"resume",actionLabel:"Resume recovery"});let v=o.createDiv({cls:"mdbase-sync-actions"}),_=v.createEl("button",{text:this.mirrorPreview?"Refresh review":"Review changes"});_.disabled=this.busy,_.onclick=()=>void this.reviewSyncChanges();let w=this.mirrorPreview?.plan.actions.filter(S=>S.command!=="advance_checkpoint").length??0,A=this.mirrorPreview?.plan.actions.some(S=>S.command==="advance_checkpoint")??!1,x=(this.mirrorPreview?.plan.summary.blocking_issues??0)>0,M=v.createEl("button",{text:this.mirrorPreview?w?`Sync ${w} ${w===1?"outcome":"outcomes"}`:A?"Confirm sync checkpoint":"Already up to date":"Review before syncing"});M.addClass("mod-cta"),M.disabled=this.busy||!this.mirrorPreview||x||this.mirrorPreview.plan.actions.length===0,M.onclick=()=>void this.perform(()=>this.applyReviewedSync()),this.renderFilePolicyControls(n,{connected:!0}),this.mirrorPreview&&this.renderMirrorPreview(n,this.mirrorPreview),this.mirrorStatus?.conflicts.length&&this.renderConflicts(n,this.mirrorStatus),this.mirrorStatus?.local_issues.length&&this.renderLocalMirrorIssues(n,this.mirrorStatus),this.renderActivity(n),this.renderConnectionDetails(n,s),window.setTimeout(()=>this.focusPendingSyncSection(),0)}async loadMirrorPreview(){this.mirrorPreview=await this.host.connectSync.preview(),this.mirrorStatus=await this.host.connectSync.status(),this.syncProblem=null,this.host.setSyncStatus(this.mirrorStatus),this.transientMessage=this.mirrorPreview.entries.length?"Review each transfer below, then sync when ready.":"This vault and the hosted collection are already aligned."}async applyReviewedSync(){if(!this.mirrorPreview){await this.loadMirrorPreview();return}let t=this.mirrorPreview;try{let n=await this.host.connectSync.sync(t,i=>{this.mirrorProgress=i,this.host.setSyncProgress(i,this.fileProgress),this.render()},i=>{this.fileProgress=i,this.host.setSyncProgress(this.mirrorProgress,i),this.render()});this.mirrorStatus=await this.host.connectSync.status(),this.mirrorPreview=await this.host.connectSync.preview(),this.syncProblem=n.status==="cancelled"?Zt(new DOMException("Synchronization stopped.","AbortError")):n.status==="stale"?Zt(Object.assign(new Error("The reviewed plan changed."),{code:"mirror_plan_stale"})):null,this.syncProblem?this.host.setSyncProblem(this.syncProblem):this.host.setSyncStatus(this.mirrorStatus,{clearLocalChanges:n.status==="applied"&&n.pending===0}),this.transientMessage=n.status==="applied"?"Sync completed and the local checkpoint was verified.":n.status==="attention"?"Completed changes are checkpointed. Review the items that still need attention.":n.status==="cancelled"?`Sync paused safely after ${n.applied} actions; ${n.pending} remain.`:n.status==="stale"?"The collection changed again. Review the newest plan; no stale decision was applied.":`Sync stopped at a durable boundary: ${n.failure?.message??n.status}.`,await this.host.recordSyncActivity({summary:n.status==="applied"?`Synchronized ${n.applied} ${n.applied===1?"change":"changes"}`:n.status==="cancelled"?"Synchronization paused safely":"Synchronization needs attention",detail:this.transientMessage,tone:n.status==="applied"?"success":"attention",requiresAcknowledgement:n.status!=="applied"})}catch(n){let i=Zt(n);if(this.syncProblem=i,this.host.setSyncProblem(i),this.transientMessage=i.message,await this.host.recordSyncActivity({summary:i.title,detail:i.message,tone:i.action==="resume"?"attention":"error",requiresAcknowledgement:!0}),!Jp(n))throw n}finally{this.mirrorProgress=null,this.fileProgress=null,this.host.setSyncProgress(null,null)}}renderRecoveryCard(t,n){let i=t.createDiv({cls:"mdbase-recovery-card"}),s=i.createDiv();s.createEl("strong",{text:n.title}),s.createDiv({text:n.message});let o=i.createEl("button",{text:n.actionLabel});o.disabled=this.busy,o.onclick=()=>{n.action==="retry"?this.reconnectCollection():n.action==="reauthorize"?this.perform(()=>this.reauthorizeCollection()):this.reviewSyncChanges()}}async reauthorizeCollection(){this.enrollmentAbort?.abort();let t=new AbortController;this.enrollmentAbort=t;try{this.mirrorStatus=await this.host.connectSync.reauthorize({signal:t.signal,onVerification:n=>{this.enrollmentVerification=n.verificationUri,this.transientMessage="Approve this vault again in Connect. Its local files and checkpoint remain unchanged.",window.open(n.verificationUri,"_blank","noopener,noreferrer"),this.render()},onStatus:n=>{this.transientMessage=n.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying approval (attempt ${n.attempt}).`,this.render()}}),this.enrollmentVerification="",this.syncProblem=null,this.host.setSyncStatus(this.mirrorStatus),this.transientMessage="Approval restored. The existing mirror checkpoint was preserved.",await this.host.recordSyncActivity({summary:"Connect approval restored",detail:"The existing mirror checkpoint and local files were preserved.",tone:"success",requiresAcknowledgement:!1})}finally{this.enrollmentAbort===t&&(this.enrollmentAbort=null)}}renderActivity(t){let n=t.createEl("section",{cls:"mdbase-editor-section mdbase-activity"});n.id="mdbase-sync-activity";let i=n.createDiv({cls:"mdbase-section-header"});i.createEl("h3",{text:"Recent activity"});let s=this.host.getSyncActivity();if(s.some(a=>!a.requiresAcknowledgement)){let a=i.createEl("button",{text:"Clear completed"});a.disabled=this.busy,a.onclick=()=>void this.host.clearCompletedSyncActivity().then(()=>this.render())}if(this.fileProgress){let a=n.createDiv({cls:"mdbase-activity-row is-current"});(0,ce.setIcon)(a.createSpan(),this.fileProgress.direction==="upload"?"upload":"download");let c=a.createDiv();c.createEl("strong",{text:`${this.fileProgress.direction==="upload"?"Uploading":"Downloading"} ${this.fileProgress.path}`}),c.createDiv({text:`${Et(this.fileProgress.transferredBytes)} of ${Et(this.fileProgress.totalBytes)}`})}let o=[...s].reverse().filter((a,c)=>a.requiresAcknowledgement||c<8);if(!o.length&&!this.fileProgress){n.createDiv({cls:"mdbase-muted",text:"No recent synchronization activity."});return}for(let a of o){let c=n.createDiv({cls:"mdbase-activity-row"});c.setAttr("data-tone",a.tone),(0,ce.setIcon)(c.createSpan(),a.tone==="success"?"check":a.tone==="info"?"info":"circle-alert");let l=c.createDiv();if(l.createEl("strong",{text:a.summary}),a.detail&&l.createDiv({text:a.detail}),l.createSpan({cls:"mdbase-muted",text:Gp(a.occurredAt)}),a.requiresAcknowledgement){let u=c.createEl("button",{text:"Dismiss"});u.disabled=this.busy,u.onclick=()=>void this.host.dismissSyncActivity(a.id).then(()=>this.render())}}}renderConnectionDetails(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section mdbase-connection-details"});i.createEl("h3",{text:"Collection connection"});let s=i.createDiv({cls:"mdbase-status-list"});qe(s,"Collection",n.name),qe(s,"Collection ID",n.collectionId),qe(s,"Vault",this.app.vault.getName()),qe(s,"Access",n.mode==="read_write"?"Read and write":"Read only"),qe(s,"Account","Approved through Connect"),qe(s,"Connect",new URL(n.controlUrl).host),qe(s,"Last successful sync",Gp(this.mirrorStatus?.last_synced_at)),i.createEl("p",{text:"This plugin is the only sync owner for this vault. Connect owns authorization and the mirror engine owns checkpoints and conflict decisions."});let o=i.createDiv({cls:"mdbase-actions"}),a=o.createEl("button",{text:"Reconnect"});a.disabled=this.busy,a.onclick=()=>void this.reconnectCollection();let c=o.createEl("button",{text:"Disconnect\u2026"});c.disabled=this.busy||this.host.connectSync.isSyncing(),c.onclick=()=>void this.disconnectCollection(n)}async disconnectCollection(t){let n=await new Qp(this.app).choose(t.name);n&&await this.perform(async()=>{let i=await this.host.connectSync.disconnect(n==="remove");this.mirrorStatus=null,this.mirrorPreview=null,this.syncProblem=null,this.host.setSyncStatus(null,{clearLocalChanges:!0});let s=n==="remove"?`${i.removed.length} unchanged synced ${i.removed.length===1?"file was":"files were"} removed. ${i.preserved.length} locally changed ${i.preserved.length===1?"file was":"files were"} preserved.`:"All local files were retained as an unsynced copy.";this.transientMessage=`Disconnected from ${t.name}. ${s}`,await this.host.recordSyncActivity({summary:`Disconnected from ${t.name}`,detail:s,tone:i.preserved.length?"attention":"info",requiresAcknowledgement:i.preserved.length>0}),await this.refresh(!0)})}focusPendingSyncSection(){if(!this.pendingSyncFocus)return;let t=this.pendingSyncFocus==="activity"?"mdbase-sync-activity":"mdbase-sync-conflicts",n=this.containerEl.querySelector(`#${t}`);n&&(this.pendingSyncFocus=null,n.scrollIntoView({behavior:"smooth",block:"start"}))}filePolicy(){return this.filePolicyDraft??=JSON.parse(JSON.stringify(this.host.connectSync.getSelectiveSync())),this.filePolicyDraft}renderFilePolicyControls(t,n){let i=this.filePolicy(),s=t.createEl("section",{cls:"mdbase-editor-section mdbase-file-policy"});s.createEl("h3",{text:n.connected?"Files on this device":"Collection files"}),s.createEl("p",{text:"Markdown always syncs. Choose which binary file classes this device should materialize; hidden and reserved paths remain excluded."});let o=s.createDiv({cls:"mdbase-file-class-grid"}),a=[["image","Images"],["audio","Audio"],["video","Video"],["pdf","PDFs"],["other","Other files"]];for(let[f,p]of a){let m=o.createEl("label"),h=m.createEl("input",{type:"checkbox"});h.setAttr("data-focus-key",`file-class-${f}`),h.checked=i.file_classes.includes(f),h.onchange=()=>{i.file_classes=h.checked?[...new Set([...i.file_classes,f])]:i.file_classes.filter(y=>y!==f),this.render()},m.createSpan({text:p})}let c=null;if(Nt(s,"Excluded folders",i.excluded_folders.join(", "),f=>{if(i.excluded_folders=f.split(",").map(p=>p.trim()).filter(Boolean),c){let p=JSON.stringify(this.host.connectSync.getSelectiveSync())!==JSON.stringify(i);c.textContent=p?"Apply file policy":"File policy applied",c.disabled=!p||this.busy}},{description:"Comma-separated collection-relative folders. Exclusions apply to Markdown and binary files on this device.",placeholder:"Archive, Private exports"}),i.file_classes.length?i.file_classes.includes("other")&&s.createDiv({cls:"mdbase-inline-message",text:"Other files includes every eligible visible non-Markdown format. Review the transfer ledger carefully before syncing."}):s.createDiv({cls:"mdbase-inline-message",text:"Binary sync is off. This mirror remains Markdown-only."}),!n.connected)return;let l=this.host.connectSync.getSelectiveSync(),u=JSON.stringify(l)!==JSON.stringify(i);c=s.createDiv({cls:"mdbase-actions"}).createEl("button",{text:u?"Apply file policy":"File policy applied"}),c.disabled=!u||this.busy,c.onclick=()=>void this.perform(async()=>{await this.host.connectSync.configureSelectiveSync(i),this.filePolicyDraft=null,this.mirrorPreview=null,this.transientMessage="File policy updated. Review the rebuild before files move.",this.render()})}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 an empty vault"}),n.createEl("p",{text:"Choose access, approve it in Connect, then review the first transfer before any files move."}),this.renderEnrollmentSteps(n,this.enrollmentVerification||this.enrollmentAbort?2:1,["Choose connection","Approve in Connect","Review first sync"]),this.enrollmentVerification){let c=n.createDiv({cls:"mdbase-approval-link"});c.createSpan({text:"Waiting for approval \xB7 "});let l=c.createEl("a",{text:"Open approval page again",href:this.enrollmentVerification});l.setAttr("target","_blank"),l.setAttr("rel","noopener noreferrer")}Nt(n,"Connect URL",this.enrollmentControlUrl,c=>{this.enrollmentControlUrl=c},{placeholder:Wp}),Nt(n,"Mirror name",this.enrollmentMirrorName,c=>{this.enrollmentMirrorName=c}),Nt(n,"Collection ID",this.enrollmentCollectionId,c=>{this.enrollmentCollectionId=c},{description:"Optional. Leave blank to choose during approval."});let i=n.createDiv({cls:"mdbase-form-row"});i.createEl("label",{text:"Access"});let s=i.createEl("select");s.createEl("option",{value:"read_write",text:"Read and write"}),s.createEl("option",{value:"read_only",text:"Read only"}),s.value=this.enrollmentMode,s.onchange=()=>{this.enrollmentMode=s.value==="read_only"?"read_only":"read_write"},this.renderFilePolicyControls(n,{connected:!1});let o=n.createDiv({cls:"mdbase-actions"}),a=o.createEl("button",{text:this.enrollmentAbort?"Waiting for approval\u2026":"Continue to approval"});if(a.addClass("mod-cta"),a.disabled=this.busy,a.onclick=()=>void this.perform(async()=>{this.enrollmentAbort?.abort();let c=new AbortController;this.enrollmentAbort=c;try{await this.host.connectSync.enroll({controlUrl:this.enrollmentControlUrl,mirrorName:this.enrollmentMirrorName,mode:this.enrollmentMode,selectiveSync:this.filePolicy(),...this.enrollmentCollectionId.trim()?{collectionId:this.enrollmentCollectionId.trim()}:{}},{signal:c.signal,onVerification:d=>{this.enrollmentVerification=d.verificationUri,this.transientMessage="Approve the mirror in the Connect page. This view will keep waiting securely.",window.open(d.verificationUri,"_blank","noopener,noreferrer"),this.render()},onStatus:d=>{this.transientMessage=d.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying enrollment (attempt ${d.attempt}).`,this.render()}}),this.enrollmentVerification="",await this.loadMirrorPreview();let l=this.mirrorPreview?.entries.reduce((d,f)=>d+(f.estimatedBytes??0),0)??0,u=this.mirrorPreview?.entries.length??0;this.transientMessage=`Mirror enrolled. The first review contains ${u} ${u===1?"item":"items"}${l?` and about ${Et(l)} of binary data`:""}. No files have moved yet.`,this.render()}catch(l){if(!Jp(l))throw l;this.transientMessage="Approval wait cancelled. No files were synchronized."}finally{this.enrollmentAbort===c&&(this.enrollmentAbort=null)}}),this.enrollmentAbort){let c=o.createEl("button",{text:"Stop waiting"});c.onclick=()=>{this.enrollmentAbort?.abort(),this.transientMessage="Approval wait cancelled. No files were synchronized.",this.render()}}}renderLocalAdoption(t){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=n?["waiting_for_approval","uploading","fenced","activating","adopted"].indexOf(n.phase)+1:1;this.renderEnrollmentSteps(i,Math.min(4,Math.max(1,s)),["Approve move","Stage snapshot","Activate authority","Reconnect mirror"]);let o=this.enrollmentVerification||n?.session.verificationUri;if(o){let l=i.createDiv({cls:"mdbase-approval-link"});l.createSpan({text:"Approval page: "});let u=l.createEl("a",{text:"Open Connect",href:o});u.setAttr("target","_blank"),u.setAttr("rel","noopener noreferrer")}if(n&&(this.enrollmentControlUrl=n.session.controlUrl,this.enrollmentMirrorName=n.session.requested.mirrorName??"Obsidian"),!n)Nt(i,"Connect URL",this.enrollmentControlUrl,l=>{this.enrollmentControlUrl=l},{placeholder:Wp}),Nt(i,"Mirror name",this.enrollmentMirrorName,l=>{this.enrollmentMirrorName=l}),this.renderFilePolicyControls(i,{connected:!1});else{let l=i.createDiv({cls:"mdbase-status-list"});qe(l,"Collection",n.session.requested.collectionId),qe(l,"Phase",n.phase.replace(/_/g," ")),qe(l,"Connect",n.session.controlUrl);let u=this.host.connectSync.getSelectiveSync();qe(l,"Files",u.file_classes.length?u.file_classes.join(", "):"Markdown only")}let a=i.createDiv({cls:"mdbase-inline-message"});a.createEl("strong",{text:"Authority cut-over: "}),a.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 c=i.createEl("button",{text:n?"Resume adoption":"Approve and host collection"});if(c.addClass("mod-cta"),c.disabled=this.busy,c.onclick=()=>void this.perform(async()=>{this.enrollmentAbort?.abort();let l=new AbortController;this.enrollmentAbort=l;let u=p=>{this.enrollmentVerification=p.verificationUri,this.transientMessage="Approve the authority move in Connect, then return here. This checkpoint is safe to resume.",this.render()},d=p=>{this.transientMessage=p.state==="waiting_for_approval"?"Waiting for authority-move approval in Connect\u2026":`Connect is retrying (attempt ${p.attempt}).`,this.render()},f=(p,m,h)=>{this.adoptionFileProgress=`${p} \xB7 ${Et(m)} of ${Et(h)}`,this.transientMessage=`Uploading collection file ${this.adoptionFileProgress}`,this.render()};try{n?await this.host.connectSync.resumeAdoption({signal:l.signal,onVerification:u,onStatus:d,onFileProgress:f}):await this.host.connectSync.adoptLocalCollection({controlUrl:this.enrollmentControlUrl,mirrorName:this.enrollmentMirrorName,selectiveSync:this.filePolicy()},{signal:l.signal,onVerification:u,onStatus:d,onFileProgress:f}),this.enrollmentVerification="",this.transientMessage="Hosted mdbase is authoritative and this vault is now its read-write mirror.",await this.refresh(!0)}catch(p){if(!Jp(p))throw p;this.transientMessage="Paused safely. Use Resume adoption to continue from the durable checkpoint."}finally{this.enrollmentAbort===l&&(this.enrollmentAbort=null)}}),this.enrollmentAbort){let l=i.createEl("button",{text:"Stop waiting"});l.onclick=()=>{this.enrollmentAbort?.abort(),this.transientMessage="Paused safely. Use Resume adoption to continue from the durable checkpoint.",this.render()}}if(n&&!["activating","adopted"].includes(n.phase)){let l=i.createEl("button",{text:"Cancel adoption"});l.disabled=this.busy,l.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)})}}renderEnrollmentSteps(t,n,i){let s=t.createEl("ol",{cls:"mdbase-enrollment-steps"});i.forEach((o,a)=>{let c=s.createEl("li"),l=a+1;c.toggleClass("is-complete",ll+(u.estimatedBytes??0),0);s.createSpan({cls:"mdbase-transfer-total",text:`${n.entries.length} ${n.entries.length===1?"item":"items"} \xB7 ${n.entries.filter(l=>l.kind==="file").length} files${a?` \xB7 about ${Et(a)}`:""}`});let c=[{direction:"download",title:"Download to this vault",empty:"No hosted changes to download."},{direction:"upload",title:"Upload to hosted",empty:"No local changes to upload."},{direction:"attention",title:"Needs attention",empty:"Nothing is blocking or excluded."}];for(let l of c){let u=n.entries.filter(h=>h.direction===l.direction);if(!u.length&&l.direction!=="attention")continue;let d=i.createEl("section",{cls:"mdbase-transfer-group"});d.setAttr("data-direction",l.direction);let f=d.createDiv({cls:"mdbase-transfer-group-heading"}),p=f.createSpan({cls:"mdbase-transfer-group-icon"});if((0,ce.setIcon)(p,l.direction==="download"?"download":l.direction==="upload"?"upload":"circle-alert"),f.createEl("h4",{text:l.title}),f.createSpan({text:String(u.length),cls:"mdbase-transfer-count"}),!u.length){d.createDiv({cls:"mdbase-transfer-empty",text:l.empty});continue}let m=d.createDiv({cls:"mdbase-transfer-ledger"});for(let h of u.slice(0,250)){let y=m.createDiv({cls:"mdbase-transfer-row"});y.createSpan({cls:"mdbase-transfer-action",text:h.action}).setAttr("data-action",h.action);let v=y.createDiv({cls:"mdbase-transfer-body"}),_=v.createDiv({cls:"mdbase-transfer-path"});if(_.createEl("code",{text:h.path}),_.createSpan({cls:"mdbase-transfer-kind",text:h.kind==="file"?"File":"Markdown"}),h.estimatedBytes!==void 0&&_.createSpan({cls:"mdbase-transfer-size",text:Et(h.estimatedBytes)}),v.createDiv({text:h.detail}),h.direction==="attention"){let w=y.createEl("button",{text:"Open"});w.onclick=()=>void this.host.openFileByPath(h.path)}}u.length>250&&m.createDiv({cls:"mdbase-transfer-more",text:`${u.length-250} more items are included in this transfer.`})}n.collisions.length?i.createDiv({cls:"mdbase-inline-error",text:"Resolve path collisions before the first sync. Existing local files are never overwritten without review."}):n.local_issues.length&&i.createDiv({cls:"mdbase-inline-message",text:"Invalid local files stay untouched and unsynced; valid changes can continue."})}renderConflicts(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.id="mdbase-sync-conflicts",i.createEl("h3",{text:"Conflicts"}),i.createEl("p",{text:"Inspect both versions before deciding. Decisions are checked again immediately before they are applied."});for(let s of n.conflicts){let o=i.createDiv({cls:"mdbase-conflict-row"}),a=o.createDiv({cls:"mdbase-conflict-summary"});a.createEl("strong",{text:s.path??s.object_id}),a.createDiv({text:s.entity==="file"?"Binary file conflict":"Note conflict",cls:"mdbase-muted"}),a.createDiv({text:s.message});let c=o.createDiv({cls:"mdbase-actions"}),l=`${s.object_id}:${s.decision_id}`,u=this.conflictComparisons.get(l),d=c.createEl("button",{text:u?"Hide versions":this.loadingConflictComparisons.has(l)?"Loading versions\u2026":"Compare versions"});d.disabled=this.busy||this.loadingConflictComparisons.has(l),d.onclick=()=>{if(u){this.conflictComparisons.delete(l),this.render();return}this.loadConflictComparison(s,l)};for(let f of["local","remote"]){let p=c.createEl("button",{text:f==="local"?"Keep local":"Use hosted"});p.disabled=this.busy,p.onclick=()=>void this.resolveMirrorConflict(s,f,!1)}if(s.path){let f=c.createEl("button",{text:"Keep both"});f.disabled=this.busy,f.onclick=()=>void this.resolveMirrorConflict(s,"remote",!0)}u&&this.renderConflictComparison(o,u)}}async loadConflictComparison(t,n){this.loadingConflictComparisons.add(n),this.render();try{this.conflictComparisons.set(n,await this.host.connectSync.conflictComparison(t))}catch(i){let s=Zt(i);this.syncProblem=s,this.host.setSyncProblem(s),this.transientMessage=s.message,s.code==="conflict_decision_stale"&&await this.refreshMirrorStatus()}finally{this.loadingConflictComparisons.delete(n),this.render()}}renderConflictComparison(t,n){let i=t.createDiv({cls:"mdbase-conflict-comparison"});if(n.entity==="record"){let o=N0(n.local.document??"",n.remote.document??""),a=i.createDiv({cls:"mdbase-conflict-legend"});a.createSpan({text:"\u2212 Local only",cls:"is-local"}),a.createSpan({text:"+ Hosted only",cls:"is-remote"});let c=i.createEl("pre",{cls:"mdbase-conflict-diff"});for(let l of o.lines){let u=c.createEl("div",{cls:`is-${l.kind}`});u.createSpan({text:l.kind==="local"?"\u2212":l.kind==="remote"?"+":" "}),u.createSpan({text:l.value||" "})}o.truncated&&i.createDiv({cls:"mdbase-muted",text:"Diff shortened for a responsive review. Open the local note to inspect it in full."});return}let s=i.createDiv({cls:"mdbase-conflict-sides"});this.renderConflictSide(s,"Local",n.local),this.renderConflictSide(s,"Hosted",n.remote)}renderConflictSide(t,n,i){let s=t.createDiv({cls:"mdbase-conflict-side"});if(s.createEl("h4",{text:n}),i.state==="absent"){s.createDiv({cls:"mdbase-muted",text:"File is absent in this version."});return}if(i.path&&s.createEl("code",{text:i.path}),i.size!==void 0&&s.createDiv({text:`Size: ${Et(i.size)}`}),i.modifiedAt&&s.createDiv({text:`Modified: ${new Date(i.modifiedAt).toLocaleString()}`}),i.revision&&s.createDiv({cls:"mdbase-conflict-digest",text:`Digest: ${i.revision}`}),i.resourceUrl&&i.path&&/\.(?:avif|gif|jpe?g|png|svg|webp)$/i.test(i.path)){let o=s.createEl("img",{cls:"mdbase-conflict-image-preview"});o.src=i.resourceUrl,o.alt=`${n} preview of ${i.path}`}else n==="Hosted"&&s.createDiv({cls:"mdbase-muted",text:"Hosted binary preview is materialized only after you choose it."})}async resolveMirrorConflict(t,n,i){await this.perform(async()=>{let s=null;try{i&&(s=await this.host.connectSync.preserveConflictCopy(t.path??"")),this.mirrorPreview=null;let o=await O0(this.host.connectSync,t.object_id,t.decision_id,n);this.mirrorStatus=o.status,this.mirrorPreview=o.preview,this.host.setSyncStatus(o.status),this.conflictComparisons.delete(`${t.object_id}:${t.decision_id}`),this.transientMessage=s?`Both versions are safe: the hosted version will use the original path and the local version was copied to ${s}. Review the refreshed plan before syncing.`:"Conflict resolved. Review the refreshed engine plan before syncing.",await this.host.recordSyncActivity({summary:s?"Conflict kept as two files":`Conflict resolved with ${n==="local"?"local":"hosted"} version`,detail:this.transientMessage,path:t.path??void 0,tone:"info",requiresAcknowledgement:!1})}catch(o){let a=Zt(o);s&&(a.message=`The local copy at ${s} is safe, but the original changed again. Review the newest versions before deciding.`),this.syncProblem=a,this.host.setSyncProblem(a),this.transientMessage=a.message,a.code==="conflict_decision_stale"&&(this.mirrorPreview=null,await this.refreshMirrorStatus()),await this.host.recordSyncActivity({summary:a.title,detail:a.message,path:t.path??void 0,tone:"attention",requiresAcknowledgement:!0})}})}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){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.setAttr("data-focus-key","issue-search"),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?.focus(),g?.setSelectionRange(g.value.length,g.value.length)};let f=this.issueQuery.trim().toLowerCase(),p=i.filter(g=>this.issueSeverity!=="all"&&g.severity!==this.issueSeverity?!1:f?`${g.path} ${g.code} ${g.field??""} ${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,[...y.get(g.path)??[],g]);for(let[g,v]of y){let _=n.createEl("section",{cls:"mdbase-issue-group"}),w=_.createDiv({cls:"mdbase-issue-group-header"}),A=w.createEl("button",{cls:"mdbase-issue-file-button"});(0,ce.setIcon)(A.createSpan({cls:"mdbase-issue-file-icon"}),"file-text"),A.createSpan({cls:"mdbase-issue-file-path",text:g}),A.onclick=()=>void this.host.openFileByPath(g),w.createSpan({cls:"mdbase-issue-file-count",text:`${v.length} ${v.length===1?"issue":"issues"}`});for(let x of v){let M=_.createDiv({cls:"mdbase-issue-row"});M.setAttr("data-severity",x.severity),M.createSpan({cls:"mdbase-issue-indicator"}).setAttr("aria-hidden","true");let S=M.createDiv({cls:"mdbase-issue-metadata"});S.createEl("code",{text:x.code}),S.createDiv({cls:"mdbase-issue-context",text:`${x.severity==="warn"?"Warning":"Error"}${x.field?` \xB7 ${x.field}`:""}`}),M.createDiv({cls:"mdbase-issue-row-message",text:x.message});let C=M.createDiv({cls:"mdbase-issue-row-actions"}),$=C.createEl("button",{text:x.field?"Open field":"Open file"});$.setAttr("aria-label",`Open ${x.path}${x.field?` at ${x.field}`:""}`),$.onclick=()=>void this.host.openFileByPath(x.path,x.field);let V=this.host.getQuickFixLabel(x);if(V){let q=C.createEl("button",{text:V});q.addClass("mod-cta"),q.onclick=()=>void this.perform(async()=>{await this.host.applyQuickFix(x)})}}}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 ce.Notice("Save or discard the current type changes before switching.");return}let i=++this.typeSelectionVersion,s=await this.host.loadTypeModel(t);if(i!==this.typeSelectionVersion)return;let o=this.host.loadTypeDraft(t),a=o?.version===1&&o.sourceRevision===(s.sourceRevision??null),c=a?Jn(o.model):s;this.selectedPath=t,this.model=c,this.originalModel=Jn(s),this.yamlDraft=a&&o.yamlDraft?o.yamlDraft:`${bt(Yp(c),c.body)} -`,this.dirty=!cl(this.originalModel,c),this.editorMode=a&&o.editorMode==="yaml"?"yaml":"design",this.editorMode==="yaml"&&(this.dirty=!0),a&&this.dirty?this.transientMessage=`Recovered unsaved changes for ${t}.`:o&&!a&&(this.transientMessage=`An older draft for ${t} was kept, but the source changed. The current file is shown.`),this.render()}createType(){if(this.dirty){new ce.Notice("Save or discard the current type changes before creating another type.");return}this.typeSelectionVersion+=1;let t=this.host.loadTypeDraft(null),n=t?.version===1?Jn(t.model):Fp();this.selectedPath=null,this.model=n,this.originalModel=null,this.yamlDraft=t?.yamlDraft??"",this.dirty=!0,t&&(this.transientMessage="Recovered an unsaved new type."),this.editorMode=t?.editorMode??"design",this.render()}switchEditorMode(t){if(!(!this.model||t===this.editorMode)){if(t==="yaml")try{this.yamlDraft=`${bt(Yp(this.model),this.model.body)} -`}catch(n){new ce.Notice(n instanceof Error?n.message:String(n));return}else if(!this.readYamlDraftIntoModel())return;this.editorMode=t,this.render()}}readYamlDraftIntoModel(){let t=dt(this.yamlDraft);if(!t.hasFrontmatter||t.error)return new ce.Notice(`Invalid type YAML: ${t.error??"frontmatter is missing"}`),!1;if(t.frontmatter.kind!=="mdbase.type")return new ce.Notice("Canonical v0.3 type YAML requires kind: mdbase.type."),!1;try{return this.model=al(t.frontmatter,t.body,this.model?.name||"type"),!0}catch(n){return new ce.Notice(n instanceof Error?n.message:String(n)),!1}}async saveCurrentType(){if(!this.model||this.model.specProfile!=="v0.3"||this.model.readOnlyReason||this.editorMode==="yaml"&&!this.readYamlDraftIntoModel())return;let n=ll(this.model,{knownTypes:this.typeEntries().map(o=>o.name),contracts:this.schema?.contracts.values()}).filter(o=>o.severity==="error");if(n.length){this.transientMessage=`${n.length} ${n.length===1?"error must":"errors must"} be fixed before saving.`,this.render(),new ce.Notice(n[0].message);return}let i=dl(this.originalModel,this.model).filter(o=>o.risk==="high");if(i.length&&!await new Xp(this.app).confirm(i))return;let s=this.model;await this.perform(async()=>{let o=this.selectedPath,a=await this.host.saveTypeModel(s,o,this.originalModel?.sourceRevision);await this.host.clearTypeDraft(o),o!==a.path&&await this.host.clearTypeDraft(a.path),this.selectedPath=a.path,this.originalModel=Jn(s),this.dirty=!1,this.transientMessage=`Saved ${a.path}.`,await this.refresh(!0)})}markDirty(t=!1){let n=this.dirty;if(this.dirty=this.editorMode==="yaml"?!0:!cl(this.originalModel,this.model),this.scheduleTypeDraftSave(),this.dirty&&!n&&(this.transientMessage=""),t||n!==this.dirty){this.render();return}let i=this.containerEl.querySelector(".mdbase-editor-title-line");i&&!i.querySelector(".mdbase-dirty")&&i.createSpan({cls:"mdbase-dirty",text:"Unsaved"});let s=this.containerEl.querySelector(".mdbase-editor-actions .mod-cta");s&&this.model?.specProfile==="v0.3"&&!this.model.readOnlyReason&&this.host.getMirrorProfile()?.mode!=="read_only"&&(s.disabled=!1);let o=this.containerEl.querySelector(".mdbase-change-review");if(o){let a=o.querySelector("p");a&&a.setText("Pending changes. Review details after leaving the current field.")}}scheduleTypeDraftSave(){this.draftSaveTimer!==null&&window.clearTimeout(this.draftSaveTimer),this.draftSaveTimer=window.setTimeout(()=>{this.draftSaveTimer=null,this.flushTypeDraft()},2e3)}async flushTypeDraft(){if(this.draftSaveTimer!==null&&(window.clearTimeout(this.draftSaveTimer),this.draftSaveTimer=null),!this.model||!this.dirty)return;let t={version:1,path:this.selectedPath,sourceRevision:this.originalModel?.sourceRevision??null,model:Jn(this.model),editorMode:this.editorMode,yamlDraft:this.editorMode==="yaml"?this.yamlDraft:void 0,updatedAt:new Date().toISOString()};await this.host.saveTypeDraft(t)}async discardCurrentType(){let t=this.selectedPath;if(await this.host.clearTypeDraft(t),t){let n=await this.host.loadTypeModel(t);this.model=n,this.originalModel=Jn(n),this.yamlDraft=`${bt(Yp(n),n.body)} -`,this.dirty=!1}else this.model=null,this.originalModel=null,this.yamlDraft="",this.dirty=!1;this.transientMessage="Unsaved changes discarded.",this.render()}async refreshMirrorStatus(){if(!this.host.connectSync.isSyncing())try{this.mirrorStatus=await this.host.connectSync.status(),this.syncProblem=null,this.host.setSyncStatus(this.mirrorStatus)}catch(t){this.mirrorStatus=null,this.syncProblem=Zt(t),this.host.setSyncProblem(this.syncProblem),this.transientMessage=this.syncProblem.message}}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 ce.Notice(i)}finally{this.busy=!1,this.render()}}}};function Yp(r){return r.specProfile==="v0.3"&&!r.readOnlyReason?Ji(r):Jn(r.originalFrontmatter??{name:r.name,fields:Object.fromEntries(r.fields.map(e=>[e.name,e.definition]))})}var Mo=class{constructor(e,t){this.delayMs=e;this.task=t;this.entries=new Map;if(!Number.isFinite(e)||e<0)throw new Error("Debounce delay must be a non-negative finite number.")}has(e){return this.entries.has(e)}schedule(e,t){let n=this.entries.get(e);n||(n={value:t,revision:0,timer:null,ready:!1,running:!1},this.entries.set(e,n)),n.value=t,n.revision+=1,n.ready=!1,n.timer!==null&&clearTimeout(n.timer),n.timer=setTimeout(()=>{this.entries.get(e)===n&&(n.timer=null,n.ready=!0,this.drain(e,n))},this.delayMs)}cancel(e){let t=this.entries.get(e);t&&(t.timer!==null&&clearTimeout(t.timer),this.entries.delete(e))}clear(){for(let e of this.entries.values())e.timer!==null&&clearTimeout(e.timer);this.entries.clear()}async drain(e,t){if(this.entries.get(e)!==t||t.running||!t.ready)return;t.ready=!1,t.running=!0;let n=t.revision,i=t.value,s=()=>this.entries.get(e)===t&&t.revision===n;try{await this.task(i,s)}finally{t.running=!1,this.entries.get(e)===t&&(t.ready?this.drain(e,t):t.timer===null&&t.revision===n&&this.entries.delete(e))}}};var zN={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null,typeDrafts:{},syncActivity:[]};function HN(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"&&(e.selectiveSync===void 0||Array.isArray(e.selectiveSync.file_classes)&&Array.isArray(e.selectiveSync.excluded_folders))}function KN(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var To=class extends O.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){this.settled||(this.settled=!0,this.resolvePromise?.(t),this.resolvePromise=null)}},eh=class extends O.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=>{let s=i.match?.path_glob??"";return`${i.name} ${i.display_name_key??""} ${i.filePath} ${s}`.toLowerCase().includes(n)}).slice(0,100):this.typeDefs.slice(0,100)}renderSuggestion(t,n){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(t.fields??{}).length} fields`}),t.match?.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 Zp(r,e){return new Promise(t=>{new eh(r,e,i=>{if(i.type==="selected"){t(i.typeDef);return}t(null)}).open()})}var th=class extends O.PluginSettingTab{constructor(e,t){super(e,t),this.plugin=t}display(){let{containerEl:e}=this;e.empty(),new O.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 O.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 O.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 O.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()}))}},pl=class extends O.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.sortedIssuesCache=null;this.mirrorStatus=null;this.mirrorProgress=null;this.fileProgress=null;this.currentSyncProblem=null;this.localChangeObserved=!1;this.schemaCache=null;this.schemaLoadPromise=null;this.saveValidationDebounceMs=2e3;this.schemaRefreshDebounceMs=2e3;this.saveValidations=new Mo(this.saveValidationDebounceMs,async(t,n)=>{try{await this.validateFileAndStore(t,"save",n)}catch(i){console.error("mdbase: background validation failed",i)}});this.schemaRefreshes=new Mo(this.schemaRefreshDebounceMs,async()=>{this.invalidateSchemaCache(),this.refreshWorkspaceViews()});this.connectSync=new nl(t,{getMirrorProfile:()=>this.getMirrorProfile(),saveMirrorProfile:async i=>{this.settings.mirrorProfile=i,await this.saveSettings(),i?this.refreshSyncStatus():(this.mirrorStatus=null,this.currentSyncProblem=null,this.localChangeObserved=!1,this.updateStatusBar())}}),this.interopBridge=new Ra(t,()=>this.settings?.interopEnabled===!0),this.api={apiVersion:1,interop:this.interopBridge,getInteropStatus:()=>({enabled:this.settings?.interopEnabled===!0,profileVersion:"0.1"})}}async onload(){await this.loadSettings(),await this.connectSync.initialize(),(0,O.addIcon)(Qi,R0),this.statusBarEl=this.addStatusBarItem(),this.statusBarEl.addClass("mdbase-status-bar"),this.statusBarEl.setAttr("role","button"),this.statusBarEl.setAttr("tabindex","0"),this.registerDomEvent(this.statusBarEl,"click",()=>void this.openStatusDestination()),this.registerDomEvent(this.statusBarEl,"keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.openStatusDestination())}),this.updateStatusBar(),this.registerView(Yn,n=>new fl(n,this)),this.addSettingTab(new th(this.app,this)),this.addRibbonIcon(Qi,"Open mdbase",()=>void this.openWorkspace()),this.addCommand({id:"mdbase-open",name:"Open workspace",callback:()=>void this.openWorkspace()}),this.addCommand({id:"mdbase-initialize-collection",name:"Initialize collection",callback:()=>void this.initializeCollectionCommand()}),this.addCommand({id:"mdbase-create-type",name:"Create type definition",callback:()=>void this.createTypeDefinitionCommand()}),this.addCommand({id:"mdbase-edit-type",name:"Edit type definition",callback:()=>void this.editTypeDefinitionCommand()}),this.addCommand({id:"mdbase-edit-current-type",name:"Edit current type definition",callback:()=>void this.editCurrentTypeDefinitionCommand()}),this.addCommand({id:"mdbase-create-note-from-type",name:"Create note from type",callback:()=>void this.createNoteFromTypeCommand()}),this.addCommand({id:"mdbase-validate-current-note",name:"Validate current note",callback:()=>void this.validateCurrentNoteCommand()}),this.addCommand({id:"mdbase-validate-collection",name:"Validate collection",callback:()=>void this.runCollectionValidation(!0)}),this.addCommand({id:"mdbase-open-issues-view",name:"Open issues view",callback:()=>void this.openWorkspace("issues")}),this.addCommand({id:"mdbase-sync",name:"Review sync changes",callback:()=>void this.reviewSyncCommand()}),this.addCommand({id:"mdbase-open-sync",name:"Open sync",callback:()=>void this.openWorkspace("sync")}),this.addCommand({id:"mdbase-sync-now",name:"Sync now",callback:()=>void this.syncNowCommand()}),this.addCommand({id:"mdbase-cancel-sync",name:"Cancel current sync",checkCallback:n=>this.connectSync.isSyncing()?(n||(this.connectSync.cancelSync(),this.setSyncProblem(Zt(new DOMException("Synchronization stopped.","AbortError")))),!0):!1}),this.addCommand({id:"mdbase-open-activity",name:"Open sync activity",callback:()=>void this.openSyncSection("activity")}),this.addCommand({id:"mdbase-resolve-conflicts",name:"Resolve sync conflicts",callback:()=>void this.openSyncSection("conflicts")}),this.addCommand({id:"mdbase-reconnect",name:"Reconnect collection",callback:()=>void this.reconnectCommand()}),this.registerEvent(this.app.vault.on("modify",n=>{n instanceof O.TFile&&this.onVaultModify(n)})),this.registerEvent(this.app.vault.on("rename",(n,i)=>{n instanceof O.TFile&&this.onVaultRename(n,i)})),this.registerEvent(this.app.vault.on("delete",n=>{n instanceof O.TFile&&this.onVaultDelete(n)})),this.registerEvent(this.app.vault.on("create",n=>{n instanceof O.TFile&&this.onVaultCreate(n)})),this.registerEvent(this.app.workspace.on("file-open",n=>{this.settings.validateOnOpen&&(!(n instanceof O.TFile)||n.extension!=="md"||this.validateFileAndStore(n,"open"))})),this.registerEvent(this.app.workspace.on("editor-change",(n,i)=>{let s=i.file;s instanceof O.TFile&&(this.saveValidations.has(s.path)&&this.scheduleSaveValidation(s),this.schemaRefreshes.has("schema")&&this.isSchemaRelevantPath(s.path)&&this.scheduleSchemaRefresh())}));let t=this.app.workspace.getActiveFile();t&&this.settings.validateOnOpen&&this.validateFileAndStore(t,"open"),this.getMirrorProfile()&&this.refreshSyncStatus(),this.registerInterval(window.setInterval(()=>{this.getMirrorProfile()&&!this.connectSync.isSyncing()&&this.refreshSyncStatus()},6e4))}onunload(){this.interopBridge.dispose().catch(t=>{console.error("mdbase: failed to dispose the interoperability bridge",t)}),this.app.workspace.getLeavesOfType(Yn).forEach(t=>t.detach()),this.saveValidations.clear(),this.schemaRefreshes.clear()}async loadSettings(){if(this.settings=Object.assign({},zN,await this.loadData()),!HN(this.settings.mirrorProfile))this.settings.mirrorProfile=null;else try{this.settings.mirrorProfile.selectiveSync=_r(this.settings.mirrorProfile.selectiveSync)}catch{this.settings.mirrorProfile.selectiveSync=_r()}(!this.settings.typeDrafts||typeof this.settings.typeDrafts!="object"||Array.isArray(this.settings.typeDrafts))&&(this.settings.typeDrafts={}),this.settings.syncActivity=D0(this.settings.syncActivity)}async saveSettings(){await this.saveData(this.settings)}getIssues(){return this.sortedIssuesCache??=Array.from(this.issueMap.values()).flat().sort((t,n)=>t.path.localeCompare(n.path)||t.severity.localeCompare(n.severity)||t.code.localeCompare(n.code)),this.sortedIssuesCache}getMirrorProfile(){return this.settings.mirrorProfile?JSON.parse(JSON.stringify(this.settings.mirrorProfile)):null}getSyncActivity(){return this.settings.syncActivity.map(t=>({...t}))}getCurrentSyncProblem(){return this.currentSyncProblem?{...this.currentSyncProblem}:null}setSyncStatus(t,n={}){this.mirrorStatus=t?JSON.parse(JSON.stringify(t)):null,n.clearLocalChanges&&(this.localChangeObserved=!1),this.currentSyncProblem=null,this.updateStatusBar()}setSyncProgress(t,n=null){this.mirrorProgress=t?{...t}:null,this.fileProgress=n?{...n}:null,this.updateStatusBar()}setSyncProblem(t){this.currentSyncProblem=t?{...t}:null,this.updateStatusBar()}async recordSyncActivity(t){this.settings.syncActivity=L0(this.settings.syncActivity,j0(t)),await this.saveSettings(),this.refreshWorkspaceViews()}async dismissSyncActivity(t){this.settings.syncActivity=this.settings.syncActivity.filter(n=>n.id!==t),await this.saveSettings(),this.refreshWorkspaceViews()}async clearCompletedSyncActivity(){this.settings.syncActivity=this.settings.syncActivity.filter(t=>t.requiresAcknowledgement),await this.saveSettings(),this.refreshWorkspaceViews()}async refreshSyncStatus(){if(!this.getMirrorProfile())return this.setSyncStatus(null),null;if(this.connectSync.isSyncing())return this.mirrorStatus;try{let t=await this.connectSync.status();return this.setSyncStatus(t),t}catch(t){return this.setSyncProblem(Zt(t)),null}}async loadWorkspaceSchema(t=!1){return this.getConfigAndTypes(t)}async loadTypeModel(t){let n=this.app.vault.getAbstractFileByPath((0,O.normalizePath)(t));if(!(n instanceof O.TFile))throw new Error(`Type file not found: ${t}`);let i=await this.app.vault.cachedRead(n),s=dt(i);if(!s.hasFrontmatter||s.error)throw new Error(`Invalid type frontmatter: ${s.error??"frontmatter is missing"}`);let o=al(s.frontmatter,s.body,n.basename);return o.sourceRevision=Hp(i),o}loadTypeDraft(t){let n=this.settings.typeDrafts[t??"__new__"];return n?JSON.parse(JSON.stringify(n)):null}async saveTypeDraft(t){this.settings.typeDrafts[t.path??"__new__"]=JSON.parse(JSON.stringify(t)),await this.saveSettings()}async clearTypeDraft(t){let n=t??"__new__";n in this.settings.typeDrafts&&(delete this.settings.typeDrafts[n],await this.saveSettings())}async saveTypeModel(t,n,i){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access. Re-enroll it with write access before editing types.");let s=await Ei(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 o=n?this.app.vault.getAbstractFileByPath((0,O.normalizePath)(n)):null;if(o!=null&&!(o instanceof O.TFile))throw new Error(`Type file not found: ${n}`);let a=await this.writeTypeDefinition(s,t,o,i);return this.refreshWorkspaceViews(!0),a}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 S0(this.app.vault)}async applyMigration(t,n){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");let i=await $0(this.app.vault,t,{allowLossy:n});if(!i.applied)throw new Error(i.restored?`Migration failed and all writes were rolled back. ${i.error??""}`.trim():`Migration needs manual recovery. See ${i.manifestPath}. ${i.error??""}`.trim());this.invalidateSchemaCache(),new O.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 O.TFile)){new O.Notice(`File not found: ${t.path}`);return}let i=await this.app.vault.cachedRead(n),s=dt(i);if(s.error){new O.Notice(`Cannot apply quick fix: invalid frontmatter (${s.error})`);return}if(["unknown_field","schema_additional_properties"].includes(t.code)&&t.field){let o=ja(t.field);if(!(o in s.frontmatter)){new O.Notice(`Field '${o}' not found in frontmatter.`);return}delete s.frontmatter[o],await this.app.vault.modify(n,`${bt(s.frontmatter,s.body)} -`),new O.Notice(`Removed '${o}' from ${n.basename}`),await this.validateFileAndStore(n,"manual");return}if(["missing_required","schema_required"].includes(t.code)&&t.field){let o=ja(t.field);s.frontmatter[o]===void 0&&(s.frontmatter[o]="TODO");let a=s.hasFrontmatter?s.body:i;await this.app.vault.modify(n,`${bt(s.frontmatter,a)} -`),new O.Notice(`Added placeholder '${o}' to ${n.basename}`),await this.validateFileAndStore(n,"manual");return}new O.Notice("No quick fix available for this issue.")}async openFileByPath(t,n){let i=this.app.vault.getAbstractFileByPath(t);if(!(i instanceof O.TFile)){new O.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 O.MarkdownView))return;let s=i.view;if(!(s.file instanceof O.TFile)||s.file.path!==t.path)return;let o=s.editor,a=o.lineCount();if(a<3)return;let c=ja(n),l=new RegExp(`^\\s*${KN(c)}\\s*:`);if(o.getLine(0).trim()==="---")for(let u=1;u({...s,path:n}))),this.sortedIssuesCache=null,this.refreshIssueViews())}clearPendingSaveValidation(t){this.saveValidations.cancel(t)}scheduleSaveValidation(t){this.saveValidations.schedule(t.path,t)}scheduleSchemaRefresh(){this.schemaRefreshes.schedule("schema",void 0)}refreshSchemaNow(){this.schemaRefreshes.cancel("schema"),this.invalidateSchemaCache(),this.refreshWorkspaceViews()}isSchemaRelevantPath(t){let n=(0,O.normalizePath)(t);if(n==="mdbase.yaml")return!0;let i=new Set(["_types","_contracts"]);this.schemaCache&&(i.add((0,O.normalizePath)(this.schemaCache.config.settings.types_folder)),i.add((0,O.normalizePath)(this.schemaCache.config.settings.contracts_folder??"_contracts")));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 Ei(this.app.vault);if(!n)return null;let i=await J_(this.app.vault,n),s=await Y_(this.app.vault,n);return{config:n,types:i,contracts:s}})();try{let n=await this.schemaLoadPromise;return n&&(this.schemaCache=n),n}finally{this.schemaLoadPromise=null}}async requireConfigAndTypes(t={}){let n=t.background??!1,i=await this.getConfigAndTypes(t.forceReload??!1);return i?(i.types.size===0&&!n&&new O.Notice(`No types found in ${i.config.settings.types_folder}`),i):(n||new O.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}onVaultModify(t){this.observeLocalMirrorChange(t.path),this.isSchemaRelevantPath(t.path)&&this.scheduleSchemaRefresh(),this.settings.validateOnSave&&t.extension==="md"&&this.scheduleSaveValidation(t)}onVaultRename(t,n){this.observeLocalMirrorChange(n),this.observeLocalMirrorChange(t.path),(this.isSchemaRelevantPath(n)||this.isSchemaRelevantPath(t.path))&&this.refreshSchemaNow(),t.extension==="md"&&(this.clearPendingSaveValidation(n),this.moveFileIssues(n,t.path),this.settings.validateOnSave&&this.scheduleSaveValidation(t))}onVaultDelete(t){this.observeLocalMirrorChange(t.path),this.isSchemaRelevantPath(t.path)&&this.refreshSchemaNow(),t.extension==="md"&&(this.clearPendingSaveValidation(t.path),this.clearFileIssues(t.path))}onVaultCreate(t){this.observeLocalMirrorChange(t.path),this.isSchemaRelevantPath(t.path)&&this.refreshSchemaNow()}observeLocalMirrorChange(t){if(!this.getMirrorProfile()||this.connectSync.isSyncing())return;let n=(0,O.normalizePath)(t);[this.app.vault.configDir,".mdbase",".trash",".git"].some(s=>n===s||n.startsWith(`${s}/`))||(this.localChangeObserved=!0,this.updateStatusBar())}async validateFileAndStore(t,n,i=()=>!0){let s=await this.requireConfigAndTypes({background:n!=="manual"});if(!i())return[];if(!s)return n!=="manual"&&this.clearFileIssues(t.path),[];let o=await $f(this.app.vault,t,s.config,s.types);return i()&&(this.setFileIssues(t.path,o),n==="save"&&this.settings.showNoticeOnSave&&o.length>0&&new O.Notice(`mdbase: ${o.length} issue${o.length===1?"":"s"} in ${t.basename}`)),o}async initializeCollectionCommand(){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()){new O.Notice("This vault is configured as a mirror. Sync it instead of initializing a local collection.");return}let{created:t}=await H_(this.app.vault);if(this.invalidateSchemaCache(),t.length===0){new O.Notice("mdbase collection already initialized.");return}new O.Notice(`Initialized mdbase collection: ${t.join(", ")}`)}async reviewSyncCommand(){let t=await this.openWorkspace("sync");this.getMirrorProfile()&&await t.reviewSyncChanges()}async syncNowCommand(){let t=await this.openWorkspace("sync");this.getMirrorProfile()&&await t.syncNow()}async openSyncSection(t){(await this.openWorkspace("sync")).focusSyncSection(t)}async reconnectCommand(){let t=await this.openWorkspace("sync");this.getMirrorProfile()&&await t.reconnectCollection()}async createTypeDefinitionCommand(){(await this.openWorkspace("types")).createNewType()}async editTypeDefinitionCommand(){let t=await this.requireConfigAndTypes();if(!t||t.types.size===0){new O.Notice("No type definitions found.");return}let n=await Zp(this.app,[...t.types.values()]);if(!n)return;await(await this.openWorkspace("types")).editType(n.filePath)}async editCurrentTypeDefinitionCommand(){let t=this.app.workspace.getActiveFile();if(!(t instanceof O.TFile)||t.extension!=="md"){new O.Notice("Open a typed Markdown note or type definition first.");return}let n=await this.requireConfigAndTypes();if(!n)return;let s=[...n.types.values()].find(a=>a.filePath===t.path)??null;if(!s){let a=dt(await this.app.vault.cachedRead(t));if(a.error){new O.Notice(`Cannot identify this note's type: ${a.error}`);return}let l=rn(t.path,a.frontmatter,n.config,n.types).flatMap(u=>{let d=n.types.get(u);return d?[d]:[]});if(l.length===0){new O.Notice("The current note does not match a known type definition.");return}s=l.length===1?l[0]:await Zp(this.app,l)}if(!s){new O.Notice("The current note does not match a known type definition.");return}await(await this.openWorkspace("types")).editType(s.filePath)}async createNoteFromTypeCommand(){this.connectSync.assertLocalAuthorityWritable();let t=await this.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new O.Notice("No type definitions found.");return}let n=await Zp(this.app,Array.from(t.types.values()));if(!n)return;let i=Z_(n,t.config),s=ev(n,i);for(let[u,d]of s){let f=`Required field: ${u}`,p=await new To(this.app,f,d.type??"string").openAndGetValue();if(p==null)return;if(p.trim().length===0){new O.Notice(`Field '${u}' is required.`);return}try{i[u]=Ef(p,d)}catch(m){new O.Notice(`Invalid value for ${u}: ${m instanceof Error?m.message:String(m)}`);return}}let o=n.display_name_key??"title";if(i[o]==null){let u=await new To(this.app,`Optional ${o} (used for filename)`,"").openAndGetValue();u&&u.trim().length>0&&(i[o]=u.trim())}let a=await rv(this.app.vault,n,i),c=await new To(this.app,"Note path","Relative path in vault",a).openAndGetValue();if(c==null)return;let l=(0,O.normalizePath)(c.trim().length>0?c.trim():a);l.endsWith(".md")||(l=`${l}.md`);try{let u=await nv(this.app.vault,l,i);await this.app.workspace.getLeaf(!0).openFile(u),new O.Notice(`Created note: ${u.path}`),await this.validateFileAndStore(u,"manual")}catch(u){new O.Notice(u instanceof Error?u.message:String(u))}}async validateCurrentNoteCommand(){let t=this.app.workspace.getActiveFile();if(!(t instanceof O.TFile)||t.extension!=="md"){new O.Notice("Open a Markdown note first.");return}let n=await this.validateFileAndStore(t,"manual");n.length===0?new O.Notice("No issues in current note."):(new O.Notice(`Found ${n.length} issue${n.length===1?"":"s"} in current note.`),await this.openIssuesView())}async runCollectionValidation(t){let n=await this.requireConfigAndTypes({background:!1});if(!n)return;let i=await Q_(this.app.vault,n.config,n.types),s=new Map;for(let o of i){let a=s.get(o.path)??[];a.push(o),s.set(o.path,a)}if(this.issueMap=s,this.sortedIssuesCache=null,this.refreshIssueViews(),t)if(i.length===0)new O.Notice("Collection validation passed with no issues.");else{let o=i.filter(c=>c.severity==="error").length,a=i.length-o;new O.Notice(`Collection validation: ${o} error(s), ${a} warning(s)`),await this.openIssuesView()}}async ensureFolderExists(t){let n=(0,O.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,s){let o=n.name.trim();if(!o)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 a=Ji(n),c=n.body.trim()||`# ${o} +`),i=t.length>200||n.length>200,s=t.slice(0,200),o=n.slice(0,200),a=Array.from({length:s.length+1},()=>new Uint16Array(o.length+1));for(let d=s.length-1;d>=0;d-=1)for(let f=o.length-1;f>=0;f-=1)a[d][f]=s[d]===o[f]?a[d+1][f+1]+1:Math.max(a[d+1][f],a[d][f+1]);let c=[],l=0,u=0;for(;(l=300);)l=o.length||l=a[l][u+1]?(c.push({kind:"local",value:s[l]}),l+=1):(c.push({kind:"remote",value:o[u]}),u+=1);return{lines:c,truncated:i||l0)return{actionLabel:"Fix local files before syncing",actionDisabled:!0,message:"Synchronization is paused. Fix every listed local file, then refresh the review."};let n=r.actions.filter(s=>s.command!=="advance_checkpoint").length,i=r.actions.some(s=>s.command==="advance_checkpoint");return{actionLabel:n?`Sync ${n} ${n===1?"outcome":"outcomes"}`:i?"Confirm sync checkpoint":"Already up to date",actionDisabled:t||r.actions.length===0,message:e?"Review each transfer below, then sync when ready.":"This vault and the hosted collection are already aligned."}}function At(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(r<10*1024?1:0)} KB`:r<1024*1024*1024?`${(r/(1024*1024)).toFixed(r<10*1024*1024?1:0)} MB`:`${(r/(1024*1024*1024)).toFixed(1)} GB`}function ch(r){let{connected:e,status:t,progress:n,fileProgress:i,problem:s,validationIssues:o,localChangeObserved:a}=r;if(!e)return o?{state:"attention",label:`mdbase: ${o} ${o===1?"issue":"issues"}`,detail:"Open validation issues",destination:"issues"}:{state:"local",label:"mdbase: Local",detail:"This vault is not connected",destination:"sync"};if(i){let l=i.totalBytes>0?Math.min(100,Math.round(i.transferredBytes/i.totalBytes*100)):100;return{state:"syncing",label:`mdbase: ${i.direction==="upload"?"Uploading":"Downloading"} ${l}%`,detail:`${i.path} \xB7 ${At(i.transferredBytes)} of ${At(i.totalBytes)}`,destination:"sync"}}if(n)return{state:"syncing",label:`mdbase: Syncing${n.total==null?"":` ${n.completed}/${n.total}`}`,detail:"Open synchronization progress",destination:"sync"};if(s)return{state:s.action==="resume"?"paused":s.action==="retry"?"offline":"attention",label:s.action==="resume"?"mdbase: Paused":s.action==="retry"?"mdbase: Offline":"mdbase: Needs attention",detail:s.title,destination:"sync"};if(t?.recovery_required||t?.conflicts.length||t?.local_issues.length||["attention","blocked","failed","stale"].includes(t?.state??""))return{state:"attention",label:"mdbase: Needs attention",detail:"Review synchronization",destination:"sync"};if(t?.state==="cancelled")return{state:"paused",label:"mdbase: Paused",detail:"Review and resume synchronization",destination:"sync"};let c=t?.pending??0;return a||c>0||t?.state==="changes_waiting"||t?.state==="planned"?{state:"waiting",label:c>0?`mdbase: ${c} ${c===1?"change":"changes"}`:"mdbase: Changes waiting",detail:"Review local and hosted changes",destination:"sync"}:t?.state==="up_to_date"?{state:"synced",label:"mdbase: Synced",detail:"Local and hosted collections are aligned",destination:"sync"}:{state:"waiting",label:"mdbase: Ready to sync",detail:"Review the first synchronization",destination:"sync"}}function nr(r){let e=xD(r);return e==="mirror_busy"?{code:e,title:"Synchronization is already running",message:"The active transfer is still using this vault. Its progress is shown below.",action:"resume",actionLabel:"Show progress"}:["mirror_credentials_missing","invalid_mirror_enrollment","mirror_enrollment_expired"].includes(e)?{code:e,title:"Connect approval is required again",message:"Your local files and mirror checkpoint are safe. Approve this vault again to restore access.",action:"reauthorize",actionLabel:"Sign in again"}:["operation_cancelled","cancelled","AbortError"].includes(e)?{code:e,title:"Synchronization paused safely",message:"Completed changes remain checkpointed. Review the current plan before resuming.",action:"resume",actionLabel:"Review and resume"}:["stale","stale_mirror_plan","mirror_plan_stale","conflict_decision_stale"].includes(e)?{code:e,title:"The collection changed again",message:"No stale decision was applied. Review the newest local and hosted versions.",action:"review",actionLabel:"Review newest changes"}:["enrollment_recovery_required","mirror_recovery_required","pending_mirror_recovery"].includes(e)?{code:e,title:"Synchronization needs recovery",message:"Your original files are safe. Resume from the durable checkpoint before disconnecting this vault.",action:"resume",actionLabel:"Resume recovery"}:{code:e,title:"Connect could not be reached",message:AD(r,"Your local files are safe. Check the connection and try again."),action:"retry",actionLabel:"Retry connection"}}function pS(r){return Array.isArray(r)?r.filter(ED).slice(-30):[]}function hS(r,e){return[...r.filter(t=>t.id!==e.id),e].slice(-30)}function mS(r){return{...r,id:crypto.randomUUID(),occurredAt:new Date().toISOString()}}function ED(r){if(!r||typeof r!="object"||Array.isArray(r))return!1;let e=r;return typeof e.id=="string"&&typeof e.occurredAt=="string"&&typeof e.summary=="string"&&(e.detail===void 0||typeof e.detail=="string")&&(e.path===void 0||typeof e.path=="string")&&["success","info","attention","error"].includes(e.tone??"")&&typeof e.requiresAcknowledgement=="boolean"}function xD(r){return r instanceof DOMException?r.name:r&&typeof r=="object"&&"code"in r&&typeof r.code=="string"?r.code:r instanceof Error&&r.name?r.name:"sync_failed"}function AD(r,e){return r instanceof Error&&r.message?r.message:e}var lh="https://connect.mdbase.dev",ai="mdbase-workspace-view",kD=["string","integer","number","boolean","date","datetime","time","enum","link","list","object","any"];function qe(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function oi(r){return JSON.parse(JSON.stringify(r))}function vl(r){return typeof r.type=="string"?r.type:"any"}function PD(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 yS(r,e,t){Object.defineProperty(r,e,{configurable:!0,enumerable:!0,writable:!0,value:t})}function Lt(r,e,t,n,i={}){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.setAttr("data-focus-key",`form-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}`),c.value=t,c.placeholder=i.placeholder??"",c.addEventListener("input",()=>n(c.value)),c}function Fe(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 CD(r){if(r<1e3)return String(r);let e=r<1e4?1:0;return`${(r/1e3).toFixed(e)}k`}function dh(r){if(!r)return"Never synced";let e=Date.parse(r);if(!Number.isFinite(e))return r;let t=Math.round((e-Date.now())/1e3),n=Math.abs(t),i=new Intl.RelativeTimeFormat(void 0,{numeric:"auto"});if(n<60)return i.format(t,"second");let s=Math.round(t/60);if(Math.abs(s)<60)return i.format(s,"minute");let o=Math.round(s/60);return Math.abs(o)<24?i.format(o,"hour"):i.format(Math.round(o/24),"day")}function MD(r){return r?r.state==="up_to_date"?"Up to date":r.state==="changes_waiting"?"Local changes waiting":["attention","blocked","failed","stale"].includes(r.state)||r.recovery_required?"Needs attention":r.state==="cancelled"?"Paused safely":r.state==="applying"?"Synchronizing":r.state==="planned"?"Review ready":"Ready for first sync":"Checking connection"}function uh(r){return r instanceof Error&&r.name==="AbortError"}var ph=class extends ce.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}confirm(t){return new Promise(n=>{this.resolve=n,this.titleEl.setText("Confirm high-impact type changes"),this.contentEl.createEl("p",{text:"These schema changes can change membership or invalidate existing records. The plugin will save only the type definition; it will not rewrite records."});let i=this.contentEl.createEl("ul",{cls:"mdbase-confirm-change-list"});for(let c of t)i.createEl("li",{text:c.summary});let s=this.contentEl.createDiv({cls:"modal-button-container"}),o=s.createEl("button",{text:"Keep reviewing"});o.onclick=()=>this.finish(!1);let a=s.createEl("button",{text:"Save high-impact changes"});a.addClass("mod-warning"),a.onclick=()=>this.finish(!0),this.open()})}onClose(){this.settled||this.finish(!1,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}},hh=class extends ce.Modal{constructor(){super(...arguments);this.resolve=null;this.settled=!1}choose(t){return new Promise(n=>{this.resolve=n,this.titleEl.setText("Disconnect this vault?"),this.contentEl.createEl("p",{text:`This stops synchronization with ${t}. It does not delete the hosted collection.`});let i=this.contentEl.createEl("ul");i.createEl("li",{text:"Keep local files leaves the current vault contents in place as an unsynced local copy."}),i.createEl("li",{text:"Remove synced files deletes only files that still exactly match the last checkpoint. Local edits are preserved."});let s=this.contentEl.createDiv({cls:"modal-button-container"}),o=s.createEl("button",{text:"Cancel"});o.onclick=()=>this.finish(null);let a=s.createEl("button",{text:"Disconnect and keep files"});a.onclick=()=>this.finish("keep");let c=s.createEl("button",{text:"Remove unchanged synced files"});c.addClass("mod-warning"),c.onclick=()=>this.finish("remove"),this.open()})}onClose(){this.settled||this.finish(null,!1),this.contentEl.empty()}finish(t,n=!0){this.settled||(this.settled=!0,this.resolve?.(t),this.resolve=null,n&&this.close())}},_l=class extends ce.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.fileProgress=null;this.syncProblem=null;this.conflictComparisons=new Map;this.loadingConflictComparisons=new Set;this.pendingSyncFocus=null;this.transientMessage="";this.issueQuery="";this.issueSeverity="all";this.issueLimit=250;this.enrollmentVerification="";this.enrollmentAbort=null;this.enrollmentControlUrl=lh;this.enrollmentMirrorName="Obsidian";this.enrollmentCollectionId="";this.enrollmentMode="read_write";this.filePolicyDraft=null;this.adoptionFileProgress="";this.draftSaveTimer=null;this.fieldQuery="";this.expandedFields=new Set;this.fieldIds=new WeakMap;this.nextFieldId=1;this.refreshVersion=0;this.typeSelectionVersion=0}getViewType(){return ai}getDisplayText(){return"mdbase"}getIcon(){return as}async onOpen(){this.containerEl.addClass("mdbase-workspace"),this.registerDomEvent(this.containerEl,"keydown",t=>{(t.metaKey||t.ctrlKey)&&t.key.toLowerCase()==="s"&&this.dirty&&(t.preventDefault(),this.saveCurrentType())}),await this.refresh(!0)}async onClose(){await this.flushTypeDraft(),this.enrollmentAbort?.abort(),this.enrollmentAbort=null}async refresh(t=!1){let n=++this.refreshVersion;try{let i=await this.host.loadWorkspaceSchema(t);if(n!==this.refreshVersion||(this.schema=i,this.selectedPath&&!this.typeEntries().some(s=>s.filePath===this.selectedPath)&&(this.selectedPath=null,this.model=null,this.originalModel=null),!this.selectedPath&&this.typeEntries().length&&!ce.Platform.isMobile&&(this.selectedPath=this.typeEntries()[0].filePath),this.selectedPath&&(!this.model||t)&&(await this.selectType(this.selectedPath,!1),n!==this.refreshVersion))||(this.destination==="sync"&&await this.refreshMirrorStatus(),n!==this.refreshVersion))return;this.render()}catch(i){if(n!==this.refreshVersion)return;this.transientMessage=i instanceof Error?i.message:String(i),this.render()}}showDestination(t){this.destination=t,t==="sync"?this.refreshMirrorStatus().then(()=>this.render()):this.render()}createNewType(){this.destination="types",this.createType()}async editType(t){this.destination="types",await this.selectType(t)}async reviewSyncChanges(){this.host.getMirrorProfile()&&await this.perform(()=>this.loadMirrorPreview())}async syncNow(){if(this.host.getMirrorProfile()){if(!this.mirrorPreview){await this.reviewSyncChanges(),this.mirrorPreview?.plan.actions.length&&new ce.Notice("The current transfer review is open. Run sync now again or confirm it in the mdbase view.");return}await this.perform(()=>this.applyReviewedSync())}}focusSyncSection(t){this.destination="sync",this.pendingSyncFocus=t,this.render(),window.setTimeout(()=>this.focusPendingSyncSection(),0)}async reconnectCollection(){await this.perform(async()=>{try{this.mirrorStatus=await this.host.connectSync.reconnect(),this.syncProblem=null,this.host.setSyncStatus(this.mirrorStatus),await this.host.recordSyncActivity({summary:"Collection reconnected",detail:"Connect credentials were renewed and the mirror checkpoint was preserved.",tone:"success",requiresAcknowledgement:!1}),this.transientMessage="Connection restored. Your mirror checkpoint was preserved."}catch(t){if(nr(t).action!=="reauthorize")throw t;await this.reauthorizeCollection()}})}typeEntries(){return this.schema?[...this.schema.types.values()].sort((t,n)=>t.name.localeCompare(n.name)):[]}render(){let t=this.containerEl,n=this.captureRenderSnapshot(t);t.empty(),t.addClass("mdbase-workspace");let i=t.createDiv({cls:"mdbase-shell"});this.renderTopbar(i),this.transientMessage&&i.createDiv({cls:"mdbase-inline-message",text:this.transientMessage}).setAttr("role","status");let s=i.createDiv({cls:"mdbase-workspace-content"});s.setAttr("data-scroll-key","workspace"),this.destination==="types"?this.renderTypes(s):this.destination==="sync"?this.renderSync(s):this.renderIssues(s),this.restoreRenderSnapshot(t,n)}captureRenderSnapshot(t){let n=t.ownerDocument,i=t.contains(n.activeElement)?n.activeElement:null,s=i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement?i:null,o=new Map;for(let a of Array.from(t.querySelectorAll("[data-scroll-key]"))){let c=a.getAttr("data-scroll-key");c&&o.set(c,{top:a.scrollTop,left:a.scrollLeft})}return{focusKey:i?.getAttr("data-focus-key")??null,selectionStart:s?.selectionStart??null,selectionEnd:s?.selectionEnd??null,scroll:o}}restoreRenderSnapshot(t,n){for(let[s,o]of n.scroll){let a=t.querySelector(`[data-scroll-key="${s}"]`);a&&(a.scrollTop=o.top,a.scrollLeft=o.left)}if(!n.focusKey)return;let i=t.querySelector(`[data-focus-key="${n.focusKey}"]`);i?.focus({preventScroll:!0}),(i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement)&&n.selectionStart!==null&&n.selectionEnd!==null&&i.setSelectionRange(n.selectionStart,n.selectionEnd)}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,ce.setIcon)(s,as),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:CD(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){let n=t.createDiv({cls:"mdbase-legacy-banner"}),i=n.createDiv();i.createEl("strong",{text:`mdbase ${this.schema?.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"});Fe(o,"Files replaced",String(n.operations.length)),Fe(o,"Type definitions",String(n.typeSummaries.length)),Fe(o,"Record reads verified",String(n.recordsVerified)),n.recordsSkipped&&Fe(o,"Records skipped",String(n.recordsSkipped)),Fe(o,"Record files rewritten","0"),Fe(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){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,ce.setIcon)(s,"plus"),s.disabled=(this.schema?.config.spec_version.startsWith("0.2.")??!0)||this.host.getMirrorProfile()?.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.setAttr("data-focus-key","type-search"),o.value=this.query,o.oninput=()=>{this.query=o.value,this.render();let u=this.containerEl.querySelector(".mdbase-type-search");u?.focus(),u?.setSelectionRange(u.value.length,u.value.length)};let a=n.createDiv({cls:"mdbase-type-list"});a.setAttr("data-scroll-key","type-list");let c=this.query.trim().toLowerCase(),l=this.typeEntries().filter(u=>`${u.name} ${u.description??""} ${u.filePath}`.toLowerCase().includes(c));if(!l.length){a.createDiv({cls:"mdbase-empty-list",text:c?"No matching types.":"No type definitions."});return}for(let u of l){let d=a.createEl("button",{cls:"mdbase-type-row"});u.filePath===this.selectedPath&&d.addClass("is-active"),d.setAttr("aria-current",u.filePath===this.selectedPath?"true":"false"),d.createSpan({cls:"mdbase-type-name",text:u.name}),d.createSpan({cls:"mdbase-type-meta",text:`${Object.keys(u.fields).length} fields \xB7 ${u.specProfile??"v0.2"}`}),d.onclick=()=>void this.selectType(u.filePath)}}renderTypeEditor(t){let n=t.createDiv({cls:"mdbase-type-editor-pane"});if(n.setAttr("data-scroll-key","type-editor"),!this.model){let h=n.createDiv({cls:"mdbase-empty-state"});h.createEl("h2",{text:"Choose a type"}),h.createEl("p",{text:"Select a type definition from the list to inspect or edit it."});return}let i=this.host.getMirrorProfile()?.mode==="read_only",s=this.model.specProfile==="v0.2"||i||!!this.model.readOnlyReason,o=this.model.readOnlyReason??(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,ce.setIcon)(c,"arrow-left"),c.onclick=()=>{if(this.dirty){new ce.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:this.model.specProfile??"v0.2"}),this.dirty&&u.createSpan({cls:"mdbase-dirty",text:"Unsaved"}),l.createDiv({cls:"mdbase-editor-path",text:this.selectedPath??"New type"});let d=a.createDiv({cls:"mdbase-editor-actions"});if(this.selectedPath){let h=this.selectedPath,y=d.createEl("button",{text:"Open source"});y.onclick=()=>void this.host.openFileByPath(h)}let f=d.createEl("button",{text:"Save"});if(f.addClass("mod-cta"),f.disabled=s||!this.dirty||this.busy,f.onclick=()=>void this.saveCurrentType(),this.dirty){let h=d.createEl("button",{text:"Discard"});h.onclick=()=>void this.discardCurrentType()}s&&n.createDiv({cls:"mdbase-readonly-note",text:o});let p=n.createDiv({cls:"mdbase-mode-switch"});p.setAttr("role","tablist");for(let[h,y]of[["design","Design"],["yaml","YAML"]]){let g=p.createEl("button",{text:y});g.setAttr("role","tab"),g.setAttr("aria-selected",String(this.editorMode===h)),this.editorMode===h&&g.addClass("is-active"),g.onclick=()=>this.switchEditorMode(h)}let m=n.createDiv({cls:"mdbase-editor-document"});m.setAttr("data-scroll-key","type-document"),this.editorMode==="design"?this.renderDesignEditor(m,this.model,s):this.renderYamlEditor(m,s),this.dirty&&!s&&this.renderDraftBar(n,this.model)}renderDraftBar(t,n){let i=bl(this.originalModel,n),o=gl(n,{knownTypes:this.typeEntries().map(p=>p.name),contracts:this.schema?.contracts.values()}).filter(p=>p.severity==="error").length,a=i.filter(p=>p.risk==="high").length,c=t.createDiv({cls:"mdbase-draft-bar"}),l=c.createDiv({cls:"mdbase-draft-summary"});l.createEl("strong",{text:`${i.length} pending ${i.length===1?"change":"changes"}`}),l.createSpan({text:o?`${o} ${o===1?"error":"errors"} to fix`:a?`${a} high-impact ${a===1?"change":"changes"}`:"Ready to save"});let u=c.createDiv({cls:"mdbase-actions"});if(this.editorMode==="design"){let p=u.createEl("button",{text:"Review"});p.onclick=()=>this.containerEl.querySelector("#mdbase-section-review")?.scrollIntoView({behavior:"smooth",block:"start"})}let d=u.createEl("button",{text:"Discard"});d.onclick=()=>void this.discardCurrentType();let f=u.createEl("button",{text:"Save changes"});f.addClass("mod-cta"),f.disabled=o>0||this.busy,f.onclick=()=>void this.saveCurrentType()}renderDesignEditor(t,n,i){let s=gl(n,{knownTypes:this.typeEntries().map(F=>F.name),contracts:this.schema?.contracts.values()});this.renderSectionNavigation(t,s);let o=t.createEl("section",{cls:"mdbase-editor-section"});o.id="mdbase-section-identity",o.createEl("h3",{text:"Identity"});let a=Lt(o,"Name",n.name,F=>{n.name=F,this.markDirty()},{description:"Stable type name used by collection records."});a.disabled=i;let c=Lt(o,"Description",n.description,F=>{n.description=F,this.markDirty()},{multiline:!0});c.disabled=i;let l=o.createDiv({cls:"mdbase-form-row"}),u=l.createEl("label",{text:"Display field"}),d=l.createEl("select");u.htmlFor=d.id="mdbase-display-field",d.createEl("option",{value:"",text:"Use the file name"});for(let F of n.fields)d.createEl("option",{value:F.name,text:F.name||"Unnamed field"});n.displayNameKey&&!n.fields.some(F=>F.name===n.displayNameKey)&&d.createEl("option",{value:n.displayNameKey,text:`${n.displayNameKey} \xB7 missing`}),d.value=n.displayNameKey,d.onchange=()=>{n.displayNameKey=d.value,this.markDirty()},d.disabled=i;let f=o.createEl("label",{cls:"mdbase-checkbox-row"}),p=f.createEl("input",{type:"checkbox"});p.checked=n.strictMode===!0,p.disabled=i,p.onchange=()=>{n.strictMode=p.checked,this.markDirty()},f.createSpan({text:"Reject undeclared fields"});let m=t.createEl("section",{cls:"mdbase-editor-section"});m.id="mdbase-section-membership",m.createEl("h3",{text:"Membership"});let h=Lt(m,"Path glob",n.matchPathGlob,F=>{n.matchPathGlob=F,this.markDirty()},{placeholder:"Projects/**/*.md"});h.disabled=i;let y=Lt(m,"Fields present",n.matchFieldsPresent,F=>{n.matchFieldsPresent=F,this.markDirty()},{description:"Comma-separated frontmatter keys."});y.disabled=i;let g=Lt(m,"Where",n.matchWhere,F=>{n.matchWhere=F,this.markDirty()},{multiline:!0,description:"YAML predicate, including contains and nested equality conditions.",placeholder:`tags: + contains: task`});g.disabled=i;let _=t.createEl("section",{cls:"mdbase-editor-section"});_.id="mdbase-section-fields";let v=_.createDiv({cls:"mdbase-section-header"});v.createEl("h3",{text:"Fields"});let w=v.createEl("button",{text:"Add field"});w.disabled=i,w.onclick=()=>{let F={type:"string"};n.fields.push({name:"",definition:F}),this.expandedFields.add(this.fieldId(F)),this.markDirty(!0)};let S=_.createDiv({cls:"mdbase-field-toolbar"}),x=n.fields.filter(F=>F.definition.required===!0).length;S.createDiv({cls:"mdbase-field-count",text:`${n.fields.length} ${n.fields.length===1?"field":"fields"} \xB7 ${x} required`});let C=S.createDiv({cls:"mdbase-field-toolbar-actions"}),$=C.createEl("input",{type:"search"});$.placeholder="Filter fields",$.setAttr("aria-label","Filter fields"),$.setAttr("data-focus-key","field-search"),$.value=this.fieldQuery,$.oninput=()=>{this.fieldQuery=$.value,this.render()};let M=C.createEl("button",{text:"Collapse all"});M.disabled=this.expandedFields.size===0,M.onclick=()=>{this.expandedFields.clear(),this.render()};let A=_.createDiv({cls:"mdbase-fields"}),W=this.fieldQuery.trim().toLowerCase(),q=n.fields.filter(F=>!W||this.fieldMatches(F.name,F.definition,W));for(let F of q){let Q=n.fields.indexOf(F);this.renderFieldRow(A,F,Q,i)}q.length||A.createDiv({cls:"mdbase-empty-list",text:n.fields.length?"No fields match this filter.":"No fields declared."});let oe=t.createEl("section",{cls:"mdbase-editor-section"});oe.id="mdbase-section-placement",oe.createEl("h3",{text:"Placement"});let P=Lt(oe,"Path pattern",n.pathPattern,F=>{n.pathPattern=F,this.markDirty()},{placeholder:"Notes/{title}.md"});P.disabled=i,this.renderContractEditor(t,n,i);let k=t.createEl("section",{cls:"mdbase-editor-section mdbase-change-review"});if(k.id="mdbase-section-review",k.createEl("h3",{text:"Change review"}),s.length){let F=k.createDiv({cls:"mdbase-diagnostic-summary"}),Q=s.filter(Xe=>Xe.severity==="error").length,fe=s.length-Q;F.createEl("strong",{text:`${Q} ${Q===1?"error":"errors"} \xB7 ${fe} ${fe===1?"warning":"warnings"}`});for(let Xe of s.slice(0,12)){let Ue=F.createDiv({cls:"mdbase-diagnostic-item"});Ue.setAttr("data-severity",Xe.severity),Ue.createEl("code",{text:Xe.path}),Ue.createSpan({text:Xe.message})}}if(!this.dirty)k.createEl("p",{text:"No pending changes."});else{let F=k.createEl("ul");for(let Q of bl(this.originalModel,n))F.createEl("li",{text:Q.summary}).setAttr("data-risk",Q.risk)}}renderSectionNavigation(t,n){let i=t.createDiv({cls:"mdbase-section-nav"});i.setAttr("aria-label","Type sections"),i.setAttr("data-scroll-key","section-nav");let s=[["identity","Overview"],["membership","Membership"],["fields","Fields"],["applications","Applications"],["review",n.some(o=>o.severity==="error")?"Review \xB7 errors":"Review"]];for(let[o,a]of s){let c=i.createEl("button",{text:a});c.onclick=()=>{this.containerEl.querySelector(`#mdbase-section-${o}`)?.scrollIntoView({behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth",block:"start"})}}}renderContractEditor(t,n,i){let s=t.createEl("section",{cls:"mdbase-editor-section mdbase-contracts-section"});s.id="mdbase-section-applications";let a=s.createDiv({cls:"mdbase-section-header"}).createDiv();a.createEl("h3",{text:"Works with applications"}),a.createDiv({cls:"mdbase-form-description",text:"Tell compatible applications what this type's fields mean."});let c=[...this.schema?.contracts.values()??[]],l=new Set(n.implementations.map(d=>`${d.contract}@${d.version}`)),u=c.filter(d=>!l.has(ss(d)));c.length||s.createDiv({cls:"mdbase-contract-empty",text:"No record contracts are installed in this collection. Add contract files under the configured contracts folder to connect this type to an application."});for(let d of n.implementations){let f=c.find(p=>p.id===d.contract&&p.version===d.version);this.renderContractImplementation(s,n,d,f,i)}if(u.length){let d=s.createDiv({cls:"mdbase-contract-add"}),f=d.createEl("label",{text:"Installed contract"}),p=d.createEl("select");f.htmlFor=p.id=`mdbase-contract-${Math.random().toString(36).slice(2)}`;for(let h of u)p.createEl("option",{value:ss(h),text:`${h.id} \xB7 ${h.version}`});let m=d.createEl("button",{text:"Connect application contract"});m.disabled=i,m.onclick=()=>{let h=u.find(y=>ss(y)===p.value);if(h)try{nS(n,h),this.markDirty(!0)}catch(y){new ce.Notice(y instanceof Error?y.message:String(y))}}}}renderContractImplementation(t,n,i,s,o){let a=t.createEl("article",{cls:"mdbase-contract-implementation"}),c=a.createDiv({cls:"mdbase-contract-header"}),l=c.createDiv();l.createEl("strong",{text:i.contract}),l.createSpan({cls:"mdbase-contract-version",text:i.version});let u=c.createEl("button",{text:"Remove"});if(u.disabled=o,u.onclick=()=>{iS(n,i.contract,i.version),this.markDirty(!0)},!s){a.createDiv({cls:"mdbase-contract-unavailable",text:"This exact contract is not installed in the collection. Restore it or remove this implementation before saving."});return}let d=Do(s),f=Lo(n),p=d.filter(v=>os(i,v)),m=d.filter(v=>v.required),h=m.filter(v=>os(i,v)).length,y=a.createEl("details");y.open=hW.reference===w),x=jo(v,S),C=_.createDiv({cls:`mdbase-contract-mapping-row ${x.level}`}),$=C.createDiv({cls:"mdbase-contract-field-definition"});$.createEl("code",{text:v.reference}),$.createSpan({cls:v.required?"mdbase-contract-required":"mdbase-contract-optional",text:v.required?"Required":"Optional"}),$.createEl("small",{text:v.description||oS(v.schema)});let M=C.createEl("select");M.setAttr("aria-label",`${i.contract} ${v.reference} source field`),M.setAttr("aria-invalid",x.level==="error"?"true":"false"),M.disabled=o,M.createEl("option",{value:"",text:v.required?"Choose a source field":"Not exposed"});for(let W of f){let q=jo(v,W),oe=M.createEl("option",{value:W.reference,text:`${W.reference} \xB7 ${W.type}${q.level==="warning"?" \xB7 review":""}`});oe.disabled=q.level==="error"}M.value=w,M.onchange=()=>{sS(i,v.reference,M.value||void 0),this.markDirty(!0)};let A=C.createDiv({cls:"mdbase-contract-mapping-status"});A.createEl("strong",{text:x.label}),A.createEl("small",{text:x.message})}if(s.binding_schema){let v=a.createEl("details",{cls:"mdbase-contract-settings"});v.open=!!i.binding;let w=v.createEl("summary");w.createSpan({text:"Contract settings"}),w.createSpan({cls:"mdbase-contract-summary",text:i.binding?"Configured":"Optional"});let S=v.createDiv({cls:"mdbase-contract-settings-body"});if(S.createEl("p",{cls:"mdbase-form-description",text:"Control how compatible applications interpret this type. Values follow the contract's schema."}),i.binding)this.renderContractSchemaValue(S,s.binding_schema,i.binding,x=>{qe(x)&&(rh(i,x),this.markDirty())},"Settings",o);else{let x=S.createEl("button",{text:"Configure settings"});x.disabled=o,x.onclick=()=>{let C=qo(s.binding_schema);qe(C)&&(rh(i,C),this.markDirty(!0))}}}}renderContractSchemaValue(t,n,i,s,o,a){if(xn(n)==="object"){let l=qe(i)?i:{},u=t.createEl("fieldset",{cls:"mdbase-contract-schema-object"});u.createEl("legend",{text:o});let d=qe(n.properties)?n.properties:{},f=new Set(Array.isArray(n.required)?n.required.map(String):[]),p=[...new Set([...f,...Object.keys(l).filter(h=>h in d)])];for(let h of p){let y=d[h];if(!qe(y))continue;let g=u.createDiv({cls:"mdbase-contract-schema-field"}),_=typeof y.description=="string"?y.description:void 0;g.createEl("label",{text:`${h}${f.has(h)?" \xB7 required":""}`}),_&&g.createEl("small",{text:_}),this.renderContractSchemaControl(g,y,l[h],v=>{s({...l,[h]:v})},h,a)}p.length||u.createDiv({cls:"mdbase-empty-list",text:"No settings declared."});let m=Object.keys(d).filter(h=>!p.includes(h));if(m.length){let h=u.createDiv({cls:"mdbase-contract-schema-add"}),y=h.createEl("select");for(let _ of m)y.createEl("option",{value:_,text:_});let g=h.createEl("button",{text:"Add optional setting"});g.disabled=a,g.onclick=()=>{let _=y.value,v=d[_];qe(v)&&s({...l,[_]:qo(v)})}}return}this.renderContractSchemaControl(t,n,i,s,o,a)}renderContractSchemaControl(t,n,i,s,o,a){let c=xn(n);if(Array.isArray(n.enum)){let u=t.createEl("select");u.setAttr("aria-label",o);for(let d of n.enum)u.createEl("option",{value:JSON.stringify(d),text:String(d)});u.value=JSON.stringify(i),u.disabled=a,u.onchange=()=>s(JSON.parse(u.value));return}if(c==="array"){let u=qe(n.items)?n.items:{type:"string"},d=Array.isArray(i)?i:[],f=t.createDiv({cls:"mdbase-contract-schema-array"});for(let[m,h]of d.entries()){let y=f.createDiv({cls:"mdbase-contract-schema-array-item"});y.createSpan({text:`${m+1}.`}),this.renderContractSchemaControl(y,u,h,_=>{s(d.map((v,w)=>w===m?_:v))},`${o} item ${m+1}`,a);let g=y.createEl("button",{text:"Remove"});g.disabled=a||d.length<=(typeof n.minItems=="number"?n.minItems:0),g.onclick=()=>s(d.filter((_,v)=>v!==m))}let p=t.createEl("button",{text:`Add ${o.toLowerCase()} item`});p.disabled=a||typeof n.maxItems=="number"&&d.length>=n.maxItems,p.onclick=()=>s([...d,qo(u)]);return}if(c==="object"){this.renderContractSchemaValue(t,n,i,s,o,a);return}if(c==="boolean"){let u=t.createEl("input",{type:"checkbox"});u.checked=i===!0,u.disabled=a,u.setAttr("aria-label",o),u.onchange=()=>s(u.checked);return}let l=t.createEl("input",{type:c==="number"||c==="integer"?"number":"text"});l.setAttr("aria-label",o),l.value=i==null?"":typeof i=="string"?i:typeof i=="number"||typeof i=="boolean"?String(i):"",l.disabled=a,l.oninput=()=>s(c==="number"||c==="integer"?Number(l.value):l.value)}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:()=>{this.model?.fields.splice(i,1),this.markDirty(!0)},readOnly:s,depth:0})}renderFieldDefinition(t,n,i){let s=t.createEl("details",{cls:"mdbase-field-node"});s.setAttr("data-depth",String(i.depth));let o=this.fieldId(n),a=!!this.fieldQuery.trim()&&this.fieldMatches(i.name??i.staticLabel??"",n,this.fieldQuery.trim().toLowerCase());s.open=this.expandedFields.has(o)||a,s.ontoggle=()=>{s.open?this.expandedFields.add(o):this.expandedFields.delete(o)};let c=s.createEl("summary",{cls:"mdbase-field-summary"});c.createSpan({cls:"mdbase-field-summary-name",text:i.name||i.staticLabel||"Unnamed field"}),c.createSpan({cls:"mdbase-field-summary-type",text:vl(n)}),c.createSpan({cls:"mdbase-field-summary-rule",text:i.required?"Required":i.staticLabel?"Item shape":"Optional"});let l=s.createDiv({cls:"mdbase-field-row"});if(i.staticLabel)l.createDiv({cls:"mdbase-field-role",text:i.staticLabel});else{let p=l.createEl("input",{type:"text",cls:"mdbase-field-name-control"});p.setAttr("data-focus-key",`field-${o}-name`),p.setAttr("aria-label",i.nameLabel),p.placeholder="fieldName",p.value=i.name??"",p.disabled=i.readOnly,i.onNameInput&&(p.oninput=()=>i.onNameInput?.(p.value)),i.onNameCommit&&(p.onchange=()=>i.onNameCommit?.(p.value,p))}let u=l.createEl("select",{cls:"mdbase-field-type-control"});u.setAttr("data-focus-key",`field-${o}-type`),u.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} type`);for(let p of kD){let m=p==="any"?"Any value":p[0].toUpperCase()+p.slice(1);u.createEl("option",{value:p,text:m})}u.value=vl(n),u.disabled=i.readOnly,u.onchange=()=>{n.type=u.value,u.value==="list"&&!qe(n.items)&&(n.items={type:"string"}),u.value==="object"&&!qe(n.fields)&&(n.fields={}),u.value==="enum"&&!Array.isArray(n.values)&&(n.values=[]),this.markDirty(!0)};let d=l.createEl("input",{type:"text",cls:"mdbase-field-description-control"});if(d.setAttr("data-focus-key",`field-${o}-description`),d.setAttr("aria-label",`${i.name||i.staticLabel||"Field"} description`),d.placeholder="Description",d.value=typeof n.description=="string"?n.description:"",d.disabled=i.readOnly,d.oninput=()=>{d.value?n.description=d.value:delete n.description,this.markDirty()},i.onRequiredChange){let p=l.createEl("label",{cls:"mdbase-field-required"}),m=p.createEl("input",{type:"checkbox"});m.setAttr("data-focus-key",`field-${o}-required`),m.checked=i.required===!0,m.disabled=i.readOnly,m.onchange=()=>i.onRequiredChange?.(m.checked),p.createSpan({text:"Required"})}if(i.onRemove){let p=l.createEl("button",{cls:"mdbase-field-remove"});p.setAttr("aria-label",`Remove ${i.name||i.staticLabel||"field"}`),(0,ce.setIcon)(p,"trash-2"),p.disabled=i.readOnly,p.onclick=i.onRemove}let f=vl(n);f==="enum"&&this.renderEnumFieldDetails(s,n,i),f==="link"&&this.renderLinkFieldDetails(s,n,i),f==="list"&&this.renderListFieldDetails(s,n,i),f==="object"&&this.renderObjectFieldDetails(s,n,i)}fieldId(t){let n=this.fieldIds.get(t);if(n)return n;let i=`field-${this.nextFieldId}`;return this.nextFieldId+=1,this.fieldIds.set(t,i),i}fieldMatches(t,n,i){return`${t} ${vl(n)} ${typeof n.description=="string"?n.description:""}`.toLowerCase().includes(i)||qe(n.items)&&this.fieldMatches("item",n.items,i)?!0:qe(n.fields)?Object.entries(n.fields).some(([o,a])=>qe(a)&&this.fieldMatches(o,a,i)):!1}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("select");a.setAttr("aria-label",`${i.name||i.staticLabel||"Link"} target type`),a.createEl("option",{value:"",text:"Any type"});let c=typeof n.target=="string"?n.target:"";for(let d of this.typeEntries())a.createEl("option",{value:d.name,text:d.name});c&&!this.typeEntries().some(d=>d.name===c)&&a.createEl("option",{value:c,text:`${c} \xB7 missing`}),a.value=c,a.disabled=i.readOnly,a.onchange=()=>{a.value?n.target=a.value:delete n.target,this.markDirty()},o.htmlFor=a.id=`mdbase-${Math.random().toString(36).slice(2)}`;let l=s.createEl("label",{cls:"mdbase-field-required"}),u=l.createEl("input",{type:"checkbox"});u.checked=n.validate_exists===!0,u.disabled=i.readOnly,u.onchange=()=>{n.validate_exists=u.checked,this.markDirty()},l.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=qe(n.items)?n.items:{type:"any"};!qe(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=qe(n.fields)?n.fields:{};!qe(n.fields)&&!i.readOnly&&(n.fields=c),a.onclick=()=>{let d=PD(c);yS(c,d,{type:"string"}),this.markDirty(!0)};let l=s.createDiv({cls:"mdbase-nested-fields"}),u=Object.entries(c).filter(d=>qe(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 ce.Notice("Nested field name is required."),h.value=p;return}if(y!==p&&Object.prototype.hasOwnProperty.call(c,y)){new ce.Notice(`Nested field already exists: ${y}`),h.value=p;return}y!==p&&(delete c[p],yS(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.setAttr("data-focus-key","yaml-editor"),s.value=this.yamlDraft,s.disabled=n,s.spellcheck=!1,s.oninput=()=>{this.yamlDraft=s.value,this.markDirty(!1)}}renderSync(t){let n=t.createDiv({cls:"mdbase-sync-document"}),i=n.createDiv({cls:"mdbase-document-header"});i.createEl("h2",{text:"Sync"}),i.createEl("p",{text:"A clear handoff between this vault and its hosted collection authority."});let s=this.host.getMirrorProfile();if(!s){this.renderEnrollment(n);return}this.syncProblem=this.host.getCurrentSyncProblem()??this.syncProblem;let o=n.createEl("section",{cls:"mdbase-sync-hero"});o.setAttr("data-state",this.mirrorStatus?.state??"checking");let a=o.createDiv({cls:"mdbase-sync-route"}),c=a.createDiv({cls:"mdbase-sync-endpoint"});(0,ce.setIcon)(c.createSpan({cls:"mdbase-sync-endpoint-icon"}),"vault");let l=c.createDiv();l.createEl("strong",{text:this.app.vault.getName()});let u=s.selectiveSync??{file_classes:[],excluded_folders:[]},d=u.file_classes.length?`Markdown + ${u.file_classes.join(", ")}`:"Markdown only";l.createSpan({text:`${s.mode==="read_write"?"Upload and download":"Downloads only"} \xB7 ${d}`});let f=a.createDiv({cls:"mdbase-sync-connection"});(0,ce.setIcon)(f.createSpan(),s.mode==="read_write"?"arrow-left-right":"arrow-left"),f.createSpan({text:MD(this.mirrorStatus)});let p=a.createDiv({cls:"mdbase-sync-endpoint"});(0,ce.setIcon)(p.createSpan({cls:"mdbase-sync-endpoint-icon"}),"cloud");let m=p.createDiv();m.createEl("strong",{text:s.name}),m.createSpan({text:"Hosted authority"});let h=o.createDiv({cls:"mdbase-sync-meta"}),y=this.mirrorStatus?.pending_files??0;if(h.createSpan({text:`${s.mode==="read_write"?"Read\u2013write mirror":"Read-only mirror"} \xB7 ${dh(this.mirrorStatus?.last_synced_at)}${y?` \xB7 ${y} queued ${y===1?"file":"files"}`:""}`}),h.createEl("code",{text:s.collectionId}).setAttr("title","Collection ID"),this.fileProgress||this.mirrorProgress){let x=o.createDiv({cls:"mdbase-sync-progress",attr:{"aria-live":"polite"}}),C=this.fileProgress?.totalBytes??this.mirrorProgress?.total??null,$=this.fileProgress?.transferredBytes??this.mirrorProgress?.completed??0,M=x.createEl("progress");M.max=C??1,M.value=C==null?0:$,C==null&&M.removeAttribute("value"),x.createDiv({cls:"mdbase-progress-label",text:this.fileProgress?`${this.fileProgress.direction==="upload"?"Uploading":"Downloading"} ${this.fileProgress.path} \xB7 ${At($)} of ${At(C??0)}`:`${this.mirrorProgress?.phase==="uploading"?"Uploading local changes":this.mirrorProgress?.phase==="downloading"?"Downloading collection files":"Applying changes"} \xB7 ${$}${C==null?"":` of ${C}`}`});let A=x.createEl("button",{text:"Stop safely"});A.onclick=()=>{this.host.connectSync.cancelSync(),this.transientMessage="Stopping after the current network request\u2026",this.render()}}(this.syncProblem||this.mirrorStatus?.recovery_required)&&this.renderRecoveryCard(o,this.syncProblem??{code:"mirror_recovery_required",title:"Synchronization needs recovery",message:"Your original files are safe. Resume from the durable checkpoint before disconnecting this vault.",action:"resume",actionLabel:"Resume recovery"});let _=o.createDiv({cls:"mdbase-sync-actions"}),v=_.createEl("button",{text:this.mirrorPreview?"Refresh review":"Review changes"});v.disabled=this.busy,v.onclick=()=>void this.reviewSyncChanges();let w=ah(this.mirrorPreview?.plan??null,this.mirrorPreview?.entries.length??0,this.busy),S=_.createEl("button",{text:w.actionLabel});S.addClass("mod-cta"),S.disabled=w.actionDisabled,S.onclick=()=>void this.perform(()=>this.applyReviewedSync()),this.renderFilePolicyControls(n,{connected:!0}),this.mirrorPreview&&this.renderMirrorPreview(n,this.mirrorPreview),this.mirrorStatus?.conflicts.length&&this.renderConflicts(n,this.mirrorStatus),this.mirrorStatus?.local_issues.length&&this.renderLocalMirrorIssues(n,this.mirrorStatus),this.renderActivity(n),this.renderConnectionDetails(n,s),window.setTimeout(()=>this.focusPendingSyncSection(),0)}async loadMirrorPreview(){this.mirrorPreview=await this.host.connectSync.preview(),this.mirrorStatus=await this.host.connectSync.status(),this.syncProblem=null,this.host.setSyncStatus(this.mirrorStatus),this.transientMessage=ah(this.mirrorPreview.plan,this.mirrorPreview.entries.length).message}async applyReviewedSync(){if(!this.mirrorPreview){await this.loadMirrorPreview();return}let t=this.mirrorPreview;try{let n=await this.host.connectSync.sync(t,i=>{this.mirrorProgress=i,this.host.setSyncProgress(i,this.fileProgress),this.render()},i=>{this.fileProgress=i,this.host.setSyncProgress(this.mirrorProgress,i),this.render()});this.mirrorStatus=await this.host.connectSync.status(),this.mirrorPreview=await this.host.connectSync.preview(),this.syncProblem=n.status==="cancelled"?nr(new DOMException("Synchronization stopped.","AbortError")):n.status==="stale"?nr(Object.assign(new Error("The reviewed plan changed."),{code:"mirror_plan_stale"})):null,this.syncProblem?this.host.setSyncProblem(this.syncProblem):this.host.setSyncStatus(this.mirrorStatus,{clearLocalChanges:n.status==="applied"&&n.pending===0}),this.transientMessage=n.status==="applied"?"Sync completed and the local checkpoint was verified.":n.status==="attention"?"Completed changes are checkpointed. Review the items that still need attention.":n.status==="cancelled"?`Sync paused safely after ${n.applied} actions; ${n.pending} remain.`:n.status==="stale"?"The collection changed again. Review the newest plan; no stale decision was applied.":`Sync stopped at a durable boundary: ${n.failure?.message??n.status}.`,await this.host.recordSyncActivity({summary:n.status==="applied"?`Synchronized ${n.applied} ${n.applied===1?"change":"changes"}`:n.status==="cancelled"?"Synchronization paused safely":"Synchronization needs attention",detail:this.transientMessage,tone:n.status==="applied"?"success":"attention",requiresAcknowledgement:n.status!=="applied"})}catch(n){let i=nr(n);if(this.syncProblem=i,this.host.setSyncProblem(i),this.transientMessage=i.message,await this.host.recordSyncActivity({summary:i.title,detail:i.message,tone:i.action==="resume"?"attention":"error",requiresAcknowledgement:!0}),!uh(n))throw n}finally{this.mirrorProgress=null,this.fileProgress=null,this.host.setSyncProgress(null,null)}}renderRecoveryCard(t,n){let i=t.createDiv({cls:"mdbase-recovery-card"}),s=i.createDiv();s.createEl("strong",{text:n.title}),s.createDiv({text:n.message});let o=i.createEl("button",{text:n.actionLabel});o.disabled=this.busy,o.onclick=()=>{n.action==="retry"?this.reconnectCollection():n.action==="reauthorize"?this.perform(()=>this.reauthorizeCollection()):this.reviewSyncChanges()}}async reauthorizeCollection(){this.enrollmentAbort?.abort();let t=new AbortController;this.enrollmentAbort=t;try{this.mirrorStatus=await this.host.connectSync.reauthorize({signal:t.signal,onVerification:n=>{this.enrollmentVerification=n.verificationUri,this.transientMessage="Approve this vault again in Connect. Its local files and checkpoint remain unchanged.",window.open(n.verificationUri,"_blank","noopener,noreferrer"),this.render()},onStatus:n=>{this.transientMessage=n.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying approval (attempt ${n.attempt}).`,this.render()}}),this.enrollmentVerification="",this.syncProblem=null,this.host.setSyncStatus(this.mirrorStatus),this.transientMessage="Approval restored. The existing mirror checkpoint was preserved.",await this.host.recordSyncActivity({summary:"Connect approval restored",detail:"The existing mirror checkpoint and local files were preserved.",tone:"success",requiresAcknowledgement:!1})}finally{this.enrollmentAbort===t&&(this.enrollmentAbort=null)}}renderActivity(t){let n=t.createEl("section",{cls:"mdbase-editor-section mdbase-activity"});n.id="mdbase-sync-activity";let i=n.createDiv({cls:"mdbase-section-header"});i.createEl("h3",{text:"Recent activity"});let s=this.host.getSyncActivity();if(s.some(a=>!a.requiresAcknowledgement)){let a=i.createEl("button",{text:"Clear completed"});a.disabled=this.busy,a.onclick=()=>void this.host.clearCompletedSyncActivity().then(()=>this.render())}if(this.fileProgress){let a=n.createDiv({cls:"mdbase-activity-row is-current"});(0,ce.setIcon)(a.createSpan(),this.fileProgress.direction==="upload"?"upload":"download");let c=a.createDiv();c.createEl("strong",{text:`${this.fileProgress.direction==="upload"?"Uploading":"Downloading"} ${this.fileProgress.path}`}),c.createDiv({text:`${At(this.fileProgress.transferredBytes)} of ${At(this.fileProgress.totalBytes)}`})}let o=[...s].reverse().filter((a,c)=>a.requiresAcknowledgement||c<8);if(!o.length&&!this.fileProgress){n.createDiv({cls:"mdbase-muted",text:"No recent synchronization activity."});return}for(let a of o){let c=n.createDiv({cls:"mdbase-activity-row"});c.setAttr("data-tone",a.tone),(0,ce.setIcon)(c.createSpan(),a.tone==="success"?"check":a.tone==="info"?"info":"circle-alert");let l=c.createDiv();if(l.createEl("strong",{text:a.summary}),a.detail&&l.createDiv({text:a.detail}),l.createSpan({cls:"mdbase-muted",text:dh(a.occurredAt)}),a.requiresAcknowledgement){let u=c.createEl("button",{text:"Dismiss"});u.disabled=this.busy,u.onclick=()=>void this.host.dismissSyncActivity(a.id).then(()=>this.render())}}}renderConnectionDetails(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section mdbase-connection-details"});i.createEl("h3",{text:"Collection connection"});let s=i.createDiv({cls:"mdbase-status-list"});Fe(s,"Collection",n.name),Fe(s,"Collection ID",n.collectionId),Fe(s,"Vault",this.app.vault.getName()),Fe(s,"Access",n.mode==="read_write"?"Read and write":"Read only"),Fe(s,"Account","Approved through Connect"),Fe(s,"Connect",new URL(n.controlUrl).host),Fe(s,"Last successful sync",dh(this.mirrorStatus?.last_synced_at)),i.createEl("p",{text:"This plugin is the only sync owner for this vault. Connect owns authorization and the mirror engine owns checkpoints and conflict decisions."});let o=i.createDiv({cls:"mdbase-actions"}),a=o.createEl("button",{text:"Reconnect"});a.disabled=this.busy,a.onclick=()=>void this.reconnectCollection();let c=o.createEl("button",{text:"Disconnect\u2026"});c.disabled=this.busy||this.host.connectSync.isSyncing(),c.onclick=()=>void this.disconnectCollection(n)}async disconnectCollection(t){let n=await new hh(this.app).choose(t.name);n&&await this.perform(async()=>{let i=await this.host.connectSync.disconnect(n==="remove");this.mirrorStatus=null,this.mirrorPreview=null,this.syncProblem=null,this.host.setSyncStatus(null,{clearLocalChanges:!0});let s=n==="remove"?`${i.removed.length} unchanged synced ${i.removed.length===1?"file was":"files were"} removed. ${i.preserved.length} locally changed ${i.preserved.length===1?"file was":"files were"} preserved.`:"All local files were retained as an unsynced copy.";this.transientMessage=`Disconnected from ${t.name}. ${s}`,await this.host.recordSyncActivity({summary:`Disconnected from ${t.name}`,detail:s,tone:i.preserved.length?"attention":"info",requiresAcknowledgement:i.preserved.length>0}),await this.refresh(!0)})}focusPendingSyncSection(){if(!this.pendingSyncFocus)return;let t=this.pendingSyncFocus==="activity"?"mdbase-sync-activity":"mdbase-sync-conflicts",n=this.containerEl.querySelector(`#${t}`);n&&(this.pendingSyncFocus=null,n.scrollIntoView({behavior:"smooth",block:"start"}))}filePolicy(){return this.filePolicyDraft??=JSON.parse(JSON.stringify(this.host.connectSync.getSelectiveSync())),this.filePolicyDraft}renderFilePolicyControls(t,n){let i=this.filePolicy(),s=t.createEl("section",{cls:"mdbase-editor-section mdbase-file-policy"});s.createEl("h3",{text:n.connected?"Files on this device":"Collection files"}),s.createEl("p",{text:"Markdown always syncs. Choose which binary file classes this device should materialize; hidden and reserved paths remain excluded."});let o=s.createDiv({cls:"mdbase-file-class-grid"}),a=[["image","Images"],["audio","Audio"],["video","Video"],["pdf","PDFs"],["other","Other files"]];for(let[f,p]of a){let m=o.createEl("label"),h=m.createEl("input",{type:"checkbox"});h.setAttr("data-focus-key",`file-class-${f}`),h.checked=i.file_classes.includes(f),h.onchange=()=>{i.file_classes=h.checked?[...new Set([...i.file_classes,f])]:i.file_classes.filter(y=>y!==f),this.render()},m.createSpan({text:p})}let c=null;if(Lt(s,"Excluded folders",i.excluded_folders.join(", "),f=>{if(i.excluded_folders=f.split(",").map(p=>p.trim()).filter(Boolean),c){let p=JSON.stringify(this.host.connectSync.getSelectiveSync())!==JSON.stringify(i);c.textContent=p?"Apply file policy":"File policy applied",c.disabled=!p||this.busy}},{description:"Comma-separated collection-relative folders. Exclusions apply to Markdown and binary files on this device.",placeholder:"Archive, Private exports"}),i.file_classes.length?i.file_classes.includes("other")&&s.createDiv({cls:"mdbase-inline-message",text:"Other files includes every eligible visible non-Markdown format. Review the transfer ledger carefully before syncing."}):s.createDiv({cls:"mdbase-inline-message",text:"Binary sync is off. This mirror remains Markdown-only."}),!n.connected)return;let l=this.host.connectSync.getSelectiveSync(),u=JSON.stringify(l)!==JSON.stringify(i);c=s.createDiv({cls:"mdbase-actions"}).createEl("button",{text:u?"Apply file policy":"File policy applied"}),c.disabled=!u||this.busy,c.onclick=()=>void this.perform(async()=>{await this.host.connectSync.configureSelectiveSync(i),this.filePolicyDraft=null,this.mirrorPreview=null,this.transientMessage="File policy updated. Review the rebuild before files move.",this.render()})}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 an empty vault"}),n.createEl("p",{text:"Choose access, approve it in Connect, then review the first transfer before any files move."}),this.renderEnrollmentSteps(n,this.enrollmentVerification||this.enrollmentAbort?2:1,["Choose connection","Approve in Connect","Review first sync"]),this.enrollmentVerification){let c=n.createDiv({cls:"mdbase-approval-link"});c.createSpan({text:"Waiting for approval \xB7 "});let l=c.createEl("a",{text:"Open approval page again",href:this.enrollmentVerification});l.setAttr("target","_blank"),l.setAttr("rel","noopener noreferrer")}Lt(n,"Connect URL",this.enrollmentControlUrl,c=>{this.enrollmentControlUrl=c},{placeholder:lh}),Lt(n,"Mirror name",this.enrollmentMirrorName,c=>{this.enrollmentMirrorName=c}),Lt(n,"Collection ID",this.enrollmentCollectionId,c=>{this.enrollmentCollectionId=c},{description:"Optional. Leave blank to choose during approval."});let i=n.createDiv({cls:"mdbase-form-row"});i.createEl("label",{text:"Access"});let s=i.createEl("select");s.createEl("option",{value:"read_write",text:"Read and write"}),s.createEl("option",{value:"read_only",text:"Read only"}),s.value=this.enrollmentMode,s.onchange=()=>{this.enrollmentMode=s.value==="read_only"?"read_only":"read_write"},this.renderFilePolicyControls(n,{connected:!1});let o=n.createDiv({cls:"mdbase-actions"}),a=o.createEl("button",{text:this.enrollmentAbort?"Waiting for approval\u2026":"Continue to approval"});if(a.addClass("mod-cta"),a.disabled=this.busy,a.onclick=()=>void this.perform(async()=>{this.enrollmentAbort?.abort();let c=new AbortController;this.enrollmentAbort=c;try{await this.host.connectSync.enroll({controlUrl:this.enrollmentControlUrl,mirrorName:this.enrollmentMirrorName,mode:this.enrollmentMode,selectiveSync:this.filePolicy(),...this.enrollmentCollectionId.trim()?{collectionId:this.enrollmentCollectionId.trim()}:{}},{signal:c.signal,onVerification:d=>{this.enrollmentVerification=d.verificationUri,this.transientMessage="Approve the mirror in the Connect page. This view will keep waiting securely.",window.open(d.verificationUri,"_blank","noopener,noreferrer"),this.render()},onStatus:d=>{this.transientMessage=d.state==="waiting_for_approval"?"Waiting for approval in Connect\u2026":`Connect is retrying enrollment (attempt ${d.attempt}).`,this.render()}}),this.enrollmentVerification="",await this.loadMirrorPreview();let l=this.mirrorPreview?.entries.reduce((d,f)=>d+(f.estimatedBytes??0),0)??0,u=this.mirrorPreview?.entries.length??0;this.transientMessage=`Mirror enrolled. The first review contains ${u} ${u===1?"item":"items"}${l?` and about ${At(l)} of binary data`:""}. No files have moved yet.`,this.render()}catch(l){if(!uh(l))throw l;this.transientMessage="Approval wait cancelled. No files were synchronized."}finally{this.enrollmentAbort===c&&(this.enrollmentAbort=null)}}),this.enrollmentAbort){let c=o.createEl("button",{text:"Stop waiting"});c.onclick=()=>{this.enrollmentAbort?.abort(),this.transientMessage="Approval wait cancelled. No files were synchronized.",this.render()}}}renderLocalAdoption(t){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=n?["waiting_for_approval","uploading","fenced","activating","adopted"].indexOf(n.phase)+1:1;this.renderEnrollmentSteps(i,Math.min(4,Math.max(1,s)),["Approve move","Stage snapshot","Activate authority","Reconnect mirror"]);let o=this.enrollmentVerification||n?.session.verificationUri;if(o){let l=i.createDiv({cls:"mdbase-approval-link"});l.createSpan({text:"Approval page: "});let u=l.createEl("a",{text:"Open Connect",href:o});u.setAttr("target","_blank"),u.setAttr("rel","noopener noreferrer")}if(n&&(this.enrollmentControlUrl=n.session.controlUrl,this.enrollmentMirrorName=n.session.requested.mirrorName??"Obsidian"),!n)Lt(i,"Connect URL",this.enrollmentControlUrl,l=>{this.enrollmentControlUrl=l},{placeholder:lh}),Lt(i,"Mirror name",this.enrollmentMirrorName,l=>{this.enrollmentMirrorName=l}),this.renderFilePolicyControls(i,{connected:!1});else{let l=i.createDiv({cls:"mdbase-status-list"});Fe(l,"Collection",n.session.requested.collectionId),Fe(l,"Phase",n.phase.replace(/_/g," ")),Fe(l,"Connect",n.session.controlUrl);let u=this.host.connectSync.getSelectiveSync();Fe(l,"Files",u.file_classes.length?u.file_classes.join(", "):"Markdown only")}let a=i.createDiv({cls:"mdbase-inline-message"});a.createEl("strong",{text:"Authority cut-over: "}),a.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 c=i.createEl("button",{text:n?"Resume adoption":"Approve and host collection"});if(c.addClass("mod-cta"),c.disabled=this.busy,c.onclick=()=>void this.perform(async()=>{this.enrollmentAbort?.abort();let l=new AbortController;this.enrollmentAbort=l;let u=p=>{this.enrollmentVerification=p.verificationUri,this.transientMessage="Approve the authority move in Connect, then return here. This checkpoint is safe to resume.",this.render()},d=p=>{this.transientMessage=p.state==="waiting_for_approval"?"Waiting for authority-move approval in Connect\u2026":`Connect is retrying (attempt ${p.attempt}).`,this.render()},f=(p,m,h)=>{this.adoptionFileProgress=`${p} \xB7 ${At(m)} of ${At(h)}`,this.transientMessage=`Uploading collection file ${this.adoptionFileProgress}`,this.render()};try{n?await this.host.connectSync.resumeAdoption({signal:l.signal,onVerification:u,onStatus:d,onFileProgress:f}):await this.host.connectSync.adoptLocalCollection({controlUrl:this.enrollmentControlUrl,mirrorName:this.enrollmentMirrorName,selectiveSync:this.filePolicy()},{signal:l.signal,onVerification:u,onStatus:d,onFileProgress:f}),this.enrollmentVerification="",this.transientMessage="Hosted mdbase is authoritative and this vault is now its read-write mirror.",await this.refresh(!0)}catch(p){if(!uh(p))throw p;this.transientMessage="Paused safely. Use Resume adoption to continue from the durable checkpoint."}finally{this.enrollmentAbort===l&&(this.enrollmentAbort=null)}}),this.enrollmentAbort){let l=i.createEl("button",{text:"Stop waiting"});l.onclick=()=>{this.enrollmentAbort?.abort(),this.transientMessage="Paused safely. Use Resume adoption to continue from the durable checkpoint.",this.render()}}if(n&&!["activating","adopted"].includes(n.phase)){let l=i.createEl("button",{text:"Cancel adoption"});l.disabled=this.busy,l.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)})}}renderEnrollmentSteps(t,n,i){let s=t.createEl("ol",{cls:"mdbase-enrollment-steps"});i.forEach((o,a)=>{let c=s.createEl("li"),l=a+1;c.toggleClass("is-complete",ll+(u.estimatedBytes??0),0);s.createSpan({cls:"mdbase-transfer-total",text:`${n.entries.length} ${n.entries.length===1?"item":"items"} \xB7 ${n.entries.filter(l=>l.kind==="file").length} files${a?` \xB7 about ${At(a)}`:""}`});let c=[{direction:"download",title:"Download to this vault",empty:"No hosted changes to download."},{direction:"upload",title:"Upload to hosted",empty:"No local changes to upload."},{direction:"attention",title:"Needs attention",empty:"Nothing is blocking or excluded."}];for(let l of c){let u=n.entries.filter(h=>h.direction===l.direction);if(!u.length&&l.direction!=="attention")continue;let d=i.createEl("section",{cls:"mdbase-transfer-group"});d.setAttr("data-direction",l.direction);let f=d.createDiv({cls:"mdbase-transfer-group-heading"}),p=f.createSpan({cls:"mdbase-transfer-group-icon"});if((0,ce.setIcon)(p,l.direction==="download"?"download":l.direction==="upload"?"upload":"circle-alert"),f.createEl("h4",{text:l.title}),f.createSpan({text:String(u.length),cls:"mdbase-transfer-count"}),!u.length){d.createDiv({cls:"mdbase-transfer-empty",text:l.empty});continue}let m=d.createDiv({cls:"mdbase-transfer-ledger"});for(let h of u.slice(0,250)){let y=m.createDiv({cls:"mdbase-transfer-row"});y.createSpan({cls:"mdbase-transfer-action",text:h.action}).setAttr("data-action",h.action);let _=y.createDiv({cls:"mdbase-transfer-body"}),v=_.createDiv({cls:"mdbase-transfer-path"});if(v.createEl("code",{text:h.path}),v.createSpan({cls:"mdbase-transfer-kind",text:h.kind==="file"?"File":"Markdown"}),h.estimatedBytes!==void 0&&v.createSpan({cls:"mdbase-transfer-size",text:At(h.estimatedBytes)}),_.createDiv({text:h.detail}),h.direction==="attention"){let w=y.createEl("button",{text:"Open"});w.onclick=()=>void this.host.openFileByPath(h.path)}}u.length>250&&m.createDiv({cls:"mdbase-transfer-more",text:`${u.length-250} more items are included in this transfer.`})}n.collisions.length?i.createDiv({cls:"mdbase-inline-error",text:"Resolve path collisions before the first sync. Existing local files are never overwritten without review."}):n.local_issues.length&&i.createDiv({cls:"mdbase-inline-message",text:"Synchronization is paused until every invalid or unreadable local file listed here is fixed."})}renderConflicts(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.id="mdbase-sync-conflicts",i.createEl("h3",{text:"Conflicts"}),i.createEl("p",{text:"Inspect both versions before deciding. Decisions are checked again immediately before they are applied."});for(let s of n.conflicts){let o=i.createDiv({cls:"mdbase-conflict-row"}),a=o.createDiv({cls:"mdbase-conflict-summary"});a.createEl("strong",{text:s.path??s.object_id}),a.createDiv({text:s.entity==="file"?"Binary file conflict":"Note conflict",cls:"mdbase-muted"}),a.createDiv({text:s.message});let c=o.createDiv({cls:"mdbase-actions"}),l=`${s.object_id}:${s.decision_id}`,u=this.conflictComparisons.get(l),d=c.createEl("button",{text:u?"Hide versions":this.loadingConflictComparisons.has(l)?"Loading versions\u2026":"Compare versions"});d.disabled=this.busy||this.loadingConflictComparisons.has(l),d.onclick=()=>{if(u){this.conflictComparisons.delete(l),this.render();return}this.loadConflictComparison(s,l)};for(let f of["local","remote"]){let p=c.createEl("button",{text:f==="local"?"Keep local":"Use hosted"});p.disabled=this.busy,p.onclick=()=>void this.resolveMirrorConflict(s,f,!1)}if(s.path){let f=c.createEl("button",{text:"Keep both"});f.disabled=this.busy,f.onclick=()=>void this.resolveMirrorConflict(s,"remote",!0)}u&&this.renderConflictComparison(o,u)}}async loadConflictComparison(t,n){this.loadingConflictComparisons.add(n),this.render();try{this.conflictComparisons.set(n,await this.host.connectSync.conflictComparison(t))}catch(i){let s=nr(i);this.syncProblem=s,this.host.setSyncProblem(s),this.transientMessage=s.message,s.code==="conflict_decision_stale"&&await this.refreshMirrorStatus()}finally{this.loadingConflictComparisons.delete(n),this.render()}}renderConflictComparison(t,n){let i=t.createDiv({cls:"mdbase-conflict-comparison"});if(n.entity==="record"){let o=fS(n.local.document??"",n.remote.document??""),a=i.createDiv({cls:"mdbase-conflict-legend"});a.createSpan({text:"\u2212 Local only",cls:"is-local"}),a.createSpan({text:"+ Hosted only",cls:"is-remote"});let c=i.createEl("pre",{cls:"mdbase-conflict-diff"});for(let l of o.lines){let u=c.createEl("div",{cls:`is-${l.kind}`});u.createSpan({text:l.kind==="local"?"\u2212":l.kind==="remote"?"+":" "}),u.createSpan({text:l.value||" "})}o.truncated&&i.createDiv({cls:"mdbase-muted",text:"Diff shortened for a responsive review. Open the local note to inspect it in full."});return}let s=i.createDiv({cls:"mdbase-conflict-sides"});this.renderConflictSide(s,"Local",n.local),this.renderConflictSide(s,"Hosted",n.remote)}renderConflictSide(t,n,i){let s=t.createDiv({cls:"mdbase-conflict-side"});if(s.createEl("h4",{text:n}),i.state==="absent"){s.createDiv({cls:"mdbase-muted",text:"File is absent in this version."});return}if(i.path&&s.createEl("code",{text:i.path}),i.size!==void 0&&s.createDiv({text:`Size: ${At(i.size)}`}),i.modifiedAt&&s.createDiv({text:`Modified: ${new Date(i.modifiedAt).toLocaleString()}`}),i.revision&&s.createDiv({cls:"mdbase-conflict-digest",text:`Digest: ${i.revision}`}),i.resourceUrl&&i.path&&/\.(?:avif|gif|jpe?g|png|svg|webp)$/i.test(i.path)){let o=s.createEl("img",{cls:"mdbase-conflict-image-preview"});o.src=i.resourceUrl,o.alt=`${n} preview of ${i.path}`}else n==="Hosted"&&s.createDiv({cls:"mdbase-muted",text:"Hosted binary preview is materialized only after you choose it."})}async resolveMirrorConflict(t,n,i){await this.perform(async()=>{let s=null;try{i&&(s=await this.host.connectSync.preserveConflictCopy(t.path??"")),this.mirrorPreview=null;let o=await uS(this.host.connectSync,t.object_id,t.decision_id,n);this.mirrorStatus=o.status,this.mirrorPreview=o.preview,this.host.setSyncStatus(o.status),this.conflictComparisons.delete(`${t.object_id}:${t.decision_id}`),this.transientMessage=s?`Both versions are safe: the hosted version will use the original path and the local version was copied to ${s}. Review the refreshed plan before syncing.`:"Conflict resolved. Review the refreshed engine plan before syncing.",await this.host.recordSyncActivity({summary:s?"Conflict kept as two files":`Conflict resolved with ${n==="local"?"local":"hosted"} version`,detail:this.transientMessage,path:t.path??void 0,tone:"info",requiresAcknowledgement:!1})}catch(o){let a=nr(o);s&&(a.message=`The local copy at ${s} is safe, but the original changed again. Review the newest versions before deciding.`),this.syncProblem=a,this.host.setSyncProblem(a),this.transientMessage=a.message,a.code==="conflict_decision_stale"&&(this.mirrorPreview=null,await this.refreshMirrorStatus()),await this.host.recordSyncActivity({summary:a.title,detail:a.message,path:t.path??void 0,tone:"attention",requiresAcknowledgement:!0})}})}renderLocalMirrorIssues(t,n){let i=t.createEl("section",{cls:"mdbase-editor-section"});i.createEl("h3",{text:"Local files needing attention"}),i.createEl("p",{text:"Synchronization is paused to keep the mirror checkpoint exact. Fix every malformed or unreadable file below, then preview again."});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){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.setAttr("data-focus-key","issue-search"),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?.focus(),g?.setSelectionRange(g.value.length,g.value.length)};let f=this.issueQuery.trim().toLowerCase(),p=i.filter(g=>this.issueSeverity!=="all"&&g.severity!==this.issueSeverity?!1:f?`${g.path} ${g.code} ${g.field??""} ${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,[...y.get(g.path)??[],g]);for(let[g,_]of y){let v=n.createEl("section",{cls:"mdbase-issue-group"}),w=v.createDiv({cls:"mdbase-issue-group-header"}),S=w.createEl("button",{cls:"mdbase-issue-file-button"});(0,ce.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),w.createSpan({cls:"mdbase-issue-file-count",text:`${_.length} ${_.length===1?"issue":"issues"}`});for(let x of _){let C=v.createDiv({cls:"mdbase-issue-row"});C.setAttr("data-severity",x.severity),C.createSpan({cls:"mdbase-issue-indicator"}).setAttr("aria-hidden","true");let $=C.createDiv({cls:"mdbase-issue-metadata"});$.createEl("code",{text:x.code}),$.createDiv({cls:"mdbase-issue-context",text:`${x.severity==="warn"?"Warning":"Error"}${x.field?` \xB7 ${x.field}`:""}`}),C.createDiv({cls:"mdbase-issue-row-message",text:x.message});let M=C.createDiv({cls:"mdbase-issue-row-actions"}),A=M.createEl("button",{text:x.field?"Open field":"Open file"});A.setAttr("aria-label",`Open ${x.path}${x.field?` at ${x.field}`:""}`),A.onclick=()=>void this.host.openFileByPath(x.path,x.field);let W=this.host.getQuickFixLabel(x);if(W){let q=M.createEl("button",{text:W});q.addClass("mod-cta"),q.onclick=()=>void this.perform(async()=>{await this.host.applyQuickFix(x)})}}}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 ce.Notice("Save or discard the current type changes before switching.");return}let i=++this.typeSelectionVersion,s=await this.host.loadTypeModel(t);if(i!==this.typeSelectionVersion)return;let o=this.host.loadTypeDraft(t),a=o?.version===1&&o.sourceRevision===(s.sourceRevision??null),c=a?oi(o.model):s;this.selectedPath=t,this.model=c,this.originalModel=oi(s),this.yamlDraft=a&&o.yamlDraft?o.yamlDraft:`${Vt(fh(c),c.body)} +`,this.dirty=!yl(this.originalModel,c),this.editorMode=a&&o.editorMode==="yaml"?"yaml":"design",this.editorMode==="yaml"&&(this.dirty=!0),a&&this.dirty?this.transientMessage=`Recovered unsaved changes for ${t}.`:o&&!a&&(this.transientMessage=`An older draft for ${t} was kept, but the source changed. The current file is shown.`),this.render()}createType(){if(this.dirty){new ce.Notice("Save or discard the current type changes before creating another type.");return}this.typeSelectionVersion+=1;let t=this.host.loadTypeDraft(null),n=t?.version===1?oi(t.model):th();this.selectedPath=null,this.model=n,this.originalModel=null,this.yamlDraft=t?.yamlDraft??"",this.dirty=!0,t&&(this.transientMessage="Recovered an unsaved new type."),this.editorMode=t?.editorMode??"design",this.render()}switchEditorMode(t){if(!(!this.model||t===this.editorMode)){if(t==="yaml")try{this.yamlDraft=`${Vt(fh(this.model),this.model.body)} +`}catch(n){new ce.Notice(n instanceof Error?n.message:String(n));return}else if(!this.readYamlDraftIntoModel())return;this.editorMode=t,this.render()}}readYamlDraftIntoModel(){let t=et(this.yamlDraft);if(!t.hasFrontmatter||t.error)return new ce.Notice(`Invalid type YAML: ${t.error??"frontmatter is missing"}`),!1;if(t.frontmatter.kind!=="mdbase.type")return new ce.Notice("Canonical v0.3 type YAML requires kind: mdbase.type."),!1;try{return this.model=ml(t.frontmatter,t.body,this.model?.name||"type"),!0}catch(n){return new ce.Notice(n instanceof Error?n.message:String(n)),!1}}async saveCurrentType(){if(!this.model||this.model.specProfile!=="v0.3"||this.model.readOnlyReason||this.editorMode==="yaml"&&!this.readYamlDraftIntoModel())return;let n=gl(this.model,{knownTypes:this.typeEntries().map(o=>o.name),contracts:this.schema?.contracts.values()}).filter(o=>o.severity==="error");if(n.length){this.transientMessage=`${n.length} ${n.length===1?"error must":"errors must"} be fixed before saving.`,this.render(),new ce.Notice(n[0].message);return}let i=bl(this.originalModel,this.model).filter(o=>o.risk==="high");if(i.length&&!await new ph(this.app).confirm(i))return;let s=this.model;await this.perform(async()=>{let o=this.selectedPath,a=await this.host.saveTypeModel(s,o,this.originalModel?.sourceRevision);await this.host.clearTypeDraft(o),o!==a.path&&await this.host.clearTypeDraft(a.path),this.selectedPath=a.path,this.originalModel=oi(s),this.dirty=!1,this.transientMessage=`Saved ${a.path}.`,await this.refresh(!0)})}markDirty(t=!1){let n=this.dirty;if(this.dirty=this.editorMode==="yaml"?!0:!yl(this.originalModel,this.model),this.scheduleTypeDraftSave(),this.dirty&&!n&&(this.transientMessage=""),t||n!==this.dirty){this.render();return}let i=this.containerEl.querySelector(".mdbase-editor-title-line");i&&!i.querySelector(".mdbase-dirty")&&i.createSpan({cls:"mdbase-dirty",text:"Unsaved"});let s=this.containerEl.querySelector(".mdbase-editor-actions .mod-cta");s&&this.model?.specProfile==="v0.3"&&!this.model.readOnlyReason&&this.host.getMirrorProfile()?.mode!=="read_only"&&(s.disabled=!1);let o=this.containerEl.querySelector(".mdbase-change-review");if(o){let a=o.querySelector("p");a&&a.setText("Pending changes. Review details after leaving the current field.")}}scheduleTypeDraftSave(){this.draftSaveTimer!==null&&window.clearTimeout(this.draftSaveTimer),this.draftSaveTimer=window.setTimeout(()=>{this.draftSaveTimer=null,this.flushTypeDraft()},2e3)}async flushTypeDraft(){if(this.draftSaveTimer!==null&&(window.clearTimeout(this.draftSaveTimer),this.draftSaveTimer=null),!this.model||!this.dirty)return;let t={version:1,path:this.selectedPath,sourceRevision:this.originalModel?.sourceRevision??null,model:oi(this.model),editorMode:this.editorMode,yamlDraft:this.editorMode==="yaml"?this.yamlDraft:void 0,updatedAt:new Date().toISOString()};await this.host.saveTypeDraft(t)}async discardCurrentType(){let t=this.selectedPath;if(await this.host.clearTypeDraft(t),t){let n=await this.host.loadTypeModel(t);this.model=n,this.originalModel=oi(n),this.yamlDraft=`${Vt(fh(n),n.body)} +`,this.dirty=!1}else this.model=null,this.originalModel=null,this.yamlDraft="",this.dirty=!1;this.transientMessage="Unsaved changes discarded.",this.render()}async refreshMirrorStatus(){if(!this.host.connectSync.isSyncing())try{this.mirrorStatus=await this.host.connectSync.status(),this.syncProblem=null,this.host.setSyncStatus(this.mirrorStatus)}catch(t){this.mirrorStatus=null,this.syncProblem=nr(t),this.host.setSyncProblem(this.syncProblem),this.transientMessage=this.syncProblem.message}}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 ce.Notice(i)}finally{this.busy=!1,this.render()}}}};function fh(r){return r.specProfile==="v0.3"&&!r.readOnlyReason?is(r):oi(r.originalFrontmatter??{name:r.name,fields:Object.fromEntries(r.fields.map(e=>[e.name,e.definition]))})}var Fo=class{constructor(e,t){this.delayMs=e;this.task=t;this.entries=new Map;if(!Number.isFinite(e)||e<0)throw new Error("Debounce delay must be a non-negative finite number.")}has(e){return this.entries.has(e)}schedule(e,t){let n=this.entries.get(e);n||(n={value:t,revision:0,timer:null,ready:!1,running:!1},this.entries.set(e,n)),n.value=t,n.revision+=1,n.ready=!1,n.timer!==null&&clearTimeout(n.timer),n.timer=setTimeout(()=>{this.entries.get(e)===n&&(n.timer=null,n.ready=!0,this.drain(e,n))},this.delayMs)}cancel(e){let t=this.entries.get(e);t&&(t.timer!==null&&clearTimeout(t.timer),this.entries.delete(e))}clear(){for(let e of this.entries.values())e.timer!==null&&clearTimeout(e.timer);this.entries.clear()}async drain(e,t){if(this.entries.get(e)!==t||t.running||!t.ready)return;t.ready=!1,t.running=!0;let n=t.revision,i=t.value,s=()=>this.entries.get(e)===t&&t.revision===n;try{await this.task(i,s)}finally{t.running=!1,this.entries.get(e)===t&&(t.ready?this.drain(e,t):t.timer===null&&t.revision===n&&this.entries.delete(e))}}};var ID={validateOnSave:!0,validateOnOpen:!0,showNoticeOnSave:!1,interopEnabled:!1,mirrorProfile:null,typeDrafts:{},syncActivity:[]};function TD(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"&&(e.selectiveSync===void 0||Array.isArray(e.selectiveSync.file_classes)&&Array.isArray(e.selectiveSync.excluded_folders))}function RD(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Uo=class extends O.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){this.settled||(this.settled=!0,this.resolvePromise?.(t),this.resolvePromise=null)}},yh=class extends O.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=>{let s=i.match?.path_glob??"";return`${i.name} ${i.display_name_key??""} ${i.filePath} ${s}`.toLowerCase().includes(n)}).slice(0,100):this.typeDefs.slice(0,100)}renderSuggestion(t,n){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(t.fields??{}).length} fields`}),t.match?.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 mh(r,e){return new Promise(t=>{new yh(r,e,i=>{if(i.type==="selected"){t(i.typeDef);return}t(null)}).open()})}var gh=class extends O.PluginSettingTab{constructor(e,t){super(e,t),this.plugin=t}display(){let{containerEl:e}=this;e.empty(),new O.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 O.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 O.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 O.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()}))}},wl=class extends O.Plugin{constructor(t,n){super(t,n);this.issueMap=new Map;this.sortedIssuesCache=null;this.mirrorStatus=null;this.mirrorProgress=null;this.fileProgress=null;this.currentSyncProblem=null;this.localChangeObserved=!1;this.schemaCache=null;this.schemaLoadPromise=null;this.saveValidationDebounceMs=2e3;this.schemaRefreshDebounceMs=2e3;this.saveValidations=new Fo(this.saveValidationDebounceMs,async(t,n)=>{try{await this.validateFileAndStore(t,"save",n)}catch(i){console.error("mdbase: background validation failed",i)}});this.schemaRefreshes=new Fo(this.schemaRefreshDebounceMs,async()=>{this.invalidateSchemaCache(),this.refreshWorkspaceViews()});this.connectSync=new ul(t,{getMirrorProfile:()=>this.getMirrorProfile(),saveMirrorProfile:async i=>{this.settings.mirrorProfile=i,await this.saveSettings(),i?this.refreshSyncStatus():(this.mirrorStatus=null,this.currentSyncProblem=null,this.localChangeObserved=!1,this.updateStatusBar())}}),this.interopBridge=new Wa(t,()=>this.settings?.interopEnabled===!0),this.api={apiVersion:1,interop:this.interopBridge,getInteropStatus:()=>({enabled:this.settings?.interopEnabled===!0,profileVersion:"0.1"})}}async onload(){await this.loadSettings(),await this.connectSync.initialize(),(0,O.addIcon)(as,dS),this.statusBarEl=this.addStatusBarItem(),this.statusBarEl.addClass("mdbase-status-bar"),this.statusBarEl.setAttr("role","button"),this.statusBarEl.setAttr("tabindex","0"),this.registerDomEvent(this.statusBarEl,"click",()=>void this.openStatusDestination()),this.registerDomEvent(this.statusBarEl,"keydown",n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),this.openStatusDestination())}),this.updateStatusBar(),this.registerView(ai,n=>new _l(n,this)),this.addSettingTab(new gh(this.app,this)),this.addRibbonIcon(as,"Open mdbase",()=>void this.openWorkspace()),this.addCommand({id:"mdbase-open",name:"Open workspace",callback:()=>void this.openWorkspace()}),this.addCommand({id:"mdbase-initialize-collection",name:"Initialize collection",callback:()=>void this.initializeCollectionCommand()}),this.addCommand({id:"mdbase-create-type",name:"Create type definition",callback:()=>void this.createTypeDefinitionCommand()}),this.addCommand({id:"mdbase-edit-type",name:"Edit type definition",callback:()=>void this.editTypeDefinitionCommand()}),this.addCommand({id:"mdbase-edit-current-type",name:"Edit current type definition",callback:()=>void this.editCurrentTypeDefinitionCommand()}),this.addCommand({id:"mdbase-create-note-from-type",name:"Create note from type",callback:()=>void this.createNoteFromTypeCommand()}),this.addCommand({id:"mdbase-validate-current-note",name:"Validate current note",callback:()=>void this.validateCurrentNoteCommand()}),this.addCommand({id:"mdbase-validate-collection",name:"Validate collection",callback:()=>void this.runCollectionValidation(!0)}),this.addCommand({id:"mdbase-open-issues-view",name:"Open issues view",callback:()=>void this.openWorkspace("issues")}),this.addCommand({id:"mdbase-sync",name:"Review sync changes",callback:()=>void this.reviewSyncCommand()}),this.addCommand({id:"mdbase-open-sync",name:"Open sync",callback:()=>void this.openWorkspace("sync")}),this.addCommand({id:"mdbase-sync-now",name:"Sync now",callback:()=>void this.syncNowCommand()}),this.addCommand({id:"mdbase-cancel-sync",name:"Cancel current sync",checkCallback:n=>this.connectSync.isSyncing()?(n||(this.connectSync.cancelSync(),this.setSyncProblem(nr(new DOMException("Synchronization stopped.","AbortError")))),!0):!1}),this.addCommand({id:"mdbase-open-activity",name:"Open sync activity",callback:()=>void this.openSyncSection("activity")}),this.addCommand({id:"mdbase-resolve-conflicts",name:"Resolve sync conflicts",callback:()=>void this.openSyncSection("conflicts")}),this.addCommand({id:"mdbase-reconnect",name:"Reconnect collection",callback:()=>void this.reconnectCommand()}),this.registerEvent(this.app.vault.on("modify",n=>{n instanceof O.TFile&&this.onVaultModify(n)})),this.registerEvent(this.app.vault.on("rename",(n,i)=>{n instanceof O.TFile&&this.onVaultRename(n,i)})),this.registerEvent(this.app.vault.on("delete",n=>{n instanceof O.TFile&&this.onVaultDelete(n)})),this.registerEvent(this.app.vault.on("create",n=>{n instanceof O.TFile&&this.onVaultCreate(n)})),this.registerEvent(this.app.workspace.on("file-open",n=>{this.settings.validateOnOpen&&(!(n instanceof O.TFile)||n.extension!=="md"||this.validateFileAndStore(n,"open"))})),this.registerEvent(this.app.workspace.on("editor-change",(n,i)=>{let s=i.file;s instanceof O.TFile&&(this.saveValidations.has(s.path)&&this.scheduleSaveValidation(s),this.schemaRefreshes.has("schema")&&this.isSchemaRelevantPath(s.path)&&this.scheduleSchemaRefresh())}));let t=this.app.workspace.getActiveFile();t&&this.settings.validateOnOpen&&this.validateFileAndStore(t,"open"),this.getMirrorProfile()&&this.refreshSyncStatus(),this.registerInterval(window.setInterval(()=>{this.getMirrorProfile()&&!this.connectSync.isSyncing()&&this.refreshSyncStatus()},6e4))}onunload(){this.connectSync.dispose(),this.interopBridge.dispose().catch(t=>{console.error("mdbase: failed to dispose the interoperability bridge",t)}),this.app.workspace.getLeavesOfType(ai).forEach(t=>t.detach()),this.saveValidations.clear(),this.schemaRefreshes.clear()}async loadSettings(){if(this.settings=Object.assign({},ID,await this.loadData()),!TD(this.settings.mirrorProfile))this.settings.mirrorProfile=null;else try{this.settings.mirrorProfile.selectiveSync=xr(this.settings.mirrorProfile.selectiveSync)}catch{this.settings.mirrorProfile.selectiveSync=xr()}(!this.settings.typeDrafts||typeof this.settings.typeDrafts!="object"||Array.isArray(this.settings.typeDrafts))&&(this.settings.typeDrafts={}),this.settings.syncActivity=pS(this.settings.syncActivity)}async saveSettings(){await this.saveData(this.settings)}getIssues(){return this.sortedIssuesCache??=Array.from(this.issueMap.values()).flat().sort((t,n)=>t.path.localeCompare(n.path)||t.severity.localeCompare(n.severity)||t.code.localeCompare(n.code)),this.sortedIssuesCache}getMirrorProfile(){return this.settings.mirrorProfile?JSON.parse(JSON.stringify(this.settings.mirrorProfile)):null}getSyncActivity(){return this.settings.syncActivity.map(t=>({...t}))}getCurrentSyncProblem(){return this.currentSyncProblem?{...this.currentSyncProblem}:null}setSyncStatus(t,n={}){this.mirrorStatus=t?JSON.parse(JSON.stringify(t)):null,n.clearLocalChanges&&(this.localChangeObserved=!1),this.currentSyncProblem=null,this.updateStatusBar()}setSyncProgress(t,n=null){this.mirrorProgress=t?{...t}:null,this.fileProgress=n?{...n}:null,this.updateStatusBar()}setSyncProblem(t){this.currentSyncProblem=t?{...t}:null,this.updateStatusBar()}async recordSyncActivity(t){this.settings.syncActivity=hS(this.settings.syncActivity,mS(t)),await this.saveSettings(),this.refreshWorkspaceViews()}async dismissSyncActivity(t){this.settings.syncActivity=this.settings.syncActivity.filter(n=>n.id!==t),await this.saveSettings(),this.refreshWorkspaceViews()}async clearCompletedSyncActivity(){this.settings.syncActivity=this.settings.syncActivity.filter(t=>t.requiresAcknowledgement),await this.saveSettings(),this.refreshWorkspaceViews()}async refreshSyncStatus(){if(!this.getMirrorProfile())return this.setSyncStatus(null),null;if(this.connectSync.isSyncing())return this.mirrorStatus;try{let t=await this.connectSync.status();return this.setSyncStatus(t),t}catch(t){return this.setSyncProblem(nr(t)),null}}async loadWorkspaceSchema(t=!1){return this.getConfigAndTypes(t)}async loadTypeModel(t){let n=this.app.vault.getAbstractFileByPath((0,O.normalizePath)(t));if(!(n instanceof O.TFile))throw new Error(`Type file not found: ${t}`);let i=await this.app.vault.cachedRead(n),s=et(i);if(!s.hasFrontmatter||s.error)throw new Error(`Invalid type frontmatter: ${s.error??"frontmatter is missing"}`);let o=ml(s.frontmatter,s.body,n.basename);return o.sourceRevision=oh(i),o}loadTypeDraft(t){let n=this.settings.typeDrafts[t??"__new__"];return n?JSON.parse(JSON.stringify(n)):null}async saveTypeDraft(t){this.settings.typeDrafts[t.path??"__new__"]=JSON.parse(JSON.stringify(t)),await this.saveSettings()}async clearTypeDraft(t){let n=t??"__new__";n in this.settings.typeDrafts&&(delete this.settings.typeDrafts[n],await this.saveSettings())}async saveTypeModel(t,n,i){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access. Re-enroll it with write access before editing types.");let s=await Ii(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 o=n?this.app.vault.getAbstractFileByPath((0,O.normalizePath)(n)):null;if(o!=null&&!(o instanceof O.TFile))throw new Error(`Type file not found: ${n}`);let a=await this.writeTypeDefinition(s,t,o,i);return this.refreshWorkspaceViews(!0),a}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 Z0(this.app.vault)}async applyMigration(t,n){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile())throw new Error("Collection authority resources must be migrated at the collection authority.");let i=await eS(this.app.vault,t,{allowLossy:n});if(!i.applied)throw new Error(i.restored?`Migration failed and all writes were rolled back. ${i.error??""}`.trim():`Migration needs manual recovery. See ${i.manifestPath}. ${i.error??""}`.trim());this.invalidateSchemaCache(),new O.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 Tb(t)}async applyQuickFix(t){this.connectSync.assertLocalAuthorityWritable();let n=this.app.vault.getAbstractFileByPath(t.path);if(!(n instanceof O.TFile)){new O.Notice(`File not found: ${t.path}`);return}if(this.getMirrorProfile()?.mode==="read_only")throw new Error("This mirror has read-only access.");let i=!1;await this.app.vault.process(n,s=>{this.connectSync.assertLocalAuthorityWritable();let o=Mb(s,t);return i=o.changed,o.content}),new O.Notice(i?`Updated '${t.field??"field"}' in ${n.basename}`:"The field changed or no safe quick fix is available. Revalidate the note."),await this.validateFileAndStore(n,"manual")}async openFileByPath(t,n){let i=this.app.vault.getAbstractFileByPath(t);if(!(i instanceof O.TFile)){new O.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 O.MarkdownView))return;let s=i.view;if(!(s.file instanceof O.TFile)||s.file.path!==t.path)return;let o=s.editor,a=o.lineCount();if(a<3)return;let c=Pb(n),l=new RegExp(`^\\s*${RD(c)}\\s*:`);if(o.getLine(0).trim()==="---")for(let u=1;u({...s,path:n}))),this.sortedIssuesCache=null,this.refreshIssueViews())}clearPendingSaveValidation(t){this.saveValidations.cancel(t)}scheduleSaveValidation(t){this.saveValidations.schedule(t.path,t)}scheduleSchemaRefresh(){this.schemaRefreshes.schedule("schema",void 0)}refreshSchemaNow(){this.schemaRefreshes.cancel("schema"),this.invalidateSchemaCache(),this.refreshWorkspaceViews()}isSchemaRelevantPath(t){let n=(0,O.normalizePath)(t);if(n==="mdbase.yaml")return!0;let i=new Set(["_types","_contracts"]);this.schemaCache&&(i.add((0,O.normalizePath)(this.schemaCache.config.settings.types_folder)),i.add((0,O.normalizePath)(this.schemaCache.config.settings.contracts_folder??"_contracts")));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 Ii(this.app.vault);if(!n)return null;let i=await vb(this.app.vault,n),s=await _b(this.app.vault,n);return{config:n,types:i,contracts:s}})();try{let n=await this.schemaLoadPromise;return n&&(this.schemaCache=n),n}finally{this.schemaLoadPromise=null}}async requireConfigAndTypes(t={}){let n=t.background??!1,i=await this.getConfigAndTypes(t.forceReload??!1);return i?(i.types.size===0&&!n&&new O.Notice(`No types found in ${i.config.settings.types_folder}`),i):(n||new O.Notice("No mdbase.yaml found. Run 'mdbase: Initialize collection' first."),null)}onVaultModify(t){this.observeLocalMirrorChange(t.path),this.isSchemaRelevantPath(t.path)&&this.scheduleSchemaRefresh(),this.settings.validateOnSave&&t.extension==="md"&&this.scheduleSaveValidation(t)}onVaultRename(t,n){this.observeLocalMirrorChange(n),this.observeLocalMirrorChange(t.path),(this.isSchemaRelevantPath(n)||this.isSchemaRelevantPath(t.path))&&this.refreshSchemaNow(),t.extension==="md"&&(this.clearPendingSaveValidation(n),this.moveFileIssues(n,t.path),this.settings.validateOnSave&&this.scheduleSaveValidation(t))}onVaultDelete(t){this.observeLocalMirrorChange(t.path),this.isSchemaRelevantPath(t.path)&&this.refreshSchemaNow(),t.extension==="md"&&(this.clearPendingSaveValidation(t.path),this.clearFileIssues(t.path))}onVaultCreate(t){this.observeLocalMirrorChange(t.path),this.isSchemaRelevantPath(t.path)&&this.refreshSchemaNow()}observeLocalMirrorChange(t){if(!this.getMirrorProfile()||this.connectSync.isSyncing())return;let n=(0,O.normalizePath)(t);[this.app.vault.configDir,".mdbase",".trash",".git"].some(s=>n===s||n.startsWith(`${s}/`))||(this.localChangeObserved=!0,this.updateStatusBar())}async validateFileAndStore(t,n,i=()=>!0){let s=await this.requireConfigAndTypes({background:n!=="manual"});if(!i())return[];if(!s)return n!=="manual"&&this.clearFileIssues(t.path),[];let o=await lf(this.app.vault,t,s.config,s.types);return i()&&(this.setFileIssues(t.path,o),n==="save"&&this.settings.showNoticeOnSave&&o.length>0&&new O.Notice(`mdbase: ${o.length} issue${o.length===1?"":"s"} in ${t.basename}`)),o}async initializeCollectionCommand(){if(this.connectSync.assertLocalAuthorityWritable(),this.getMirrorProfile()){new O.Notice("This vault is configured as a mirror. Sync it instead of initializing a local collection.");return}let{created:t}=await mb(this.app.vault);if(this.invalidateSchemaCache(),t.length===0){new O.Notice("mdbase collection already initialized.");return}new O.Notice(`Initialized mdbase collection: ${t.join(", ")}`)}async reviewSyncCommand(){let t=await this.openWorkspace("sync");this.getMirrorProfile()&&await t.reviewSyncChanges()}async syncNowCommand(){let t=await this.openWorkspace("sync");this.getMirrorProfile()&&await t.syncNow()}async openSyncSection(t){(await this.openWorkspace("sync")).focusSyncSection(t)}async reconnectCommand(){let t=await this.openWorkspace("sync");this.getMirrorProfile()&&await t.reconnectCollection()}async createTypeDefinitionCommand(){(await this.openWorkspace("types")).createNewType()}async editTypeDefinitionCommand(){let t=await this.requireConfigAndTypes();if(!t||t.types.size===0){new O.Notice("No type definitions found.");return}let n=await mh(this.app,[...t.types.values()]);if(!n)return;await(await this.openWorkspace("types")).editType(n.filePath)}async editCurrentTypeDefinitionCommand(){let t=this.app.workspace.getActiveFile();if(!(t instanceof O.TFile)||t.extension!=="md"){new O.Notice("Open a typed Markdown note or type definition first.");return}let n=await this.requireConfigAndTypes();if(!n)return;let s=[...n.types.values()].find(a=>a.filePath===t.path)??null;if(!s){let a=et(await this.app.vault.cachedRead(t));if(a.error){new O.Notice(`Cannot identify this note's type: ${a.error}`);return}let l=sn(t.path,a.frontmatter,n.config,n.types).flatMap(u=>{let d=n.types.get(u);return d?[d]:[]});if(l.length===0){new O.Notice("The current note does not match a known type definition.");return}s=l.length===1?l[0]:await mh(this.app,l)}if(!s){new O.Notice("The current note does not match a known type definition.");return}await(await this.openWorkspace("types")).editType(s.filePath)}async createNoteFromTypeCommand(){this.connectSync.assertLocalAuthorityWritable();let t=await this.requireConfigAndTypes();if(!t)return;if(t.types.size===0){new O.Notice("No type definitions found.");return}let n=await mh(this.app,Array.from(t.types.values()));if(!n)return;let i=$b(n,t.config),s=Eb(n,i);for(let[u,d]of s){let f=`Required field: ${u}`,p=await new Uo(this.app,f,d.type??"string").openAndGetValue();if(p==null)return;if(p.trim().length===0){new O.Notice(`Field '${u}' is required.`);return}try{i[u]=df(p,d)}catch(m){new O.Notice(`Invalid value for ${u}: ${m instanceof Error?m.message:String(m)}`);return}}let o=n.display_name_key??"title";if(i[o]==null){let u=await new Uo(this.app,`Optional ${o} (used for filename)`,"").openAndGetValue();u&&u.trim().length>0&&(i[o]=u.trim())}let a=await Ab(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,O.normalizePath)(c.trim().length>0?c.trim():a);l.endsWith(".md")||(l=`${l}.md`);try{let u=await kb(this.app.vault,l,i);await this.app.workspace.getLeaf(!0).openFile(u),new O.Notice(`Created note: ${u.path}`),await this.validateFileAndStore(u,"manual")}catch(u){new O.Notice(u instanceof Error?u.message:String(u))}}async validateCurrentNoteCommand(){let t=this.app.workspace.getActiveFile();if(!(t instanceof O.TFile)||t.extension!=="md"){new O.Notice("Open a Markdown note first.");return}let n=await this.validateFileAndStore(t,"manual");n.length===0?new O.Notice("No issues in current note."):(new O.Notice(`Found ${n.length} issue${n.length===1?"":"s"} in current note.`),await this.openIssuesView())}async runCollectionValidation(t){let n=await this.requireConfigAndTypes({background:!1});if(!n)return;let i=await Sb(this.app.vault,n.config,n.types),s=new Map;for(let o of i){let a=s.get(o.path)??[];a.push(o),s.set(o.path,a)}if(this.issueMap=s,this.sortedIssuesCache=null,this.refreshIssueViews(),t)if(i.length===0)new O.Notice("Collection validation passed with no issues.");else{let o=i.filter(c=>c.severity==="error").length,a=i.length-o;new O.Notice(`Collection validation: ${o} error(s), ${a} warning(s)`),await this.openIssuesView()}}async ensureFolderExists(t){let n=(0,O.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,s){let o=n.name.trim();if(!o)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 a=is(n),c=n.body.trim()||`# ${o} -Type definition for ${o}.`,l=`${bt(a,c)} -`,u=(0,O.normalizePath)(t.settings.types_folder),d=(0,O.normalizePath)(`${u}/${o}.md`);if(!i){if(await this.ensureFolderExists(u),await this.app.vault.adapter.exists(d))throw new Error(`Type already exists: ${d}`);let _=await this.app.vault.create(d,l);return this.invalidateSchemaCache(),_}let f=i.path,p=await this.app.vault.cachedRead(i);if(s&&Hp(p)!==s)throw new Error(`The source changed after this draft was opened: ${f}. Reopen the type and review both versions before saving.`);let m=i.path.lastIndexOf("/"),h=m>=0?i.path.slice(0,m):"",g=(0,O.normalizePath)(`${h?`${h}/`:""}${o}.md`)||d;if(g!==i.path&&await this.app.vault.adapter.exists(g))throw new Error(`Cannot rename type file to ${g}; file already exists.`);let v=!1;try{g!==i.path&&(await this.app.fileManager.renameFile(i,g),v=!0);let _=this.app.vault.getAbstractFileByPath(g);if(!(_ instanceof O.TFile))throw new Error(`Unable to access updated type file: ${g}`);return await this.app.vault.modify(_,l),this.invalidateSchemaCache(),_}catch(_){try{let w=this.app.vault.getAbstractFileByPath(v?g:f);w instanceof O.TFile&&(await this.app.vault.modify(w,p),v&&await this.app.fileManager.renameFile(w,f))}catch(w){throw new Error(`Saving the type failed and automatic recovery also failed. Review '${f}' and '${g}'. ${_ instanceof Error?_.message:String(_)}; recovery: ${w instanceof Error?w.message:String(w)}`)}throw _}}}; +Type definition for ${o}.`,l=`${Vt(a,c)} +`,u=(0,O.normalizePath)(t.settings.types_folder),d=(0,O.normalizePath)(`${u}/${o}.md`);if(!i){if(await this.ensureFolderExists(u),await this.app.vault.adapter.exists(d))throw new Error(`Type already exists: ${d}`);let v=await this.app.vault.create(d,l);return this.invalidateSchemaCache(),v}let f=i.path,p=await this.app.vault.cachedRead(i);if(s&&oh(p)!==s)throw new Error(`The source changed after this draft was opened: ${f}. Reopen the type and review both versions before saving.`);let m=i.path.lastIndexOf("/"),h=m>=0?i.path.slice(0,m):"",g=(0,O.normalizePath)(`${h?`${h}/`:""}${o}.md`)||d;if(g!==i.path&&await this.app.vault.adapter.exists(g))throw new Error(`Cannot rename type file to ${g}; file already exists.`);let _=!1;try{g!==i.path&&(await this.app.fileManager.renameFile(i,g),_=!0);let v=this.app.vault.getAbstractFileByPath(g);if(!(v instanceof O.TFile))throw new Error(`Unable to access updated type file: ${g}`);return await this.app.vault.modify(v,l),this.invalidateSchemaCache(),v}catch(v){try{let w=this.app.vault.getAbstractFileByPath(_?g:f);w instanceof O.TFile&&(await this.app.vault.modify(w,p),_&&await this.app.fileManager.renameFile(w,f))}catch(w){throw new Error(`Saving the type failed and automatic recovery also failed. Review '${f}' and '${g}'. ${v instanceof Error?v.message:String(v)}; recovery: ${w instanceof Error?w.message:String(w)}`)}throw v}}}; diff --git a/main.ts b/main.ts index 94ef61d..774eb0d 100644 --- a/main.ts +++ b/main.ts @@ -1,3 +1,4 @@ +import { applyQuickFixToDocument, quickFixLabel } from "./src/quickFix"; import { App, addIcon, @@ -601,6 +602,7 @@ export default class MdbasePlugin extends Plugin { } onunload(): void { + this.connectSync.dispose(); void this.interopBridge.dispose().catch((error: unknown) => { console.error("mdbase: failed to dispose the interoperability bridge", error); }); @@ -808,9 +810,7 @@ export default class MdbasePlugin extends Plugin { } getQuickFixLabel(issue: MdbaseIssue): string | null { - if (["unknown_field", "schema_additional_properties"].includes(issue.code) && issue.field) return "Remove field"; - if (["missing_required", "schema_required"].includes(issue.code) && issue.field) return "Add placeholder"; - return null; + return quickFixLabel(issue); } async applyQuickFix(issue: MdbaseIssue): Promise { @@ -821,42 +821,16 @@ export default class MdbasePlugin extends Plugin { return; } - const raw = await this.app.vault.cachedRead(file); - const parsed = parseFrontmatter(raw); - - if (parsed.error) { - new Notice(`Cannot apply quick fix: invalid frontmatter (${parsed.error})`); - return; - } - - if (["unknown_field", "schema_additional_properties"].includes(issue.code) && issue.field) { - const key = getTopLevelFieldFromIssuePath(issue.field); - if (!(key in parsed.frontmatter)) { - new Notice(`Field '${key}' not found in frontmatter.`); - return; - } - - delete parsed.frontmatter[key]; - await this.app.vault.modify(file, `${formatMarkdown(parsed.frontmatter, parsed.body)}\n`); - new Notice(`Removed '${key}' from ${file.basename}`); - await this.validateFileAndStore(file, "manual"); - return; - } - - if (["missing_required", "schema_required"].includes(issue.code) && issue.field) { - const key = getTopLevelFieldFromIssuePath(issue.field); - if (parsed.frontmatter[key] === undefined) { - parsed.frontmatter[key] = "TODO"; - } - - const body = parsed.hasFrontmatter ? parsed.body : raw; - await this.app.vault.modify(file, `${formatMarkdown(parsed.frontmatter, body)}\n`); - new Notice(`Added placeholder '${key}' to ${file.basename}`); - await this.validateFileAndStore(file, "manual"); - return; - } - - new Notice("No quick fix available for this issue."); + if (this.getMirrorProfile()?.mode === "read_only") throw new Error("This mirror has read-only access."); + let changed = false; + await this.app.vault.process(file, (raw) => { + this.connectSync.assertLocalAuthorityWritable(); + const result = applyQuickFixToDocument(raw, issue); + changed = result.changed; + return result.content; + }); + new Notice(changed ? `Updated '${issue.field ?? "field"}' in ${file.basename}` : "The field changed or no safe quick fix is available. Revalidate the note."); + await this.validateFileAndStore(file, "manual"); } async openFileByPath(path: string, field?: string): Promise { diff --git a/package-lock.json b/package-lock.json index 14770c5..fa352d6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,8 +10,8 @@ "license": "MIT", "dependencies": { "@callumalpass/mdbase-interop": "0.1.0-rc.2", - "@mdbase-dev/connect-protocol": "0.1.0-beta.69", - "@mdbase-dev/connect-sync": "0.1.0-beta.69", + "@mdbase-dev/connect-protocol": "0.1.0-beta.91", + "@mdbase-dev/connect-sync": "0.1.0-beta.91", "ajv": "^8.20.0", "ajv-formats": "^3.0.1", "picomatch": "^4.0.5" @@ -26,6 +26,7 @@ "eslint": "^9.39.5", "eslint-config-prettier": "^10.1.8", "eslint-plugin-obsidianmd": "^0.3.0", + "fake-indexeddb": "^6.2.5", "globals": "^15.15.0", "obsidian": "latest", "postcss-selector-parser": "^7.1.5", @@ -1109,9 +1110,9 @@ "peer": true }, "node_modules/@mdbase-dev/connect-protocol": { - "version": "0.1.0-beta.69", - "resolved": "https://registry.npmjs.org/@mdbase-dev/connect-protocol/-/connect-protocol-0.1.0-beta.69.tgz", - "integrity": "sha512-BDs378h5o7+bFcMc+u3cLAuk8zfjF333ZX9NsjSmZ39EasQQ3AqjG0Hgf79MezuSHczqskXUhgL5hqHZQ9ivsw==", + "version": "0.1.0-beta.91", + "resolved": "https://registry.npmjs.org/@mdbase-dev/connect-protocol/-/connect-protocol-0.1.0-beta.91.tgz", + "integrity": "sha512-7CUgW1unwNLcQqhot+UzBTbwmqSpF9uTYxtZkwOYKVDyTg2mxDF4htW5G0sIhkrDu/JRr4UK4HlnQhEQXPmljA==", "license": "MIT", "dependencies": { "ajv": "^8.20.0", @@ -1119,12 +1120,12 @@ } }, "node_modules/@mdbase-dev/connect-sync": { - "version": "0.1.0-beta.69", - "resolved": "https://registry.npmjs.org/@mdbase-dev/connect-sync/-/connect-sync-0.1.0-beta.69.tgz", - "integrity": "sha512-UWSKBspLw91vDbvw559quj3hJN2MFwH1VqpAGuuqk5+zTAkw3G5lhRJE26Uyzw/BN7+CJGWmp8zw5oBxHl3GAQ==", + "version": "0.1.0-beta.91", + "resolved": "https://registry.npmjs.org/@mdbase-dev/connect-sync/-/connect-sync-0.1.0-beta.91.tgz", + "integrity": "sha512-7OsD2ENCdI6WKjENm9dxXdpmcfO+I+XGDOoN1obxuKWu0Zem6XazMDfSPuxUixCArL10gBhux1pInKQq2luFAg==", "license": "MIT", "dependencies": { - "@mdbase-dev/connect-protocol": "0.1.0-beta.69", + "@mdbase-dev/connect-protocol": "0.1.0-beta.91", "@noble/hashes": "^2.2.0", "yaml": "^2.9.0" }, @@ -3320,6 +3321,16 @@ "node": ">=0.10.0" } }, + "node_modules/fake-indexeddb": { + "version": "6.2.5", + "resolved": "https://registry.npmjs.org/fake-indexeddb/-/fake-indexeddb-6.2.5.tgz", + "integrity": "sha512-CGnyrvbhPlWYMngksqrSSUT1BAVP49dZocrHuK0SvtR0D5TMs5wP0o3j7jexDJW01KSadjBp1M/71o/KR3nD1w==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -3371,9 +3382,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz", - "integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==", + "version": "3.1.7", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.7.tgz", + "integrity": "sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==", "funding": [ { "type": "github", diff --git a/package.json b/package.json index 4ec2d9b..bd485df 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ "eslint": "^9.39.5", "eslint-config-prettier": "^10.1.8", "eslint-plugin-obsidianmd": "^0.3.0", + "fake-indexeddb": "^6.2.5", "globals": "^15.15.0", "obsidian": "latest", "postcss-selector-parser": "^7.1.5", @@ -50,8 +51,8 @@ }, "dependencies": { "@callumalpass/mdbase-interop": "0.1.0-rc.2", - "@mdbase-dev/connect-protocol": "0.1.0-beta.69", - "@mdbase-dev/connect-sync": "0.1.0-beta.69", + "@mdbase-dev/connect-protocol": "0.1.0-beta.91", + "@mdbase-dev/connect-sync": "0.1.0-beta.91", "ajv": "^8.20.0", "ajv-formats": "^3.0.1", "picomatch": "^4.0.5" diff --git a/src/connectSync.ts b/src/connectSync.ts index fdff2c4..f3a26a4 100644 --- a/src/connectSync.ts +++ b/src/connectSync.ts @@ -58,6 +58,7 @@ import { type MirrorLease, type MirrorProgress, type MirrorState, + type MirrorTextReadResult, type MirrorStateStore, type MirrorStatus, WritableDirectoryMirror, @@ -160,6 +161,14 @@ const BLOB_DATABASE = "mdbase-obsidian-connect-blobs"; const BLOB_MANIFEST_STORE = "manifests"; const BLOB_CHUNK_STORE = "chunks"; const BLOB_CHUNK_BYTES = 1024 * 1024; +// Vault APIs materialize whole files. Bound peak allocations on mobile as well as desktop. +export const MAX_BINARY_FILE_BYTES = 32 * 1024 * 1024; + +function assertBinarySize(size: number): void { + if (!Number.isSafeInteger(size) || size < 0 || size > MAX_BINARY_FILE_BYTES) { + throw new SyncError("file_too_large", "Binary sync supports files up to 32 MiB on this device. Exclude this file's folder to continue."); + } +} const ACCESS_SECRET_PREFIX = "mdbase-connect-access-"; const REFRESH_SECRET_PREFIX = "mdbase-connect-refresh-"; const ADOPTION_SECRET_PREFIX = "mdbase-connect-adoption-"; @@ -255,7 +264,7 @@ async function collectBinary(source: AsyncIterable): Promise { } async *downloadFile(file: CollectionFileDescriptor): AsyncGenerator { + assertBinarySize(file.size); const transferId = crypto.randomUUID(); try { let transferredBytes = 0; @@ -541,6 +551,7 @@ implements SyncTransport { request: OpenFileUploadRequest, source: AsyncIterable, ): Promise { + assertBinarySize(request.size); const session = await this.fileRequest("POST", "uploads", request); if ( session.protocol_version !== 1 @@ -863,6 +874,7 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { private readonly vault: Vault, // eslint-disable-next-line obsidianmd/prefer-file-manager-trash-file -- Tests and standalone adapters lack an App; production injects FileManager.trashFile below. private readonly trashFile: (file: TFile) => Promise = (file) => vault.delete(file, true), + private readonly assertActive: () => void = () => undefined, ) {} async exists(input: string): Promise { @@ -871,13 +883,38 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { } async read(input: string): Promise { + const result = await this.readText(input); + if (result === null || typeof result === "string") return result; + throw new SyncError(result.code, result.reason); + } + + async readText(input: string): Promise { const path = safeMirrorPath(this.vault, input); const file = this.vault.getAbstractFileByPath(path); - if (file == null) return null; - if (!(file instanceof TFile)) { + if (file instanceof TFolder) { throw new SyncError("mirror_path_collision", `Expected a file at ${path}.`); } - return this.vault.cachedRead(file); + let bytes: ArrayBuffer; + try { + bytes = await this.vault.adapter.readBinary(path); + } catch { + try { + if (!await this.vault.adapter.exists(path)) return null; + } catch { + // Report the original read failure when existence cannot be established. + } + throw new SyncError("file_read_failed", `Could not read ${path}.`); + } + try { + return new TextDecoder("utf-8", { fatal: true }).decode(bytes); + } catch { + return { + kind: "invalid", + code: "invalid_utf8", + reason: "File is not valid UTF-8.", + revision: (await binaryInfo(bytes)).content_digest, + }; + } } async write(input: string, value: string): Promise { @@ -888,6 +925,7 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { if (existing instanceof TFolder) { throw new SyncError("mirror_path_collision", `A folder blocks the mirror file ${path}.`); } + this.assertActive(); if (existing instanceof TFile) { await this.vault.modify(existing, value); } else { @@ -907,6 +945,7 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { } const slash = target.lastIndexOf("/"); if (slash >= 0) await ensureFolder(this.vault, target.slice(0, slash)); + this.assertActive(); await this.vault.rename(file, target); } @@ -917,6 +956,7 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { if (!(existing instanceof TFile)) { throw new SyncError("mirror_path_collision", `Expected a file at ${path}.`); } + this.assertActive(); await this.trashFile(existing); } @@ -935,7 +975,10 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { 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}.`); - return binaryInfo(await this.vault.readBinary(file)); + assertBinarySize(file.stat.size); + const bytes = await this.vault.readBinary(file); + assertBinarySize(bytes.byteLength); + return binaryInfo(bytes); } async writeBinary(input: string, source: AsyncIterable): Promise { @@ -945,6 +988,7 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { 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}.`); + this.assertActive(); if (existing instanceof TFile) await this.vault.modifyBinary(existing, bytes); else await this.vault.createBinary(path, bytes); } @@ -969,7 +1013,9 @@ export class ObsidianMirrorFileSystem implements MirrorFileSystem { 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}.`); + assertBinarySize(file.stat.size); const bytes = new Uint8Array(await this.vault.readBinary(file)); + assertBinarySize(bytes.byteLength); return (async function* (): AsyncGenerator { for (let offset = 0; offset < bytes.byteLength; offset += BLOB_CHUNK_BYTES) { yield bytes.subarray(offset, Math.min(bytes.byteLength, offset + BLOB_CHUNK_BYTES)); @@ -1023,11 +1069,15 @@ export class IndexedDbMirrorBlobStore implements MirrorBlobStore { } } await this.put(BLOB_MANIFEST_STORE, this.manifestKey(contentDigest), { stage, chunks, size } satisfies BlobManifest); - if (previous && previous.stage !== stage) await this.removeStage(previous.stage, previous.chunks); } catch (error) { await this.removeStage(stage, chunks).catch(() => undefined); throw error; } + // Once published, the new stage is authoritative. Cleanup failure must not + // delete it and leave the durable manifest pointing at missing chunks. + if (previous && previous.stage !== stage) { + await this.removeStage(previous.stage, previous.chunks).catch(() => undefined); + } } async remove(contentDigest: `sha256:${string}`): Promise { @@ -1127,6 +1177,11 @@ export class IndexedDbMirrorBlobStore implements MirrorBlobStore { }); } + close(): void { + void this.database?.then((database) => database.close(), () => undefined); + this.database = null; + } + private open(): Promise { if (typeof indexedDB === "undefined") throw new SyncError("storage_unavailable", "IndexedDB is required for binary file sync."); this.database ??= new Promise((resolve, reject) => { @@ -1178,6 +1233,11 @@ export class IndexedDbMirrorStateStore implements MirrorStateStore { }); } + close(): void { + void this.database?.then((database) => database.close(), () => undefined); + this.database = null; + } + private open(): Promise { if (typeof indexedDB === "undefined") { throw new SyncError("storage_unavailable", "IndexedDB is required for persistent mirror state."); @@ -1229,6 +1289,40 @@ export interface ConnectSyncControllerOptions { } export class ConnectSyncController { + private disposed = false; + private readonly lifetime = new AbortController(); + private readonly stateStores = new Map(); + private readonly blobStores = new Map(); + + dispose(): void { + this.disposed = true; + this.lifetime.abort(); + this.cancelSync(); + for (const store of this.stateStores.values()) store.close(); + for (const store of this.blobStores.values()) store.close(); + this.stateStores.clear(); + this.blobStores.clear(); + } + + private async withLifetime(signal: AbortSignal | undefined, operation: (signal: AbortSignal) => Promise): Promise { + this.assertActive(); + const controller = new AbortController(); + const abort = () => controller.abort(); + this.lifetime.signal.addEventListener("abort", abort, { once: true }); + signal?.addEventListener("abort", abort, { once: true }); + if (signal?.aborted) controller.abort(); + try { + abortIfNeeded(controller.signal); + return await operation(controller.signal); + } finally { + this.lifetime.signal.removeEventListener("abort", abort); + signal?.removeEventListener("abort", abort); + } + } + + private assertActive(): void { + if (this.disposed) throw new DOMException("Plugin unloaded.", "AbortError"); + } private progress: MirrorProgress | null = null; private fileProgress: FileTransferProgress | null = null; private syncAbort: AbortController | null = null; @@ -1247,6 +1341,7 @@ export class ConnectSyncController { this.fileSystem = options.fileSystem ?? new ObsidianMirrorFileSystem( app.vault, (file) => app.fileManager.trashFile(file), + () => this.assertActive(), ); this.enrollmentClient = options.enrollmentClient ?? new MirrorEnrollmentClient({ request: createObsidianEnrollmentRequester(), @@ -1258,7 +1353,14 @@ export class ConnectSyncController { async initialize(): Promise { this.adoptionMarker = await this.readAdoptionMarker(); - if (this.adoptionMarker && this.settingsHost.getMirrorProfile()) { + const profile = this.settingsHost.getMirrorProfile(); + if (this.adoptionMarker && profile) { + if (this.adoptionMarker.phase === "adopted" + && this.adoptionMarker.session.requested.collectionId === profile.collectionId) { + await this.assertMirror(profile.collectionId); + await this.clearAdoptionCheckpoint(this.adoptionMarker.session.adoptionId); + return; + } throw new SyncError( "authority_adoption_state_conflict", "This vault contains both an authority-adoption checkpoint and a mirror profile.", @@ -1290,6 +1392,7 @@ export class ConnectSyncController { } assertLocalAuthorityWritable(): void { + this.assertActive(); if (this.adoptionMarker && ["fenced", "activating", "adopted"].includes(this.adoptionMarker.phase)) { throw new SyncError( "local_authority_fenced", @@ -1300,7 +1403,11 @@ export class ConnectSyncController { } } - async adoptLocalCollection( + async adoptLocalCollection(input: AdoptLocalCollectionInput, callbacks: AdoptLocalCollectionCallbacks): Promise { + return this.withLifetime(callbacks.signal, (signal) => this.adoptLocalCollectionActive(input, { ...callbacks, signal })); + } + + private async adoptLocalCollectionActive( input: AdoptLocalCollectionInput, callbacks: AdoptLocalCollectionCallbacks, ): Promise { @@ -1352,13 +1459,18 @@ export class ConnectSyncController { if (marker.phase === "waiting_for_approval") { await callbacks.onVerification?.(publicAdoptionSession(session)); } - return this.runAdoptionWithRecovery(session, { + return this.withLifetime(callbacks.signal, (signal) => this.runAdoptionWithRecovery(session, { ...callbacks, + signal, onVerification: (verification) => callbacks.onVerification?.(verification), - }); + })); } async cancelAdoption(signal?: AbortSignal): Promise { + return this.withLifetime(signal, (activeSignal) => this.cancelAdoptionActive(activeSignal)); + } + + private async cancelAdoptionActive(signal: AbortSignal): Promise { const marker = this.adoptionMarker ?? await this.readAdoptionMarker(); if (!marker) return; if (["activating", "adopted"].includes(marker.phase)) { @@ -1378,7 +1490,11 @@ export class ConnectSyncController { await this.clearAdoptionCheckpoint(marker.session.adoptionId); } - async enroll( + async enroll(input: EnrollMirrorInput, callbacks: EnrollMirrorCallbacks): Promise { + return this.withLifetime(callbacks.signal, (signal) => this.enrollActive(input, { ...callbacks, signal })); + } + + private async enrollActive( input: EnrollMirrorInput, callbacks: EnrollMirrorCallbacks, ): Promise { @@ -1463,6 +1579,10 @@ export class ConnectSyncController { } async reauthorize(callbacks: EnrollMirrorCallbacks): Promise { + return this.withLifetime(callbacks.signal, (signal) => this.reauthorizeActive({ ...callbacks, signal })); + } + + private async reauthorizeActive(callbacks: EnrollMirrorCallbacks): Promise { const profile = this.requireProfile(); const oldStore = this.stateStoreFor(profile); const oldState = await oldStore.read(); @@ -1683,6 +1803,7 @@ export class ConnectSyncController { this.mirrorOperationTail = new Promise((resolve) => { release = resolve; }); await predecessor; try { + this.assertActive(); return await operation(); } finally { release(); @@ -1929,7 +2050,7 @@ export class ConnectSyncController { private adoptionBlobStore(collectionId: string): MirrorBlobStore { return this.options.adoptionBlobStoreFactory?.(collectionId) - ?? new IndexedDbMirrorBlobStore(`adoption:${collectionId}`); + ?? this.cachedBlobStore(`adoption:${collectionId}`); } private adoptionUploadOptions( @@ -1975,6 +2096,7 @@ export class ConnectSyncController { ? parsed["x-mdbase-connect"] : {}; parsed["x-mdbase-connect"] = { ...extension, collection_id: collectionId }; + this.assertActive(); await this.app.vault.adapter.write("mdbase.yaml", stringifyYaml(parsed)); } else if (typeof existing === "string" && UUID_PATTERN.test(existing)) { collectionId = existing; @@ -1991,13 +2113,30 @@ export class ConnectSyncController { } private stateStoreFor(profile: MirrorProfile): MirrorStateStore { - return this.options.stateStoreFactory?.(profile) - ?? new IndexedDbMirrorStateStore(`${profile.collectionId}:${profile.replicaId}`); + this.assertActive(); + if (this.options.stateStoreFactory) return this.options.stateStoreFactory(profile); + const key = `${profile.collectionId}:${profile.replicaId}`; + let store = this.stateStores.get(key); + if (!store) { + store = new IndexedDbMirrorStateStore(key); + this.stateStores.set(key, store); + } + return store; + } + + private cachedBlobStore(key: string): IndexedDbMirrorBlobStore { + this.assertActive(); + let store = this.blobStores.get(key); + if (!store) { + store = new IndexedDbMirrorBlobStore(key); + this.blobStores.set(key, store); + } + return store; } private blobStoreFor(profile: MirrorProfile): MirrorBlobStore { return this.options.blobStoreFactory?.(profile) - ?? new IndexedDbMirrorBlobStore(`${profile.collectionId}:${profile.replicaId}`); + ?? this.cachedBlobStore(`${profile.collectionId}:${profile.replicaId}`); } private async transportFor( @@ -2005,7 +2144,9 @@ export class ConnectSyncController { signal?: AbortSignal, onFileProgress?: (progress: FileTransferProgress) => void, ): Promise> { + this.assertActive(); const accessToken = await this.freshAccessToken(profile); + this.assertActive(); const transport = this.options.transportFactory?.(profile, accessToken) ?? new ObsidianSyncTransport(profile.syncUrl, accessToken, resilientRequestUrl, onFileProgress); return abortableSyncTransport(transport, signal); @@ -2034,6 +2175,7 @@ export class ConnectSyncController { } private requireProfile(): MirrorProfile { + this.assertActive(); const profile = this.settingsHost.getMirrorProfile(); if (!profile) throw new SyncError("mirror_not_configured", "This vault is not connected to a collection authority."); return profile; @@ -2056,6 +2198,7 @@ export class ConnectSyncController { } private async persistEnrollment(enrollment: MirrorEnrollment, selectiveSync?: SelectiveSyncPolicy): Promise { + this.assertActive(); this.app.secretStorage.setSecret(this.accessSecretId(enrollment.collectionId), enrollment.accessToken); this.app.secretStorage.setSecret(this.refreshSecretId(enrollment.collectionId), enrollment.refreshCredential); await this.settingsHost.saveMirrorProfile(profileFromEnrollment( @@ -2209,6 +2352,7 @@ export class ConnectSyncController { } private async markMirror(collectionId: string): Promise { + this.assertActive(); const marker = await this.readMarker(); if (marker) { if (marker.collection_id !== collectionId) { @@ -2217,6 +2361,7 @@ export class ConnectSyncController { return false; } await ensureFolder(this.app.vault, ".mdbase"); + this.assertActive(); await this.app.vault.adapter.write(ROLE_MARKER_PATH, `${JSON.stringify({ version: 1, role: "mirror", @@ -2285,6 +2430,7 @@ export class ConnectSyncController { private async writeAdoptionMarker(marker: AdoptionMarker): Promise { await ensureFolder(this.app.vault, ".mdbase"); + this.assertActive(); await this.app.vault.adapter.write( ADOPTION_MARKER_PATH, `${JSON.stringify(marker, null, 2)}\n`, @@ -2313,7 +2459,9 @@ export class ConnectSyncController { } private async writeAdoptionSnapshot(snapshot: AuthorityImportSnapshot): Promise { + this.assertActive(); await ensureFolder(this.app.vault, ".mdbase"); + this.assertActive(); await this.app.vault.adapter.write( ADOPTION_SNAPSHOT_PATH, JSON.stringify(snapshot), @@ -2352,12 +2500,14 @@ export class ConnectSyncController { private async clearAdoptionCheckpoint(adoptionId: string): Promise { const collectionId = this.adoptionMarker?.session.requested.collectionId; - if (await this.app.vault.adapter.exists(ADOPTION_MARKER_PATH)) { - await this.app.vault.adapter.remove(ADOPTION_MARKER_PATH); - } + // Keep the recovery marker until ancillary cleanup succeeds, so a restart + // can retry cleanup instead of silently forgetting the interrupted transition. if (await this.app.vault.adapter.exists(ADOPTION_SNAPSHOT_PATH)) { await this.app.vault.adapter.remove(ADOPTION_SNAPSHOT_PATH); } + if (await this.app.vault.adapter.exists(ADOPTION_MARKER_PATH)) { + await this.app.vault.adapter.remove(ADOPTION_MARKER_PATH); + } // Obsidian currently has no SecretStorage delete API. Emptying the value // makes the one-time adoption credential unusable without writing it to disk. this.app.secretStorage.setSecret(this.adoptionSecretId(adoptionId), ""); diff --git a/src/mdbaseCore.ts b/src/mdbaseCore.ts index f731aaa..9f9d780 100644 --- a/src/mdbaseCore.ts +++ b/src/mdbaseCore.ts @@ -1365,6 +1365,7 @@ function ajvErrorToIssue(error: ErrorObject, filePath: string, typeName: string) details: { instance_path: error.instancePath, schema_path: error.schemaPath, + ...(child === undefined ? {} : { property: child }), }, }; } diff --git a/src/quickFix.ts b/src/quickFix.ts new file mode 100644 index 0000000..a94d516 --- /dev/null +++ b/src/quickFix.ts @@ -0,0 +1,53 @@ +import { stringifyYaml } from "obsidian"; +import { parseFrontmatter, type MdbaseIssue } from "./mdbaseCore"; + +export function applyQuickFixToDocument(raw: string, issue: MdbaseIssue): { content: string; changed: boolean } { + const parsed = parseFrontmatter(raw); + if (parsed.error) throw new Error(`Invalid frontmatter: ${parsed.error}`); + if (!applyFieldQuickFix(parsed.frontmatter, issue)) return { content: raw, changed: false }; + // Generic Markdown formatting normalizes body whitespace. Quick fixes must + // replace only frontmatter and preserve every byte following its delimiter. + const yaml = stringifyYaml(parsed.frontmatter).trimEnd(); + return { content: `---\n${yaml}\n---\n${parsed.body}`, changed: true }; +} + +function target(issue: MdbaseIssue): string[] | null { + if (!issue.field) return null; + if (["unknown_field", "missing_required"].includes(issue.code)) { + // Legacy nested paths are ambiguous; only offer unambiguous fixes. + return /[.[\]]/.test(issue.field) ? null : [issue.field]; + } + if (!["schema_additional_properties", "schema_required"].includes(issue.code)) return null; + const pointer = issue.details?.instance_path; + const property = issue.details?.property; + if (typeof pointer !== "string" || typeof property !== "string") return null; + return [...(pointer === "" ? [] : pointer.slice(1).split("/").map((part) => part.replace(/~1/g, "/").replace(/~0/g, "~"))), property]; +} + +export function quickFixLabel(issue: MdbaseIssue): string | null { + if (!target(issue)) return null; + return ["unknown_field", "schema_additional_properties"].includes(issue.code) ? "Remove field" : "Add placeholder"; +} + +/** Mutate only an own property of the exact parent identified by validation. */ +export function applyFieldQuickFix(frontmatter: Record, issue: MdbaseIssue): boolean { + const path = target(issue); + if (!path?.length) return false; + let parent: unknown = frontmatter; + for (const segment of path.slice(0, -1)) { + if (!parent || typeof parent !== "object" || !Object.prototype.hasOwnProperty.call(parent, segment)) return false; + parent = (parent as Record)[segment]; + } + if (!parent || typeof parent !== "object" || Array.isArray(parent)) return false; + const object = parent as Record; + const key = path[path.length - 1]; + const exists = Object.prototype.hasOwnProperty.call(object, key); + if (["unknown_field", "schema_additional_properties"].includes(issue.code)) { + if (!exists) return false; + delete object[key]; + } else { + if (exists) return false; + Object.defineProperty(object, key, { value: "TODO", enumerable: true, configurable: true, writable: true }); + } + return true; +} diff --git a/src/syncPreview.ts b/src/syncPreview.ts index 6223cd5..db22a63 100644 --- a/src/syncPreview.ts +++ b/src/syncPreview.ts @@ -1,5 +1,6 @@ import type { MirrorInitializationPreview, + MirrorLocalIssue, MirrorPlanAction, MirrorSyncPlan, } from "@mdbase-dev/connect-sync/mirror"; @@ -64,10 +65,11 @@ export function previewFromPlan(plan: MirrorSyncPlan): MdbaseSyncPreview { issue.blocking && issue.code === "local_collision" && issue.path !== undefined) .map((issue) => issue.path), local_issues: plan.issues - .filter((issue): issue is typeof issue & { path: string } => - issue.code === "invalid_frontmatter" && issue.path !== undefined) + .filter((issue): issue is typeof issue & { path: string; code: MirrorLocalIssue["code"] } => + ["invalid_frontmatter", "file_read_failed"].includes(issue.code) + && issue.path !== undefined) .map((issue) => ({ - code: "invalid_frontmatter" as const, + code: issue.code, message: issue.message, path: issue.path, })), diff --git a/src/syncUx.ts b/src/syncUx.ts index cc2f557..10cc6f8 100644 --- a/src/syncUx.ts +++ b/src/syncUx.ts @@ -1,4 +1,4 @@ -import type { MirrorProgress, MirrorStatus } from "@mdbase-dev/connect-sync/mirror"; +import type { MirrorProgress, MirrorStatus, MirrorSyncPlan } from "@mdbase-dev/connect-sync/mirror"; export interface FileTransferProgress { direction: "upload" | "download"; @@ -36,6 +36,46 @@ export interface SyncIndicator { const MAX_ACTIVITY = 30; +export interface SyncReviewPresentation { + actionLabel: string; + actionDisabled: boolean; + message: string; +} + +export function syncReviewPresentation( + plan: MirrorSyncPlan | null, + entryCount: number, + busy = false, +): SyncReviewPresentation { + if (!plan) { + return { + actionLabel: "Review before syncing", + actionDisabled: true, + message: "Review local and hosted changes before syncing.", + }; + } + if (plan.summary.blocking_issues > 0) { + return { + actionLabel: "Fix local files before syncing", + actionDisabled: true, + message: "Synchronization is paused. Fix every listed local file, then refresh the review.", + }; + } + const outcomes = plan.actions.filter((action) => action.command !== "advance_checkpoint").length; + const hasCheckpoint = plan.actions.some((action) => action.command === "advance_checkpoint"); + return { + actionLabel: outcomes + ? `Sync ${outcomes} ${outcomes === 1 ? "outcome" : "outcomes"}` + : hasCheckpoint + ? "Confirm sync checkpoint" + : "Already up to date", + actionDisabled: busy || plan.actions.length === 0, + message: entryCount + ? "Review each transfer below, then sync when ready." + : "This vault and the hosted collection are already aligned.", + }; +} + export function formatBytes(value: number): string { if (value < 1024) return `${value} B`; if (value < 1024 * 1024) return `${(value / 1024).toFixed(value < 10 * 1024 ? 1 : 0)} KB`; diff --git a/src/workspaceView.ts b/src/workspaceView.ts index 93f376e..3460f1d 100644 --- a/src/workspaceView.ts +++ b/src/workspaceView.ts @@ -36,6 +36,7 @@ import { boundedLineDiff } from "./conflictPresentation"; import { formatBytes, syncProblem, + syncReviewPresentation, type FileTransferProgress, type SyncActivityEntry, type SyncProblem, @@ -1660,23 +1661,14 @@ export class MdbaseWorkspaceView extends ItemView { const preview = actions.createEl("button", { text: this.mirrorPreview ? "Refresh review" : "Review changes" }); preview.disabled = this.busy; preview.onclick = () => void this.reviewSyncChanges(); - const plannedOutcomeCount = this.mirrorPreview?.plan.actions - .filter((action) => action.command !== "advance_checkpoint").length ?? 0; - const hasCheckpointAction = this.mirrorPreview?.plan.actions - .some((action) => action.command === "advance_checkpoint") ?? false; - const hasBlockingIssue = (this.mirrorPreview?.plan.summary.blocking_issues ?? 0) > 0; - const sync = actions.createEl("button", { - text: this.mirrorPreview - ? plannedOutcomeCount - ? `Sync ${plannedOutcomeCount} ${plannedOutcomeCount === 1 ? "outcome" : "outcomes"}` - : hasCheckpointAction - ? "Confirm sync checkpoint" - : "Already up to date" - : "Review before syncing", - }); + const syncPresentation = syncReviewPresentation( + this.mirrorPreview?.plan ?? null, + this.mirrorPreview?.entries.length ?? 0, + this.busy, + ); + const sync = actions.createEl("button", { text: syncPresentation.actionLabel }); sync.addClass("mod-cta"); - sync.disabled = this.busy || !this.mirrorPreview || hasBlockingIssue - || this.mirrorPreview.plan.actions.length === 0; + sync.disabled = syncPresentation.actionDisabled; sync.onclick = () => void this.perform(() => this.applyReviewedSync()); this.renderFilePolicyControls(document, { connected: true }); @@ -1696,9 +1688,10 @@ export class MdbaseWorkspaceView extends ItemView { this.mirrorStatus = await this.host.connectSync.status(); this.syncProblem = null; this.host.setSyncStatus(this.mirrorStatus); - this.transientMessage = this.mirrorPreview.entries.length - ? "Review each transfer below, then sync when ready." - : "This vault and the hosted collection are already aligned."; + this.transientMessage = syncReviewPresentation( + this.mirrorPreview.plan, + this.mirrorPreview.entries.length, + ).message; } private async applyReviewedSync(): Promise { @@ -2286,7 +2279,7 @@ export class MdbaseWorkspaceView extends ItemView { } else if (preview.local_issues.length) { section.createDiv({ cls: "mdbase-inline-message", - text: "Invalid local files stay untouched and unsynced; valid changes can continue.", + text: "Synchronization is paused until every invalid or unreadable local file listed here is fixed.", }); } } @@ -2460,7 +2453,7 @@ export class MdbaseWorkspaceView extends ItemView { const section = container.createEl("section", { cls: "mdbase-editor-section" }); section.createEl("h3", { text: "Local files needing attention" }); section.createEl("p", { - text: "These files remain untouched and unsynced. Other valid Markdown continues to synchronize.", + text: "Synchronization is paused to keep the mirror checkpoint exact. Fix every malformed or unreadable file below, then preview again.", }); for (const issue of status.local_issues) { const row = section.createDiv({ cls: "mdbase-conflict-row" }); diff --git a/test/binaryLimits.test.ts b/test/binaryLimits.test.ts new file mode 100644 index 0000000..af5731e --- /dev/null +++ b/test/binaryLimits.test.ts @@ -0,0 +1,39 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { TFile } from "obsidian"; +import { MAX_BINARY_FILE_BYTES, ObsidianMirrorFileSystem } from "../src/connectSync"; + +test("oversized local binaries are rejected before the Vault allocates their contents", async () => { + const file = new (TFile as unknown as { new(path: string): TFile })("large.mp4"); + file.stat.size = MAX_BINARY_FILE_BYTES + 1; + let reads = 0; + const adapter = new ObsidianMirrorFileSystem({ + getAbstractFileByPath: () => file, + readBinary: () => { reads++; throw new Error("must not read"); }, + } as never); + await assert.rejects(adapter.readBinary("large.mp4"), /32 MiB/); + await assert.rejects(adapter.inspectBinary("large.mp4"), /32 MiB/); + assert.equal(reads, 0); +}); + +test("oversized incoming streams never reach a Vault write", async () => { + const adapter = new ObsidianMirrorFileSystem({} as never); + await assert.rejects(adapter.writeBinary("large.mp4", (async function* () { + const chunk = new Uint8Array(1024 * 1024); + for (let i = 0; i < 33; i++) yield chunk; + })()), /32 MiB/); +}); + +test("unload during download prevents materialization after the stream completes", async () => { + let disposed = false; + let writes = 0; + const adapter = new ObsidianMirrorFileSystem({ + getAbstractFileByPath: () => null, + createBinary: () => { writes++; }, + } as never, undefined, () => { if (disposed) throw new Error("unloaded"); }); + await assert.rejects(adapter.writeBinary("image.png", (async function* () { + yield Uint8Array.of(1, 2, 3); + disposed = true; + })()), /unloaded/); + assert.equal(writes, 0); +}); diff --git a/test/connectSync.adoption.test.ts b/test/connectSync.adoption.test.ts index 157f975..aa59103 100644 --- a/test/connectSync.adoption.test.ts +++ b/test/connectSync.adoption.test.ts @@ -357,6 +357,50 @@ async function fixture(options: FakeAdoptionOptions = {}) { return { app, vault, settings, adoption, controller, collectionId }; } +test("restart completes cleanup after enrollment is saved but adoption marker removal fails", async () => { + const { app, vault, settings, controller } = await fixture(); + const remove = vault.adapter.remove; + vault.adapter.remove = async (path) => { + if (path === ".mdbase/authority-adoption.json") throw new Error("injected cleanup failure"); + await remove(path); + }; + await assert.rejects(controller.adoptLocalCollection({ controlUrl: "https://connect.example", mirrorName: "Obsidian" }, callbacks), /cleanup failure/); + assert.ok(settings.profile); + assert.equal(await vault.adapter.exists(".mdbase/authority-adoption.json"), true); + vault.adapter.remove = remove; + const restarted = new ConnectSyncController(app as never, settings, { adoptionBlobStoreFactory: () => new MemoryMirrorBlobStore() }); + await restarted.initialize(); + assert.equal(restarted.getAdoptionMarker(), null); + assert.equal(await vault.adapter.exists(".mdbase/authority-adoption.json"), false); + restarted.assertLocalAuthorityWritable(); +}); + +test("adoption restart does not erase a checkpoint belonging to another collection", async () => { + const { app, vault, settings, controller } = await fixture(); + const remove = vault.adapter.remove; + vault.adapter.remove = async (path) => { + if (path === ".mdbase/authority-adoption.json") throw new Error("injected cleanup failure"); + await remove(path); + }; + await assert.rejects(controller.adoptLocalCollection({ controlUrl: "https://connect.example", mirrorName: "Obsidian" }, callbacks)); + assert.ok(settings.profile); + settings.profile = { ...settings.profile, collectionId: randomUUID() }; + vault.adapter.remove = remove; + const restarted = new ConnectSyncController(app as never, settings); + await assert.rejects(restarted.initialize(), /both an authority-adoption checkpoint and a mirror profile/); + assert.equal(await vault.adapter.exists(".mdbase/authority-adoption.json"), true); +}); + +test("disposing during approval cancels adoption and prevents later activation", async () => { + const { controller, settings } = await fixture(); + await assert.rejects(controller.adoptLocalCollection({ controlUrl: "https://connect.example", mirrorName: "Obsidian" }, { + onVerification: () => controller.dispose(), + })); + assert.equal(settings.profile, null); + assert.throws(() => controller.assertLocalAuthorityWritable(), /unloaded/); + await assert.rejects(controller.preview(), /unloaded/); +}); + const callbacks = { onVerification: () => undefined, onStatus: () => undefined, diff --git a/test/indexedDb.test.ts b/test/indexedDb.test.ts new file mode 100644 index 0000000..e58c95a --- /dev/null +++ b/test/indexedDb.test.ts @@ -0,0 +1,78 @@ +import "fake-indexeddb/auto"; +import assert from "node:assert/strict"; +import test from "node:test"; +import { IndexedDbMirrorBlobStore, IndexedDbMirrorStateStore } from "../src/connectSync"; +import type { MirrorState } from "@mdbase-dev/connect-sync/mirror"; + +test("aborted IndexedDB writes reject without replacing the last durable checkpoint", async () => { + const key = crypto.randomUUID(); + const store = new IndexedDbMirrorStateStore(key); + const original = { replica_id: key, generation: 1 } as MirrorState; + await store.write(original); + const put = IDBObjectStore.prototype.put; + IDBObjectStore.prototype.put = function (...args: Parameters) { + const request = put.apply(this, args); + this.transaction.abort(); + return request; + }; + try { + await assert.rejects(store.write({ ...original, generation: 2 })); + } finally { + IDBObjectStore.prototype.put = put; + } + store.close(); + assert.deepEqual(await new IndexedDbMirrorStateStore(key).read(), original); +}); + +test("old binary-stage cleanup failure cannot corrupt a published replacement", async () => { + const store = new IndexedDbMirrorBlobStore(crypto.randomUUID()); + await store.write(digest, bytes()); + const remove = IDBObjectStore.prototype.delete; + IDBObjectStore.prototype.delete = function (key) { + const request = remove.call(this, key); + if (this.name === "chunks") this.transaction.abort(); + return request; + }; + try { + await store.write(digest, bytes()); + } finally { + IDBObjectStore.prototype.delete = remove; + } + const result = []; + for await (const chunk of store.read(digest)) result.push(...chunk); + assert.deepEqual(result, [0, 1, 255]); + await store.prune(new Set([digest])); + assert.equal(await store.has(digest), true); +}); + +const digest = `sha256:${"a".repeat(64)}` as const; +async function* bytes() { yield Uint8Array.of(0, 1, 255); } + +test("IndexedDB checkpoint survives adapter recreation and isolates replicas", async () => { + const key = crypto.randomUUID(); + const state = { replica_id: key, batch: { pending: true } } as unknown as MirrorState; + await new IndexedDbMirrorStateStore(key).write(state); + assert.deepEqual(await new IndexedDbMirrorStateStore(key).read(), state); + assert.equal(await new IndexedDbMirrorStateStore(`${key}-other`).read(), null); + await new IndexedDbMirrorStateStore(key).clear(); + assert.equal(await new IndexedDbMirrorStateStore(key).read(), null); +}); + +test("IndexedDB binary snapshot survives restart and an interrupted replacement", async () => { + const key = crypto.randomUUID(); + const store = new IndexedDbMirrorBlobStore(key); + await store.write(digest, bytes()); + await assert.rejects(store.write(digest, (async function* () { + yield Uint8Array.of(9); + throw new Error("interrupted source"); + })()), /interrupted/); + const restarted = new IndexedDbMirrorBlobStore(key); + const result = []; + for await (const chunk of restarted.read(digest)) result.push(...chunk); + assert.deepEqual(result, [0, 1, 255]); + assert.equal(await new IndexedDbMirrorBlobStore(`${key}-other`).has(digest), false); + await restarted.prune(new Set([digest])); + assert.equal(await restarted.has(digest), true); + await restarted.prune(new Set()); + assert.equal(await restarted.has(digest), false); +}); diff --git a/test/obsidian-mock.cjs b/test/obsidian-mock.cjs index 90dda82..77e8092 100644 --- a/test/obsidian-mock.cjs +++ b/test/obsidian-mock.cjs @@ -37,6 +37,7 @@ function getFrontMatterInfo(content) { class TFile { constructor(path) { this.path = normalizePath(path); + this.stat = { size: 0, mtime: 0, ctime: 0 }; const segments = this.path.split("/"); const filename = segments[segments.length - 1] || ""; const dotIndex = filename.lastIndexOf("."); diff --git a/test/quickFix.test.ts b/test/quickFix.test.ts new file mode 100644 index 0000000..68cc09f --- /dev/null +++ b/test/quickFix.test.ts @@ -0,0 +1,42 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { applyFieldQuickFix, applyQuickFixToDocument, quickFixLabel } from "../src/quickFix"; +import { parseFrontmatter } from "../src/mdbaseCore"; +import type { MdbaseIssue } from "../src/mdbaseCore"; + +function issue(code: string, pointer: string, property: string): MdbaseIssue { + return { path: "note.md", severity: "error", message: "invalid", code, field: "nested.field", details: { instance_path: pointer, property } }; +} + +test("repeated document fixes preserve body bytes including whitespace and missing final newline", () => { + for (const body of ["\nBody\n", "\n\n Body\r\n\r\n", "Body without final newline", ""]) { + const raw = `---\n${JSON.stringify({ address: { city: "Edinburgh", unexpected: 1 } })}\n---\n${body}`; + const first = applyQuickFixToDocument(raw, issue("schema_additional_properties", "/address", "unexpected")); + const second = applyQuickFixToDocument(first.content, issue("schema_required", "/address", "postcode")); + assert.equal(parseFrontmatter(first.content).body, body); + assert.equal(parseFrontmatter(second.content).body, body); + assert.equal(applyQuickFixToDocument(second.content, issue("schema_required", "/address", "postcode")).content, second.content); + } +}); + +test("nested removal preserves the parent and valid siblings", () => { + const value = { address: { city: "Edinburgh", unexpected: 1 }, title: "Keep" }; + assert.equal(applyFieldQuickFix(value, issue("schema_additional_properties", "/address", "unexpected")), true); + assert.deepEqual(value, { address: { city: "Edinburgh" }, title: "Keep" }); +}); + +test("required fixes reach list objects and decode JSON pointer keys without flattening", () => { + const value = { "a/b": [{ "c~d": {} }] }; + const error = issue("schema_required", "/a~1b/0/c~0d", "literal.dot"); + assert.equal(applyFieldQuickFix(value, error), true); + assert.deepEqual(value, { "a/b": [{ "c~d": { "literal.dot": "TODO" } }] }); + assert.equal(applyFieldQuickFix(value, error), false); +}); + +test("stale parents and prototype paths are not mutated", () => { + const value = {}; + assert.equal(applyFieldQuickFix(value, issue("schema_required", "/gone", "field")), false); + assert.equal(applyFieldQuickFix(value, issue("schema_required", "/__proto__", "polluted")), false); + assert.deepEqual(value, {}); + assert.equal(quickFixLabel({ ...issue("missing_required", "", "x"), field: "ambiguous.nested" }), null); +}); diff --git a/test/syncPreview.test.ts b/test/syncPreview.test.ts index 821b369..5c33eb8 100644 --- a/test/syncPreview.test.ts +++ b/test/syncPreview.test.ts @@ -120,6 +120,39 @@ test("plan conflicts and blocking issues are shown as attention without inventin assert.deepEqual(preview.collisions, ["notes/collision.md"]); }); +test("preview retains malformed-frontmatter and file-read local issues", () => { + const preview = previewFromPlan(plan({ + issues: [ + { + code: "invalid_frontmatter", + message: "Frontmatter is invalid YAML.", + path: "notes/malformed.md", + blocking: true, + }, + { + code: "file_read_failed", + message: "Could not read notes/unreadable.md.", + path: "notes/unreadable.md", + blocking: true, + }, + ], + summary: { uploads: 0, downloads: 0, conflicts: 0, blocking_issues: 2 }, + })); + + assert.deepEqual(preview.local_issues, [ + { + code: "invalid_frontmatter", + message: "Frontmatter is invalid YAML.", + path: "notes/malformed.md", + }, + { + code: "file_read_failed", + message: "Could not read notes/unreadable.md.", + path: "notes/unreadable.md", + }, + ]); +}); + test("resolved conflict cleanup is projected without inventing a transfer", () => { const exact = { state: "exact" as const, diff --git a/test/syncUx.test.ts b/test/syncUx.test.ts index a08442c..4225eca 100644 --- a/test/syncUx.test.ts +++ b/test/syncUx.test.ts @@ -1,11 +1,12 @@ import * as assert from "node:assert/strict"; import { test } from "node:test"; -import type { MirrorStatus } from "@mdbase-dev/connect-sync/mirror"; +import type { MirrorStatus, MirrorSyncPlan } from "@mdbase-dev/connect-sync/mirror"; import { appendActivity, normalizeActivity, syncIndicator, syncProblem, + syncReviewPresentation, type SyncActivityEntry, } from "../src/syncUx"; @@ -23,6 +24,46 @@ function status(overrides: Partial = {}): MirrorStatus { }; } +function plan(overrides: Partial = {}): MirrorSyncPlan { + return { + plan_version: 1, + engine_profile: "exact_document_plan_only_v1", + protocol_profile: "exact_document_v1", + planner_policy: "three_way_exact_document_v1", + projection_policy: "portable_mirror_projection_v1", + fingerprint: `sha256:${"0".repeat(64)}`, + replica_id: "replica", + mode: "read_write", + kind: "incremental", + base_cursor: 1, + authority_cursor: 1, + scope_epoch: 1, + checkpoint_generation: 1, + selective_sync: { file_classes: [], excluded_folders: [] }, + actions: [], + issues: [], + summary: { uploads: 0, downloads: 0, conflicts: 0, blocking_issues: 0 }, + ...overrides, + }; +} + +test("blocking sync reviews use fix-first wording and disable apply", () => { + const presentation = syncReviewPresentation(plan({ + issues: [{ + code: "file_read_failed", + message: "Could not read broken.md.", + path: "broken.md", + blocking: true, + }], + summary: { uploads: 0, downloads: 0, conflicts: 0, blocking_issues: 1 }, + }), 1); + + assert.equal(presentation.actionLabel, "Fix local files before syncing"); + assert.equal(presentation.actionDisabled, true); + assert.match(presentation.message, /paused.*fix every listed local file/i); + assert.doesNotMatch(`${presentation.actionLabel} ${presentation.message}`, /up to date|sync when ready/i); +}); + test("sync indicator gives transfer, attention, waiting, and synced states stable priority", () => { const base = { connected: true, status: status(), progress: null, fileProgress: null, problem: null, validationIssues: 0, localChangeObserved: false }; assert.equal(syncIndicator(base).state, "synced"); diff --git a/test/v3-foundations.test.ts b/test/v3-foundations.test.ts index af91773..ed35ea8 100644 --- a/test/v3-foundations.test.ts +++ b/test/v3-foundations.test.ts @@ -1,9 +1,10 @@ +import "fake-indexeddb/auto"; import * as assert from "node:assert/strict"; 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-dev/connect-sync"; +import { MemoryAuthority, SyncError } from "@mdbase-dev/connect-sync"; import type { SyncTransport } from "@mdbase-dev/connect-sync"; import type { CollectionFileDescriptor } from "@mdbase-dev/connect-protocol"; import { @@ -16,6 +17,7 @@ import { import { ConnectSyncController, DeviceMirrorLease, + IndexedDbMirrorStateStore, ObsidianMirrorFileSystem, } from "../src/connectSync"; import { MirrorEnrollmentClient } from "@mdbase-dev/connect-sync/enrollment"; @@ -84,6 +86,7 @@ class MemoryVault { readonly folders = new Map(); failTargetPath: string | null = null; failCreatePath: string | null = null; + failReadPath: string | null = null; corruptTargetPath: string | null = null; targetWrites = 0; @@ -97,6 +100,15 @@ class MemoryVault { if (!entry) throw new Error(`missing ${path}`); return entry.content; }, + readBinary: async (path: string): Promise => { + const normalized = normalizePath(path); + if (normalized === this.failReadPath) throw new Error(`unreadable ${path}`); + const text = this.files.get(normalized); + if (text) return new TextEncoder().encode(text.content).buffer; + const binary = this.binaryFiles.get(normalized); + if (binary) return binary.content.slice(0); + throw new Error(`missing ${path}`); + }, write: async (path: string, content: string): Promise => { const normalized = normalizePath(path); const existing = this.files.get(normalized)?.file ?? new TestFile(normalized); @@ -132,7 +144,10 @@ class MemoryVault { } getMarkdownFiles(): TFile[] { - return [...this.files.values()].map((entry) => entry.file).filter((file) => file.extension === "md"); + return [ + ...[...this.files.values()].map((entry) => entry.file), + ...[...this.binaryFiles.values()].map((entry) => entry.file), + ].filter((file) => file.extension === "md"); } getFiles(): TFile[] { @@ -642,6 +657,33 @@ test("Obsidian mirror adapter rejects traversal and reserved paths", async () => assert.equal(await fs.read("notes/ok.md"), null); }); +test("Obsidian mirror adapter classifies text bytes, missing files, and read failures", async () => { + const vault = new MemoryVault(); + const fs = new ObsidianMirrorFileSystem(vault as never); + await vault.create("notes/valid.md", "---\ntitle: Café\n---\n"); + assert.equal(await fs.readText("notes/valid.md"), "---\ntitle: Café\n---\n"); + assert.equal(await fs.readText("notes/missing.md"), null); + + const invalidBytes = Uint8Array.of(0x66, 0x80, 0x6f); + await vault.createBinary("notes/invalid.md", invalidBytes.buffer); + assert.deepEqual(await fs.readText("notes/invalid.md"), { + kind: "invalid", + code: "invalid_utf8", + reason: "File is not valid UTF-8.", + revision: `sha256:${createHash("sha256").update(invalidBytes).digest("hex")}`, + }); + await assert.rejects( + fs.read("notes/invalid.md"), + (error: unknown) => error instanceof SyncError && error.code === "invalid_utf8", + ); + + vault.failReadPath = "notes/valid.md"; + await assert.rejects( + fs.readText("notes/valid.md"), + (error: unknown) => error instanceof SyncError && error.code === "file_read_failed", + ); +}); + 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"; @@ -876,6 +918,77 @@ test("device lease rejects concurrent mirror ownership and releases after failur await lease.runExclusive(async () => undefined); }); +test("beta.91 fences invalid or unreadable local Markdown and every valid sibling until repair", async () => { + const invalidCases: Array<[string, string | Uint8Array]> = [ + ["broken.md", "---\nbroken: [\n---\nBody"], + ["duplicate.md", "---\na: 1\na: 2\n---\nBody"], + ["scalar.md", "---\nhello\n---\nBody"], + ["null.md", "---\nnull\n---\nBody"], + ["list.md", "---\n- one\n- two\n---\nBody"], + ["bytes.md", Uint8Array.of(0x62, 0x61, 0x64, 0xff)], + ]; + for (const [path, invalid] of invalidCases) { + const hosted = new MemoryAuthority(); + const replica = hosted.registerReplica({ name: "Obsidian writer", mode: "read_write" }); + const vault = new MemoryVault(); + if (typeof invalid === "string") await vault.create(path, invalid); + else await vault.createBinary(path, Uint8Array.from(invalid).buffer); + await vault.create("valid.md", "# Valid sibling"); + const mirror = new WritableDirectoryMirror(replica, hosted.transport(replica), { + fileSystem: new ObsidianMirrorFileSystem(vault as never), + stateStore: new MemoryMirrorStateStore(), + }); + + const blocked = await mirror.inspect(); + assert.deepEqual(blocked.actions, []); + assert.ok(blocked.issues.some((issue) => + issue.code === "invalid_frontmatter" && issue.path === path && issue.blocking)); + assert.deepEqual((await mirror.status()).local_issues.map((issue) => [issue.code, issue.path]), [ + ["invalid_frontmatter", path], + ]); + let snapshot = await hosted.transport(replica).snapshot((await hosted.transport(replica).openSession()).snapshot_id); + assert.deepEqual(snapshot.records, []); + + const invalidFile = vault.getAbstractFileByPath(path); + assert.ok(invalidFile instanceof TFile); + if (typeof invalid === "string") await vault.modify(invalidFile, "# Fixed local note"); + else { + await vault.delete(invalidFile); + await vault.create(path, "# Fixed local note"); + } + await mirror.sync(); + snapshot = await hosted.transport(replica).snapshot((await hosted.transport(replica).openSession()).snapshot_id); + assert.deepEqual(snapshot.records.map((record) => record.path).sort(), [path, "valid.md"].sort()); + await mirror.sync(); + assert.deepEqual((await mirror.status()).local_issues, []); + } + + const hosted = new MemoryAuthority(); + const replica = hosted.registerReplica({ name: "Unreadable Obsidian writer", mode: "read_write" }); + const vault = new MemoryVault(); + await vault.create("unreadable.md", "# Cannot read this now"); + await vault.create("valid.md", "# Also fenced"); + vault.failReadPath = "unreadable.md"; + const mirror = new WritableDirectoryMirror(replica, hosted.transport(replica), { + fileSystem: new ObsidianMirrorFileSystem(vault as never), + stateStore: new MemoryMirrorStateStore(), + }); + const blocked = await mirror.inspect(); + assert.deepEqual(blocked.actions, []); + assert.ok(blocked.issues.some((issue) => + issue.code === "file_read_failed" && issue.path === "unreadable.md" && issue.blocking)); + assert.deepEqual((await mirror.status()).local_issues.map((issue) => [issue.code, issue.path]), [ + ["file_read_failed", "unreadable.md"], + ]); + + vault.failReadPath = null; + await mirror.sync(); + const snapshot = await hosted.transport(replica).snapshot((await hosted.transport(replica).openSession()).snapshot_id); + assert.deepEqual(snapshot.records.map((record) => record.path).sort(), ["unreadable.md", "valid.md"]); + await mirror.sync(); + assert.deepEqual((await mirror.status()).local_issues, []); +}); + test("portable mirror materializes resources and records through Obsidian Vault APIs", async () => { const configuration = "spec_version: 0.3.0\n"; const noteType = "---\nkind: mdbase.type\n---\n"; @@ -1290,7 +1403,7 @@ test("writable mirror uploads local edits and collision preflight makes no write assert.equal(await collisionState.read(), null); }); -test("interrupted mirror write does not advance the checkpoint and a retry converges", async () => { +test("interrupted mirror write resumes its IndexedDB checkpoint after adapter recreation", async () => { const hosted = new MemoryAuthority({ snapshotPageSize: 1 }); hosted.seed([ { @@ -1311,7 +1424,7 @@ test("interrupted mirror write does not advance the checkpoint and a retry conve const replica = hosted.registerReplica({ name: "Fault injection", mode: "read_only" }); const vault = new MemoryVault(); vault.failCreatePath = "notes/two.md"; - const state = new MemoryMirrorStateStore(); + const state = new IndexedDbMirrorStateStore(replica); const mirror = new DirectoryMirror(replica, hosted.transport(replica), { fileSystem: new ObsidianMirrorFileSystem(vault as never), stateStore: state, @@ -1324,9 +1437,14 @@ test("interrupted mirror write does not advance the checkpoint and a retry conve assert.equal(recovery?.batch?.phase, "blocked"); assert.equal(recovery?.batch?.next_action, 1); vault.failCreatePath = null; - const applied = await mirror.sync(); + state.close(); + const restarted = new DirectoryMirror(replica, hosted.transport(replica), { + fileSystem: new ObsidianMirrorFileSystem(vault as never), + stateStore: new IndexedDbMirrorStateStore(replica), + }); + const applied = await restarted.sync(); assert.equal(applied.status, "applied", JSON.stringify(applied)); - assert.equal((await mirror.status()).state, "up_to_date"); + assert.equal((await restarted.status()).state, "up_to_date"); assert.equal(vault.getMarkdownFiles().length, 2); });