@mdbase-dev/sdk 0.2.66 → 0.2.68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- "use strict";var MdbaseSDK=(()=>{var qg=Object.defineProperty;var rq=Object.getOwnPropertyDescriptor;var oq=Object.getOwnPropertyNames;var sq=Object.prototype.hasOwnProperty;var I=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(i){throw t=[i],i}};var Ca=(n,e)=>{for(var t in e)qg(n,t,{get:e[t],enumerable:!0})},aq=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of oq(e))!sq.call(n,o)&&o!==t&&qg(n,o,{get:()=>e[o],enumerable:!(i=rq(e,o))||i.enumerable});return n};var lq=n=>aq(qg({},"__esModule",{value:!0}),n);function vo(n){return Object.prototype.hasOwnProperty.call(vu,n)}function cq(n){return vo(n)?vu[n]:"contact_support"}function A(n,e,t={}){let i=typeof t=="string"?{reason:t}:t;return new oe({code:n,recovery:vu[n],message:e,...i})}function X(n,e){return n instanceof oe&&(e===void 0||n.code===e)}var vu,oe,re=I(()=>{"use strict";vu={invalid_request:"fix_request",invalid_record:"fix_request",not_found:"refresh",conflict:"resolve_conflict",unauthenticated:"reauthorize",forbidden:"reauthorize",collection_invalid:"repair_collection",unavailable:"retry",rate_limited:"retry",quota_exceeded:"free_space",too_large:"fix_request",upgrade_required:"upgrade",outcome_unknown:"resolve_outcome",cancelled:"none",internal:"contact_support"};oe=class extends Error{code;recovery;reason;details;retryAfterMs;issues;traceId;mutationId;constructor(e,t={}){super(e.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="MdbaseError",this.code=vo(e.code)?e.code:"internal",this.recovery=vo(e.code)?e.recovery:"contact_support",e.reason!==void 0&&(this.reason=e.reason),e.details!==void 0&&(this.details=e.details),e.retryAfterMs!==void 0&&(this.retryAfterMs=e.retryAfterMs),e.issues!==void 0&&(this.issues=e.issues),e.traceId!==void 0&&(this.traceId=e.traceId),t.mutationId!==void 0&&(this.mutationId=t.mutationId)}toProblem(){let e={code:this.code,recovery:this.recovery,message:this.message};return this.reason!==void 0&&(e.reason=this.reason),this.details!==void 0&&(e.details=this.details),this.retryAfterMs!==void 0&&(e.retryAfterMs=this.retryAfterMs),this.issues!==void 0&&(e.issues=this.issues),this.traceId!==void 0&&(e.traceId=this.traceId),e}}});function hq(n){let e=n.isWellFormed;if(e)return e.call(n);for(let t=0;t<n.length;t++){let i=n.charCodeAt(t);if(i>=55296&&i<=56319){let o=n.charCodeAt(t+1);if(!(o>=56320&&o<=57343))return!1;t++}else if(i>=56320&&i<=57343)return!1}return!0}function tk(n,e){let t=typeof e=="bigint"?e:BigInt(e);if(t>=0n){if(t>pq)throw new Me("unencodable","integer above 2^64-1");n.head(0,typeof e=="number"?e:t)}else{if(t<dq)throw new Me("unencodable","integer below -2^63");let i=-1n-t;n.head(1,i<=BigInt(Number.MAX_SAFE_INTEGER)?Number(i):i)}}function mq(n,e,t){let i=[...e.entries()];ik(i.map(([o])=>o)),n.head(5,i.length);for(let[o,s]of i)typeof o=="number"?n.head(0,o):nk(n,o),Au(n,s,t+1)}function nk(n,e){if(e.length<24&&!/[^\x00-\x7f]/u.test(e))return n.shortAscii(e);if(!hq(e))throw new Me("utf8","text is not well-formed UTF-16");let t=uq.encode(e);try{n.head(3,t.length),n.bytes(t)}finally{n.wipeTemporary(t)}}function ik(n){if(n.length===0)return;if(typeof n[0]=="string"){let t=new Set;for(let i of n){if(typeof i!="string")throw new Me("mixed_map_keys");if(t.has(i))throw new Me("duplicate_key",`duplicate data map key ${JSON.stringify(i)}`);t.add(i)}return}let e;for(let t of n){if(typeof t=="string")throw new Me("mixed_map_keys");if(typeof t=="number"&&!(Number.isSafeInteger(t)&&t>=0))throw new Me("mixed_map_keys","struct map keys must be unsigned integers");let i=BigInt(t);if(i<0n)throw new Me("mixed_map_keys");if(e!==void 0&&e>=i)throw new Me("unsorted_keys");e=i}}function Au(n,e,t){if(t>Mg)throw new Me("too_deep");if(e===null)return n.byte(246);switch(typeof e){case"boolean":return n.byte(e?245:244);case"number":return Number.isSafeInteger(e)&&!Object.is(e,-0)?tk(n,e):n.float(e);case"bigint":return tk(n,e);case"string":return nk(n,e)}if(e instanceof vt)return n.float(e.value);if(e instanceof Uint8Array)return n.head(2,e.length),n.bytes(e);if(Array.isArray(e)){n.head(4,e.length);for(let i of e)Au(n,i,t+1);return}if(e instanceof Map)return mq(n,e,t);throw new Me("unencodable",`cannot encode ${Object.prototype.toString.call(e)}`)}function fe(n){let e=new _u;return Au(e,n,0),e.result()}function zn(n){let e=new _u(!0);try{return Au(e,n,0),e.result()}finally{e.buf.fill(0)}}function we(n){let e=new Tg(n),t=e.item(0);if(e.remaining!==0)throw new Me("trailing_bytes");return t}function yq(n){try{return we(n),!0}catch{return!1}}function Lg(n){let e=new Map;for(let[t,i]of n)i!==void 0&&e.set(t,i);return e}function ut(n){let e="";for(let t of n)e+=gq[t];return e}function Br(n){if(n.length%2!==0||!/^[0-9a-fA-F]*$/.test(n))throw new Error("invalid hex");let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function jg(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!==e[t])return!1;return!0}var vt,Mg,Me,pq,dq,uq,fq,_u,Tg,gq,Je=I(()=>{"use strict";vt=class{constructor(e){this.value=e}value;valueOf(){return this.value}toJSON(){return this.value}},Mg=128,Me=class extends Error{constructor(t,i){super(i??t);this.kind=t;this.name="CborError"}kind},pq=(1n<<64n)-1n,dq=-(1n<<63n),uq=new TextEncoder,fq=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),_u=class{constructor(e=!1){this.sensitive=e}sensitive;buf=new Uint8Array(256);len=0;view=new DataView(this.buf.buffer);ensure(e){if(this.len+e<=this.buf.length)return;let t=this.buf.length*2;for(;t<this.len+e;)t*=2;let i=new Uint8Array(t);i.set(this.buf.subarray(0,this.len)),this.sensitive&&this.buf.fill(0),this.buf=i,this.view=new DataView(i.buffer)}byte(e){this.ensure(1),this.buf[this.len++]=e}bytes(e){this.ensure(e.length),this.buf.set(e,this.len),this.len+=e.length}shortAscii(e){this.ensure(1+e.length),this.buf[this.len++]=96|e.length;for(let t=0;t<e.length;t++)this.buf[this.len++]=e.charCodeAt(t)}head(e,t){let i=e<<5;if(typeof t=="number"&&t<24)this.byte(i|t);else if(typeof t=="number"&&t<=255)this.ensure(2),this.buf[this.len++]=i|24,this.buf[this.len++]=t;else if(typeof t=="number"&&t<=65535)this.ensure(3),this.buf[this.len++]=i|25,this.view.setUint16(this.len,t),this.len+=2;else if(typeof t=="number"&&t<=4294967295)this.ensure(5),this.buf[this.len++]=i|26,this.view.setUint32(this.len,t),this.len+=4;else{let o=BigInt(t);if(o<=0xffffffffn)return this.head(e,Number(o));this.ensure(9),this.buf[this.len++]=i|27,this.view.setBigUint64(this.len,o),this.len+=8}}float(e){if(!Number.isFinite(e))throw new Me("float","float must be finite");this.ensure(9),this.buf[this.len++]=251,this.view.setFloat64(this.len,e),this.len+=8}wipeTemporary(e){this.sensitive&&e.fill(0)}result(){return this.buf.slice(0,this.len)}};Tg=class{constructor(e){this.buf=e;this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}buf;pos=0;view;get remaining(){return this.buf.length-this.pos}need(e){if(e>this.remaining)throw new Me("unexpected_end")}byte(){return this.need(1),this.buf[this.pos++]}take(e){this.need(e);let t=this.buf.subarray(this.pos,this.pos+e);return this.pos+=e,t}arg(e){if(e<24)return e;switch(e){case 24:{let t=this.byte();if(t<24)throw new Me("non_canonical_head");return t}case 25:{this.need(2);let t=this.view.getUint16(this.pos);if(this.pos+=2,t<=255)throw new Me("non_canonical_head");return t}case 26:{this.need(4);let t=this.view.getUint32(this.pos);if(this.pos+=4,t<=65535)throw new Me("non_canonical_head");return t}case 27:{this.need(8);let t=this.view.getBigUint64(this.pos);if(this.pos+=8,t<=0xffffffffn)throw new Me("non_canonical_head");return t<=BigInt(Number.MAX_SAFE_INTEGER)?Number(t):t}case 31:throw new Me("indefinite");default:throw new Me("non_canonical_head","reserved additional info")}}len(e){let t=this.arg(e);if(typeof t=="bigint")throw new Me("too_long");if(t>this.remaining)throw new Me("unexpected_end");return t}item(e){if(e>Mg)throw new Me("too_deep");let t=this.byte(),i=t>>5,o=t&31;switch(i){case 0:return this.arg(o);case 1:{let s=this.arg(o);if(typeof s=="number"){let r=-1-s;return Number.isSafeInteger(r)?r:-1n-BigInt(s)}return-1n-s}case 2:return this.take(this.len(o)).slice();case 3:{let s=this.take(this.len(o));try{return fq.decode(s)}catch{throw new Me("utf8")}}case 4:{let s=this.len(o),r=new Array(s);for(let a=0;a<s;a++)r[a]=this.item(e+1);return r}case 5:{let s=this.len(o),r=[],a=[];for(let l=0;l<s;l++){let p=this.item(e+1);if(typeof p!="string"&&typeof p!="number"&&typeof p!="bigint")throw new Me("mixed_map_keys");if((typeof p=="number"||typeof p=="bigint")&&p<0)throw new Me("mixed_map_keys");r.push(p),a.push(this.item(e+1))}ik(r);let c=new Map;for(let l=0;l<s;l++){let p=r[l];if(typeof p=="bigint")throw new Me("too_long","struct key beyond 2^53");c.set(p,a[l])}return c}case 6:throw new Me("tag");default:switch(o){case 20:return!1;case 21:return!0;case 22:return null;case 27:{this.need(8);let s=this.view.getFloat64(this.pos);if(this.pos+=8,!Number.isFinite(s))throw new Me("float");return Number.isInteger(s)?new vt(s):s}case 25:case 26:throw new Me("float","float must be binary64");case 31:throw new Me("indefinite");default:throw new Me("simple")}}}};gq=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"))});function ei(n){return n===null||typeof n=="boolean"||typeof n=="number"||typeof n=="string"?n:typeof n=="bigint"?n.toString():n instanceof vt?n.value:n instanceof Uint8Array?ut(n):Array.isArray(n)?n.map(ei):Object.fromEntries([...n].map(([e,t])=>[String(e),ei(t)]))}function de(n,e){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.hasOwn(n,e)?n[e]:void 0}function Fe(n){if(n==null)return null;if(typeof n!="object"||n instanceof vt)return n;if(Array.isArray(n))return n.map(Fe);if(n instanceof Map){let t=new Map;for(let[i,o]of n)t.set(i,Fe(o));return t}if(n instanceof Date)return n.toISOString();let e=new Map;for(let[t,i]of Object.entries(n))i!==void 0&&e.set(t,Fe(i));return e}var un=I(()=>{"use strict";Je()});function _o(n,e){let t=Fc;Fc=!0;try{return n.dec(e)}finally{Fc=t}}function ku(n){return{name:n.name,enc:()=>{throw new ae(n.name,"an answer is decoded, never encoded")},dec:e=>_o(n,e)}}function bq(n){return n===null?"null":n instanceof Uint8Array?"bytes":n instanceof vt?"float":Array.isArray(n)?"array":n instanceof Map?"map":typeof n=="number"?Number.isInteger(n)?"int":"float":typeof n}function $n(n,e,t){return new ae(n,`expected ${e}, found ${bq(t)}`)}function ok(n,e){return{name:e,enc:t=>{if(!(t instanceof Uint8Array)||t.length!==n)throw new ae(e,`must be ${n} bytes`);return t},dec:t=>{if(!(t instanceof Uint8Array))throw $n(e,"bytes",t);if(t.length!==n)throw new ae(e,`must be ${n} bytes`);return t}}}function N(n){if(!wq.test(n))throw new ae("uuid",`not a UUID: ${n}`);return Br(n.replace(/-/g,""))}function Wc(n){let e=ut(n);return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20,32)}`}function Su(n){let e=/^sha256:([0-9a-f]{64})$/.exec(n);if(!e)throw new ae("hash",`not a sha256: revision token: ${n}`);return Br(e[1])}function Ug(n){return`sha256:${ut(n)}`}function Kc(n,e=0){if(e>128)throw new ae("value","nesting too deep");if(n instanceof Uint8Array)throw new ae("value","byte strings are not values");if(typeof n=="bigint"){if(n>0x7fffffffffffffffn||n<-0x8000000000000000n)throw new ae("value","integer outside int64");return}if(Array.isArray(n))for(let t of n)Kc(t,e+1);else if(n instanceof Map)for(let[t,i]of n){if(typeof t!="string")throw new ae("value","map keys must be text");Kc(i,e+1)}}function G(n,e={}){let t=`[${n.name}]`;return{name:t,enc:i=>{if(e.nonEmpty&&i.length===0)throw new ae(t,"list must not be empty");return i.map(o=>n.enc(o))},dec:i=>{if(!Array.isArray(i))throw $n(t,"array",i);if(e.nonEmpty&&i.length===0)throw new ae(t,"list must not be empty");return i.map(o=>n.dec(o))}}}function Hc(n){let e=`{tstr => ${n.name}}`;return{name:e,enc:t=>{let i=new Map;for(let[o,s]of t)i.set(o,n.enc(s));return i},dec:t=>{if(!(t instanceof Map))throw $n(e,"map",t);let i=new Map;for(let[o,s]of t){if(typeof o!="string")throw new ae(e,"data map keys must be text");i.set(o,n.dec(s))}return Fc?Object.fromEntries(i):i}}}function xu(n,e,t,i,o){return{name:n,enc:s=>t(s)?e.enc(s):o.enc(s),dec:s=>i(s)?e.dec(s):o.dec(s)}}function Se(n,e,t=0){let i=new Map(e.map((o,s)=>[o,s+t]));return{name:n,values:e,enc:o=>{let s=i.get(o);if(s===void 0)throw new ae(n,`unknown value ${JSON.stringify(o)}`);return s},dec:o=>{if(typeof o=="bigint")throw new ae(n,`unknown variant ${o}`,!0);if(typeof o!="number"||!Number.isInteger(o)||o<0)throw $n(n,"uint enum",o);let s=o>=t?e[o-t]:void 0;if(s===void 0)throw new ae(n,`unknown variant ${o}`,!0);return s}}}function z(n,e){for(let t=1;t<e.length;t++)if(e[t][0]<=e[t-1][0])throw new Error(`${n}: field keys must ascend`);return{name:n,enc:t=>{let i=new Map,o=t;for(let[s,r,a,c="req"]of e){let l=o[r];if(l===void 0){if(c==="req"||c==="req1")throw new ae(n,`missing required field ${r}`);continue}if((c==="req1"||c==="opt1")&&Array.isArray(l)&&l.length===0)throw new ae(n,`${r} must not be empty`);i.set(s,a.enc(l))}return i},dec:t=>{if(!(t instanceof Map))throw $n(n,"struct map",t);let i=t;for(let s of i.keys())if(typeof s!="number")throw $n(n,"struct map",t);let o={};for(let[s,r,a,c="req"]of e){let l=i.get(s);if(l===void 0){if(c==="req"||c==="req1")throw new ae(n,`missing required key ${s} (${r})`);continue}let p=a.dec(l);if((c==="req1"||c==="opt1")&&Array.isArray(p)&&p.length===0)throw new ae(n,`${r} must not be empty`);o[r]=p}return o}}}function Gc(n,e){let t=new Map,i=new Map;for(let[o,s,r]of e){let a=z(`${n}.${s}`,r);t.set(o,[s,a]),i.set(s,[o,a])}return{name:n,enc:o=>{let s=i.get(o.kind);if(!s)throw new ae(n,`unknown kind ${JSON.stringify(o.kind)}`);let r=s[1].enc(o);return new Map([[0,s[0]],...r])},dec:o=>{if(!(o instanceof Map))throw $n(n,"struct map",o);let s=o.get(0);if(s===void 0)throw new ae(n,"missing discriminator");if(typeof s=="bigint")throw new ae(n,`unknown variant ${s}`,!0);if(typeof s!="number")throw $n(n,"uint discriminator",s);let r=t.get(s);if(!r)throw new ae(n,`unknown variant ${s}`,!0);return{kind:r[0],...r[1].dec(o)}}}}function Ng(n,e,t,i){return{name:n,enc:o=>e.enc(i(o)),dec:o=>t(e.dec(o))}}function Dg(n,e){return{name:n,enc:t=>e.map((i,o)=>i.enc(t[o])),dec:t=>{if(!Array.isArray(t))throw $n(n,"array",t);if(t.length!==e.length)throw new ae(n,"wrong number of elements");return e.map((i,o)=>i.dec(t[o]))}}}var ae,Fc,F,An,T,Ee,rk,bs,pr,wq,M,Z,Pu,Ht,Ia,ve=I(()=>{"use strict";Je();un();ae=class extends Error{constructor(t,i,o=!1){super(`${t}: ${i}`);this.ty=t;this.unknown=o;this.name="SchemaError"}ty;unknown},Fc=!1;F={name:"uint",enc:n=>{if(!Number.isSafeInteger(n)||n<0)throw new ae("uint",`not an unsigned integer: ${n}`);return n},dec:n=>{if(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)return n;throw typeof n=="bigint"&&n>=0n?new ae("uint","value beyond 2^53 is not supported here"):$n("uint","uint",n)}},An={name:"int",enc:n=>{if(!Number.isSafeInteger(n))throw new ae("int",`not an integer: ${n}`);return n},dec:n=>{if(typeof n=="number"&&Number.isInteger(n))return n;throw $n("int","int",n)}},T={name:"tstr",enc:n=>{if(typeof n!="string")throw new ae("tstr","not a string");return n},dec:n=>{if(typeof n=="string")return n;throw $n("tstr","text",n)}},Ee={name:"bool",enc:n=>n,dec:n=>{if(typeof n=="boolean")return n;throw $n("bool","bool",n)}},rk={name:"bstr",enc:n=>n,dec:n=>{if(n instanceof Uint8Array)return n;throw $n("bstr","bytes",n)}};bs=ok(16,"b16"),pr=ok(32,"b32"),wq=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;M={name:"uuid",enc:n=>N(n),dec:n=>Wc(bs.dec(n))};Z={name:"hash",enc:n=>Su(n),dec:n=>Ug(pr.dec(n))},Pu={name:"any",enc:n=>n,dec:n=>n},Ht={name:"value",enc:n=>(Kc(n),n),dec:n=>(Kc(n),Fc?ei(n):n)},Ia={name:"value",enc:n=>Ht.enc(Fe(n)),dec:n=>(Kc(n),ei(n))}});function lk(n,e,t){if(!Array.isArray(n)||n.length!==e)throw new ae(t,`must have exactly ${e} elements`);if(F.dec(n[0])!==1)throw new ae(t,"unknown version",!0);return n}var Cu,sk,ak,Ao,zg=I(()=>{"use strict";ve();Cu={name:"attachment-uint64",enc:n=>{if(typeof n=="number")return F.enc(n);if(typeof n!="bigint"||n<0n||n>0xffffffffffffffffn)throw new ae("attachment-uint64","outside uint64");return n},dec:n=>{if(typeof n=="number")return F.dec(n);if(typeof n!="bigint"||n<0n||n>0xffffffffffffffffn)throw new ae("attachment-uint64","outside uint64");return n<=BigInt(Number.MAX_SAFE_INTEGER)?Number(n):n}},sk=8388608;ak={name:"attachment-ref-v1",enc:n=>[1,M.enc(n.collection),Cu.enc(n.keyEpoch),pr.enc(n.attachmentId),sk,Z.enc(n.manifestCipherHash)],dec:n=>{let e=lk(n,6,"attachment-ref-v1");if(F.dec(e[4])!==sk)throw new ae("attachment-ref-v1","unknown chunk profile",!0);return{collection:M.dec(e[1]),keyEpoch:Cu.dec(e[2]),attachmentId:pr.dec(e[3]),manifestCipherHash:Z.dec(e[5])}}},Ao={name:"attachment-content-v1",enc:n=>[1,ak.enc(n.reference),Z.enc(n.wholePlainHash),Cu.enc(n.totalPlainBytes)],dec:n=>{let e=lk(n,4,"attachment-content-v1");return{reference:ak.dec(e[1]),wholePlainHash:Z.dec(e[2]),totalPlainBytes:Cu.dec(e[3])}}}});function ck(n){return n.content.form==="blob"?n.content.blob.size:n.content.content.totalPlainBytes}function vq(n){return n.kind==="ordinary_attachment_continuation"||n.kind==="file_attach"||n.kind==="unindexed_markdown_put"||n.kind==="record_to_unindexed_markdown"||n.kind==="unindexed_markdown_to_record"||n.kind==="ordinary_file_to_record"}function uk(n,e){return{name:n,enc:t=>e().enc(t),dec:t=>e().dec(t)}}var Ou,Iu,pk,dk,Ru,m4,fk=I(()=>{"use strict";ve();en();zg();Ou={name:"file-content",enc:n=>n.form==="blob"?Vr.enc(n.blob):Ao.enc(n.content),dec:n=>Array.isArray(n)?{form:"attachment",content:Ao.dec(n)}:{form:"blob",blob:Vr.dec(n)}};Iu={name:"unindexed-markdown-payload-v1",enc:n=>{if(ck(n)<=1048576)throw new ae("unindexed-markdown-payload-v1","declared size must exceed record cap");return[2,1,1,Ou.enc(n.content)]},dec:n=>{let e="unindexed-markdown-payload-v1";if(!Array.isArray(n)||n.length!==4)throw new ae(e,"must have exactly four elements");if(F.dec(n[0])!==2||F.dec(n[1])!==1||F.dec(n[2])!==1)throw new ae(e,"unknown discriminator/profile/kind",!0);let t={content:Ou.dec(n[3])};if(ck(t)<=1048576)throw new ae(e,"declared size must exceed record cap");return t}},pk=xu("text",T,n=>typeof n=="string",n=>typeof n=="string",F),dk=Gc("extended-runtime-op",[[13,"file_attach",[[1,"id",M],[2,"path",T],[3,"content",Ao],[4,"ifRevision",Z,"opt"],[5,"base",Z,"opt"]]],[14,"unindexed_markdown_put",[[1,"id",M],[2,"path",T],[3,"payload",Iu],[4,"expected",Iu,"opt"]]],[15,"record_to_unindexed_markdown",[[1,"id",M],[2,"path",T],[3,"payload",Iu],[4,"priorRevision",Z]]],[16,"unindexed_markdown_to_record",[[1,"id",M],[2,"path",T],[3,"doc",pk],[4,"prior",Iu]]],[18,"ordinary_attachment_continuation",[[1,"id",M],[2,"path",T],[3,"content",Ao],[4,"prior",Ou]]],[17,"ordinary_file_to_record",[[1,"id",M],[2,"path",T],[3,"doc",pk],[4,"prior",Ou]]]]);Ru={name:"runtime-v1-op",enc:n=>vq(n)?dk.enc(n):Oa.enc(n),dec:n=>{let e=n instanceof Map?F.dec(n.get(0)):void 0;return e!==void 0&&e>=13&&e<=18?dk.dec(n):Oa.dec(n)}};m4=z("runtime-v1-mutation",[[0,"id",M],[1,"origin",M],[2,"baseSeq",F],[3,"clock",uk("op-clock",()=>ws)],[4,"seed",pr],[5,"source",Se("source",["api","external"])],[6,"ops",G(Ru,{nonEmpty:!0}),"req1"],[7,"onBehalf",M,"opt"],[8,"conflictMode",uk("conflict-mode",()=>Yc),"opt"],[9,"validatedAt",Se("level",["off","warn","error"]),"opt"],[10,"room",z("room-checkpoint",[[0,"stream",bs],[1,"state",Z]]),"opt"]])});var _b={};Ca(_b,{DESCRIBE_TYPING_MAX_PATHS:()=>tp,DESCRIBE_TYPING_MAX_TYPES:()=>ep,HOLD_REASONS:()=>Sk,HOLD_RESOLUTIONS:()=>Pk,INCIDENT_KINDS:()=>vk,MEDIA_CLASSES:()=>Ok,PUSH_CODECS:()=>kq,RECOVERY:()=>yk,ROLES:()=>bk,TEMPORAL_HINTS:()=>Ku,TRANSFER_PHASES:()=>Lk,appliedPrefix:()=>Hg,appliedPrefixParams:()=>Wg,authorRef:()=>Mu,b16:()=>bs,b32:()=>pr,backlinksResult:()=>mb,baseField:()=>Nu,blobRef:()=>Vr,bodyEdit:()=>nb,change:()=>Ik,changesResult:()=>vs,clientFrame:()=>Kr,confirmedHead:()=>ju,conflict:()=>ob,conflictEntry:()=>Zc,conflictMode:()=>Yc,conflictValue:()=>qu,describeResult:()=>bb,describeTypingResult:()=>vb,docVersion:()=>Bg,executeViewParams:()=>Rq,fenceApply:()=>db,fenceReport:()=>ub,fenceResult:()=>fb,fileChunk:()=>Du,fileInclusion:()=>ib,fileStreamFailure:()=>zu,fileView:()=>Qc,fmMap:()=>kn,grantInfo:()=>Kg,helloParams:()=>Fg,helloResult:()=>Gg,hold:()=>Jc,holdReason:()=>Yg,holdRef:()=>Jg,holdResolution:()=>Xg,incident:()=>_k,include:()=>Ra,issue:()=>Fr,linkResolution:()=>Zg,linkView:()=>Qg,listFilesResult:()=>ab,listPendingResult:()=>wb,listResourcesResult:()=>hb,listViewsResult:()=>xq,materialization:()=>Bu,mediaClass:()=>Ea,mutation:()=>Sq,newTypeFile:()=>gb,op:()=>Oa,opClock:()=>ws,openUploadParams:()=>lb,openUploadResult:()=>cb,peer:()=>jk,preflight:()=>qk,presencePush:()=>Vu,problem:()=>ti,progress:()=>Ak,publishState:()=>Ek,queryGroup:()=>tb,queryMetadata:()=>Ck,queryParams:()=>Oq,queryResult:()=>Xc,queryUpdate:()=>Uu,receipt:()=>Sn,recordState:()=>xk,recordView:()=>ko,recovery:()=>gk,resolveLinksResult:()=>yb,resourceView:()=>Fu,resyncing:()=>kk,role:()=>wk,severity:()=>Lu,submitParams:()=>rb,submitResult:()=>sb,syncStatus:()=>Wr,target:()=>Vg,temporalHint:()=>Uk,textOrBlob:()=>Eu,transferProgress:()=>$u,typingEntry:()=>Nk,uploadChunkParams:()=>pb,version:()=>Tu,viewRef:()=>eb,viewSourceDocument:()=>Cq});function Mk(n){throw new ae(n,"wrong type")}var Tu,yk,gk,Lu,Fr,ti,Kr,Fg,bk,wk,Kg,vk,_k,Ak,kk,ju,Wg,Hg,Wr,Gg,Vr,Eu,Sk,Yg,Jg,Jc,Pk,Xg,xk,Zg,Qg,Mu,kn,ko,Ra,eb,tb,Ck,Xc,Uu,Ik,vs,Ok,Ea,Yc,Nu,nb,Bg,ib,hk,mk,_q,Oa,Rk,rb,Aq,qu,ob,Ek,qk,Sn,sb,Zc,Tk,$g,Qc,ab,lb,cb,pb,Du,zu,Lk,$u,Bu,jk,Vu,db,ub,fb,kq,ws,Sq,Pq,Fu,hb,mb,yb,xq,Cq,gb,bb,Iq,wb,Vg,Oq,Rq,Ku,Uk,Nk,vb,ep,tp,en=I(()=>{"use strict";fk();zg();ve();Tu=Ng("version",Dg("version",[F,F]),([n,e])=>({major:n,minor:e}),n=>[n.major,n.minor]),yk=["fix_request","refresh","resolve_conflict","reauthorize","repair_collection","retry","free_space","upgrade","resolve_outcome","none","contact_support"],gk=Se("recovery",yk),Lu=Se("severity",["warning","error"]),Fr=z("issue",[[0,"code",T],[1,"severity",Lu],[2,"message",T],[3,"details",Ia,"opt"]]),ti=z("problem",[[0,"code",T],[1,"recovery",gk],[2,"message",T],[3,"reason",T,"opt"],[4,"details",Ia,"opt"],[5,"retryAfterMs",F,"opt"],[6,"issues",G(Fr),"opt"],[7,"traceId",T,"opt"]]),Kr=Gc("client-frame",[[0,"request",[[1,"id",F],[2,"method",T],[3,"params",Pu]]],[1,"response",[[1,"id",F],[2,"result",Pu,"opt"],[3,"problem",ti,"opt"]]],[2,"push",[[1,"type",T],[2,"payload",Pu]]]]),Fg=z("hello-params",[[0,"versions",G(Tu,{nonEmpty:!0}),"req1"],[1,"clientName",T],[2,"clientVersion",T],[3,"features",G(T),"opt"],[4,"timezone",T,"opt"]]),bk=["viewer","editor","owner"],wk=Se("role",bk),Kg=z("grant-info",[[0,"grant",M,"opt"],[1,"capabilities",G(T,{nonEmpty:!0}),"req1"],[2,"role",wk],[3,"account",M,"opt"],[4,"fileFolders",G(T),"opt"]]),vk=["upgrade_required","waiting_for_key","integrity","access_revoked","quota_exceeded","read_only","verification_mismatch","voided_items","key_inconsistent","foreign_sync_tool","gone","lost_entries","log_regressed"],_k=z("incident",[[0,"kind",Se("incident-kind",vk)],[1,"details",Ia,"opt"]]),Ak=z("progress",[[0,"done",F],[1,"total",F]]),kk=z("resyncing",[[0,"phase",Se("resync-phase",["probing","repairing","rolling_back","awaiting_control"])],[1,"positions",F]]),ju=z("confirmed-head",[[0,"seq",F],[1,"chain",Z],[2,"policyGeneration",Z],[3,"catalogGeneration",Z]]),Wg=z("applied-prefix-params",[[0,"seq",F]]),Hg=z("applied-prefix",[[0,"appliedThrough",F],[1,"seq",F],[2,"chain",Z,"opt"]]),Wr=z("sync-status",[[0,"mode",Se("sync-mode",["local_only","synced"])],[1,"confirmedThrough",F],[2,"headKnown",F],[3,"pending",F],[4,"oldestPending",An,"opt"],[5,"holds",F],[6,"unresolved",F],[7,"connection",Se("connection",["online","connecting","offline"])],[8,"installing",Ak,"opt"],[9,"incidents",G(_k)],[10,"resyncing",kk,"opt"],[11,"confirmedHead",ju,"opt"],[12,"grant",Kg,"opt"]]),Gg=z("hello-result",[[0,"version",Tu],[1,"runtimeVersion",T],[2,"sem",Tu],[3,"collection",M],[4,"grant",Kg],[5,"status",Wr],[6,"features",G(T)],[7,"headWitness",rk,"opt"]]),Vr=z("blob-ref",[[0,"plainHash",Z],[1,"size",F],[2,"blobId",pr],[3,"idEpoch",F],[4,"partSize",F]]),Eu={name:"text-or-blob",enc:n=>{if(typeof n=="string")return T.enc(n);if("form"in n){if(n.form!=="attachment")throw new ae("text-or-blob","unknown arm",!0);return[1,Ao.enc(n.content)]}return Vr.enc(n)},dec:n=>{if(typeof n=="string")return T.dec(n);if(Array.isArray(n)){if(n.length!==2)throw new ae("text-or-blob","attachment arm must have exactly two elements");if(F.dec(n[0])!==1)throw new ae("text-or-blob","unknown attachment arm",!0);return{form:"attachment",content:Ao.dec(n[1])}}return Vr.dec(n)}},Sk=["conflict","unknown_provenance","deleted_elsewhere","read_only","editor_busy","suspect_write"],Yg=Se("hold-reason",Sk),Jg=z("hold-ref",[[0,"id",M],[1,"reason",Yg]]),Jc=z("hold",[[0,"id",M],[1,"path",T],[2,"reason",Yg],[3,"since",An],[4,"base",Eu,"opt"],[5,"mine",Eu],[6,"theirs",Eu,"opt"],[7,"saves",F]]),Pk=["keep_mine","take_theirs","use","delete","keep_both"],Xg=Se("hold-resolution",Pk),xk=z("record-state",[[0,"state",Se("confirmation",["confirmed","pending"])],[1,"confirmedSeq",F],[2,"hold",Jg,"opt"],[3,"unresolved",F,"opt"]]),Zg=z("link-resolution",[[0,"kind",Se("link-kind",["record","file","ambiguous","not_found","invalid"])],[1,"target",M,"opt"],[2,"path",T,"opt"],[3,"candidates",G(T,{nonEmpty:!0}),"opt"]]),Qg=z("link-view",[[0,"raw",T],[1,"embed",Ee],[2,"resolution",Zg],[3,"field",T,"opt"]]),Mu=z("author-ref",[[0,"account",M],[1,"device",M],[2,"grant",M,"opt"],[3,"grantAccount",M,"opt"]]),kn=Hc(Ht),ko=z("record-view",[[0,"id",M],[1,"path",T],[2,"revision",Z],[3,"frontmatter",kn],[4,"effective",kn,"opt"],[5,"body",T,"opt"],[6,"document",T,"opt"],[7,"types",G(T)],[8,"state",xk],[9,"diagnostics",G(Fr),"opt"],[10,"values",kn,"opt"],[11,"mtime",An,"opt"],[12,"links",G(Qg),"opt"],[13,"createdBy",Mu,"opt"],[14,"modifiedBy",Mu,"opt"]]),Ra=z("include",[[0,"effective",Ee,"opt"],[1,"body",Ee,"opt"],[2,"document",Ee,"opt"],[3,"diagnostics",Ee,"opt"],[4,"links",Ee,"opt"]]),eb=z("view-ref",[[0,"path",T],[1,"view",T]]),tb=z("query-group",[[0,"values",kn],[1,"count",F],[2,"summaries",kn,"opt"]]),Ck=z("query-metadata",[[0,"columns",G(T),"opt"],[1,"totalCount",F,"opt"],[2,"diagnostics",G(Fr),"opt"],[3,"view",eb,"opt"],[4,"groups",G(tb),"opt"],[5,"hasMore",Ee,"opt"]]),Xc=z("query-result",[[0,"records",G(ko)],[1,"cursor",T,"opt"],[2,"complete",Ee],[3,"asOf",F],[4,"columns",G(T),"opt"],[5,"totalCount",F,"opt"],[6,"diagnostics",G(Fr),"opt"],[7,"view",eb,"opt"],[8,"groups",G(tb),"opt"],[9,"hasMore",Ee,"opt"]]),Uu=z("query-update",[[0,"sub",F],[1,"kind",Se("update-kind",["snapshot","diff","reset"])],[2,"added",G(ko),"opt"],[3,"changed",G(ko),"opt"],[4,"removed",G(M),"opt"],[5,"order",G(M),"opt"],[6,"complete",Ee],[7,"asOf",F],[8,"metadata",Ck,"opt"]]),Ik=z("change",[[0,"id",M],[1,"path",T],[2,"kind",Se("change-kind",["put","remove"])],[3,"version",F],[4,"author",Mu,"opt"],[5,"entity",Se("change-entity",["record","file"]),"opt"],[6,"types",G(T),"opt"]]),vs=z("changes-result",[[0,"changes",G(Ik)],[1,"cursor",T],[2,"reset",Ee]]),Ok=["image","audio","video","pdf","other"],Ea=Se("media-class",Ok),Yc=Se("conflict-mode",["record","reject"]),Nu={name:"base-field",enc:n=>n.observed===void 0?[n.key]:[n.key,Ht.enc(n.observed)],dec:n=>{if(!Array.isArray(n)||n.length<1||n.length>2)throw new ae("base-field","must have 1 or 2 elements");return n.length===1?{key:T.dec(n[0])}:{key:T.dec(n[0]),observed:Ht.dec(n[1])}}},nb=Dg("body-edit",[F,F,T]),Bg=z("doc-version",[[0,"path",T],[1,"doc",T]]),ib=z("file-inclusion",[[0,"include",G(Ea)],[1,"exclude",G(T),"opt"],[2,"maxSize",F,"opt"]]),hk=Hc(G(Ht)),mk=[[1,"id",M],[2,"patch",kn,"opt"],[3,"unset",G(T),"opt1"],[4,"add",hk,"opt"],[5,"remove",hk,"opt"],[6,"body",T,"opt"],[7,"bodyEdits",G(nb),"opt1"],[8,"bodyBase",Z,"opt"],[9,"bodyBaseText",T,"opt"],[10,"base",G(Nu),"opt1"],[11,"ifRevision",Z,"opt"],[12,"updateRefs",Ee,"opt"]],_q=Gc("op",[[1,"create",[[1,"id",M],[2,"path",T,"opt"],[3,"type",T,"opt"],[4,"frontmatter",kn,"opt"],[5,"body",T,"opt"],[6,"document",T,"opt"]]],[2,"update",mk],[19,"update_live",mk],[3,"document",[[1,"id",M],[2,"base",Bg,"opt"],[3,"new",Bg,"opt"],[4,"ifRevision",Z,"opt"]]],[4,"delete",[[1,"id",M],[2,"baseRevision",Z,"opt"],[3,"ifRevision",Z,"opt"]]],[5,"rename",[[1,"id",M],[2,"from",T],[3,"to",T],[4,"updateRefs",Ee],[5,"ifRevision",Z,"opt"]]],[6,"resource_put",[[1,"path",T],[2,"doc",T],[3,"baseRevision",Z,"opt"],[4,"mustNotExist",Ee,"opt"]]],[7,"resource_delete",[[1,"path",T],[2,"baseRevision",Z,"opt"]]],[8,"file_put",[[1,"id",M],[2,"path",T],[3,"blob",Vr],[4,"ifRevision",Z,"opt"],[5,"base",Z,"opt"]]],[9,"file_delete",[[1,"id",M],[2,"ifRevision",Z,"opt"],[3,"base",Z,"opt"]]],[10,"file_move",[[1,"id",M],[2,"from",T],[3,"to",T],[4,"updateRefs",Ee],[5,"ifRevision",Z,"opt"]]],[11,"conflict_dismiss",[[1,"mutation",M],[2,"record",M]]],[12,"sync_settings",[[1,"inclusion",ib]]]]),Oa=Ng("op",_q,n=>n.kind==="update_live"?{...n,kind:"update",requireLive:!0}:n,n=>n.kind==="update"&&n.requireLive?{...n,kind:"update_live"}:n),Rk=Se("level",["off","warn","error"]),rb=z("submit-params",[[0,"ops",G(Oa,{nonEmpty:!0}),"req1"],[1,"mutationId",M,"opt"],[2,"conflictMode",Yc,"opt"],[3,"timezone",T,"opt"],[4,"allowPartial",Ee,"opt"],[5,"mutationIds",G(M),"opt1"],[6,"dryRun",Ee,"opt"],[7,"include",Ra,"opt"],[8,"wait",Se("wait-for",["pending","confirmed","published"]),"opt"],[9,"validation",Rk,"opt"]]),Aq=["missing","value","text","blob","deleted"],qu={name:"conflict-value",enc:n=>{switch(n.form){case"missing":return[0];case"value":return[1,Ht.enc(n.value)];case"text":return[2,n.text];case"blob":return[3,Vr.enc(n.blob)];case"deleted":return[4]}},dec:n=>{if(!Array.isArray(n)||n.length===0)throw new ae("conflict-value","malformed conflict value");let e=n[0];if(typeof e!="number")throw new ae("conflict-value","malformed conflict value");if(e>4)throw new ae("conflict-value",`unknown variant ${e}`,!0);let t=Aq[e];if(t==="missing"||t==="deleted"){if(n.length!==1)throw new ae("conflict-value","malformed conflict value");return{form:t}}if(n.length!==2)throw new ae("conflict-value","malformed conflict value");return t==="value"?{form:t,value:Ht.dec(n[1])}:t==="text"?{form:t,text:T.dec(n[1])}:{form:t,blob:Vr.dec(n[1])}}},ob=z("conflict",[[0,"kind",Se("conflict-kind",["field","frontmatter","body","path","delete","file"],1)],[1,"id",M],[2,"field",T,"opt"],[3,"base",qu,"opt"],[4,"kept",qu],[5,"lost",qu]]),Ek=Se("publish-state",["publishing","published","not_published"]),qk=z("preflight",[[0,"rewrites",G(z("link-rewrite",[[0,"record",M],[1,"path",T],[2,"from",T],[3,"to",T],[4,"field",T,"opt"]]))],[1,"broken",G(z("broken-link",[[0,"record",M],[1,"path",T],[2,"raw",T],[3,"target",M],[4,"field",T,"opt"]]))]]),Sn=z("receipt",[[0,"mutation",M],[1,"state",Se("receipt-state",["pending","confirmed","rejected","unknown"])],[2,"seq",F,"opt"],[3,"status",Se("status",["applied","merged","conflicted"]),"opt"],[4,"conflicts",G(ob),"opt1"],[5,"records",G(ko),"opt"],[6,"problem",ti,"opt"],[7,"published",Ek,"opt"],[8,"preflight",qk,"opt"],[9,"relocatedFrom",F,"opt"]]),sb=G(Sn,{nonEmpty:!0}),Zc=z("conflict-entry",[[0,"mutation",M],[1,"seq",F],[2,"conflict",ob]]),Tk=Se("file-content-profile",["ordinary_blob","ordinary_attachment_v1","unindexed_markdown_blob","unindexed_markdown_attachment_v1"]),$g=z("file-view",[[0,"id",M],[1,"path",T],[2,"size",F],[3,"digest",Z],[4,"media",Ea],[5,"state",Se("file-state",["materialized","remote","fetching","pending_upload"])],[6,"confirmedSeq",F],[7,"hold",Jg,"opt"],[8,"mtime",An,"opt"],[9,"mediaType",T,"opt"],[10,"contentProfile",Tk,"opt"]]),Qc={...$g,dec(n){let e=n instanceof Map?n:void 0;if(e?.has(10))try{Tk.dec(e.get(10))}catch(t){if(!(t instanceof ae)||!t.unknown)throw t;let i=new Map(e);return i.delete(10),$g.dec(i)}return $g.dec(n)}},ab=z("list-files-result",[[0,"files",G(Qc)],[1,"cursor",T,"opt"],[2,"complete",Ee]]),lb=z("open-upload-params",[[0,"transfer",M],[1,"path",T],[2,"size",F],[3,"digest",Z,"opt"],[4,"fileId",M,"opt"],[5,"ifRevision",Z,"opt"],[6,"mutationId",M,"opt"]]),cb=z("open-upload-result",[[0,"transfer",M],[1,"chunkSize",F],[2,"received",G(F)],[3,"expiresAt",An],[4,"fileId",M,"opt"]]),pb=z("upload-chunk-params",[[0,"transfer",M],[1,"index",F],[2,"bytes",{name:"bstr",enc:n=>n,dec:n=>n instanceof Uint8Array?n:Mk("bstr")}]]);Du=z("file-chunk",[[0,"stream",F],[1,"offset",F],[2,"bytes",{name:"bstr",enc:n=>n,dec:n=>n instanceof Uint8Array?n:Mk("bstr")}],[3,"last",Ee]]),zu=z("file-stream-failure",[[0,"stream",F],[1,"problem",ti]]),Lk=["receiving","sealing","uploading","appending","confirmed","fetching","streaming","done"],$u=z("transfer-progress",[[0,"id",xu("transfer-id",M,n=>typeof n=="string",n=>n instanceof Uint8Array,F)],[1,"phase",Se("phase",Lk)],[2,"done",F],[3,"total",F]]),Bu=z("materialization",[[0,"mode",Se("materialize-mode",["all","on_demand"])],[1,"pinned",G(T),"opt"],[2,"media",G(Ea),"opt"],[3,"maxSize",F,"opt"]]),jk=z("peer",[[0,"session",bs],[1,"account",M,"opt"],[2,"app",T,"opt"],[3,"state",Ht],[4,"lastSeen",An]]),Vu=z("presence",[[0,"record",M],[1,"peers",G(jk)]]),db=z("fence-apply",[[0,"path",T],[1,"base",Z],[2,"edits",G(nb,{nonEmpty:!0}),"req1"],[3,"expected",Z]]),ub=z("fence-report",[[0,"open",G(z("fence-open",[[0,"path",T],[1,"dirty",Ee],[2,"buffer",Z]]))]]),fb=z("fence-result",[[0,"outcome",Se("fence-outcome",["applied","not_open","buffer_changed"])],[1,"buffer",T,"opt"]]),kq={query_update:Uu,receipt:Sn,status:Wr,holds:G(Jc),conflicts:G(Zc),presence:Vu,file_chunk:Du,file_stream_failed:zu,transfer_progress:$u,changes:vs},ws=z("op-clock",[[0,"instant",An],[1,"tz",T],[2,"localDate",T]]),Sq=z("mutation",[[0,"id",M],[1,"origin",M],[2,"baseSeq",F],[3,"clock",ws],[4,"seed",pr],[5,"source",Se("source",["api","external"])],[6,"ops",G(Oa,{nonEmpty:!0}),"req1"],[7,"onBehalf",M,"opt"],[8,"conflictMode",Yc,"opt"],[9,"validatedAt",Rk,"opt"],[10,"room",z("room-checkpoint",[[0,"stream",bs],[1,"state",Z]]),"opt"]]),Pq=Se("confirmation",["confirmed","pending"]),Fu=z("resource-view",[[0,"path",T],[1,"revision",Z],[2,"size",F],[3,"state",Pq],[4,"text",T,"opt"]]),hb=z("list-resources-result",[[0,"resources",G(Fu)],[1,"complete",Ee],[2,"cursor",T,"opt"]]),mb=z("backlinks-result",[[0,"backlinks",G(z("backlink",[[0,"record",ko],[1,"links",G(Qg,{nonEmpty:!0}),"req1"]]))],[1,"cursor",T,"opt"],[2,"complete",Ee],[3,"asOf",F]]),yb=z("resolve-links-result",[[0,"resolutions",G(Zg)],[1,"asOf",F],[2,"complete",Ee]]),xq=z("list-views-result",[[0,"sources",G(z("view-source",[[0,"record",M],[1,"id",T],[2,"name",T],[3,"source",z("view-source-ref",[[0,"path",T],[1,"format",T],[2,"revision",Z],[3,"writable",Ee]])],[4,"views",G(z("view-descriptor",[[0,"id",T],[1,"name",T],[2,"properties",G(z("view-property",[[0,"key",T],[1,"label",T,"opt"],[2,"description",T,"opt"],[3,"format",T,"opt"],[4,"hidden",Ee,"opt"]]))],[3,"presentation",Ht,"opt"]]))]]))],[1,"diagnostics",G(Fr)],[2,"complete",Ee]]),Cq=z("view-source-document",[[0,"path",T],[1,"format",T],[2,"revision",Z],[3,"document",T],[4,"record",M]]),gb=z("new-type-file",[[0,"name",T],[1,"path",T]]),bb=z("describe-result",[[0,"specVersion",T],[1,"types",G(z("type-summary",[[0,"name",T],[1,"path",T],[2,"implements",G(z("implementation",[[0,"contract",T],[1,"version",T],[2,"fields",Hc(T)],[3,"binding",Ht,"opt"],[4,"digest",Z,"opt"]]))],[3,"version",An,"opt"],[4,"revision",Z,"opt"],[5,"definition",Ht,"opt"],[6,"schema",Ht,"opt"]]))],[2,"settings",Ht],[3,"inclusion",ib],[4,"issues",G(Fr)],[5,"contracts",G(z("contract-summary",[[0,"id",T],[1,"version",T],[2,"path",T],[3,"digest",Z],[4,"contractType",T],[5,"implementedBy",G(T)],[6,"schemas",Hc(Ht),"opt"]]))]]),Iq={name:"pending-runtime-op",enc:n=>Ru.enc(n),dec:n=>Ru.dec(n)},wb=z("list-pending-result",[[0,"pending",G(z("pending-mutation",[[0,"receipt",Sn],[1,"captured",An],[2,"ops",G(Iq,{nonEmpty:!0}),"req1"]]))],[1,"next",M,"opt"]]),Vg={name:"target",enc:n=>typeof n=="string"?M.enc(n):n.path,dec:n=>typeof n=="string"?{path:n}:M.dec(n)},Oq=z("query-params",[[0,"query",Ht],[1,"include",Ra,"opt"],[2,"contract",T,"opt"]]),Rq=z("execute-view-params",[[0,"source",Vg],[1,"view",T],[2,"context",Vg,"opt"],[3,"limit",F,"opt"],[4,"offset",F,"opt"],[5,"timezone",T,"opt"],[6,"include",Ra,"opt"]]),Ku=["none","date","date_time"],Uk=Se("temporal-hint",Ku),Nk=z("typing-entry",[[0,"path",T],[1,"hint",Uk]]),vb=z("describe-typing-result",[[0,"catalogGeneration",F],[1,"fields",G(Nk)]]),ep=64,tp=256});function So(n){typeof performance<"u"&&performance.mark(n)}var Wu=I(()=>{"use strict"});function Eq(n,e=!1){return e?{h:Number(n&Hu),l:Number(n>>Dk&Hu)}:{h:Number(n>>Dk&Hu)|0,l:Number(n&Hu)|0}}function zk(n,e=!1){let t=n.length,i=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:r,l:a}=Eq(n[s],e);[i[s],o[s]]=[r,a]}return[i,o]}function $k(n,e,t,i){let o=Ab(t),s=kb(t);n.setUint32(e,i?s:o,i),n.setUint32(e+4,i?o:s,i)}function ni(n,e,t,i){let o=(e>>>0)+(i>>>0);return{h:n+t+(o/2**32|0)|0,l:o|0}}var Hu,Dk,Ab,kb,Sb,Pb,dr,ur,_s,As,Bk,Vk,np,ip,Fk,Kk,Wk,Hk,Gu=I(()=>{Hu=BigInt(4294967295),Dk=BigInt(32);Ab=n=>n/2**32|0,kb=n=>n>>>0;Sb=(n,e,t)=>n>>>t,Pb=(n,e,t)=>n<<32-t|e>>>t,dr=(n,e,t)=>n>>>t|e<<32-t,ur=(n,e,t)=>n<<32-t|e>>>t,_s=(n,e,t)=>n<<64-t|e>>>t-32,As=(n,e,t)=>n>>>t-32|e<<64-t,Bk=(n,e)=>e,Vk=(n,e)=>n;np=(n,e,t)=>(n>>>0)+(e>>>0)+(t>>>0),ip=(n,e,t,i)=>e+t+i+(n/2**32|0)|0,Fk=(n,e,t,i)=>(n>>>0)+(e>>>0)+(t>>>0)+(i>>>0),Kk=(n,e,t,i,o)=>e+t+i+o+(n/2**32|0)|0,Wk=(n,e,t,i,o)=>(n>>>0)+(e>>>0)+(t>>>0)+(i>>>0)+(o>>>0),Hk=(n,e,t,i,o,s)=>e+t+i+o+s+(n/2**32|0)|0});function Yu(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}function Pn(n,e=""){if(typeof n!="number")throw new TypeError(xb(e)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(xb(e)+"expected integer >= 0, got "+n);return n}function ft(n,e,t=""){if(Yu(n)&&(e===void 0||n.length===e))return n;e!==void 0&&Pn(e,"length");let i=Yu(n),o=e!==void 0?` of length ${e}`:"",s=i?`length=${n.length}`:`type=${typeof n}`,r=xb(t)+"expected Uint8Array"+o+", got "+s;throw i?new RangeError(r):new TypeError(r)}function Cb(n){return Uint8Array.from(ft(n))}function rp(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Pn(n.outputLen),Pn(n.blockLen),n.outputLen<1||n.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}function Hr(n,e=!0){if(n.destroyed)throw new Error("hash was destroyed");if(e&&n.finished)throw new Error("digest() was already called")}function qa(n,e){ft(n,void 0,"output");let t=e.outputLen;if(!(n.length>=t))throw new RangeError('"output" expected length >= '+t)}function op(n){return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function Po(n){return new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4))}function at(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function Ju(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Ui(n,e){return n<<32-e|n>>>e}function Zk(n){return n<<24&4278190080|n<<8&16711680|n>>>8&65280|n>>>24&255}function Tq(n){for(let e=0;e<n.length;e++)n[e]=Zk(n[e]);return n}function Ta(n){if(ft(n),Qk)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=Mq[n[t]];return e}function Jk(n){return n>=48&&n<=57?n-48:n>=65&&n<=70?n-55:n>=97&&n<=102?n-87:void 0}function Xu(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);if(Qk)try{return Uint8Array.fromHex(n)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=n.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let i=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let r=Jk(n.charCodeAt(s)),a=Jk(n.charCodeAt(s+1));if(r===void 0||a===void 0){let c=n[s]+n[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}i[o]=r*16+a}return i}function eS(n){let e=globalThis;if(typeof e.scheduler?.yield=="function"){let t=e.scheduler.yield();return n&&t.catch(n),t}return new Promise(t=>e.setTimeout(t,0))}function Ib(n){if(typeof n!="string")throw new TypeError("string expected");let e=new TextEncoder().encode(n);try{return new Uint8Array(e)}finally{at(e)}}function Zu(n,e=""){return typeof n=="string"?Ib(n):ft(n,void 0,e)}function Ob(...n){let e=0;for(let i=0;i<n.length;i++){let o=n[i];ft(o),e+=o.length}let t=new Uint8Array(e);for(let i=0,o=0;i<n.length;i++){let s=n[i];t.set(s,o),o+=s.length}return t}function sp(n,e,t="opts"){return Yk(n,"defaults"),e!==void 0&&Yk(e,t),Object.assign(Object.create(null),n,e)}function ap(n,e={}){if(typeof n!="function")throw new TypeError('"hashCons" expected function, got type='+typeof n);e=sp({},e,"info");let t=(o,s)=>n(s).update(o).digest(),i=n(void 0);return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.canXOF=i.canXOF,t.create=o=>n(o),Object.assign(t,e),Object.freeze(t)}function tS(n=32){Pn(n,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(n>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${n}`);return e.getRandomValues(new Uint8Array(n))}var xb,qq,Yk,Xk,tn,Ni,Qk,Mq,Rb,fr=I(()=>{xb=n=>n?`"${n}" `:"";qq=(n,e)=>{if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof n)},Yk=(n,e)=>{qq(n,e);let t=Object.getPrototypeOf(n);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(n,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};Xk=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;tn=Xk?n=>n:n=>Zk(n)>>>0;Ni=Xk?n=>n:Tq,Qk=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Mq=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));Rb=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])})});function nS(n,e,t){return n&e^~n&t}function iS(n,e,t){return n&e^n&t^e&t}var lp,rS,oS,sS=I(()=>{Gu();fr();lp=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,i,o){this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Ju(this.buffer)}update(e){Hr(this),ft(e);let{view:t,buffer:i,blockLen:o}=this,s=e.length,r=!1;for(let a=0;a<s;){let c=Math.min(o-this.pos,s-a);if(c===o){let l=Ju(e);for(;o<=s-a;a+=o)this.process(l,a);r=!0;continue}i.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(t,0),this.pos=0,r=!0)}return this.length+=e.length,r&&this.roundClean(),this}digestInto(e){Hr(this),qa(e,this),this.finished=!0;let{buffer:t,view:i,blockLen:o,isLE:s}=this,{pos:r}=this;t[r++]=128,t.fill(0,r),this.padOffset>o-r&&(this.process(i,0),t.fill(0)),$k(i,o-8,this.length*8,s),this.process(i,0),this.roundClean();let a=e===t?i:Ju(e),c=this.outputLen,l=c/4,p=this.get();if(c%4||l>p.length)throw new Error("invalid outputLen");for(let d=0;d<l;d++)a.setUint32(4*d,p[d],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let i=e.slice(0,t);return this.destroy(),i}_cloneIntoMeta(e){let{buffer:t,length:i,finished:o,destroyed:s,pos:r}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=r,r&&e.buffer.set(t),e}clone(){return this._cloneInto()}},rS=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),oS=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});var Lq,xo,Eb,qb,aS,jq,Uq,Co,Io,Tb,Mb,Ze,Lb,hr=I(()=>{sS();Gu();fr();Lq=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),xo=new Uint32Array(64),Eb=class extends lp{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:i,D:o,E:s,F:r,G:a,H:c}=this;return[e,t,i,o,s,r,a,c]}set(e,t,i,o,s,r,a,c){this.A=e|0,this.B=t|0,this.C=i|0,this.D=o|0,this.E=s|0,this.F=r|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)xo[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let u=xo[d-15],f=xo[d-2],h=Ui(u,7)^Ui(u,18)^u>>>3,m=Ui(f,17)^Ui(f,19)^f>>>10;xo[d]=m+xo[d-7]+h+xo[d-16]|0}let{A:i,B:o,C:s,D:r,E:a,F:c,G:l,H:p}=this;for(let d=0;d<64;d++){let u=Ui(a,6)^Ui(a,11)^Ui(a,25),f=p+u+nS(a,c,l)+Lq[d]+xo[d]|0,m=(Ui(i,2)^Ui(i,13)^Ui(i,22))+iS(i,o,s)|0;p=l,l=c,c=a,a=r+f|0,r=s,s=o,o=i,i=f+m|0}i=i+this.A|0,o=o+this.B|0,s=s+this.C|0,r=r+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,p=p+this.H|0,this.set(i,o,s,r,a,c,l,p)}roundClean(){at(xo)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),at(this.buffer)}},qb=class extends Eb{constructor(){super(32,rS)}},aS=zk(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(n=>BigInt(n))),jq=aS[0],Uq=aS[1],Co=new Uint32Array(80),Io=new Uint32Array(80),Tb=class extends lp{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:i,Bl:o,Ch:s,Cl:r,Dh:a,Dl:c,Eh:l,El:p,Fh:d,Fl:u,Gh:f,Gl:h,Hh:m,Hl:w}=this;return[e,t,i,o,s,r,a,c,l,p,d,u,f,h,m,w]}set(e,t,i,o,s,r,a,c,l,p,d,u,f,h,m,w){this.Ah=e|0,this.Al=t|0,this.Bh=i|0,this.Bl=o|0,this.Ch=s|0,this.Cl=r|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=p|0,this.Fh=d|0,this.Fl=u|0,this.Gh=f|0,this.Gl=h|0,this.Hh=m|0,this.Hl=w|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let y=0;y<16;y++,t+=4)Co[y]=e.getUint32(t),Io[y]=e.getUint32(t+=4);for(let y=16;y<80;y++){let _=Co[y-15]|0,v=Io[y-15]|0,k=dr(_,v,1)^dr(_,v,8)^Sb(_,v,7),S=ur(_,v,1)^ur(_,v,8)^Pb(_,v,7),x=Co[y-2]|0,P=Io[y-2]|0,C=dr(x,P,19)^_s(x,P,61)^Sb(x,P,6),R=ur(x,P,19)^As(x,P,61)^Pb(x,P,6),O=Fk(S,R,Io[y-7],Io[y-16]),E=Kk(O,k,C,Co[y-7],Co[y-16]);Co[y]=E|0,Io[y]=O|0}let{Ah:i,Al:o,Bh:s,Bl:r,Ch:a,Cl:c,Dh:l,Dl:p,Eh:d,El:u,Fh:f,Fl:h,Gh:m,Gl:w,Hh:b,Hl:g}=this;for(let y=0;y<80;y++){let _=dr(d,u,14)^dr(d,u,18)^_s(d,u,41),v=ur(d,u,14)^ur(d,u,18)^As(d,u,41),k=d&f^~d&m,S=u&h^~u&w,x=Wk(g,v,S,Uq[y],Io[y]),P=Hk(x,b,_,k,jq[y],Co[y]),C=x|0,R=dr(i,o,28)^_s(i,o,34)^_s(i,o,39),O=ur(i,o,28)^As(i,o,34)^As(i,o,39),E=i&s^i&a^s&a,j=o&r^o&c^r&c;b=m|0,g=w|0,m=f|0,w=h|0,f=d|0,h=u|0,{h:d,l:u}=ni(l|0,p|0,P|0,C|0),l=a|0,p=c|0,a=s|0,c=r|0,s=i|0,r=o|0;let B=np(C,O,j);i=ip(B,P,R,E),o=B|0}({h:i,l:o}=ni(this.Ah|0,this.Al|0,i|0,o|0)),{h:s,l:r}=ni(this.Bh|0,this.Bl|0,s|0,r|0),{h:a,l:c}=ni(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:p}=ni(this.Dh|0,this.Dl|0,l|0,p|0),{h:d,l:u}=ni(this.Eh|0,this.El|0,d|0,u|0),{h:f,l:h}=ni(this.Fh|0,this.Fl|0,f|0,h|0),{h:m,l:w}=ni(this.Gh|0,this.Gl|0,m|0,w|0),{h:b,l:g}=ni(this.Hh|0,this.Hl|0,b|0,g|0),this.set(i,o,s,r,a,c,l,p,d,u,f,h,m,w,b,g)}roundClean(){at(Co,Io)}destroy(){this.destroyed=!0,at(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Mb=class extends Tb{constructor(){super(64,oS)}},Ze=ap(()=>new qb,Rb(1)),Lb=ap(()=>new Mb,Rb(3))});function cp(n){return Fe(n)}function Oo(n,e){if(n===e)return!0;if(n instanceof vt&&e instanceof vt)return Object.is(n.value,e.value)||n.value===e.value;if(typeof n=="bigint"||typeof e=="bigint")return BigInt(n)===BigInt(e);if(Array.isArray(n)&&Array.isArray(e))return n.length===e.length&&n.every((t,i)=>Oo(t,e[i]));if(n instanceof Map&&e instanceof Map){if(n.size!==e.size)return!1;let t=[...n],i=[...e];return t.every(([o,s],r)=>i[r][0]===o&&Oo(s,i[r][1]))}return!1}function Di(n){let e=typeof n=="string"?new TextEncoder().encode(n):n;return`sha256:${ut(Ze(e))}`}function Nq(n){let e=new Uint8Array(n);return globalThis.crypto.getRandomValues(e),e}function zi(n=Date.now()){let e=Nq(16);n<=Qu?(n=Qu,ks=ks+1&4095,ks===0&&(n=++Qu)):(ks=(e[6]&15)<<8|e[7],ks&=2047),Qu=n;let t=BigInt(n);for(let i=0;i<6;i++)e[i]=Number(t>>BigInt(8*(5-i))&0xffn);return e[6]=112|ks>>8&15,e[7]=ks&255,e[8]=128|e[8]&63,Wc(e)}function ef(n,e){if(n===e)return[];let t=Array.from(n),i=Array.from(e),o=0;for(;o<t.length&&o<i.length&&t[o]===i[o];)o++;let s=0;for(;s<t.length-o&&s<i.length-o&&t[t.length-1-s]===i[i.length-1-s];)s++;return[[o,t.length-s,i.slice(o,i.length-s).join("")]]}var Qu,ks,mr=I(()=>{"use strict";hr();Je();ve();un();un();un();Qu=0,ks=0});function Le(n,e=$q){if(typeof n!="string"||$i.encode(n).length>e)throw pe("bounded text required");return n}function xn(n,e){let t=F.dec(n);if(t>e)throw pe("integer exceeds bound");return t}function Dt(n,e){if(!Array.isArray(n)||n.length>e)throw pe("bounded array required");return n}function Ma(n,e){let t=Dt(n,e);if(t.length!==e)throw pe("wrong tuple length");return t}function bi(n,e){if(!(n instanceof Map))throw pe("exact struct required");let t=n;if(t.size!==e.length||e.some(i=>!t.has(i)))throw pe("exact struct required");return n}function lS(n){let e=n instanceof vt?n.value:n;if(typeof e!="number"||!Number.isFinite(e)||!(n instanceof vt)&&Number.isInteger(e))throw pe("finite binary64 required");return e}function pS(n){return n.kind==="list"?n.values.every(pS):n.kind!=="map"&&n.kind!=="duration"&&n.kind!=="error"&&n.kind!=="unavailable"}function Ps(n,e=1){if(!Number.isInteger(e)||e<1||e>32)throw pe("cell depth exceeds bound");let t=Dt(n,5),i=F.dec(t[0]),o=s=>{if(t.length!==s)throw pe("wrong tagged cell length")};switch(i){case 0:return o(1),{kind:"null"};case 1:return o(2),{kind:"boolean",value:Ee.dec(t[1])};case 2:return o(2),{kind:"number",value:lS(t[1])};case 3:return o(2),{kind:"text",value:Le(t[1])};case 4:{o(5);let s=An.dec(t[1]);if(!Number.isSafeInteger(s))throw pe("date millis exceeds JS-safe range");return{kind:"date",millis:s,display:Le(t[2]),authoritativeZone:Le(t[3]),dateOnly:Ee.dec(t[4])}}case 5:return o(3),{kind:"duration",components:Ma(t[1],8).map(lS),display:Le(t[2])};case 6:return o(2),{kind:"list",values:Dt(t[1],Ss).map(s=>Ps(s,e+1))};case 7:{if(o(2),!(t[1]instanceof Map)||t[1].size>Ss)throw pe("bounded cell data map required");let s=new Map,r=null;for(let[a,c]of t[1]){let l=Le(a),p=$i.encode(l);if(r&&Fq(r,p)>=0)throw pe("cell data map keys must ascend");r=p,s.set(l,Ps(c,e+1))}return{kind:"map",values:s}}case 8:return o(2),{kind:"error",message:Le(t[1])};case 9:return o(3),{kind:"unavailable",code:Le(t[1]),detail:Le(t[2])};default:throw pe("unknown tagged cell",!0)}}function Fq(n,e){for(let t=0;t<Math.min(n.length,e.length);t++)if(n[t]!==e[t])return n[t]-e[t];return n.length-e.length}function Kq(n){let e=new Map,t=0,i=0,o=r=>{if(++t>4096||(i+=r)>1024*1024)throw pe("summary metadata exceeds bound")},s=(r,a)=>{if(a>32)throw pe("summary value depth exceeds bound");o(128);let c=Dt(r,5),l=F.dec(c[0]);if(l===3||l===8)o($i.encode(Le(c[1])).length);else if(l===4)o($i.encode(Le(c[2])).length+$i.encode(Le(c[3])).length);else if(l===5)o($i.encode(Le(c[2])).length);else if(l===6)for(let p of Dt(c[1],Ss))s(p,a+1);else if(l===7){if(!(c[1]instanceof Map)||c[1].size>Ss)throw pe("bounded summary data map required");for(let[p,d]of c[1])o($i.encode(Le(p)).length+64),s(d,a+1)}else if(l!==0&&l!==1&&l!==2)throw pe("summary must be a tagged value",!0)};for(let r of Dt(n,64)){let a=Ma(r,2),c=Le(a[0],1024);if(c.length===0||/[\u0000-\u001f\u007f-\u009f]/u.test(c)||e.has(c))throw pe("unique nonempty summary name required");o($i.encode(c).length+64),s(a[1],1),e.set(c,Ps(a[1]))}return e}function jb(n){let e=xn(n.offset,4294967295),t=xn(n.limit,ii);if(t===0)throw pe("window limit must be positive");return{offset:e,limit:t}}function dS(n){if(!Array.isArray(n)||n.length>cS)throw pe("bounded rowProperties list required");let e=new Set,t=[],i=0;for(let o of n){if(typeof o!="string"||o.length===0)throw pe("non-empty row property name required");let s=$i.encode(o).length;if(s>Bq||e.has(o))throw pe("distinct bounded row property name required");if(i+=s,i>Vq)throw pe("row property names exceed bound");e.add(o),t.push(o)}return t}function tf(n){if(!(n.hints instanceof Map)||n.hints.size>Ss)throw pe("bounded hints map required");let e=new Map,t=0;for(let[s,r]of n.hints){if(Le(s),Le(r),t+=$i.encode(s).length+$i.encode(r).length,t>65536)throw pe("hint bytes exceed bound");e.set(s,r)}let i=new Map([[0,M.enc(n.record)],[1,Z.enc(n.sourceRevision)],[2,xn(n.ordinal,4294967295)],[3,e],[4,Le(n.captureTimezone,128)],[5,Ub]]);if(n.window!==void 0){let s=jb(n.window);i.set(6,new Map([[0,s.offset],[1,s.limit]]))}n.rowProperties!==void 0&&i.set(7,dS(n.rowProperties));let o=fe(i);if(o.length>zq)throw pe("request bytes exceed bound");return o}function uS(n){let e=bi(n,[0,1,2,3,4,5,6]);return{record:M.dec(e.get(0)),path:Le(e.get(1)),sourceRevision:Z.dec(e.get(2)),ordinal:xn(e.get(3),4294967295),name:e.get(4)===null?null:Le(e.get(4)),viewType:Le(e.get(5)),implementations:Dt(e.get(6),Ss).map(t=>{let i=bi(t,[0,1,2,3]);return{typeName:Le(i.get(0)),version:Le(i.get(1)),contractDigest:Z.dec(i.get(2)),implementationDigest:Z.dec(i.get(3))}})}}function nf(n,e,t){if(!(n instanceof Uint8Array)||!n.length||n.length>Dq)throw pe("response bytes exceed bound");let i=we(n);if(!(i instanceof Map))throw pe("result struct required");let o=i;if(o.get(0)!==1)throw pe("unknown result version",!0);if(o.has(7)){let v=bi(o,[0,7]);return{kind:"refusal",problem:ti.dec(v.get(7))}}let s=o.has(8),r=o.has(9),a=o.has(10),c=!(t==null||t===!1);if(a!==c)throw pe("rowProperties response differs from request");let l=Array.isArray(t)?new Set(dS(t)):null,p=bi(o,[0,1,2,3,4,5,6,...s?[8]:[],...r?[9]:[],...a?[10]:[]]);if(e!==void 0&&s!==(e!==null))throw pe("window response differs from request");let d=uS(p.get(1)),u=bi(p.get(2),[0,1]),f=Dt(u.get(0),64).map(v=>Le(v)),h=Dt(u.get(1),64).map(v=>{let k=bi(v,[0,1,2]),S=xn(k.get(0),63);if(S>=f.length)throw pe("unavailable column index out of bounds");return{index:S,code:Le(k.get(1)),detail:Le(k.get(2))}}),m=Dt(p.get(3),ii).map(v=>{let k=Ma(v,4),S=Dt(k[3],64);if(S.length!==f.length)throw pe("row cell count differs from columns");return{record:M.dec(k[0]),path:Le(k[1]),sourceRevision:Z.dec(k[2]),cells:S.map(x=>Ps(x))}}),w=a?(()=>{let v=Dt(p.get(10),ii);if(v.length!==m.length)throw pe("rowProperties count differs from rows");return m.map((k,S)=>{let x=Ma(v[S],2),P=Dt(x[0],Ss).map(O=>Le(O)),C=kn.dec(x[1]);if(C.size>cS)throw pe("rowProperties entry exceeds bound");let R=Object.create(null);for(let[O,E]of C){if(l&&!l.has(O))throw pe("unexpected row property in response");Object.defineProperty(R,O,{value:ei(E),enumerable:!0,writable:!0,configurable:!0})}return{...k,types:P,properties:{...R}}})})():m,b=Dt(p.get(4),ii).map(v=>{let k=Ma(v,2),S=Ps(k[0]);if(!pS(S))throw pe("group key must be a qualified scalar or list");let x=Dt(k[1],ii).map(P=>{let C=xn(P,ii-1);if(C>=w.length)throw pe("group row index out of bounds");return C});return{key:S,rowIndices:x}}),g;if(s){let v=bi(p.get(8),[0,1,2,3]),k=jb({offset:xn(v.get(0),4294967295),limit:xn(v.get(1),ii)}),S=xn(v.get(2),ii);if(w.length!==Math.min(k.limit,Math.max(S-k.offset,0)))throw pe("window row count differs from total/request");if(e!=null){let R=jb(e);if(k.offset!==R.offset||k.limit!==R.limit)throw pe("window echo differs from request")}let x=-1,P=Dt(v.get(3),ii);if(P.length!==b.length||b.some(R=>R.rowIndices.length===0))throw pe("group placements must align represented groups");let C=P.map((R,O)=>{let E=Ma(R,3),j=xn(E[0],ii-1),B=xn(E[1],ii);if(j<=x||j>=S||B===0||B>S)throw pe("group placement bounds/order invalid");x=j;let D=-1,J=Dt(E[2],ii).map(V=>{let U=xn(V,ii-1);if(U<=D||U>=B)throw pe("group row ordinal bounds/order invalid");return D=U,U});if(J.length!==b[O].rowIndices.length)throw pe("group ordinal count differs from represented rows");return{globalGroupOrdinal:j,totalGroupRows:B,rowOrdinals:J}});g={...k,totalMatchedRows:S,groupPlacements:C}}let y=ws.dec(p.get(5));if(!Number.isSafeInteger(y.instant))throw pe("clock instant exceeds JS-safe range");let _=r?Kq(p.get(9)):void 0;return{kind:"success",view:d,columns:f,unavailableColumns:h,rows:w,groups:b,clock:y,collectionRevision:Z.dec(p.get(6)),...g===void 0?{}:{window:g},..._===void 0?{}:{summaries:_}}}function fS(n){if(n==null)return null;if(!(n instanceof Uint8Array)||n.length!==32)throw pe("native discovery handle must be 32 bytes");return new Uint8Array(n)}function pp(n){let e=xn(n.limit,128);if(!e)throw pe("discovery limit must be positive");return fe(new Map([[0,n.reportUnreadable?2:1],[1,Le(n.captureTimezone,128)],[2,e],[3,fS(n.continuation)]]))}function rf(n){return fe(new Map([[0,1],[1,M.enc(n.record)],[2,Z.enc(n.sourceRevision)],[3,xn(n.ordinal,4294967295)],[4,Le(n.captureTimezone,128)]]))}function hS(n){if(!(n instanceof Uint8Array)||!n.length||n.length>1024*1024)throw pe("discovery response bytes exceed bound");let e=we(n);if(!(e instanceof Map))throw pe("discovery result struct required");let t=e;if(t.get(0)!==1)throw pe("unknown discovery result version");return t}function mS(n){let e=uS(n);if(!e.implementations.length||e.implementations.length>16)throw pe("bounded native implementation provenance required");return e}function yS(n){let e=ws.dec(n);if(!Number.isSafeInteger(e.instant))throw pe("clock instant exceeds JS-safe range");return Le(e.tz,128),Le(e.localDate,128),e}function Wq(n){let e=bi(n,[0,1,2,3,4]);return{record:M.dec(e.get(0)),path:Le(e.get(1)),sourceRevision:Z.dec(e.get(2)),reason:Le(e.get(3),128),detail:Le(e.get(4),128)}}function of(n,e=128,t=!1){let i=xn(e,128);if(!i)throw pe("discovery limit must be positive");let o=hS(n);if(o.has(7)){let l=bi(o,[0,7]);return{kind:"refusal",problem:ti.dec(l.get(7))}}let s=bi(o,t?[0,1,2,3,4,5]:[0,1,2,3,4]),r=t?Dt(s.get(5),128).map(Wq):[];for(let l=1;l<r.length;l++)if(r[l-1].record>=r[l].record)throw pe("unreadable sources must ascend by record");let a=Dt(s.get(1),i).map(mS);for(let l=1;l<a.length;l++){let p=a[l-1],d=a[l];if(p.record>d.record||p.record===d.record&&p.ordinal>=d.ordinal)throw pe("discovery source/ordinal frontier must ascend");if(p.record===d.record&&(p.path!==d.path||p.sourceRevision!==d.sourceRevision))throw pe("one source identity cannot have two revisions/paths within a page")}let c=s.get(4);if(c!==null&&!(c instanceof Uint8Array))throw pe("native discovery handle required");return{kind:"success",views:a,unreadable:r,clock:yS(s.get(2)),collectionRevision:Z.dec(s.get(3)),continuation:fS(c)}}function sf(n,e){let t=hS(n);if(t.has(7)){let r=bi(t,[0,7]);return{kind:"refusal",problem:ti.dec(r.get(7))}}let i=bi(t,[0,1,2,3,4]),o=mS(i.get(1)),s=Le(i.get(2),512*1024);if(Di(s)!==o.sourceRevision)throw pe("exact native source SHA differs from bytes");if(e&&(o.record!==M.dec(M.enc(e.record))||o.sourceRevision!==Z.dec(Z.enc(e.sourceRevision))||o.ordinal!==e.ordinal))throw pe("exact source identity/revision/ordinal differs from request");return{kind:"success",view:o,source:s,clock:yS(i.get(3)),collectionRevision:Z.dec(i.get(4))}}var Ub,Dq,zq,$q,Ss,ii,cS,Bq,Vq,$i,pe,Nb=I(()=>{"use strict";Je();ve();un();mr();en();Ub="whole-view-synthetic-policy-reference-v1",Dq=16*1024*1024,zq=128*1024,$q=4096,Ss=4096,ii=65536,cS=128,Bq=256,Vq=16*1024,$i=new TextEncoder,pe=(n,e=!1)=>new ae("app-bases-v1",n,e)});async function*bS(n,e,t={}){let i=gS(t.firstPageSize,200),o=gS(t.pageSize,1e3),s=e.window?.offset??0,r=0,a=0,c;for(;;){t.signal?.throwIfAborted();let l=await n({...e,window:{offset:s,limit:a===0?i:o}},t.signal);if(l.kind==="refusal"){yield l;return}let p=l.window?.totalMatchedRows;if(p===void 0)throw A("internal","native Bases page omitted its window");c??={revision:l.collectionRevision,total:p},r+=l.rows.length;let d=l.rows.length===0||s+l.rows.length>=p;if(yield{...l,page:a,offset:s,loaded:r,complete:d,changedSinceFirst:c.revision!==l.collectionRevision||c.total!==p},d)return;s+=l.rows.length,a+=1}}var gS,wS=I(()=>{"use strict";re();gS=(n,e)=>{if(n===void 0)return e;if(!Number.isInteger(n)||n<1||n>65536)throw A("invalid_request","page size must be 1..65536");return n}});function vS(n){if(n==="request"||n==="single_record"||n==="cross_record")return n;throw new ae("validation-tier","unknown diagnostic tier",!0)}function kS(n){if(n===void 0)return{targets:void 0,expected:void 0};if(!Array.isArray(n)||n.length>1e3)throw A("invalid_request","At most 1000 validation selections are allowed.","validation_bounds");let e=[],t=[];for(let i of Array.from(n)){if(typeof i=="string"){let s=M.dec(M.enc(i));e.push(M.enc(s)),t.push({id:s});continue}if(!i||typeof i!="object")throw A("invalid_request","Validation needs UUID, path or record selections.","validation_selection");if("id"in i){let s=M.dec(M.enc(i.id)),r=Z.dec(Z.enc(i.revision));e.push(M.enc(s)),t.push({id:s,revision:r});continue}let o=i.path;if(typeof o!="string"||!o||o.length>4096||new TextEncoder().encode(o).byteLength>4096)throw A("invalid_request","Validation paths must be nonempty and at most 4096 UTF-8 bytes.","validation_selection");e.push(o),t.push({})}return{targets:e,expected:t}}function SS(n,e){if(e&&(n.length!==e.length||n.some((t,i)=>e[i]?.id!==void 0&&e[i].id!==t.id)))throw A("internal","Validation did not return the complete selected record identities.","invalid_validation_result");if(e&&n.some((t,i)=>e[i]?.revision!==void 0&&e[i].revision!==t.revision))throw A("unavailable","The validated document differs from the selected record revision.","record_validation_stale");return n}var Hq,Gq,Yq,_S,Ro,AS,PS=I(()=>{"use strict";ve();Je();en();re();Hq={name:"validation-tier",enc:vS,dec:vS},Gq=z("validation-issue",[[0,"code",T],[1,"severity",Lu],[2,"message",T],[3,"details",Ia,"opt"],[4,"location",T,"opt"],[5,"typeName",T,"opt"],[6,"tier",Hq]]),Yq=z("record-validation",[[0,"id",M],[1,"issues",G(Gq)],[2,"path",T],[3,"revision",Z]]),_S=G(Yq),Ro=n=>new ae("record-validations",n),AS={name:"record-validations",enc:n=>_S.enc(n),dec:n=>{if(!Array.isArray(n)||n.length>1e3)throw Ro("invalid inventory");let e=0,t=0,i=[[n,0]];for(;i.length;){let[s,r]=i.pop();if(++t>65536||r>32)throw Ro("result exceeds tree bounds");if(Array.isArray(s)){if(s.length>65536)throw Ro("oversized array");for(let a of s)i.push([a,r+1])}else if(s instanceof Map){if(s.size>32768)throw Ro("oversized map");for(let[a,c]of s)i.push([a,r+1],[c,r+1])}}for(let s of n){let r=s instanceof Map?s.get(1):void 0;if(!Array.isArray(r))throw Ro("missing diagnostics");if(e+=r.length,e>4096)throw Ro("too many diagnostics")}if(fe(n).byteLength>1024*1024)throw Ro("result exceeds byte bounds");let o=_S.dec(n);for(let s of o)if(!s.path||new TextEncoder().encode(s.path).byteLength>4096)throw Ro("invalid current path");return o}}});function Jq(n){if(n.length>Eo)throw A("too_large",`frame of ${n.length} bytes exceeds ${Eo}`);let e=new Uint8Array(4+n.length);return new DataView(e.buffer).setUint32(0,n.length),e.set(n,4),e}function Db(n){return xS.has(n)}function af(n){let e=new dp,t=!1,i=null,o=[],s={get onframe(){return i},set onframe(a){if(i=a,a&&o.length)for(let c of o.splice(0))a(c)},onclose:null,send(a){if(t)throw A("unavailable","connection closed");n.write(Jq(fe(a)))},close(){t||(t=!0,n.close(),s.onclose?.())}};xS.add(s),n.ondata=a=>{try{for(let c of e.push(a)){let l=we(c);if(i)i(l);else if(o.length<1024)o.push(l);else throw A("too_large","too many frames before the session started")}}catch(c){r(c instanceof oe?c:A("internal",`invalid frame from replica: ${String(c)}`))}},n.onclose=a=>r(a);function r(a){t||(t=!0,n.close(),s.onclose?.(a))}return s}function CS(){let n=()=>({onframe:null,onclose:null,closed:!1,send(i){if(this.closed)throw A("unavailable","connection closed");let o=this.peer;queueMicrotask(()=>{o.closed||o.onframe?.(i)})},close(){if(this.closed)return;this.closed=!0,this.onclose?.();let i=this.peer;i.closed||(i.closed=!0,queueMicrotask(()=>i.onclose?.()))}}),e=n(),t=n();return e.peer=t,t.peer=e,[e,t]}var Eo,dp,xS,up=I(()=>{"use strict";Je();re();Eo=16*1024*1024,dp=class{chunks=[];head=0;buffered=0;push(e){e.length&&(this.chunks.push(e),this.buffered+=e.length);let t=[];for(;!(this.buffered<4);){let i=new DataView(this.peek(4).buffer).getUint32(0);if(i>Eo)throw A("too_large",`frame of ${i} bytes exceeds ${Eo}`);if(this.buffered<4+i)break;this.skip(4),t.push(this.take(i))}return t}peek(e){let t=new Uint8Array(e),i=0,o=this.head;for(let s of this.chunks){let r=Math.min(e-i,s.length-o);if(t.set(s.subarray(o,o+r),i),i+=r,o=0,i===e)break}return t}take(e){let t=this.peek(e);return this.skip(e),t}skip(e){for(this.buffered-=e;e>0;){let i=this.chunks[0].length-this.head;if(e<i){this.head+=e;return}e-=i,this.chunks.shift(),this.head=0}}};xS=new WeakSet});var lf,IS=I(()=>{"use strict";re();lf=class{constructor(e){this.request=e}request;tail=Promise.resolve();occupied=0;read(e,t,i,o){if(o?.aborted)return Promise.reject(A("cancelled","Bases READ cancelled"));if(this.occupied>=33)return Promise.reject(A("unavailable","Bases read queue is full","bases_read_backpressure"));let s=t.slice();this.occupied++;let r,a,c=!1,l=new Promise((u,f)=>{r=u,a=f}),p=()=>{c||(c=!0,s.fill(0),a(A("cancelled","Bases READ cancelled")))};o?.addEventListener("abort",p,{once:!0});let d=async()=>{try{if(c)return;let u=await this.request(e,s);if(!(u instanceof Uint8Array)||!u.length||u.length>i)throw u instanceof Uint8Array&&u.fill(0),A("internal","native Bases response bytes exceed bound");if(c||o?.aborted){u.fill(0),p();return}c=!0,r(u)}catch(u){c||(c=!0,a(u))}finally{s.fill(0),o?.removeEventListener("abort",p),this.occupied--}};return this.tail=this.tail.then(d,d),l}}});function OS(n,e){cf.set(n,e)}function RS(n,e){let t=cf.get(n);t&&cf.set(e,t)}function ES(n){return cf.get(n)}var cf,zb=I(()=>{"use strict";cf=new WeakMap});function pf(n){return qS.add(n),n}function fp(n){return qS.has(n)}var qS,hp=I(()=>{"use strict";qS=new WeakSet});function Bn(n,e){return X(n)?n:n instanceof ae&&n.unknown?A("upgrade_required",`${e}: ${n.message}`,{reason:"unknown_variant"}):A("internal",`${e}: ${n instanceof Error?n.message:String(n)}`)}function La(n,e,t){return new oe(Bn(n,e).toProblem(),{...t,cause:n})}var df,xs,TS,ja,Cs,Ua=I(()=>{"use strict";ve();re();up();IS();zb();hp();en();df=[{major:1,minor:4},{major:1,minor:3},{major:1,minor:2},{major:1,minor:1},{major:1,minor:0}];xs=class extends oe{constructor(e,t={}){super(Bn(e,"submit").toProblem(),{...t,cause:e})}},TS=new WeakSet,ja=n=>n instanceof oe&&TS.has(n),Cs=class n{constructor(e,t){this.port=e;this.hello=t;e.onframe=i=>this.onFrame(i),e.onclose=i=>this.onClosed(i)}port;hello;nextId=1;pending=new Map;pushHandlers=new Map;requestHandlers=new Map;closeError;closedFlag=!1;closeListeners=new Set;basesReads=new lf((e,t)=>this.request(e,new Map([[0,t]])));device;static async open(e,t,i){let o=Kr.enc({kind:"request",id:0,method:"hello",params:Fg.enc(t)}),s;try{s=await e.open(o,i)}catch(c){throw X(c)?c:A("unavailable",`cannot reach the replica (${e.description}): ${String(c)}`)}let r;try{let c=Kr.dec(s.helloResponse);if(c.kind!=="response"||c.id!==0)throw A("internal","replica answered hello with another frame");if(c.problem)throw c.problem.code==="unavailable"&&c.problem.reason==="not_serving"&&fp(e)?new oe({...c.problem,reason:"not_served"}):new oe(c.problem);r=Gg.dec(c.result??null)}catch(c){throw s.port.close(),Bn(c,"hello")}let a=new n(s.port,r);return RS(s.port,a),a.device=s.device,a}get closed(){return this.closedFlag}get error(){return this.closeError}onClose(e){return this.closedFlag?(queueMicrotask(()=>e(this.closeError)),()=>{}):(this.closeListeners.add(e),()=>this.closeListeners.delete(e))}async readAppBases(e,t){if(this.closedFlag)throw this.closeError??A("unavailable","session closed");if(t?.aborted)throw A("cancelled","Bases read cancelled");if(!(e instanceof Uint8Array)||!e.length||e.length>128*1024)throw A("invalid_request","Bases request bytes exceed bound");let i=this.port;if(typeof i.readAppBases!="function"&&!Db(i))throw A("invalid_request","this transport does not support app Bases reads",{reason:"unsupported"});let o=typeof i.readAppBases=="function"?await i.readAppBases(e,t):await this.basesReads.read("app_bases_execute_v1",e,16*1024*1024,t);try{if(t?.aborted)throw A("cancelled","Bases read cancelled");if(this.closedFlag||this.port!==i)throw this.closeError??A("unavailable","original Bases session closed");if(!(o instanceof Uint8Array)||!o.length||o.length>16*1024*1024)throw A("internal","Bases response bytes exceed bound");return o}catch(s){throw o instanceof Uint8Array&&o.fill(0),s}}async readAppBasesDiscovery(e,t,i){if(this.closedFlag)throw this.closeError??A("unavailable","session closed");if(i?.aborted)throw A("cancelled","Bases discovery cancelled");if(e!=="list-views"&&e!=="read-view-source")throw A("invalid_request","unknown native Bases read");if(!(t instanceof Uint8Array)||!t.length||t.length>128*1024)throw A("invalid_request","Bases request bytes exceed bound");let o=this.port;if(typeof o.readAppBasesDiscovery!="function"&&!Db(o))throw A("invalid_request","this transport does not support native Bases discovery",{reason:"unsupported"});let s=typeof o.readAppBasesDiscovery=="function"?await o.readAppBasesDiscovery(e,t,i):await this.basesReads.read(e==="list-views"?"app_bases_list_views_v1":"app_bases_read_view_source_v1",t,1024*1024,i);try{if(i?.aborted)throw A("cancelled","Bases discovery cancelled");if(this.closedFlag||this.port!==o)throw this.closeError??A("unavailable","original Bases session closed");if(!(s instanceof Uint8Array)||!s.length||s.length>1024*1024)throw A("internal","Bases discovery response bytes exceed bound");return s}catch(r){throw s instanceof Uint8Array&&s.fill(0),r}}async declaredSetup(e,t){if(!this.hello.features.includes("declared-collection-setup-v1"))throw A("upgrade_required","This computer needs an update to set up this app.","declared_setup_unsupported");if(!e.length||e.length>2*1024*1024)throw A("too_large","Setup request exceeds its fixed bound.");let i=await this.request("app_collection_setup_v1",new Map([[0,e]]),{signal:t});if(this.closed||t?.aborted)throw i instanceof Uint8Array&&i.fill(0),this.error??A("unavailable","Original setup session closed.");if(!(i instanceof Uint8Array)||!i.length||i.length>256*1024)throw i instanceof Uint8Array&&i.fill(0),A("internal","Invalid bounded Native setup reply.");return i}request(e,t,i={}){if(this.closedFlag)return Promise.reject(this.closeError??A("unavailable","session closed"));if(i.signal?.aborted)return Promise.reject(A("cancelled","request aborted before sending"));let o=this.nextId++;return new Promise((s,r)=>{let a=()=>{try{this.sendFrame({kind:"request",id:this.nextId++,method:"cancel",params:new Map([[0,o]])})}catch{}c.reject(A("cancelled",`${e} cancelled`))},c={resolve:l=>{c.cleanup();try{s(i.codec?i.codec.dec(l):l)}catch(p){r(Bn(p,`${e} result`))}},reject:l=>{c.cleanup(),r(l)},cleanup:()=>{this.pending.delete(o),i.signal?.removeEventListener("abort",a)}};this.pending.set(o,c),i.signal?.addEventListener("abort",a,{once:!0});try{this.sendFrame({kind:"request",id:o,method:e,params:t})}catch(l){c.reject(X(l)?l:A("unavailable",String(l)))}})}onPush(e,t){let i=this.pushHandlers.get(e);return i||this.pushHandlers.set(e,i=new Set),i.add(t),()=>i.delete(t)}handle(e,t){this.requestHandlers.set(e,t)}close(){this.port.close(),this.onClosed()}closeWith(e){this.fail(e)}sendFrame(e){this.port.send(Kr.enc(e))}onFrame(e){let t;try{t=Kr.dec(e)}catch(i){if(i instanceof ae&&i.unknown)return;this.fail(A("internal",`malformed frame from replica: ${String(i)}`));return}switch(t.kind){case"response":{let i=this.pending.get(t.id);if(!i)return;if(t.problem){let o=new oe(t.problem);TS.add(o),i.reject(o)}else i.resolve(t.result??null);return}case"push":{let i=this.pushHandlers.get(t.type);if(!i)return;for(let o of[...i])try{o(t.payload)}catch(s){queueMicrotask(()=>{throw s})}return}case"request":this.serve(t.id,t.method,t.params);return}}async serve(e,t,i){let o=this.requestHandlers.get(t),s,r;if(!o)r=A("invalid_request",`client does not serve ${t}`,{reason:"unknown_method"}).toProblem();else try{s=await o(i)}catch(a){r=(X(a)?a:A("internal",String(a))).toProblem()}if(!this.closedFlag)try{this.port.send(Kr.enc(r?{kind:"response",id:e,problem:r}:{kind:"response",id:e,result:s??null}))}catch{}}fail(e){this.port.onclose=null,this.port.close(),this.onClosed(e)}onClosed(e){if(this.closedFlag)return;this.closedFlag=!0,this.closeError=e;let t=e??A("unavailable","connection to the replica closed");for(let i of[...this.pending.values()])i.reject(t);this.pending.clear();for(let i of[...this.closeListeners])i(e);this.closeListeners.clear()}}});function LS(n,e){return X(n,"unavailable")&&n.reason==="hosted_chunk_busy"&&Date.now()<e}function jS(n,e,t){let i=Math.min(Math.max(n.retryAfterMs??1e3,250),5e3);return new Promise((o,s)=>{if(t?.aborted)return s(A("cancelled",`${e} aborted`));let a=setTimeout(()=>{t?.removeEventListener("abort",c),o()},i),c=()=>{clearTimeout(a),s(A("cancelled",`${e} aborted`))};t?.addEventListener("abort",c,{once:!0})})}function Bb(n){let{grant:e}=n;if(e.grant!==void 0&&n.version.major===1&&n.version.minor<2)return null;let t=new Set(e.capabilities),i=Zq.filter(([,s])=>t.has(s)&&(s==="collection.read"||e.role!=="viewer")).map(([s])=>s),o=e.fileFolders===void 0?Object.freeze({kind:"collection"}):Object.freeze({kind:"selected_folders",folders:Object.freeze([...e.fileFolders])});return Object.freeze({actions:Object.freeze(i),scope:o})}function DS(n,e){mp.set(n,e)}function US(n){return typeof n=="string"?M.enc(n):"id"in n?M.enc(n.id):n.path}function $b(n){if(typeof n=="string")return n;if("id"in n)return n.id;throw A("invalid_request","this operation needs a file ID; get() the file first")}function Gr(n){let e=new Map;for(let[t,i]of n)i!==void 0&&e.set(t,i);return e}async function NS(n,e,t){return n instanceof Uint8Array?n.subarray(e,t):n instanceof ArrayBuffer?new Uint8Array(n,e,t-e):new Uint8Array(await n.slice(e,t).arrayBuffer())}function Qq(n){return n instanceof Uint8Array||n instanceof ArrayBuffer?n.byteLength:n.size}var MS,uf,Xq,Zq,mp,Na,yp=I(()=>{"use strict";hr();ve();re();Ua();mr();en();MS=9e4;uf=64*1024*1024,Xq=8*1024*1024,Zq=[["list","collection.read"],["read","collection.read"],["add","records.create"],["replace","records.edit"],["move","records.edit"],["delete","records.delete"]];mp=new WeakMap;Na=class{constructor(e){this.client=e;e.onSession(t=>this.wire(t))}client;uploading=Promise.resolve();progress=new Map;streams=new Map;wired=new WeakSet;opening=0;early=new Map;earlyFailures=new Map;get grant(){let e=Bb(this.client.hello),t=mp.get(this);return e&&t?Object.freeze({...e,actions:Object.freeze(e.actions.filter(i=>i==="list"||i==="read"||t.allows(i)))}):e}watch(e,t={}){let{version:i}=this.client.hello;if(i.major!==1||i.minor<2)throw A("upgrade_required","this replica's change feed does not name files","change_entity_unsupported");return this.client.watchChanges(o=>{let s=o.changes.filter(a=>a.entity==="file"||a.entity===void 0&&a.kind==="remove");o.changes.some(a=>a.entity===void 0&&a.kind==="put")?e({changes:[],cursor:o.cursor,reset:!0}):(s.length||o.reset)&&e({changes:s,cursor:o.cursor,reset:o.reset})},t)}wire(e){this.wired.has(e)||(this.wired.add(e),e.onPush("transfer_progress",t=>{try{let i=$u.dec(t);this.progress.get(i.id)?.(i)}catch{}}),e.onPush("file_chunk",t=>{try{let i=Du.dec(t),o=this.streams.get(i.stream);if(o)o.onChunk(i);else if(this.opening>0){let s=this.early.get(i.stream)??[];s.reduce((a,c)=>a+c.bytes.length,0)+i.bytes.length<=Xq&&this.early.size<16&&(s.push(i),this.early.set(i.stream,s))}}catch{}}),e.onPush("file_stream_failed",t=>{try{let{stream:i,problem:o}=zu.dec(t),s=this.streams.get(i);s?(this.streams.delete(i),s.onEnd(new oe(o))):this.opening>0&&this.earlyFailures.size<16&&this.earlyFailures.set(i,new oe(o))}catch{}}),e.onClose(t=>{for(let i of this.streams.values())i.onEnd(t??A("unavailable","connection closed"));this.streams.clear()}))}async session(e,t=!1){let i=await(t?this.client.readyForRead(e):this.client.ready({signal:e}));return this.wire(i),i}listPage(e={}){return this.client.call("list_files",Gr([[0,e.folder],[1,e.media?.map(t=>Ea.enc(t))],[2,e.cursor],[3,e.limit]]),{codec:ab,retry:!0,...e.signal?{signal:e.signal}:{}})}async*list(e={}){let t;for(;;){let i=await this.listPage({...e,...t?{cursor:t}:{},...e.pageSize?{limit:e.pageSize}:{}});if(yield*i.files,!i.cursor)return;t=i.cursor}}get(e,t={}){return this.client.call("get_file",Gr([[0,US(e)]]),{codec:Qc,retry:!0,...t.signal?{signal:t.signal}:{}})}async upload(e,t,i={}){let o={...i},s=this.uploading.then(()=>this.uploadQueued(e,t,o));return this.uploading=s.then(()=>{},()=>{}),s}async uploadQueued(e,t,i){if(mp.get(this)?.check(i.fileId?"replace":"add"),i.signal?.aborted)throw A("cancelled","upload aborted");let o=Qq(t),s=Ze.create(),r=4*1024*1024;for(let d=0;d<o;d+=r)s.update(await NS(t,d,Math.min(o,d+r)));let a=Ug(s.digest()),c=i.transferId??zi(),l={transfer:c,path:e,size:o,digest:a,mutationId:i.mutationId??zi()};i.fileId&&(l.fileId=i.fileId),i.ifRevision&&(l.ifRevision=i.ifRevision),i.onProgress&&this.progress.set(c,i.onProgress);let p=Date.now()+MS;for(;;)try{return await this.uploadOnce(t,o,l,i)}catch(d){if(X(d,"unavailable")&&this.client.link==="reconnecting")continue;if(LS(d,p)){await jS(d,"upload",i.signal);continue}throw this.progress.delete(c),await this.abortUpload(c).catch(()=>{}),La(d,"upload",{mutationId:l.mutationId})}}async uploadOnce(e,t,i,o){let s=await this.session(o.signal),r=o.signal?{signal:o.signal}:{},a=await s.request("open_upload",lb.enc(i),{codec:cb,...r});if(a.fileId===void 0){let h=s.hello.version.minor>=1;throw A(h?"internal":"upgrade_required","the replica does not return upload file identity",{reason:h?"file_upload_identity_missing":"file_upload_identity_unsupported"})}if(a.transfer!==i.transfer||i.fileId!==void 0&&a.fileId!==i.fileId)throw A("internal","the replica returned an unrelated upload identity",{reason:"file_upload_identity_mismatch"});let c=new Set(a.received),l=Math.ceil(t/a.chunkSize),p=c.size*a.chunkSize,d=new Set;for(let h=0;h<l;h++){if(c.has(h))continue;let m=h*a.chunkSize,w=await NS(e,m,Math.min(t,m+a.chunkSize)),b=s.request("upload_chunk",pb.enc({transfer:i.transfer,index:h,bytes:w}),r).then(()=>{p+=w.length,o.onProgress?.({id:i.transfer,phase:"receiving",done:Math.min(p,t),total:t})});d.add(b),b.finally(()=>d.delete(b)).catch(()=>{}),d.size>=4&&await Promise.race(d)}await Promise.all(d);let u=await s.request("commit_upload",Gr([[0,M.enc(i.transfer)]]),{codec:ku(Sn),...r}),f=Object.assign(this.client._track(u),{fileId:a.fileId});return o.onProgress?f.confirmed.finally(()=>this.progress.delete(i.transfer)).catch(()=>{}):this.progress.delete(i.transfer),f}abortUpload(e){return this.client.call("abort_upload",Gr([[0,M.enc(e)]])).then(()=>{})}downloadStream(e,t={}){let i=null,o=null,s,r,a=new Promise((g,y)=>(s=g,r=y));a.catch(()=>{});let c=this,l=new AbortController,p=A("cancelled","file download cancelled"),d=!1,u=!1,f=!1,h=()=>{},m=()=>{i!==null&&(c.streams.delete(i),c.early.delete(i),f||(f=!0,o?.request("cancel_stream",Gr([[0,i]])).catch(()=>{})))},w=()=>{u||(d=!0,h(),r(p),l.abort(),m())},b=new ReadableStream({async start(g){let y=()=>{u||d||(w(),g.error(p))};if(h=()=>t.signal?.removeEventListener("abort",y),t.signal?.addEventListener("abort",y,{once:!0}),t.signal?.aborted){y();return}try{if(o=await c.session(l.signal,!0),d)return;let _=Gr([[0,US(e)]]);t.range&&_.set(1,[t.range[0],t.range[1]]),t.revision&&_.set(2,Z.enc(t.revision));let v=0,k=0;c.opening++;let S;try{let O=Date.now()+MS;for(;;)try{S=await o.request("read_file",_,{signal:l.signal});break}catch(E){if(!LS(E,O))throw E;await jS(E,"download",l.signal)}}finally{c.opening--}i=F.dec(S.get(0)??null);let x=c.early.get(i)??[],P=c.earlyFailures.get(i);if(c.early.delete(i),c.earlyFailures.delete(i),c.opening===0&&(c.early.clear(),c.earlyFailures.clear()),d){m(),u=!0;return}let C=Qc.dec(S.get(1)??null);s(C),v=t.range?t.range[1]:C.size;let R=O=>{d||u||(g.enqueue(O.bytes),k+=O.bytes.length,t.onProgress?.({id:i,phase:"streaming",done:k,total:v}),!(d||u)&&(o.request("ack_chunks",Gr([[0,i],[1,O.offset+O.bytes.length]])).catch(()=>{}),O.last&&!d&&!u&&(u=!0,h(),c.streams.delete(i),g.close())))};c.streams.set(i,{onChunk:R,onEnd:O=>{u=!0,h(),g.error(O??A("unavailable","stream ended"))}});for(let O of x)R(O);P&&!u&&(c.streams.delete(i),u=!0,h(),g.error(P))}catch(_){u=!0,h(),c.opening===0&&(c.early.clear(),c.earlyFailures.clear()),m(),r(_),g.error(_)}},cancel:w});return Object.assign(b,{file:a})}async download(e,t={}){let i=typeof e=="object"&&"size"in e?e:await this.get(e,t);if(i.size>uf)throw A("too_large",`file is ${i.size} bytes; use downloadStream`,{details:{limit:uf}});let o=new Uint8Array(i.size),s=0,r=this.downloadStream(i,t).getReader();for(;;){let{done:a,value:c}=await r.read();if(a)break;o.set(c,s),s+=c.length}return o.subarray(0,s)}fetch(e,t={}){return this.client.call("fetch_file",Gr([[0,M.enc($b(e))]]),{retry:!0,...t.signal?{signal:t.signal}:{}}).then(()=>{})}evict(e){return this.client.call("evict_file",Gr([[0,M.enc($b(e))]])).then(()=>{})}getMaterialization(){return this.client.call("get_materialization",null,{codec:Bu,retry:!0})}setMaterialization(e){return this.client.call("set_materialization",Bu.enc(e)).then(()=>{})}async move(e,t,i={}){mp.get(this)?.check("move");let o={kind:"file_move",id:e.id,from:e.path,to:t,updateRefs:i.updateRefs??!0};return this.client.submit([i.ifRevision?{...o,ifRevision:i.ifRevision}:o],i)}async delete(e,t={}){mp.get(this)?.check("delete");let i={kind:"file_delete",id:$b(e)};return typeof e=="object"&&"digest"in e&&(i.base=e.digest),t.ifRevision&&(i.ifRevision=t.ifRevision),this.client.submit([i],t)}}});function HS(n){return/^\d{6}$/.test(n)?`${n.slice(0,3)} ${n.slice(3)}`:n}var Vb,zS,Fb,$S,VS,BS,FS,KS,WS,Kb,eT,GS,ff=I(()=>{"use strict";ve();en();Vb=["desktop","mobile","app_runtime","cli","hosted","escrow","recovery"],zS=Se("device-kind",Vb),Fb={name:"device-kind",enc:n=>zS.enc(n),dec:n=>{try{return zS.dec(n)}catch{return"unknown"}}},$S=z("pending-device",[[0,"device",M],[1,"account",M],[2,"kind",Fb],[3,"sas",T,"opt"],[4,"exchangeReady",Ee]]),VS={...$S,enc:n=>$S.enc({...n,sas:void 0})},BS=z("approval-readiness",[[0,"device",M],[1,"sas",T,"opt"],[2,"exchangeReady",Ee]]),FS={...BS,enc:n=>BS.enc({...n,sas:void 0})},KS=z("recovery-key-status",[[0,"configured",Ee],[1,"device",M,"opt"]]),WS=z("recovery-key-created",[[0,"phrase",T],[1,"device",M]]);Kb=["idle","reading_ahead","pending_grant","keyed","refused"],eT=Se("account-key-state",Kb),GS=z("account-key-status",[[0,"state",eT],[1,"problem",ti,"opt"]])});var YS,JS,tT,nT,XS,ZS,QS=I(()=>{"use strict";ve();ff();YS=z("record-history-params",[[0,"record",M],[1,"before",F,"opt"],[2,"limit",F,"opt"]]),JS=z("record-version-params",[[0,"record",M],[1,"seq",F]]),tT=z("author-ref",[[0,"account",M],[1,"device",M],[2,"grant",M,"opt"],[3,"grantAccount",M,"opt"]]),nT=z("history-version",[[0,"seq",F],[1,"time",An],[2,"author",tT],[3,"kind",Se("version-kind",["created","edited","moved","deleted"])],[4,"path",T],[5,"revision",Z,"opt"],[6,"source",Se("source",["api","external"])],[7,"deviceKind",Fb],[8,"app",T,"opt"]]),XS=z("record-history",[[0,"versions",G(nT)],[1,"from",F],[2,"fromTime",An,"opt"],[3,"next",F,"opt"]]),ZS=z("record-version",[[0,"path",T],[1,"document",T]])});function Wb(n,e,t,i){return Object.freeze({outcome:"unknown",mutationId:n,...i?{receipt:i}:{},problem:{code:"outcome_unknown",recovery:"resolve_outcome",reason:e,message:t}})}async function tP(n,e,t={}){let i=t.signal,o,s,r;if(typeof e=="string"){s=e;try{r=await n.receipt(s,{signal:i})}catch(l){if(gp(l))throw l;return X(l,"not_found")?Object.freeze({outcome:"rejected",mutationId:s,problem:l.toProblem()}):Wb(s,"receipt_unavailable",`The write's result could not be read: ${eP(l)}`)}}else try{o=await e,s=o.mutationId,r=o.receipt}catch(l){if(!(l instanceof oe)||gp(l))throw l;if(l.mutationId===void 0)return Object.freeze({outcome:"rejected",problem:l.toProblem()});s=l.mutationId;try{r=await n.receipt(s,{signal:i})}catch(p){if(gp(p))throw p;return X(p,"not_found")?Object.freeze({outcome:"rejected",mutationId:s,problem:l.toProblem()}):Wb(s,"receipt_unavailable",`The write may have been saved: ${l.message}`)}}if(r.state==="pending")try{r=await n.awaitReceipt(s,{timeoutMs:t.timeoutMs??iT,signal:i}),o?.update(r)}catch(l){if(gp(l))throw l;r=o?.receipt??r}if(r.mutation!==s)throw new oe({code:"internal",recovery:"contact_support",message:"the replica answered with another mutation's receipt"},{mutationId:s});if(r.state==="unknown"){let l=r.problem??{code:"outcome_unknown",recovery:"resolve_outcome",message:"The write's result is not known."};return Object.freeze({outcome:"unknown",mutationId:s,receipt:r,problem:l})}if(r.state==="rejected"){let l=r.problem??{code:"internal",recovery:"contact_support",message:"The write was rejected without a reason."};return Object.freeze({outcome:"rejected",mutationId:s,receipt:r,problem:l})}let a;if(t.read){let l=t.read===!0?{}:t.read,p=r.records?.length===1?r.records[0].id:void 0,d=l.record??o?.recordId??p;if(d===void 0)throw new oe({code:"invalid_request",recovery:"fix_request",message:"settle cannot tell which record to read back; pass read.record"},{mutationId:s});try{a=await rT(n,d,l,i)}catch(u){if(gp(u))throw u;return Wb(s,"readback_failed",`The write was kept, but the record could not be read back: ${eP(u)}`,r)}}let c={mutationId:s,receipt:r,...a};return r.state==="pending"?Object.freeze({outcome:"saved_on_device",...c}):r.status==="conflicted"?Object.freeze({outcome:"conflicted",...c,conflicts:Object.freeze([...r.conflicts??[]])}):Object.freeze({outcome:"confirmed",...c})}async function rT(n,e,t,i){let o;try{o=await n.get(e,{include:t.include,signal:i})}catch(s){if(!X(s,"not_found"))throw s;return t.contract?{record:null,contractRecord:null}:{record:null}}return t.contract?{record:o,contractRecord:await n.getContract(o,t.contract,{signal:i})}:{record:o}}var iT,gp,eP,nP=I(()=>{"use strict";re();iT=3e3,gp=n=>X(n,"cancelled"),eP=n=>n instanceof Error?n.message:String(n)});async function hf(n,e,t={}){let{include:i,signal:o}=t;o?.throwIfAborted();let s=t.concurrency??8;if(!Number.isSafeInteger(s)||s<1||s>Gb)throw A("invalid_request","readMany concurrency must be 1..16","read_many_bounds");if(!Array.isArray(e)||e.length>Hb)throw A("invalid_request","readMany accepts at most 1000 record selections","read_many_bounds");let r=Array.from(e,oT),a=i?Object.freeze({...i}):void 0,c={...a?{include:a}:{},...o?{signal:o}:{}},l=new Array(r.length),p=0,d=!1,u;async function f(){for(;!d&&p<r.length;)try{o?.throwIfAborted();let h=p++,m=r[h],w=await n.get(m,c);if(o?.throwIfAborted(),d)return;if(typeof m=="string"&&w.id!==m)throw A("invalid_request","readMany readback belongs to another UUID","read_many_identity_mismatch");l[h]=w}catch(h){d||(d=!0,u=h);return}}if(await Promise.all(Array.from({length:Math.min(s,r.length)},()=>f())),d)throw u;return o?.throwIfAborted(),l}function oT(n){if(typeof n=="string")return M.dec(M.enc(n));if(!n||typeof n!="object")throw A("invalid_request","readMany needs UUID, path or record selections","read_many_selection");if("id"in n)return M.dec(M.enc(n.id));if(typeof n.path!="string"||n.path.length===0||n.path.length>4096||new TextEncoder().encode(n.path).byteLength>4096)throw A("invalid_request","readMany path must be nonempty and at most 4096 UTF-8 bytes","read_many_bounds");return Object.freeze({path:n.path})}function mf(n,e,t={}){return n.pages(e,t)}async function iP(n,e,t={}){let i=t.signal,o=t.isCurrent?.bind(t),s=()=>A("unavailable","original record link binding changed","record_links_fenced");function r(){if(i?.throwIfAborted(),o){let k=!1;try{k=o()===!0}catch{}if(!k)throw s()}}r();let a=e?.path,c=e?.field,l=k=>typeof k=="string"&&k.length>0&&k.length<=4096&&new TextEncoder().encode(k).byteLength<=4096;if(!l(a)||!l(c))throw A("invalid_request","record link path/field must be nonempty and bounded","record_links_bounds");let p=JSON.stringify(c),d=`(${p} in raw ? raw[${p}] : null)`,u=k=>`${k}.asFile() == null ? null : ${k}.asFile().file.path`,f=`${d} == null ? [] : type(${d}) == "list" ? ${d}.map(l, ${u("l")}) : [${u(d)}]`;if(new TextEncoder().encode(f).byteLength>64*1024)throw A("invalid_request","record link expression exceeds native source bound","record_links_bounds");r();let h=await n.query({where:`file.path == ${JSON.stringify(a)}`,limit:2,select:[{name:"raw",expr:d},{name:"paths",expr:f}]},i?{signal:i}:{});r();let m=()=>A("unavailable","invalid or incomplete native record link projection","record_links_response");if(h.complete!==!0||h.cursor!=null)throw m();if(h.columns===void 0)throw A("upgrade_required","native record link projection unsupported","record_links_unsupported");if(h.columns.length!==2||h.columns[0]!=="raw"||h.columns[1]!=="paths"||h.diagnostics?.some(k=>k.code==="expression_evaluation_error"))throw m();if(h.records.length===0)throw A("not_found","selected record not found","record_links_missing");if(h.records.length!==1||h.records[0].path!==a)throw m();let w=h.records[0].values;if(w===void 0)throw A("upgrade_required","native record link projection unsupported","record_links_unsupported");let b=de(w,"raw"),g=de(w,"paths");if(Object.keys(w).length!==2||b===void 0||g===void 0)throw m();let y=b===null?[]:typeof b=="string"?[b]:b;if(!Array.isArray(y)||!Array.isArray(g)||y.length!==g.length||y.length>1e3)throw m();let _=0,v=[];for(let k=0;k<y.length;k++){let S=y[k],x=g[k];if(typeof S!="string"||S.length>(1<<20)-_||x!==null&&!l(x)||(_+=new TextEncoder().encode(S).byteLength+(x===null?0:new TextEncoder().encode(x).byteLength),_>1<<20))throw m();v.push(Object.freeze({raw:S,path:x}))}return r(),Object.freeze(v)}var Hb,Gb,Yb=I(()=>{"use strict";ve();re();un();Hb=1e3,Gb=16});function Da(n,e){if((n.document?.length??0)>bp||(n.body?.length??0)>bp)throw A("invalid_request","native record exceeds the record session source budget","record_session_budget");if(e!==void 0&&n.id!==e||typeof n.document!="string"||typeof n.body!="string"||Di(n.document)!==n.revision)throw A("invalid_request","record session needs actual complete, revision-consistent source and identity","record_witness_required")}function Yr(n){return n.state.hold!==void 0||n.state.unresolved!==void 0&&n.state.unresolved!==0}function za(n){return n.state.state==="confirmed"&&!Yr(n)}function _t(n){return structuredClone(n)}function $a(n){return n instanceof oe?n.toProblem():n instanceof Error&&(n.name==="AbortError"||n.name==="TimeoutError")?A("cancelled",n.message).toProblem():A("internal",n instanceof Error?n.message:"record session failure").toProblem()}function Gt(n,e,t){return new oe({code:n,message:e,reason:t,recovery:n==="conflict"?"resolve_conflict":n==="outcome_unknown"?"resolve_outcome":"retry"})}function yf(n){return JSON.stringify(n,(e,t)=>typeof t=="bigint"?t.toString():t instanceof Uint8Array?ut(t):t).length*2}function Jb(n){if(n.length>bp)throw A("invalid_request","record session draft exceeds retained budget","record_session_budget");return new TextEncoder().encode(n).byteLength*2}function vp(n){let e=n??3e4;if(!Number.isSafeInteger(e)||e<1||e>12e4)throw A("invalid_request","record session timeout must be 1..120000ms","invalid_timeout");return e}var wp,bp,gf=I(()=>{"use strict";Je();re();mr();wp={body:!0,document:!0,effective:!0},bp=8*1024*1024});function bf(n,e,t){if(e===null)return t===n.body;let i=de(n.frontmatter,e);return i===void 0||t===void 0?i===t:Xb(Fe(i),Fe(ei(t)))}function Xb(n,e){let t=fe(n),i=fe(e);return t.length===i.length&&t.every((o,s)=>o===i[s])}function sT(n){let e=new AbortController,t=setTimeout(()=>e.abort(new DOMException("record flush timed out","TimeoutError")),n);return{signal:e.signal,clear:()=>clearTimeout(t)}}function aT(n,e){return e?new Promise((t,i)=>{let o=()=>{s(),i(A("cancelled","record flush waiter cancelled"))},s=()=>e.removeEventListener("abort",o);if(e.aborted){o();return}e.addEventListener("abort",o,{once:!0}),n.then(r=>{s(),t(r)},r=>{s(),i(r)})}):n}var wf,rP=I(()=>{"use strict";Je();re();Ua();mr();un();gf();wf=class{constructor(e,t,i){this.client=e;this.reserve=i;Da(t),this.base=_t(t),this.body=t.body,this.state=Yr(t)?"conflict":this.restState,this.publish()}client;reserve;base;body;patch=new Map;remote=null;captured=null;pendingEdits=new Map;driveGeneration=0;lastReceipt=null;state;why=null;snapshot;listeners=new Set;life=new AbortController;running=null;writing=!1;refreshRunning=null;refreshAgain=!1;timer;active=!1;idle=!1;requireLive=!1;defaultTimeout=3e4;async restore(e,t){if(this.captured){if(t&&t.mutationId!==this.captured.recovery.mutationId)throw A("invalid_request","record already owns another recovery identity","record_recovery_mismatch");return}if(t){if(t.recordId!==this.id)throw A("invalid_request","recovery belongs to another native record","record_identity_mismatch");this.captured={bound:!1,body:this.body,patch:new Map,recovery:{...t,receipt:null,write:null}}}if(!this.active&&!t&&this.base.state.state==="pending"&&!this.pendingEdits.size){let i=new Map;for(let{ops:o,receipt:s}of await this.client.pendingWrites({signal:e}))for(let r of o){if(r.kind!=="update"||r.id!==this.id)continue;let a=s.mutation;if(r.body!==void 0||r.bodyEdits?.length){let c=r.body??s.records?.find(l=>l.id===this.id)?.body??this.base.body;i.set(null,{mutation:a,value:c})}for(let[c,l]of Object.entries(r.patch??{}))i.set(c,{mutation:a,value:Fe(l)});for(let c of r.unset??[])i.set(c,{mutation:a,value:void 0})}this.charge(this.body,this.patch,this.base,this.remote,this.lastReceipt,this.captured,i),this.pendingEdits=i}e?.throwIfAborted(),this.captured&&(this.state="recovery",this.why=Gt("outcome_unknown","recover the original native mutation before another edit","record_recovery_required").toProblem(),this.publish())}get id(){return this.base.id}get dirty(){return this.body!==this.base.body||this.patch.size>0}get restState(){return!this.pendingEdits.size&&za(this.base)?"saved":"saved_on_device"}get retained(){return this.dirty||this.captured!==null||this.pendingEdits.size>0||!za(this.base)}getSnapshot=()=>this.snapshot;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));resume(e){this.active||(this.life=new AbortController,this.active=!0),this.requireLive=e.requireLive??!1,this.defaultTimeout=vp(e.timeoutMs),this.idle=e.autosave?e.autosave.idleMs:!1,this.schedule()}suspend(){this.active=!1,this.clearTimer(),this.life.abort()}ensure(){if(!this.active)throw A("cancelled","record lease has been released")}setBody=e=>{if(this.ensure(),typeof e!="string")throw A("invalid_request","record body must be text");this.charge(e,this.patch),this.body=e,this.edited()};patchFrontmatter=e=>{this.ensure();let t=new Map(this.patch);for(let[i,o]of e instanceof Map?e:Object.entries(e)){let s=o===void 0?void 0:we(fe(Fe(o))),r=Object.hasOwn(this.base.frontmatter,i)?Fe(this.base.frontmatter[i]):void 0;!this.captured?.patch.has(i)&&(s===void 0&&r===void 0||s!==void 0&&r!==void 0&&Xb(s,r))?t.delete(i):t.set(i,s)}this.charge(this.body,t),this.patch=t,this.edited()};edited(){!this.captured&&this.state!=="conflict"&&this.state!=="deleted"&&(this.state=this.dirty?"unsaved":this.restState,this.why=null),this.publish(),this.schedule()}charge(e=this.body,t=this.patch,i=this.base,o=this.remote,s=this.lastReceipt,r=this.captured,a=this.pendingEdits){let c=yf(i)+Jb(e)+fe(new Map([...t].map(([l,p])=>[l,p??null]))).byteLength*2;o&&(c+=yf(o)),r&&(c+=Jb(r.body)+fe(new Map([...r.patch].map(([l,p])=>[l,p??null]))).byteLength*2);for(let[l,p]of a)c+=fe([l,p.mutation,p.value??null]).byteLength*2;s&&(c+=yf(s)),this.reserve(c)}publish(){this.charge();let e=new Map(Object.entries(this.base.frontmatter));for(let[t,i]of this.patch)i===void 0?e.delete(t):e.set(t,ei(i));this.snapshot=Object.freeze({state:this.state,body:this.body,frontmatter:structuredClone(Object.fromEntries(e)),record:_t(this.base),remote:this.remote?_t(this.remote):null,dirty:this.dirty,problem:this.why,lastReceipt:this.lastReceipt?_t(this.lastReceipt):null,recovery:this.captured?Object.freeze({...this.captured.recovery}):null});for(let t of[...this.listeners])try{t()}catch{}}clearTimer(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}schedule(){this.clearTimer(),this.active&&this.idle!==!1&&this.dirty&&this.state==="unsaved"&&!this.running&&(this.timer=setTimeout(()=>{this.timer=void 0,this.flush().catch(()=>{})},this.idle))}async read(e){let t=await this.client.get(this.id,{include:wp,signal:e});return e.throwIfAborted(),Da(t,this.id),t}async readWithReceipts(e){let t=new Map;for(;;){let i=await this.read(e);if(this.captured)return{current:i,receipts:t};let o=t.size;for(let[s,{mutation:r,value:a}]of this.pendingEdits){let c=bf(i,s,a);if(!za(i)&&c)continue;if(!t.has(r)){let p=await this.client.receipt(r,{signal:e});if(e.throwIfAborted(),p.mutation!==r)throw Gt("outcome_unknown","native receipt changed identity","mutation_identity_mismatch");t.set(r,p)}let l=t.get(r);if(l.state==="unknown"||l.state==="pending"&&!c)throw Gt("outcome_unknown","the projection does not qualify this device write yet","unqualified_readback")}if(t.size===o)return{current:i,receipts:t}}}reconcilePending(e,t){if(!t.size)return;let i=new Map(this.pendingEdits),o=new Map(this.patch),s=this.body!==this.base.body,r=s?this.body:e.body,a=!1;for(let[l,{mutation:p,value:d}]of this.pendingEdits){let u=t.get(p);!u||u.state==="pending"||u.state==="unknown"||(i.delete(l),!(u.state!=="rejected"&&u.status!=="conflicted"||bf(e,l,d))&&(a=!0,l===null?s||(r=d):o.has(l)||o.set(l,d)))}let c=this.lastReceipt&&(t.get(this.lastReceipt.mutation)??this.lastReceipt);if(a){for(let[p,d]of o)bf(e,p,d)&&o.delete(p);let l=r!==e.body||o.size>0;this.charge(r,o,e,l?e:null,c,this.captured,i),this.base=_t(e),this.remote=l?_t(e):null,this.body=r,this.patch=o,l&&(this.state="conflict",this.why=Gt("conflict","a device write was refused at head","record_session_conflict").toProblem())}else this.charge(this.body,this.patch,this.base,this.remote,c,this.captured,i);this.pendingEdits=i,this.lastReceipt=c}refresh=()=>{if(!this.active)return Promise.resolve();if(this.refreshRunning)return this.refreshAgain=!0,this.refreshRunning;let e=this.life.signal;return this.refreshRunning=(async()=>{do{this.refreshAgain=!1;let t=this.driveGeneration;try{let{current:i,receipts:o}=await this.readWithReceipts(e);if(t!==this.driveGeneration){this.refreshAgain=!0;continue}if(this.captured||this.running){this.captured&&!this.running&&this.start(!1,{}).catch(()=>{});continue}this.reconcilePending(i,o),this.charge(this.body,this.patch,this.base,i),this.dirty?(i.revision!==this.base.revision||Yr(i))&&(this.remote=_t(i),this.state="conflict",this.why=Gt("conflict","record changed while this draft was open","record_session_conflict").toProblem()):(this.base=_t(i),this.body=i.body,this.remote=null,this.state=Yr(i)?"conflict":this.restState,this.why=null),this.publish()}catch(i){if(e.aborted)return;if(t!==this.driveGeneration||this.running){this.refreshAgain=!this.running;continue}this.why=$a(i),this.state=this.why.code==="not_found"?"deleted":this.captured?"recovery":"error",this.publish()}}while(this.refreshAgain&&!e.aborted)})().finally(()=>{this.refreshRunning=null}),this.refreshRunning};observerProblem(e){this.active&&(this.why=e,this.state=this.captured?"recovery":"error",this.publish())}flush=(e={})=>(this.ensure(),this.clearTimer(),this.start(!0,e));start(e,t){let i=vp(t.timeoutMs??this.defaultTimeout),o=sT(i),s=AbortSignal.any([...t.signal?[t.signal]:[],o.signal]),r=this.running;if(r&&(this.writing||!e))return aT(r,s).finally(o.clear);let a=AbortSignal.any([this.life.signal,s]),c={until:Date.now()+i,margin:Math.min(2e3,Math.floor(i/4))},l=()=>(this.driveGeneration++,this.drive(a,c,e)),p=(r?r.then(l,l):l()).finally(()=>{this.driveGeneration++,o.clear(),this.running===p&&(this.running=null,this.writing=!1,this.schedule())});return this.running=p,this.writing=e,p}async drive(e,t,i){try{for(;;){if(e.throwIfAborted(),this.captured){await this.settle(e,t);continue}if(!i)return this.restState==="saved"?{ok:!0,record:_t(this.base)}:{ok:!0,record:_t(this.base),saved:"on_device"};let{current:o,receipts:s}=await this.readWithReceipts(e);if(this.reconcilePending(o,s),Yr(o))throw this.charge(this.body,this.patch,this.base,o),this.remote=_t(o),Gt("conflict","native hold/unresolved edits require native resolution before saving","native_protection_resolution_required");if(this.state==="deleted")throw Gt("conflict","the original record was deleted","record_deleted");if(!this.dirty)return this.charge(o.body,this.patch,o,null),this.base=_t(o),this.body=o.body,this.remote=null,this.state=this.restState,this.why=null,this.publish(),this.restState==="saved"?{ok:!0,record:_t(o)}:{ok:!0,record:_t(o),saved:"on_device"};if(o.revision!==this.base.revision||this.state==="conflict")throw this.charge(this.body,this.patch,this.base,o),this.remote=_t(o),Gt("conflict","explicitly resolve the current native revision before saving","record_session_conflict");Da(this.base,this.id),this.base=_t(o);let r=this.body,a=new Map(this.patch),c=zi(),l={bound:!0,body:r,patch:a,recovery:{mutationId:c,recordId:this.id,baseRevision:this.base.revision,receipt:null,write:null}};this.charge(this.body,this.patch,this.base,this.remote,this.lastReceipt,l),this.captured=l,this.state="saving",this.why=null,this.publish();let p={ifRevision:this.base.revision};this.requireLive&&(p.requireLive=!0),r!==this.base.body&&(p.body=r);let d=new Map,u=[];for(let[h,m]of a)m===void 0?u.push(h):d.set(h,m);d.size&&(p.patch=d),u.length&&(p.unset=u);let f;try{f=await this.client.update(_t(this.base),p,{mutationId:c,include:wp,conflictMode:"reject",signal:e})}catch(h){throw h instanceof xs&&(this.captured=null),h}if(e.throwIfAborted(),f.mutationId!==c)throw Gt("outcome_unknown","native write changed its original mutation identity","mutation_identity_mismatch");this.captured.recovery={...this.captured.recovery,write:f,receipt:f.receipt},this.publish()}}catch(o){if(this.why=$a(o),!this.captured&&this.why.code==="conflict"&&!this.remote)try{let s=await this.read(e);this.charge(this.body,this.patch,this.base,s),this.remote=_t(s)}catch(s){this.why=$a(s)}return this.state=this.captured?"recovery":this.why.code==="conflict"?"conflict":this.why.code==="not_found"?"deleted":this.why.code==="outcome_unknown"?"recovery":"error",this.publish(),{ok:!1,problem:this.why}}}async settle(e,t){let i=this.captured,o=i.recovery,s=await this.client.awaitReceipt(o.mutationId,{timeoutMs:Math.max(1,t.until-Date.now()-t.margin),signal:e});if(e.throwIfAborted(),s.mutation!==o.mutationId)throw Gt("outcome_unknown","native receipt belongs to another mutation","mutation_identity_mismatch");let r=s.records?.some(f=>f.id===o.recordId)??!1;if(s.records?.length&&!r||!i.bound&&s.state==="confirmed"&&!r)throw Gt("outcome_unknown","receipt does not bind the original native record identity","receipt_record_witness_required");if(r&&(i.bound=!0),this.charge(this.body,this.patch,this.base,this.remote,s),this.lastReceipt=s,i.recovery={...o,receipt:s},this.publish(),s.state==="unknown")throw Gt("outcome_unknown","original native mutation is not settled; no resubmit","record_receipt_pending");if(s.state==="rejected"||s.status==="conflicted")throw this.captured=null,s.problem?new oe(s.problem):Gt("conflict","original mutation conflicted","record_session_conflict");let a=await this.read(e),c=s.state==="pending",l=new Map(this.pendingEdits),p=new Map(i.patch);i.body!==this.base.body&&p.set(null,i.body);for(let[f,h]of p)c?l.set(f,{mutation:s.mutation,value:h}):l.delete(f);if(c?Yr(a)||[...p].some(([f,h])=>!bf(a,f,h)):!za(a))throw Gt("outcome_unknown","record readback does not qualify the native receipt","unqualified_readback");let d=this.body===i.body,u=!c&&!d&&a.body!==i.body&&a.body!==this.body;this.charge(this.body,this.patch,a,u?a:null,s,null,l),this.pendingEdits=l;for(let[f,h]of i.patch){let m=this.patch.get(f);this.patch.has(f)&&(h===void 0?m===void 0:m!==void 0&&Xb(h,m))&&this.patch.delete(f)}if(this.base=_t(a),d&&(this.body=a.body),this.captured=null,this.remote=u?_t(a):null,u)throw Gt("conflict","record body changed while saving an earlier draft","record_session_conflict");this.state=this.dirty?"unsaved":this.restState,this.why=null,this.publish()}resolve=e=>{if(this.ensure(),this.captured||this.running)throw Gt("outcome_unknown","recover the original mutation before resolving or preparing another","record_recovery_required");let t=this.remote;if(!t||!za(t))throw Gt("conflict","a confirmed unprotected native record is required for resolution","native_protection_resolution_required");let i="body"in e?e.body:e.keep==="theirs"||this.body===this.base.body?t.body:this.body,o="keep"in e&&e.keep==="theirs"?new Map:this.patch;this.charge(i,o,t,null),this.base=_t(t),this.body=i,this.patch=o,this.remote=null,this.state=this.dirty?"unsaved":"saved",this.why=null,this.publish(),this.schedule()}}});var vf,oP=I(()=>{"use strict";re();ve();rP();gf();vf=class{constructor(e){this.client=e}client;slots=new Map;bytes=0;closed=!1;opening=Promise.resolve();watch=null;offWatch=null;offStatus=null;open(e,t={}){let i={...t,autosave:t.autosave?{...t.autosave}:t.autosave,...t.recovery?{recovery:{...t.recovery}}:{}};if(i.recovery&&(i.recovery={...i.recovery,mutationId:M.dec(M.enc(i.recovery.mutationId)),recordId:M.dec(M.enc(i.recovery.recordId))},i.recovery.baseRevision!==null&&Z.enc(i.recovery.baseRevision)),vp(i.timeoutMs),i.autosave&&(!Number.isSafeInteger(i.autosave.idleMs)||i.autosave.idleMs<1||i.autosave.idleMs>12e4))throw A("invalid_request","record autosave idleMs must be 1..120000","invalid_autosave");let o=typeof e=="string"?e:"id"in e?e.id:{path:e.path},s=this.opening.catch(()=>{}).then(()=>this.acquire(o,i));return this.opening=s.then(()=>{},()=>{}),s}async acquire(e,t){if(this.closed)throw A("unavailable","record sessions client closed");t.signal?.throwIfAborted();let i=await this.client.get(e,{include:wp,signal:t.signal});if(t.signal?.throwIfAborted(),this.closed)throw A("unavailable","record sessions client closed");Da(i);let o=typeof e=="string"?e:"id"in e?e.id:void 0,s=o===void 0?void 0:M.dec(M.enc(o));if(s!==void 0&&s!==i.id)throw A("invalid_request","record open readback changed the requested UUID","record_identity_mismatch");let r=JSON.stringify([t.autosave?t.autosave.idleMs:!1,t.timeoutMs??3e4,t.requireLive??!1]),a=this.slots.get(i.id);if(a&&a.leases>0&&a.policy!==r)throw A("invalid_request","active record leases must use the same editing policy","record_lease_policy");if(a)await a.session.restore(t.signal,t.recovery),t.signal?.throwIfAborted();else{if(this.slots.size>=64)throw A("invalid_request","retained record sessions exceed 64; settle drafts before opening more","record_session_budget");a={session:null,leases:0,bytes:0,policy:r};let h=a;try{a.session=new wf(this.client,i,m=>{let w=this.bytes-h.bytes+m;if(w>bp)throw A("invalid_request","record session retained data exceeds 8MiB","record_session_budget");this.bytes=w,h.bytes=m}),await a.session.restore(t.signal,t.recovery),t.signal?.throwIfAborted()}catch(m){throw this.bytes-=h.bytes,m}this.slots.set(i.id,a)}a.leases++,a.policy=r,a.session.resume(t),this.startWatch();let c=a,l=!1,p=new Set,d=()=>{if(l)throw A("cancelled","record lease released")},u=Object.freeze({getSnapshot:c.session.getSnapshot,subscribe:h=>{d();let m=c.session.subscribe(h);return p.add(m),()=>{p.delete(m),m()}},setBody:h=>{d(),c.session.setBody(h)},patchFrontmatter:h=>{d(),c.session.patchFrontmatter(h)},resolve:h=>{d(),c.session.resolve(h)},flush:h=>(d(),c.session.flush(h))}),f=()=>{if(!l){l=!0,t.signal?.removeEventListener("abort",f);for(let h of p)h();p.clear(),--c.leases===0&&(c.session.suspend(),c.session.retained||(this.bytes-=c.bytes,this.slots.delete(i.id))),[...this.slots.values()].some(h=>h.leases>0)||this.stopWatch()}};return t.signal?.addEventListener("abort",f,{once:!0}),t.signal?.aborted&&(f(),t.signal.throwIfAborted()),c.session.refresh(),Object.freeze({session:u,release:f})}startWatch(){if(this.watch)return;let e=this.client.watchChanges(i=>{for(let[o,s]of this.slots)s.leases>0&&(i.reset||i.changes.some(r=>r.id===o))&&s.session.refresh()});this.watch=e;let t=-1;this.offStatus=this.client.onStatus(i=>{let o=i.pending<t;if(t=i.pending,o&&this.watch===e)for(let s of this.slots.values())s.leases>0&&s.session.refresh()}),this.offWatch=e.subscribe((i,o)=>{if(this.watch===e){if(i==="active")for(let s of this.slots.values())s.leases>0&&s.session.refresh();else if(o)for(let s of this.slots.values())s.leases>0&&s.session.observerProblem(o.toProblem())}}),e.ready.catch(i=>{if(this.watch===e)for(let o of this.slots.values())o.leases>0&&o.session.observerProblem($a(i))})}stopWatch(){this.offWatch?.(),this.offWatch=null,this.offStatus?.(),this.offStatus=null;let e=this.watch;this.watch=null,e?.()}dispose(){this.closed=!0,this.stopWatch();for(let e of this.slots.values())e.session.suspend()}}});function lT(n,e){let t=Bi(de(n,"properties")),i=[];for(let o of _f(de(e,"select"))){let s=Bi(o),r=Cn(o),a=s?Cn(de(s,"name")):r?.slice(r.lastIndexOf(".")+1);if(!a)continue;let c=Bi(de(t,s||!r?a:r))??Bi(de(t,a)),l={key:a},p=Cn(de(s,"label"))??Cn(de(c,"label")),d=Cn(de(s,"description"))??Cn(de(c,"description")),u=Cn(de(c,"format")),f=de(c,"hidden");p!==void 0&&(l.label=p),d!==void 0&&(l.description=d),u!==void 0&&(l.format=u),typeof f=="boolean"&&(l.hidden=f),i.push(l)}return i}async function cP(n,e={}){let{folder:t,signal:i}=e,o=[],s=[],r=t?t.replace(/\/?$/,"/"):"",a,c=!0;do{let l;try{l=await n.queryContract(_p,{...a?{cursor:a}:{},...i?{signal:i}:{}})}catch(p){if(X(p,"not_found")&&p.reason==="data_contract_not_found")return{sources:o,diagnostics:s,complete:!0};throw p}c&&=l.page.complete,l.records.forEach((p,d)=>{let u=l.page.records[d];if(!u.path.startsWith(r))return;let f=p.implementations[0],h=f?.issues.find(g=>g.severity==="error");if(!f||h){s.push(sP("invalid_view",h?.message??"View record does not implement mdbase.view.",u.path));return}let m=f.fields,w=[],b=new Set;for(let g of _f(de(m,"views"))){let y=Bi(g),_=Cn(de(y,"id")),v=Cn(de(y,"name"));if(!y||!_||!v)continue;if(b.has(_)){s.push(sP("invalid_view","View record contains duplicate named-view IDs.",u.path));return}b.add(_);let k={id:_,name:v,properties:lT(m,y)},S=de(y,"presentation");S!==void 0&&(k.presentation=S),w.push(k)}o.push({record:u.id,id:Cn(de(m,"id"))??u.path,name:Cn(de(m,"name"))??u.path,source:{path:u.path,format:_p.id,revision:u.revision,writable:!0},views:w})}),a=l.page.cursor}while(a);return o.sort((l,p)=>l.source.path<p.source.path?-1:l.source.path>p.source.path?1:0),{sources:o,diagnostics:s,complete:c}}async function pP(n,e,t,i={}){let o=i.signal,s=await n.getContract(e,_p,{signal:o}).catch(v=>aP(v,lP(e))),r=s.fields,a=s.path,c=_f(de(r,"views")).map(Bi),l=c.map(v=>Cn(de(v,"id")));if(new Set(l).size!==l.length)throw A("invalid_request","View record contains duplicate named-view IDs.","invalid_view");let p=c[l.indexOf(t)];if(!p)throw A("not_found",`named view '${t}' was not found`,"view_not_found");let d=Bi(de(r,"query")),u=new Map,f=de(p,"types")??de(d,"types");f!==void 0&&u.set("types",f);let h=[Cn(de(d,"where")),Cn(de(p,"where"))].filter(v=>!!v);h.length&&u.set("where",h.length===2?`(${h[0]}) && (${h[1]})`:h[0]);let m=new Map(Object.entries(Bi(de(d,"projections"))??{}));for(let[v,k]of Object.entries(Bi(de(p,"projections"))??{})){let S=m.get(v);if(S!==void 0&&Af(S)!==Af(k))throw A("invalid_request",`Projection '${v}' has conflicting definitions.`,"invalid_view");m.set(v,k)}m.size&&u.set("projections",Object.fromEntries(m));for(let v of["select","order_by","group_by","summaries","limit","offset","include_body","frontmatter_mode"]){let k=de(p,v);k!==void 0&&u.set(v,k)}let w=de(r,"summary_functions");w!==void 0&&u.set("summary_functions",w),i.limit!==void 0&&u.set("limit",i.limit),i.offset!==void 0&&u.set("offset",i.offset),i.timezone!==void 0&&u.set("timezone",i.timezone);let b=Bi(de(Bi(de(p,"context")??de(d,"context")),"this")),g=Cn(de(b,"on_missing"))??"view",y=i.context;if(y===void 0&&g==="error")throw A("invalid_request","This named view requires an invocation context.","context_required");if(y===void 0&&g==="view"&&(y={path:a}),y!==void 0){let v=_f(de(b,"types")).filter(S=>typeof S=="string"),k=typeof y=="string"?void 0:y.path;if(v.length||k===void 0){let S=await n.get(y,{signal:o});if(k=S.path,v.length&&!S.types.some(x=>v.some(P=>P.toLowerCase()===x.toLowerCase())))throw A("invalid_request","The invocation context does not match an allowed context type.","context_type_mismatch")}u.set("context",{this:{path:k}})}return{...await n.query(Object.fromEntries(u),{include:i.include,signal:o}),view:{path:a,view:t}}}async function dP(n,e,t={}){let i=t.signal,o=await n.getContract(e,_p,{signal:i}).catch(r=>aP(r,lP(e))),s=await n.get(o.id,{include:{document:!0},signal:i});if(s.revision!==o.revision||typeof s.document!="string")throw A("unavailable","saved view source changed while it was read","view_source_changed");return{path:s.path,format:_p.id,revision:s.revision,document:s.document,record:s.id}}function Af(n){return Array.isArray(n)?`[${n.map(Af).join(",")}]`:n!==null&&typeof n=="object"?`{${Object.keys(n).sort().map(e=>`${JSON.stringify(e)}:${Af(n[e])}`).join(",")}}`:JSON.stringify(n)}var _p,Bi,_f,Cn,sP,aP,lP,uP=I(()=>{"use strict";re();un();_p=Object.freeze({id:"mdbase.view",version:"1.0.0"}),Bi=n=>n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0,_f=n=>Array.isArray(n)?n:[],Cn=n=>typeof n=="string"?n:void 0,sP=(n,e,t)=>({code:n,severity:"warning",message:e,details:{path:t}}),aP=(n,e)=>{throw X(n,"not_found")?A("not_found",`saved view source '${e}' was not found`,"view_not_found"):n},lP=n=>typeof n=="string"?n:n.path});function Jr(n){return A("invalid_request",n,"view_source_witness_required")}function Zb(n){try{M.enc(n)}catch{throw Jr("view source writes need their original record and mutation UUIDs")}}function fP(n){if(!n||typeof n.path!="string"||n.path.length===0||typeof n.document!="string")throw Jr("view source update needs the complete RecordView read with document included");Zb(n.id);try{Z.enc(n.revision)}catch{throw Jr("view source needs its original source revision")}if(Di(n.document)!==n.revision)throw Jr("view source document differs from its captured revision")}function hP(n){return Zb(n?.mutationId),{...n,include:{...n.include,document:!0}}}async function kf(n,e,t={}){let i=typeof e=="string"?e:"id"in e?e.id:void 0,o=i===void 0?void 0:M.dec(M.enc(i)),s=await n.get(e,{include:{...t.include,document:!0},signal:t.signal});if(fP(s),o!==void 0&&s.id!==o)throw Jr("view source readback belongs to another record");return s}function Sf(n,e,t){if(Zb(e?.id),typeof e.path!="string"||e.path.length===0||typeof e.document!="string")throw Jr("view source create needs the exact path and complete source document");let i={id:e.id,path:e.path,document:e.document};return e.type!==void 0&&(i.type=e.type),n.create(i,hP(t))}function Pf(n,e,t,i){fP(e);let o=e.state;if(!o||o.state!=="pending"&&o.state!=="confirmed"||!Number.isSafeInteger(o.confirmedSeq)||o.confirmedSeq<0)throw Jr("view source update needs actual native record state, not inferred confirmation");if(o.hold!==void 0||o.unresolved!==void 0&&o.unresolved!==0)throw Jr("resolve the original view source hold or unresolved mutation before replacing its document");if(typeof t!="string")throw Jr("view source update needs complete source text");return n.replaceDocument(e,t,{...hP(i),ifRevision:e.revision})}var Qb=I(()=>{"use strict";ve();re();mr()});var mP,yP,gP=I(()=>{"use strict";ve();en();mP=z("contract-record-v1",[[0,"version",F],[1,"id",M],[2,"path",T],[3,"revision",Z],[4,"type",T],[5,"fields",kn],[6,"contractDigest",Z],[7,"implementationDigest",Z]]),yP=z("contract-write-plan-v1",[[0,"version",F],[1,"type",T],[2,"patch",kn],[3,"unset",G(T)],[4,"base",G(Nu)],[5,"contractDigest",Z],[6,"implementationDigest",Z],[7,"id",M,"opt"],[8,"path",T,"opt"],[9,"revision",Z,"opt"]])});var bP,wP=I(()=>{"use strict";ve();en();bP=z("contract-query-v1",[[0,"version",F],[1,"page",Xc],[2,"records",G(z("contract-query-record",[[0,"id",M],[1,"implementations",G(z("contract-projection",[[0,"typeName",T],[1,"fields",kn],[2,"issues",G(Fr)]]))]]))],[3,"contractDigest",Z]])});var xf,vP=I(()=>{"use strict";xf=class{byId=new Map;order=[];cached=[];complete=!1;asOf=0;stale=!0;metadata;get records(){return this.cached??=this.order.map(e=>this.byId.get(e)).filter(Boolean)}get(e){return this.byId.get(e)}markStale(){this.stale=!0,this.metadata=void 0}apply(e){switch(e.kind){case"reset":this.stale=!0;break;case"snapshot":{this.byId.clear(),this.order=[];for(let t of e.added??[])this.byId.has(t.id)||this.order.push(t.id),this.byId.set(t.id,t);e.order&&this.reorder(e.order),this.stale=!1;break}case"diff":{if(e.removed?.length){let t=new Set(e.removed);for(let i of t)this.byId.delete(i);this.order=this.order.filter(i=>!t.has(i))}for(let t of e.changed??[])this.byId.has(t.id)||this.order.push(t.id),this.byId.set(t.id,t);for(let t of e.added??[])this.byId.has(t.id)||this.order.push(t.id),this.byId.set(t.id,t);e.order&&this.reorder(e.order);break}}this.metadata=e.kind==="reset"||this.stale?void 0:e.metadata,this.complete=e.complete,this.asOf=e.asOf,this.cached=null}reorder(e){let t=new Set,i=[];for(let o of e)this.byId.has(o)&&!t.has(o)&&(t.add(o),i.push(o));for(let o of this.order)t.has(o)||i.push(o);this.order=i}}});function _P(n){return n instanceof oe?n.recovery==="retry"?!0:n.code==="invalid_request"&&(n.reason==="cursor_stale"||n.reason==="cursor_expired")||n.code==="conflict"&&n.reason==="collection_changed":!1}var cT,pT,dT,ew,uT,fT,AP,hT,mT,Ba,tw=I(()=>{"use strict";re();cT=1e3,pT=500,dT=8,ew=250,uT=3e4;fT=n=>n instanceof oe?n.toProblem():{code:"internal",recovery:"contact_support",message:n instanceof Error?n.message:String(n)},AP=n=>n.replace(/[A-Z]/g,e=>e.toLowerCase()),hT=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),mT=(n,e)=>n.revision===e.revision&&n.path===e.path&&n.state.state===e.state.state&&n.state.hold?.id===e.state.hold?.id&&n.state.unresolved===e.state.unresolved&&hT(n.types,e.types),Ba=class{constructor(e,t={}){this.client=e;this.signal=t.signal,this.pending=e.status.pending,this.types=t.types?.length?[...t.types]:void 0,this.folded=this.types?.map(AP),this.include=t.include?{...t.include}:void 0,this.ready=new Promise((i,o)=>{this.resolveReady=i,this.rejectReady=o}),this.ready.catch(()=>{}),this.offStatus=e.onStatus(i=>{let o=i.pending<this.pending;if(this.pending=i.pending,!!o){for(let s of this.byId.values())s.state.state==="pending"&&this.queued.add(s.id);this.work()}}),this.startWatch(),this.signal?.addEventListener("abort",this.abort,{once:!0}),this.signal?.aborted&&this.close()}client;ready;resolveReady;rejectReady;lifetime=new AbortController;listeners=new Set;types;folded;include;byId=new Map;view=Object.freeze({records:Object.freeze([]),state:"loading",problem:null});touched=!1;state="loading";problem=null;watch;offWatch=()=>{};offStatus;abort=()=>this.close();cursor;queued=new Set;loaded=!1;dirty=!0;working=!1;timer;again;delay=ew;pending;signal;getSnapshot=()=>this.view;get(e){return this.byId.get(e)}subscribe=e=>(this.state!=="closed"&&this.listeners.add(e),()=>{this.listeners.delete(e)});reload(){return this.state==="closed"?Promise.reject(A("cancelled","record set closed")):(this.dirty=!0,this.delay=ew,this.state==="failed"&&(this.problem=null,this.publish(this.loaded?"stale":"loading"),(this.watch.state==="failed"||this.watch.state==="closed")&&this.startWatch()),new Promise((e,t)=>{let i=this.subscribe(()=>{this.state==="current"&&!this.dirty?(i(),e()):(this.state==="failed"||this.state==="closed")&&(i(),t(new oe(this.problem??{code:"cancelled",recovery:"none",message:"record set closed"})))});this.resume()}))}close(){this.state!=="closed"&&(this.lifetime.abort(),this.cancelRetry(),this.signal?.removeEventListener("abort",this.abort),this.offStatus(),this.offWatch(),this.watch(),this.rejectReady(A("cancelled","record set closed")),this.publish("closed"),this.listeners.clear())}startWatch(){this.offWatch();let e=this.client.watchChanges(t=>{this.watch===e&&this.changed(t)},{cursor:this.cursor});this.watch=e,this.cursor===void 0&&(this.dirty=!0),this.offWatch=e.subscribe((t,i)=>{if(!(this.watch!==e||this.state==="closed"||this.state==="failed")){if(t==="active"){this.work();return}if(t==="stale"){this.loaded&&this.publish("stale");return}if(t==="closed"){this.close();return}t==="failed"&&(i&&_P(i)&&this.client.link!=="closed"?this.retry(i,()=>this.startWatch()):this.fail(i??A("unavailable","the change watch stopped")))}})}changed(e){this.cursor=e.cursor,e.reset&&(this.dirty=!0);for(let t of e.changes)t.entity!=="file"&&(t.kind==="put"&&this.types&&t.types&&!this.byId.has(t.id)&&!this.member(t.types)||t.kind==="remove"&&!this.byId.has(t.id)||this.queued.add(t.id));this.work()}member(e){return!this.folded||e.some(t=>this.folded.includes(AP(t)))}async work(){if(!(this.working||this.timer!==void 0)){this.working=!0;try{for(;this.state!=="closed"&&this.state!=="failed"&&this.watch.state==="active"&&(this.dirty||this.queued.size);){if(!this.dirty&&this.queued.size<=pT)await this.reread();else if(!await this.load()){this.retry(null,()=>{this.work()});return}this.delay=ew}}catch(e){if(this.state==="closed"||X(e,"cancelled"))return;_P(e)?this.retry(e,()=>{this.work()}):this.fail(e);return}finally{this.working=!1}this.state==="closed"||this.state==="failed"||this.watch.state!=="active"||(this.problem=null,this.publish("current"),this.resolveReady())}}retry(e,t){this.problem=e?.toProblem()??null,this.publish(this.loaded?"stale":"loading");let i=this.delay;this.delay=Math.min(i*2,uT),clearTimeout(this.timer),this.again=t,this.timer=setTimeout(()=>this.resume(),i)}resume(){clearTimeout(this.timer),this.timer=void 0;let e=this.again??(()=>{this.work()});this.again=void 0,this.state!=="closed"&&e()}cancelRetry(){clearTimeout(this.timer),this.timer=void 0,this.again=void 0}fail(e){this.cancelRetry(),this.problem=fT(e),this.rejectReady(e instanceof oe?e:new oe(this.problem)),this.publish("failed")}async load(){let e=this.lifetime.signal;this.dirty=!1,this.queued.clear(),this.publish(this.loaded?"stale":"loading");let t=new Map,i=!0;try{let r={...this.types?{types:[...this.types]}:{},limit:cT};for await(let a of this.client.pages(r,{include:this.include,signal:e})){for(let c of a.records)t.set(c.id,c);i&&=a.complete,this.loaded||this.apply(a.records.map(c=>({record:c})),this.state)}}catch(r){throw this.dirty=!0,r}let o=[...t.values()].map(r=>({record:r})),s=[...this.byId.keys()].filter(r=>!t.has(r)).map(r=>({id:r}));return this.loaded||=i,i||(this.dirty=!0),this.apply([...o,...s],this.state),i}async reread(){let e=this.lifetime.signal,t=[...this.queued];this.queued.clear();let i=new Array(t.length),o=0;try{await Promise.all(Array.from({length:Math.min(dT,t.length)},async()=>{for(;o<t.length;){let s=o++;i[s]=await this.client.find(t[s],{include:this.include,signal:e})}}))}catch(s){for(let r of t)this.queued.add(r);throw s}this.apply(t.map((s,r)=>i[r]&&this.member(i[r].types)?{record:i[r]}:{id:s}),this.state)}apply(e,t){let i=[];for(let o of e){let s="record"in o?o.record.id:o.id,r=this.byId.get(s);"record"in o?(this.byId.set(s,o.record),r?mT(r,o.record)||i.push({kind:"put",record:o.record,previous:r}):i.push({kind:"put",record:o.record})):r&&(this.byId.delete(s),i.push({kind:"remove",previous:r}))}this.touched||=e.length>0,this.publish(t,i)}publish(e,t=[]){if(this.state==="closed")return;let i=e==="current"?null:this.problem;if(!(!this.touched&&e===this.state&&i===this.view.problem)){this.state=e,this.view=Object.freeze({records:this.touched?Object.freeze([...this.byId.values()]):this.view.records,state:e,problem:i}),this.touched=!1;for(let o of[...this.listeners])try{o(t)}catch{}}}}});var kP,yT,Va,nw=I(()=>{"use strict";ve();re();mr();en();kP=4096,yT=100,Va=class{constructor(e){this.client=e;e.onSession(async t=>{this.wire(t);for(let[i,o]of this.joined)await t.request("presence_join",this.params(i,o.state));for(let i of this.watchers.keys())await t.request("subscribe_presence",new Map([[0,M.enc(i)]]))})}client;joined=new Map;watchers=new Map;wired=new WeakSet;wire(e){this.wired.has(e)||(this.wired.add(e),e.onPush("presence",t=>{try{let i=_o(Vu,t);for(let o of this.watchers.get(i.record)??[])o(i.peers)}catch{}}))}params(e,t){return new Map([[0,M.enc(e)],[1,t]])}check(e){if(JSON.stringify(e,(i,o)=>typeof o=="bigint"?o.toString():o instanceof Map?[...o]:o).length>kP)throw A("too_large","presence state over 4 KiB",{details:{limit:kP}})}async join(e,t){let i=Fe(t);this.check(i),this.joined.set(e,{state:i,last:Date.now(),timer:null});let o=await this.client.ready();this.wire(o),await o.request("presence_join",this.params(e,i))}update(e,t){let i=this.joined.get(e);if(!i)throw A("invalid_request","join the record's presence first");if(i.state=Fe(t),this.check(i.state),i.timer)return;let o=Math.max(0,i.last+yT-Date.now());i.timer=setTimeout(()=>{i.timer=null,i.last=Date.now(),this.joined.get(e)===i&&this.client.call("presence_update",this.params(e,i.state)).catch(()=>{})},o)}async leave(e){let t=this.joined.get(e);t?.timer&&clearTimeout(t.timer),this.joined.delete(e),await this.client.call("presence_leave",new Map([[0,M.enc(e)]])).catch(()=>{})}subscribe(e,t){let i=this.watchers.get(e),o=!i;return i||this.watchers.set(e,i=new Set),i.add(t),o&&this.client.ready().then(s=>(this.wire(s),s.request("subscribe_presence",new Map([[0,M.enc(e)]])))).catch(()=>{}),()=>{i.delete(t),i.size===0&&this.watchers.delete(e)}}}});function SP(n){try{let e=we(n);if(!(e instanceof Map))return null;let t=e.get(2),i=e.get(3);return!(t instanceof Uint8Array)||typeof i!="number"?null:{device:ut(t),seq:i}}catch{return null}}function bT(n){return n.replace(/-/g,"").toLowerCase()}function PP(n,e,t){if(!t)return;let i=SP(e);if(!i||bT(t)!==i.device)return;let o=iw.get(n);o||iw.set(n,o=new Map);let s=o.get(i.device);if(!s){if(o.size>=gT)return;o.set(i.device,s=new Map)}let r="self",a=s.get(r);(!a||a[0]<i.seq)&&s.set(r,[i.seq,e])}function xP(n,e){let t=e?SP(e)?.device:void 0,i=[];for(let[o,s]of iw.get(n)??[])if(o!==t)for(let[,r]of s.values())i.push(r);return i}var gT,iw,CP=I(()=>{"use strict";Je();gT=64,iw=new Map});function Vn(n,e){return e===void 0?{}:{[n]:e}}function rw(n){let e=Is(n);return{id:it(e.id),version:it(e.version),digest:it(e.digest),installedBy:it(e.installed_by),resources:(Array.isArray(e.resources)?e.resources:[]).map(t=>{let i=Is(t);return{source:it(i.source),target:it(i.target),kind:it(i.kind),mode:it(i.mode),digest:it(i.digest),...Vn("originDigest",it(i.origin_digest))}})}}function AT(n){let e=Is(n),t=e.upgrade_baseline===void 0?void 0:Is(e.upgrade_baseline),i=t&&(typeof t.version=="number"?t.version:typeof t.version=="string"?Number(t.version):void 0);return{source:it(e.source)??"",target:it(e.target),kind:it(e.kind),mode:it(e.mode),action:it(e.action),...Vn("digest",it(e.digest)),...Vn("currentDigest",it(e.current_digest)),...Vn("installedDigest",it(e.installed_digest)),...Vn("adoptedFromDigest",it(e.adopted_from_digest)),...Vn("upgradeBaseline",t&&{digest:it(t.digest),...Vn("version",i)}),...Vn("reason",it(e.reason))}}function kT(n,e){return e?n.installedDigest!==void 0?`${n.target} was changed after this pack installed it. Review it, then adopt it to replace it with this pack's version.`:`${n.target} already exists with different content. Review it, then adopt it to let this pack manage it.`:n.reason?`${n.target} can't be changed: ${n.reason}.`:`${n.target} can't be changed by this pack.`}function OP(n,e,t){let i=Is(n),o=(Array.isArray(i.resources)?i.resources:[]).map(AT),s=rw(i.desired),r=new Set(s.resources.map(h=>h.target)),a=Object.fromEntries(_T.map(h=>[h,o.filter(m=>m.action===h).map(m=>m.target)])),c={},l=o.filter(h=>h.action==="conflict").map(h=>{let m=h.mode==="managed"&&h.currentDigest!==void 0&&r.has(h.target);return m&&(c[h.target]=h.currentDigest),{target:h.target,kind:h.kind,...Vn("reason",h.reason),message:kT(h,m),...Vn("adoptable",m?{digest:h.currentDigest}:void 0)}}),p=it(i.status),d=Array.isArray(i.issues)?i.issues.map(Is):[],u;if(i.definitions_manage!==!0)u={code:"forbidden",message:"This app doesn't have permission to change the collection's types."};else if(p==="downgrade"){let h=i.current===void 0?"a newer version":`version ${rw(i.current).version}`;u={code:"type_pack_downgrade",message:`${s.id} ${h} is installed; ${s.version} is older.`}}else if(l.length){let h=l.length;u={code:"type_pack_conflict",message:Object.keys(c).length===h?`${h===1?"A type already exists":`${h} types already exist`} with different content. Review and adopt ${h===1?"it":"them"} to continue.`:l.map(m=>m.message).join(" ")}}else(d.length||i.applicable!==!0)&&(u={code:"invalid_type_pack",message:`This pack would leave the collection invalid: ${it(d[0]?.message)??"the staged types do not validate"}.`});let f=Is(i.lock);return Object.freeze({status:p,canApply:i.applicable===!0&&u===void 0,digest:it(i.assessment_digest),summary:a,conflicts:l,adoptable:c,resources:o,...Vn("current",i.current===void 0?void 0:rw(i.current)),desired:s,lock:{target:it(f.target),action:it(f.action),digest:it(f.digest)},...Vn("refusal",u),pack:e,options:t})}function IP(n){return n&&Object.keys(n).length?Fe(n):void 0}function ST(n){return n==null?!1:Array.isArray(n)?n.length>0:typeof n=="object"&&Object.keys(n).length>0}async function RP(n,e,t,i){if(ST(t.contractSetups))throw A("invalid_request","Contract setup during type pack install is not supported yet.","type_pack_contract_setups_unsupported");let o=new Map([["manifest",Fe(e.manifest)],["resources",e.resources.map(c=>new Map([["source",c.source],["document",c.document]]))]]);e.provides!==void 0&&o.set("provides",Fe(e.provides));let s=new Map([[0,1],[1,o],[2,t.installedBy]]),r=IP(t.adopt);r!==void 0&&s.set(3,r),t.preserveSeedTargets?.length&&s.set(4,[...t.preserveSeedTargets]);let a=IP(t.targetOverrides);a!==void 0&&s.set(5,a),t.allowDowngrade&&s.set(6,!0),i!==void 0&&s.set(7,Z.enc(i));try{let c=await n.call("plan_type_pack_v1",s,{codec:vT,retry:!0,...t.signal?{signal:t.signal}:{}});if(c.version!==1)throw A("upgrade_required","unsupported type pack plan","type_packs_unsupported");return c}catch(c){throw X(c,"invalid_request")&&c.reason==="unknown_method"?A("upgrade_required","This collection's replica can't install type packs yet.","type_packs_unsupported"):c}}async function EP(n,e,t){return OP((await RP(n,e,t)).assessment,e,t)}async function qP(n,e,t={}){if(e.refusal)throw A(PT[e.refusal.code],e.refusal.message,e.refusal.code);let i=t.signal?{...e.options,signal:t.signal}:e.options,o=await RP(n,e.pack,i,e.digest),s=OP(o.assessment,e.pack,e.options),r=o.writes??[];if(!r.length)return{outcome:"already_current",receipt:s.desired};let a=r.map(p=>p.doc===void 0?{kind:"resource_delete",path:p.path,...Vn("baseRevision",p.baseRevision)}:{kind:"resource_put",path:p.path,doc:p.doc,...Vn("baseRevision",p.baseRevision),...p.mustNotExist?{mustNotExist:!0}:{}}),c=await n.submit(a,t),l=c.receipt;if(l.state==="rejected"||l.state==="unknown")throw new oe(l.problem??(l.state==="unknown"?{code:"outcome_unknown",recovery:"resolve_outcome",message:"The type pack install outcome is unknown."}:{code:"internal",recovery:"contact_support",message:"The type pack install was rejected."}),{mutationId:l.mutation});if(t.dryRun)return{outcome:"preview",receipt:s.desired,write:c};if(l.status==="conflicted"||(l.conflicts?.length??0)>0)throw new oe({code:"conflict",recovery:"resolve_conflict",reason:"type_pack_conflict",message:"The type pack install has a conflict. Resolve it before continuing."},{mutationId:l.mutation});return{outcome:l.state==="confirmed"?"applied":"pending",receipt:s.desired,write:c}}var wT,vT,_T,Is,it,PT,TP=I(()=>{"use strict";ve();re();mr();wT=z("type-pack-write-v1",[[0,"path",T],[1,"doc",T,"opt"],[2,"baseRevision",Z,"opt"],[3,"mustNotExist",Ee]]),vT=z("type-pack-plan-v1",[[0,"version",F],[1,"assessment",Ht],[2,"writes",G(wT),"opt"]]),_T=["create","update","delete","adopt","unchanged","preserve","conflict"],Is=n=>n&&typeof n=="object"&&!Array.isArray(n)?n:{},it=n=>typeof n=="string"?n:void 0;PT={forbidden:"forbidden",type_pack_conflict:"conflict",type_pack_downgrade:"conflict",invalid_type_pack:"invalid_request",type_pack_contract_setups_unsupported:"invalid_request"}});function If(){let n=new Map;return{list:async()=>[...n.values()],put:async e=>{n.set(e.mutationId,e)},remove:async e=>{n.delete(e)}}}var ow,Ap,Cf,sw=I(()=>{"use strict";re();ow=n=>[...new Set(n.flatMap(e=>{let t=e,i=t.id??t.record;return typeof i=="string"?[i]:[]}))],Ap=(n,e,t,i,o=Date.now())=>i?{mutationId:n,records:e,createdAt:o,state:t,problem:i}:{mutationId:n,records:e,createdAt:o,state:t},Cf=class{constructor(e,t){this.store=e;this.native=t}store;native;entries=new Map;listeners=new Set;snapshot=null;io=Promise.resolve();deferred=!1;restored=!1;checking=!1;getSnapshot=()=>{let e=[...this.entries.values()];return this.snapshot??={pending:e.filter(t=>t.state==="pending"),rejected:e.filter(t=>t.state==="rejected"),saveState:this.stateOf(),restored:this.restored}};subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});stateOf(e){let t=!1;for(let i of this.entries.values())if(!(e!==void 0&&!i.records.includes(e))){if(i.state==="rejected")return"rejected";t=!0}return t?this.deferred?"saved_on_device":"saving":"saved"}async acknowledge(e){this.entries.get(e)?.state==="rejected"&&await this.drop(e)}get pendingCount(){return this.getSnapshot().pending.length}setDeferred(e){e!==this.deferred&&(this.deferred=e,this.changed())}begin(e,t){return this.set(Ap(e,ow(t),"pending"))}observe(e){let t=this.entries.get(e.mutation),i=t?.records??(e.records??[]).map(o=>o.id);e.state==="confirmed"?t&&this.drop(e.mutation):e.state==="pending"?t||this.set(Ap(e.mutation,i,"pending")):t?.state!=="rejected"&&this.set(Ap(e.mutation,i,"rejected",e.problem??(e.state==="unknown"?{code:"outcome_unknown",recovery:"resolve_outcome",message:"mutation unknown"}:{code:"internal",recovery:"contact_support",message:"mutation rejected"}),t?.createdAt))}async restore(){try{let[e,t]=await Promise.all([this.store.list().catch(()=>[]),this.native.pendingWrites().catch(()=>null)]);for(let o of t??[])this.entries.has(o.receipt.mutation)||this.entries.set(o.receipt.mutation,Ap(o.receipt.mutation,ow(o.ops),"pending"));for(let o of e)(o.state==="rejected"||!this.entries.has(o.mutationId))&&this.entries.set(o.mutationId,o);this.changed();let i=new Set(t?.map(o=>o.receipt.mutation));t&&await Promise.all(e.filter(o=>o.state==="pending"&&!i.has(o.mutationId)).map(o=>this.settle(o.mutationId)))}finally{this.restored=!0,this.changed()}}async recheck(){if(!this.checking){this.checking=!0;try{for(let e of this.getSnapshot().pending)await this.settle(e.mutationId)}finally{this.checking=!1}}}async adopt(){let e=await this.native.pendingWrites().catch(()=>null),t=!1;for(let i of e??[])this.entries.has(i.receipt.mutation)||(this.entries.set(i.receipt.mutation,Ap(i.receipt.mutation,ow(i.ops),"pending")),t=!0);t&&this.changed()}async settle(e){try{this.observe(await this.native.receipt(e))}catch(t){X(t,"not_found")&&this.entries.get(e)?.state==="pending"&&await this.drop(e)}}set(e){return this.entries.set(e.mutationId,e),this.changed(),this.persist(()=>this.entries.get(e.mutationId)===e?this.store.put(e):void 0)}drop(e){return this.entries.delete(e),this.changed(),this.persist(()=>this.entries.has(e)?void 0:this.store.remove(e))}persist(e){return this.io=this.io.then(e).catch(()=>{})}changed(){this.snapshot=null;for(let e of[...this.listeners])try{e()}catch{}}}});var Mf={};Ca(Mf,{LiveQuery:()=>Fa,MdbaseClient:()=>yr,Write:()=>Os,connect:()=>pw});function Ef(n){return n instanceof vt?new vt(n.value):n instanceof Date?new Date(n):Array.isArray(n)?n.map(e=>Ef(e)):n instanceof Map?new Map([...n].map(([e,t])=>[e,Ef(t)])):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Ef(t)])):n}function Of(n){return typeof n=="string"?M.enc(n):"id"in n&&typeof n.id=="string"?M.enc(n.id):n.path}function Rf(n){if(typeof n=="string")return n;if("id"in n)return n.id;throw A("invalid_request","this operation needs a record ID, not a path; get() the record first")}function qf(n){return n?Ra.enc(n):void 0}function MP(n){if(!(n instanceof Uint8Array)||n.length!==32)throw A("invalid_request","the account secret is 32 bytes","account_secret_length")}function Ke(n){let e=new Map;for(let[t,i]of n)i!==void 0&&e.set(t,i);return e}function zP(n){return n.catch(e=>{throw X(e,"invalid_request")&&e.reason==="unknown_method"?A("upgrade_required","This collection's replica has no record history.","history_unsupported"):e})}function lw(n,e){let t=n.grant;return!e||t.grant===e.grant&&t.role===e.role&&Oo(t.capabilities,e.capabilities)&&Oo(t.fileFolders??null,e.fileFolders??null)?n:{...n,grant:e}}async function $P(n,e){if(typeof e!="string"||!e)throw A("invalid_request","intent must be a non-empty string");let t=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`mdbase-intent/1\0${n}\0${e}`))),i=o=>{let s=t.slice(o,o+16);return s[6]=128|s[6]&15,s[8]=128|s[8]&63,Wc(s)};return[i(0),i(16)]}function cw(n){return n.state==="pending"||n.state==="confirmed"&&n.published==="publishing"}function Tf(n,e){let t=e.published;return t==="published"||t==="not_published"||n.published===void 0&&t!==void 0?{...n,published:t}:n}function pw(n){return yr.connect(n)}var aw,xT,LP,jP,UP,NP,DP,Os,Fa,CT,yr,Rs=I(()=>{"use strict";Wu();Je();Nb();wS();ve();PS();re();yp();QS();nP();Yb();oP();uP();Qb();gP();wP();vP();tw();nw();CP();Ua();hp();TP();mr();ff();en();sw();ve();en();aw=1e3,xT=new Set(["no_device_online","not_served","device_not_serving"]);LP="validate-page-v1",jP="bases-discovery-unreadable-v1",UP="bases-row-properties-v1",NP="contract-query-order-v1",DP="contract-query-order-mtime-v1";Os=class{constructor(e){this.receipt=e;this.confirmed=new Promise((t,i)=>this.settle={resolve:t,reject:i}),this.published=new Promise((t,i)=>this.settlePublished={resolve:t,reject:i}),this.confirmed.catch(()=>{}),this.published.catch(()=>{}),this.update(e)}receipt;listeners=new Set;settle;settlePublished;confirmed;published;recordId;get mutationId(){return this.receipt.mutation}get records(){return this.receipt.records??[]}get state(){return this.receipt.state}onReceipt(e){return this.listeners.add(e),()=>this.listeners.delete(e)}update(e){let t=e.records||!this.receipt.records?e:{...e,records:this.receipt.records};t=Tf(t,this.receipt),this.receipt=t;for(let i of[...this.listeners])i(this.receipt);if(e.state==="rejected"||e.state==="unknown"){let i=new oe(e.problem??{code:e.state==="unknown"?"outcome_unknown":"internal",recovery:e.state==="unknown"?"resolve_outcome":"contact_support",message:`mutation ${e.state}`},{mutationId:e.mutation});this.settle.reject(i),this.settlePublished.reject(i)}else{let i=this.receipt.published;(i==="published"||i==="not_published"||e.state==="confirmed"&&i===void 0)&&this.settlePublished.resolve(this.receipt),e.state==="confirmed"&&this.settle.resolve(this.receipt)}}},Fa=class{constructor(e,t,i){this.client=e;this.query=t;this.include=i;this.ready=new Promise((o,s)=>(this.readyResolve=o,this.readyReject=s)),this.ready.catch(()=>{})}client;query;include;result=new xf;listeners=new Set;subId=null;closedFlag=!1;ready;readyResolve;readyReject;error=null;get records(){return this.result.records}get complete(){return this.result.complete}get asOf(){return this.result.asOf}get stale(){return this.result.stale}get metadata(){return this.result.metadata}get closed(){return this.closedFlag}get(e){return this.result.get(e)}subscribe(e){return this.listeners.add(e),e(this,null),()=>this.listeners.delete(e)}async setQuery(e,t={}){let{include:i=this.include}=t;this.query=e,this.include=i,this.result.markStale(),this.emit(null),await this.client._resubscribeLive(this)}close(){this.closedFlag||(this.closedFlag=!0,this.result.markStale(),this.client._closeLive(this),this.listeners.clear())}_params(){return Ke([[0,Fe(this.query)],[1,qf(this.include)]])}_setSub(e){this.subId=e}get _sub(){return this.subId}_apply(e){this.closedFlag||(this.result.apply(e),e.kind==="snapshot"&&(this.error=null,this.readyResolve()),this.emit(e))}_markStale(){this.result.markStale(),this.emit(null)}_fail(e,t){this.error=e,t&&this.readyReject(e),this.emit(null)}emit(e){for(let t of[...this.listeners])t(this,e)}},CT=new Set(["get","query","query_contract_v1","subscribe","changes","backlinks","list_resources","get_resource","describe","describe_typing","list_files","get_file","read_file","list_holds","list_conflicts","validate","new_type_file","get_contract_v1","map_contract_write_v1","plan_type_pack_v1","record_history","record_version"]),yr=class n{constructor(e,t){this.opts=e;this.session=t,this.collectionId=t.hello.collection,this.lastStatus=t.hello.status,this.currentHello=lw(t.hello,t.hello.status.grant),this.fenceReads=fp(e.connector),this.readFloor=t.hello.status.confirmedThrough,this.files=new Na(this),this.presence=new Va(this),this.writeLedger=new Cf(e.ledger??If(),{receipt:i=>this.receipt(i),pendingWrites:()=>this.pendingWrites()}),this.attach(t),t.request("subscribe_status",null).catch(()=>{}),e.ledger&&this.startLedger()}opts;session;linkState="open";linkError=null;linkListeners=new Set;lastStatus;currentHello;statusListeners=new Set;lives=new Set;livesBySub=new Map;subscribing=0;early=new Map;writes=new Map;unclaimed=new Map;reconnectWaiters=[];restorers=[];fenceHandler=null;fenceReads;readFloor;readFencedAt=null;readFenceWaiters=[];closing=!1;collectionId;holdsWatch={listeners:new Set,last:null};conflictsWatch={listeners:new Set,last:null};files;presence;writeLedger;ledgerStarted=!1;queryAnswered=!1;transportDeferred=!1;get ledger(){return this.startLedger(),this.writeLedger}startLedger(){if(this.ledgerStarted)return;this.ledgerStarted=!0;let e=-1;this.onStatus(t=>{let i=e>t.pending;e=t.pending,this.updateDeferred(),i?this.writeLedger.recheck():t.pending>this.writeLedger.pendingCount&&this.writeLedger.adopt()}),this.onLink(()=>this.updateDeferred()),this.writeLedger.restore()}updateDeferred(){this.writeLedger.setDeferred(this.transportDeferred||this.linkState!=="open"||this.lastStatus.connection==="offline")}setTransportDeferred(e){this.transportDeferred=e,this.ledgerStarted&&this.updateDeferred()}static async connect(e){let t=fp(e.connector);t&&(e={...e});let i=e.reconnect&&e.reconnect.minDelayMs||1e3,o=e.signal,s,r,a,c=()=>e.signal?.aborted||!a?A("cancelled","connect aborted"):a;try{for(;;)try{let l=o,p=await new Promise((d,u)=>{let f=()=>u(c());if(l?.aborted){f();return}l?.addEventListener("abort",f,{once:!0}),Cs.open(e.connector,n.helloParams(e),l).then(h=>{if(l?.removeEventListener("abort",f),l?.aborted){try{h.close()}catch{}u(c())}else d(h)},h=>{l?.removeEventListener("abort",f),u(h)})});if(o?.aborted)throw p.close(),c();return new n(e,p)}catch(l){if(o?.aborted)throw c();let p=t&&X(l,"unavailable")&&(l.reason==="grant_lease_expired"||l.reason==="authorization_unavailable");if(!(p||e.waitForDevice&&X(l,"unavailable")&&xT.has(l.reason??"")))throw l;p&&!s&&(s=new AbortController,a=A("unavailable","The approved grant did not become live within 30 seconds",{reason:"grant_activation_timeout",details:l.toProblem().details}),o=e.signal?AbortSignal.any([e.signal,s.signal]):s.signal,r=setTimeout(()=>s.abort(),3e4)),e.onWaiting?.(l),await new Promise((d,u)=>{let f=()=>{clearTimeout(m),o?.removeEventListener("abort",h)},h=()=>{f(),u(c())},m=setTimeout(()=>{f(),d()},p?Math.min(1e3,i):i);o?.aborted?h():o?.addEventListener("abort",h,{once:!0})}),i=Math.min(15e3,i*2)}}finally{clearTimeout(r)}}static helloParams(e){let t=e.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone;return{versions:df,clientName:e.app.name,clientVersion:e.app.version,features:[...new Set([...e.features??[],"declared-collection-setup-v1","file-stream-failure-v1",LP,jP,UP,NP,DP])],...t?{timezone:t}:{}}}get hello(){return this.currentSession(),this.currentHello}get collection(){return this.collectionId}get link(){return this.linkState}get linkProblem(){return this.linkError}onLink(e){return this.linkListeners.add(e),()=>this.linkListeners.delete(e)}close(){this.closing=!0,this.recordSessions.dispose(),this.session?.close(),this.setLink("closed"),this.wakeReadFence()}get readFenced(){return this.readFencedAt!==null}async readFence(e){if(this.fenceReads){for(;this.readFencedAt!==null;){if(this.linkState==="closed")throw this.linkError??A("unavailable","client closed");if(e?.aborted)throw A("cancelled","aborted while the replica catches up");await new Promise(t=>{let i=()=>{e?.removeEventListener("abort",i);let o=this.readFenceWaiters.indexOf(i);o>=0&&this.readFenceWaiters.splice(o,1),t()};this.readFenceWaiters.push(i),e?.addEventListener("abort",i,{once:!0})})}if(this.linkState==="closed")throw this.linkError??A("unavailable","client closed");if(e?.aborted)throw A("cancelled","aborted while the replica catches up")}}async readyForRead(e,t=!1){if(!this.fenceReads)return t?this.currentSession():this.ready({signal:e});for(;;){let i=t?this.currentSession():await this.ready({signal:e});if(await this.readFence(e),i===this.session&&!i.closed&&this.readFencedAt===null)return i;t&&this.currentSession()}}wakeReadFence(){for(let e of this.readFenceWaiters.splice(0))e()}noteReplica(e){if(!this.fenceReads)return;let t=e.hello.status.confirmedThrough<this.readFloor;this.readFencedAt=t?this.readFloor:null,t||this.wakeReadFence()}noteReceipt(e){this.ledgerStarted&&this.writeLedger.observe(e),this.fenceReads&&this.readFencedAt===null&&e.state==="confirmed"&&e.seq!==void 0&&(this.readFloor=Math.max(this.readFloor,e.seq))}currentSession(){if(!this.session||this.session.closed)throw this.linkState==="closed"&&this.linkError?this.linkError:A("unavailable","not connected to the replica",{reason:"reconnecting"});return this.session}async ready(e={}){let t=e.signal;for(;;){if(this.linkState==="closed")throw this.linkError??A("unavailable","client closed");if(this.session&&!this.session.closed)return this.session;if(t?.aborted)throw A("cancelled","aborted while reconnecting");await new Promise(i=>{this.reconnectWaiters.push(i),t?.addEventListener("abort",()=>i(),{once:!0})})}}async call(e,t,i={}){let o=i.codec,s=this.fenceReads&&CT.has(e),r=!1;for(;;){let a=s?await this.readyForRead(i.signal,!i.retry):i.retry?await this.ready({signal:i.signal}):this.currentSession();try{let c=await a.request(e,t,{...i.signal?{signal:i.signal}:{},...o?{codec:ku(o)}:{}});if(s&&(a!==this.session||a.closed||this.closing)){if(i.retry&&!this.closing)continue;throw A("unavailable","the session changed during the read",{reason:"reconnecting"})}return a===this.session&&!a.closed&&!this.closing&&o===Sn&&(e==="receipt"||e==="await")&&this.noteReceipt(c),c}catch(c){let l=X(c,"unavailable")&&a.closed;if(!(i.retry&&l&&this.opts.reconnect!==!1&&!this.closing))throw r&&ja(c)?new oe(c.toProblem(),{cause:c}):c;r=!0}}}onSession(e){this.restorers.push(e)}relayWitnesses(e){let t=e.hello.headWitness;t&&PP(this.collectionId,t,e.device);let i=xP(this.collectionId,t);i.length&&e.request("report_witnesses",Ke([[0,i]])).catch(()=>{})}get authenticatedDevice(){return this.currentSession().device}get headWitness(){return this.session?.hello.headWitness}attach(e){this.relayWitnesses(e),e.onPush("query_update",t=>{if(this.fenceReads&&this.session!==e)return;let i;try{i=_o(Uu,t)}catch{return}let o=this.livesBySub.get(i.sub);if(o)o._apply(i);else if(this.subscribing>0){let s=this.early.get(i.sub)??[];s.length<64&&this.early.size<64&&(s.push(i),this.early.set(i.sub,s))}}),e.onPush("receipt",t=>{try{let i=_o(Sn,t);this.session===e&&this.noteReceipt(i);let o=this.writes.get(i.mutation);if(o)o.update(i),cw(o.receipt)||this.writes.delete(i.mutation);else{let s=this.unclaimed.get(i.mutation);this.unclaimed.set(i.mutation,s?Tf(i,s):i),this.unclaimed.size>256&&this.unclaimed.delete(this.unclaimed.keys().next().value)}}catch{}}),e.onPush("status",t=>{if(this.session===e)try{this.setStatus(Wr.dec(t))}catch{}}),e.onPush("holds",t=>{try{this.emitHolds(G(Jc).dec(t))}catch{}}),e.onPush("conflicts",t=>{try{this.emitConflicts(_o(G(Zc),t))}catch{}}),e.onPush("closed",t=>{let i;try{i=new oe(ti.dec(t))}catch{i=A("unauthenticated","the replica closed the session")}e.closeWith(i)}),e.handle("fence_apply",async t=>{if(!this.fenceHandler)throw A("invalid_request","this client offers no fence",{reason:"unknown_method"});return fb.enc(await this.fenceHandler(db.dec(t)))}),e.onClose(t=>this.onSessionClosed(e,t))}onSessionClosed(e,t){if(this.session===e){for(let i of this.lives)i._setSub(null),i._markStale();if(this.livesBySub.clear(),this.early.clear(),this.closing||this.opts.reconnect===!1){this.setLink("closed",t??null);return}if(t&&(t.code==="unauthenticated"||t.code==="upgrade_required"||t.code==="forbidden")){this.setLink("closed",t);return}this.setLink("reconnecting",t??null),this.reconnectLoop()}}async reconnectLoop(){let e=this.opts.reconnect||{},t=e.minDelayMs??250,i=e.maxDelayMs??15e3,o=t;for(;!this.closing;)try{let s=await Cs.open(this.opts.connector,n.helloParams(this.opts));if(this.closing){s.close();return}if(s.hello.collection!==this.collectionId)throw s.close(),A("invalid_request","reconnected to a different collection");this.session=s,this.currentHello=lw(s.hello,s.hello.status.grant),this.attach(s),this.noteReplica(s),this.setStatus(s.hello.status),this.setLink("open");for(let r of this.reconnectWaiters.splice(0))r();await this.restore(s);return}catch(s){if(X(s)&&["unauthenticated","forbidden","upgrade_required"].includes(s.code)){this.setLink("closed",s);return}X(s)&&this.setLink("reconnecting",s);let r=X(s)?s.retryAfterMs??0:0;await new Promise(a=>setTimeout(a,Math.max(r,o*(.5+Math.random()/2)))),o=Math.min(i,o*2)}}async restore(e){let t=[];t.push(e.request("subscribe_status",null).catch(()=>{})),this.holdsWatch.listeners.size&&t.push(this.refreshHolds(!0).catch(()=>{})),this.conflictsWatch.listeners.size&&t.push(this.refreshConflicts(!0).catch(()=>{}));for(let i of this.lives)t.push(this._resubscribeLive(i,!1,e).catch(()=>{}));for(let[i,o]of this.writes)t.push(this.awaitReceipt(i).then(s=>{o.update(s),cw(o.receipt)||this.writes.delete(i)}).catch(()=>{}));for(let i of this.restorers)t.push(Promise.resolve(i(e)).catch(()=>{}));await Promise.all(t)}setLink(e,t=null){if(this.linkState!=="closed"&&(e==="closed"&&this.fenceReads&&queueMicrotask(()=>this.wakeReadFence()),!(this.linkState===e&&this.linkError?.reason===t?.reason))){if(this.linkState=e,this.linkError=e==="open"?null:t,e==="closed")for(let i of this.reconnectWaiters.splice(0))i();for(let i of[...this.linkListeners])i(e,this.linkError)}}get status(){return this.lastStatus}async getStatus(){if(!this.fenceReads){let e=await this.call("get_status",null,{codec:Wr,retry:!0});return this.setStatus(e),e}for(;;){let e=await this.ready(),t;try{t=await e.request("get_status",null,{codec:Wr})}catch(i){if(X(i,"unavailable")&&e.closed&&!this.closing&&this.opts.reconnect!==!1)continue;throw i}if(e!==this.session||e.closed){if(this.closing)throw A("unavailable","client closed");continue}return this.setStatus(t),t}}async appliedPrefix(e,t={}){let i=Wg.enc({seq:e}),o=await this.call("applied_prefix",i,{codec:Hg,retry:!1,...t.signal?{signal:t.signal}:{}});if(o.seq!==e||o.chain!==void 0&&(e===0||o.appliedThrough<e))throw A("invalid_request","applied_prefix: inconsistent historical proof","prefix_response");return o}onStatus(e){return this.statusListeners.add(e),e(this.lastStatus),()=>this.statusListeners.delete(e)}setStatus(e){this.fenceReads&&(this.readFencedAt!==null&&e.confirmedThrough>=this.readFencedAt&&(this.readFencedAt=null,this.wakeReadFence()),this.readFencedAt===null&&(this.readFloor=Math.max(this.readFloor,e.confirmedThrough))),this.lastStatus=e,this.currentHello=lw(this.currentHello,e.grant);for(let t of[...this.statusListeners])t(e)}async describe(e={}){let t=await this.call("describe",e.definitions?Ke([[0,!0]]):null,{codec:bb,retry:!0,...e.signal?{signal:e.signal}:{}});if(e.definitions&&(t.types.some(i=>i.definition===void 0)||t.contracts.some(i=>i.schemas===void 0)))throw A("upgrade_required","this replica does not describe definitions","describe_definitions_unsupported");return t}async createType(e,t={}){let{name:i,path:o}=await this.call("new_type_file",Ke([[0,e]]),{codec:gb,retry:!0,...t.signal?{signal:t.signal}:{}}),s=await this.resources.put(o,e,{...t,mustNotExist:!0});return{name:i,path:o,write:s}}describeTyping(e,t,i={}){let o=(s,r)=>Array.isArray(s)&&s.length<=r&&s.every(a=>typeof a=="string"&&a.length>0&&a.length<=1024);return!o(e,ep)||!o(t,tp)?Promise.reject(A("invalid_request","describe_typing: at most 64 types and 256 non-empty paths","typing_bounds")):this.call("describe_typing",Ke([[0,[...e]],[1,[...t]]]),{codec:vb,retry:!0,...i.signal?{signal:i.signal}:{}}).then(s=>{if(s.fields.length!==t.length||s.fields.some((r,a)=>r.path!==t[a]))throw A("internal","describe_typing answered for different paths","invalid_typing_response");return s})}get(e,t={}){return this.call("get",Ke([[0,Of(e)],[1,qf(t.include)]]),{codec:ko,retry:!0,...t.signal?{signal:t.signal}:{}})}async getContract(e,t,i={}){let o=await this.contractCall("get_contract_v1",Ke([[0,1],[1,Of(e)],[2,t.id],[3,t.version],[4,t.type]]),s=>_o(mP,s),i.signal);if(o.version!==1)throw A("upgrade_required","unsupported contract record","contract_records_unsupported");return{id:o.id,path:o.path,revision:o.revision,fields:o.fields,contract:{id:t.id,version:t.version,digest:o.contractDigest,type:o.type,implementationDigest:o.implementationDigest}}}async contractPlan(e,t,i,o,s,r=!1){let a=await this.contractCall("map_contract_write_v1",Ke([[0,1],[1,e.id],[2,e.version],[3,e.type],[4,t===void 0?void 0:Of(t)],[5,i],[6,o?.length?o:void 0],[7,r?!0:void 0]]),yP.dec,s);if(a.version!==1)throw A("upgrade_required","unsupported contract write plan","contract_records_unsupported");return a}async contractCall(e,t,i,o){let s;try{s=await this.call(e,t,{retry:!0,...o?{signal:o}:{}})}catch(r){throw X(r,"invalid_request")&&r.reason==="unknown_method"?A("upgrade_required","this replica does not serve contract-scoped records","contract_records_unsupported"):r}try{return i(s)}catch(r){throw Bn(r,`${e} result`)}}readMany(e,t={}){return hf(this,e,t)}async find(e,t={}){try{return await this.get(e,t)}catch(i){if(X(i,"not_found"))return null;throw i}}query(e,t={}){return this.call("query",Ke([[0,Fe(e)],[1,qf(t.include)],[2,t.contract]]),{codec:Xc,retry:!0,...t.signal?{signal:t.signal}:{}}).then(i=>this.firstQueryResult(i))}firstQueryResult(e){return this.queryAnswered||(this.queryAnswered=!0,So("mdbase:query:first-result")),e}async queryContract(e,t={}){let i=t.pageSize??128;if(!Number.isInteger(i)||i<1||!e.id||e.id.length>1024||!e.version||e.version.length>128||t.where!==void 0&&(!t.where||t.where.length>4096))throw A("invalid_request","invalid contract page selection");let o,s=!1;if(t.orderBy!==void 0){if(!Array.isArray(t.orderBy)||t.orderBy.length<1||t.orderBy.length>8)throw A("invalid_request","invalid contract order_by","invalid_query");let p=[];for(let d of t.orderBy){if(!d||typeof d!="object"||Array.isArray(d))throw A("invalid_request","invalid contract order_by term","invalid_query");if(Object.keys(d).some(f=>f!=="field"&&f!=="direction")||typeof d.field!="string"||!d.field||d.field.length>256||d.direction!==void 0&&d.direction!=="asc"&&d.direction!=="desc")throw A("invalid_request","invalid contract order_by term","invalid_query");d.field==="file.mtime"&&(s=!0),p.push(d.direction===void 0?{field:d.field}:{field:d.field,direction:d.direction})}o=Fe(p)}let r=await this.readyForRead(t.signal),a=r.hello.features.includes(NP);if(o!==void 0&&!a)throw A("upgrade_required","This replica does not support ordered contract queries.","contract_query_order_unsupported");if(s&&!r.hello.features.includes(DP))throw A("upgrade_required","This replica does not support ordering contract queries by file.mtime.","contract_query_order_mtime_unsupported");let c=Math.min(i,a?1e3:128),l=await this.call("query_contract_v1",Ke([[0,1],[1,e.id],[2,e.version],[3,c],[4,t.cursor],[5,t.where],[6,o]]),{codec:bP,retry:!0,...t.signal?{signal:t.signal}:{}});if(l.version!==1)throw A("upgrade_required","unsupported contract query result","contract_query_version");if(l.records.length!==l.page.records.length||l.records.some((p,d)=>p.id!==l.page.records[d]?.id))throw A("unavailable","invalid contract query record binding","contract_query_response");return this.firstQueryResult(l)}backlinks(e,t={}){return this.call("backlinks",Ke([[0,Of(e)],[1,qf(t.include)],[2,t.limit],[3,t.cursor]]),{codec:mb,retry:!0,...t.signal?{signal:t.signal}:{}}).catch(i=>{throw X(i,"invalid_request")&&i.reason==="unknown_method"?A("upgrade_required","This collection's replica can't list backlinks yet.","backlinks_unsupported"):i})}resolveLinks(e,t,i={}){return this.call("resolve_links",Ke([[0,e],[1,[...t]]]),{codec:yb,retry:!0,...i.signal?{signal:i.signal}:{}}).catch(o=>{throw X(o,"invalid_request")&&o.reason==="unknown_method"?A("upgrade_required","This collection's replica can't resolve links yet.","resolve_links_unsupported"):o})}history={list:(e,t={})=>zP(this.call("record_history",YS.enc({record:e,before:t.before,limit:t.limit}),{codec:XS,retry:!0,...t.signal?{signal:t.signal}:{}})),version:(e,t,i={})=>zP(this.call("record_version",JS.enc({record:e,seq:t}),{codec:ZS,retry:!0,...i.signal?{signal:i.signal}:{}}))};resources={get:(e,t={})=>this.call("get_resource",Ke([[0,e]]),{codec:Fu,retry:!0,...t.signal?{signal:t.signal}:{}}),list:(e={})=>this.call("list_resources",Ke([[0,e.folder],[1,e.text],[2,e.cursor],[3,e.limit]]),{codec:hb,retry:!0,...e.signal?{signal:e.signal}:{}}),put:(e,t,i={})=>i.baseRevision&&i.mustNotExist?Promise.reject(A("invalid_request","baseRevision and mustNotExist are exclusive")):this.submit([{kind:"resource_put",path:e,doc:t,...i.baseRevision?{baseRevision:i.baseRevision}:{},...i.mustNotExist?{mustNotExist:!0}:{}}],i),delete:(e,t={})=>this.submit([{kind:"resource_delete",path:e,...t.baseRevision?{baseRevision:t.baseRevision}:{}}],t)};typePacks=Object.freeze({plan:(e,t)=>EP(this,e,t),apply:(e,t)=>qP(this,e,t)});recordSessions=new vf(this);records=Object.freeze({open:(e,t)=>this.recordSessions.open(e,t)});views={createSource:(e,t)=>Sf(this,e,t),updateSource:(e,t,i)=>Pf(this,e,t,i),getSourceRecord:(e,t={})=>kf(this,e,t),list:(e={})=>cP(this,e),execute:(e,t,i={})=>pP(this,e,t,i),readSource:(e,t={})=>dP(this,e,t)};async pendingWrites(e={}){let t=e.signal,i=[],o;for(;;){let s=await this.call("list_pending",Ke([[0,o?M.enc(o):void 0]]),{codec:wb,retry:!0,...t?{signal:t}:{}});if(i.push(...s.pending),!s.next)return i;o=s.next}}async preflightRename(e,t,i={}){return this.preflight({kind:"rename",id:e.id,from:e.path,to:t,updateRefs:i.updateRefs??!0})}async preflightDelete(e){return this.preflight({kind:"delete",id:Rf(e)})}async preflight(e){let t=(await this.submit([e],{dryRun:!0})).receipt;if(t.state==="rejected")throw new oe(t.problem);return t.preflight??{rewrites:[],broken:[]}}async*pages(e,t={}){let{include:i,signal:o,onReset:s}=t,r=Ef(e);r.limit===void 0&&(r.limit=500);let a=i?{...i}:void 0,c={...a?{include:a}:{},...o?{signal:o}:{}},l=r.cursor,p=!1,d=0;for(delete r.cursor;;){o?.throwIfAborted();let u;try{u=await this.query(l!==void 0?{...r,cursor:l}:{...r},c)}catch(f){if(!s||p||!X(f,"invalid_request")||f.recovery!=="fix_request"||f.reason!=="cursor_expired"&&f.reason!=="cursor_stale")throw f;o?.throwIfAborted(),await s({reason:f.reason,error:f,pagesYielded:d,...o?{signal:o}:{}}),o?.throwIfAborted(),p=!0,l=void 0,d=0;continue}if(o?.throwIfAborted(),u.hasMore&&!u.cursor)throw A("invalid_request","Query requires offset paging","query_cursor_required");if(yield u,d++,!u.cursor)return;l=u.cursor}}queryPages(e,t={}){return mf(this,e,t)}recordSet(e={}){return new Ba(this,e)}live(e,t={}){let i=new Fa(this,e,t.include);return this.lives.add(i),i.ready.then(()=>{this.firstQueryResult(void 0)},()=>{}),this._resubscribeLive(i,!0),i}async _resubscribeLive(e,t=!1,i){let o=e._sub;o!==null&&(this.livesBySub.delete(o),e._setSub(null),this.call("unsubscribe",Ke([[0,o]])).catch(()=>{}));try{let s=await this.readyForRead();if(this.fenceReads&&(e.closed||i&&i!==s))return;this.subscribing++;let r;try{let c=await s.request("subscribe",e._params());r=F.dec(c.get(0)??null)}finally{this.subscribing--}let a=this.early.get(r)??[];if(this.early.delete(r),this.subscribing===0&&this.early.clear(),e.closed||this.fenceReads&&(s!==this.session||s.closed)){s.request("unsubscribe",Ke([[0,r]])).catch(()=>{});return}e._setSub(r),this.livesBySub.set(r,e);for(let c of a)e._apply(c)}catch(s){let r=Bn(s,"subscribe");X(r,"unavailable")&&this.linkState==="reconnecting"||e._fail(r,t)}}_closeLive(e){this.lives.delete(e);let t=e._sub;t!==null&&(this.livesBySub.delete(t),this.call("unsubscribe",Ke([[0,t]])).catch(()=>{}))}changes(e={}){return this.call("changes",Ke([[0,e.cursor??null],[1,e.limit]]),{codec:vs,retry:!0,...e.signal?{signal:e.signal}:{}})}watchChanges(e,t={}){let i=t.cursor,o=!1,s=0,r="starting",a=null,c=null,l=null,p=null,d=null,u=()=>{},f,h,m=new Promise((C,R)=>{f=C,h=R});m.catch(()=>{});let w=new Set,b=C=>{try{C(r,a)}catch{}},g=(C,R=null)=>{r=C,a=R;for(let O of[...w])b(O)},y=()=>{p?.(),p=null,d?.(),d=null;let C=l;l=null,u(),u=()=>{},C?.abort(),c=null},_=()=>{this.restorers=this.restorers.filter(C=>C!==S),x()},v=C=>{o||(o=!0,s++,y(),_(),h(C),g("failed",C),w.clear())},k=()=>{r!=="closed"&&(o=!0,s++,y(),_(),h(A("cancelled","change watch closed")),g("closed"),w.clear())},S=async C=>{if(o||C.closed||C!==this.session||c===C)return;s++,y(),c=C;let R=s,O=()=>!o&&R===s&&!C.closed&&C===this.session;l=new AbortController;let E=l.signal;try{await this.readFence(E)}catch(V){O()&&v(Bn(V,"changes watch"));return}if(!O())return;let j=!0,B=[],D=0;u=()=>{B.length=0,D=0};let J=V=>{if(O()){i=V.cursor;try{e(V)}catch{}}};if(d=C.onClose(V=>{if(o||R!==s)return;s++,y();let U=V??A("unavailable","change watch session closed");h(U),g("stale",U)}),p=C.onPush("changes",V=>{if(O())try{let U=vs.dec(V);if(!j){J(U);return}let ce=64+U.cursor.length*2+U.changes.reduce((ee,te)=>ee+384+te.path.length*2,0);if(B.length>=16||D+ce>1024*1024){v(A("unavailable","change watch startup buffer exceeded"));return}D+=ce,B.push(U)}catch(U){v(Bn(U,"changes push"))}}),g("starting"),!!O())try{let V=await C.request("changes",Ke([[0,i??null],[1,aw],[2,!0]]),{codec:vs,signal:E});for(;;){if(!O()||(i=V.cursor,(V.changes.length||V.reset)&&J(V),!O()))return;if(V.changes.length<aw)break;u(),V=await C.request("changes",Ke([[0,i],[1,aw]]),{codec:vs,signal:E})}for(;B.length&&O();)J(B.shift());if(u(),j=!1,!O())return;g("active"),O()&&f()}catch(V){O()&&v(Bn(V,"changes watch"))}},x=this.onLink((C,R)=>{C==="closed"&&(R?v(R):k())});this.onSession(S),this.ready().then(S).catch(C=>v(Bn(C,"changes watch")));let P=Object.assign(k,{ready:m,subscribe:C=>(r!=="closed"&&r!=="failed"&&w.add(C),b(C),()=>{w.delete(C)})});return Object.defineProperties(P,{state:{get:()=>r},error:{get:()=>a},cursor:{get:()=>i}}),Object.freeze(P)}async validate(e={}){let t=e.signal;t?.throwIfAborted();let{targets:i,expected:o}=kS(e.refs),s=a=>this.call("validate",a,{codec:AS,retry:!0,...t?{signal:t}:{}});if(i!==void 0||!this.hello.features.includes(LP)){let a=await s(Ke([[0,i]]));return t?.throwIfAborted(),SS(a,o)}let r=[];for(let a;;){let c=await s(Ke([[1,new Map(a===void 0?[]:[[0,M.enc(a)]])]]));t?.throwIfAborted();let l=c[c.length-1];if(l===void 0)return r;r.push(...c),a=l.id}}async executeAppBases(e,t={}){let i=t.signal,o=e.window===void 0?null:{...e.window},s=e.rowProperties===void 0?void 0:[...e.rowProperties],r=tf({...e,...o===null?{}:{window:o},...s===void 0?{}:{rowProperties:s}}),a=await this.readyForRead(i);if(s!==void 0&&!a.hello.features.includes(UP))throw A("upgrade_required","This replica does not support projected Bases row properties.","bases_row_properties_unsupported");let c=await a.readAppBases(r,i);if(a!==this.session||a.closed||this.readFencedAt!==null)throw A("unavailable","original Bases session is no longer current");try{return nf(c,o,s??null)}catch(l){throw Bn(l,"app Bases result")}}executeAppBasesPages(e,t={}){return bS((i,o)=>this.executeAppBases(i,o?{signal:o}:{}),e,t)}async listAppBasesViews(e,t={}){let i=t.signal,o=e.limit;pp(e);let s=await this.readyForRead(i),r=e.reportUnreadable===!0&&s.hello.features.includes(jP),a=pp({...e,reportUnreadable:r}),c=await s.readAppBasesDiscovery("list-views",a,i);try{if(s!==this.session||s.closed||this.readFencedAt!==null)throw A("unavailable","original Bases session is no longer current");return of(c,o,r)}catch(l){throw Bn(l,"app Bases discovery")}finally{c.fill(0)}}async readAppBasesViewSource(e,t={}){let i=t.signal,o={...e},s=rf(o),r=await this.readyForRead(i),a=await r.readAppBasesDiscovery("read-view-source",s,i);try{if(r!==this.session||r.closed||this.readFencedAt!==null)throw A("unavailable","original Bases session is no longer current");return sf(a,o)}catch(c){throw Bn(c,"app Bases exact source")}finally{a.fill(0)}}async submit(e,t={}){if(this.hello.version.minor>=3&&this.hello.grant.role==="viewer")throw new xs(A("forbidden","You have view access, so changes can't be saved.","read_only"));t.intent!==void 0&&t.mutationId===void 0&&(t={...t,mutationId:(await $P(this.collectionId,t.intent))[0]});let i=t.mutationId??zi(),o={ops:e,mutationId:i};t.conflictMode&&(o.conflictMode=t.conflictMode),t.timezone&&(o.timezone=t.timezone),t.dryRun&&(o.dryRun=!0),t.include&&(o.include=t.include),t.wait&&(o.wait=t.wait),t.validation&&(o.validation=t.validation),t.dryRun||(this.startLedger(),await this.writeLedger.begin(i,e));let s;try{let r=await this.call("submit",rb.enc(o),{codec:sb,retry:!0,...t.signal?{signal:t.signal}:{}});if(r.length!==1)throw A("internal","submit answered without exactly one receipt","invalid_submit_response");s=r[0]}catch(r){throw t.dryRun?r:(this.writeLedger.settle(i),ja(r)&&["invalid_request","invalid_record","not_found","conflict","unauthenticated","forbidden","collection_invalid","rate_limited","too_large","upgrade_required"].includes(r.code)?new xs(r,{mutationId:i}):La(r,"submit",{mutationId:i}))}return t.dryRun?new Os(s):this._track(s)}async record(e,t){return Object.assign(await this.submit([e],t),{recordId:e.id})}create(e,t={}){if(t.intent!==void 0&&t.mutationId===void 0)return $P(this.collectionId,t.intent).then(([o,s])=>this.create({...e,id:e.id??s},{...t,mutationId:o}));if(e.contract)return this.createThroughContract(e,e.contract,t);let i={kind:"create",id:e.id??zi()};return e.path!==void 0&&(i.path=e.path),e.type!==void 0&&(i.type=e.type),e.frontmatter!==void 0&&(i.frontmatter=cp(e.frontmatter)),e.body!==void 0&&(i.body=e.body),e.document!==void 0&&(i.document=e.document),this.record(i,t)}async createThroughContract(e,t,i){if(e.document!==void 0)throw A("invalid_request","a contract create takes frontmatter fields, not a document");if(e.type!==void 0&&t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())throw A("invalid_request","the create type and contract type must name the same type");let o=t.type===void 0&&e.type!==void 0?{...t,type:e.type}:t,s=await this.contractPlan(o,void 0,cp(e.frontmatter??{}),void 0,i.signal),r={kind:"create",id:e.id??zi(),type:s.type,frontmatter:s.patch};return e.path!==void 0&&(r.path=e.path),e.body!==void 0&&(r.body=e.body),this.record(r,i)}update(e,t,i={}){return t.contract?this.updateThroughContract(e,t,t.contract,i):this.record(this.updateOp(e,t),i)}async updateThroughContract(e,t,i,o){if(t.add||t.remove)throw A("invalid_request","a contract update takes only patch, unset, body and ifRevision");let s=await this.contractPlan(i,e,t.patch?cp(t.patch):void 0,t.unset,o.signal,t.promote),r=typeof e=="object"&&"frontmatter"in e?e:s.id,a=this.updateOp(r,{body:t.body,bodyEdits:t.bodyEdits,bodyBase:t.bodyBase}),c={kind:"update",id:s.id};return a.body!==void 0&&(c.body=a.body),a.bodyEdits&&(c.bodyEdits=a.bodyEdits),a.bodyBase!==void 0&&(c.bodyBase=a.bodyBase),s.patch.size&&(c.patch=s.patch),s.unset.length&&(c.unset=s.unset),s.base.length&&(c.base=s.base),t.requireLive&&(c.requireLive=!0),t.updateRefs!==void 0&&(c.updateRefs=t.updateRefs),t.ifRevision&&(c.ifRevision=t.ifRevision),this.record(c,o)}updateOp(e,t){if(t.contract||t.promote)throw A("invalid_request","contract updates are mapped by the replica; use update()");let i={kind:"update",id:Rf(e)},o=typeof e=="object"&&"frontmatter"in e?e:null;if(t.requireLive&&(i.requireLive=!0),t.updateRefs!==void 0&&(i.updateRefs=t.updateRefs),t.patch&&(i.patch=cp(t.patch)),t.unset?.length&&(i.unset=t.unset),t.add&&(i.add=new Map(Object.entries(t.add).map(([s,r])=>[s,r.map(Fe)]))),t.remove&&(i.remove=new Map(Object.entries(t.remove).map(([s,r])=>[s,r.map(Fe)]))),t.ifRevision&&(i.ifRevision=t.ifRevision),t.bodyEdits?.length){i.bodyEdits=t.bodyEdits;let s=t.bodyBase??(o?.body!==void 0?Di(o.body):void 0);if(!s)throw A("invalid_request","bodyEdits need bodyBase (or a RecordView read with its body)");i.bodyBase=s}else if(t.body!==void 0)if(o?.body!==void 0&&t.bodyBase===void 0){let s=ef(o.body,t.body);s.length&&(i.bodyEdits=s,i.bodyBase=Di(o.body))}else i.body=t.body,t.bodyBase&&(i.bodyBase=t.bodyBase);if(o){let s=[],r=[...i.patch?.keys()??[],...i.unset??[]];for(let a of new Set(r)){let c=Object.hasOwn(o.frontmatter,a)?o.frontmatter[a]:void 0;s.push(c===void 0?{key:a}:{key:a,observed:Fe(c)})}s.length&&(i.base=s)}if(o&&i.patch){for(let[s,r]of[...i.patch]){let a=Object.hasOwn(o.frontmatter,s)?o.frontmatter[s]:void 0;a!==void 0&&Oo(Fe(a),r)&&(i.patch.delete(s),i.base=i.base?.filter(c=>c.key!==s))}i.patch.size===0&&delete i.patch,i.base?.length===0&&delete i.base}return i}replaceDocument(e,t,i={}){let o=typeof e=="object"&&"path"in e&&"revision"in e?e:null,s={kind:"document",id:Rf(e),new:{path:o?.path??"",doc:t}};if(!o)throw A("invalid_request","replaceDocument needs the RecordView it was edited from");return o.document!==void 0&&(s.base={path:o.path,doc:o.document}),i.ifRevision&&(s.ifRevision=i.ifRevision),this.record(s,i)}delete(e,t={}){if(t.contract){let{contract:o,...s}=t;return this.contractPlan(o,e,void 0,void 0,t.signal).then(r=>{let a={kind:"delete",id:r.id,baseRevision:r.revision};return s.ifRevision&&(a.ifRevision=s.ifRevision),this.record(a,s)})}let i={kind:"delete",id:Rf(e)};return typeof e=="object"&&"revision"in e&&(i.baseRevision=e.revision),t.ifRevision&&(i.ifRevision=t.ifRevision),this.record(i,t)}rename(e,t,i={}){if(i.contract){let{contract:s,...r}=i;return this.contractPlan(s,e.id,void 0,void 0,i.signal).then(a=>this.rename({...e,id:a.id,path:a.path},t,r))}let o={kind:"rename",id:e.id,from:e.path,to:t,updateRefs:i.updateRefs??!0};return i.ifRevision&&(o.ifRevision=i.ifRevision),this.record(o,i)}_track(e){this.noteReceipt(e);let t=e,i=this.unclaimed.get(e.mutation);i&&(this.unclaimed.delete(e.mutation),t=Tf(e,i),(e.state==="pending"||e.state==="confirmed"&&(i.state==="rejected"||i.state==="unknown"))&&(t=Tf({...e,...i},t)));let o=this.writes.get(e.mutation);return o?o.update(t):o=new Os(t),cw(o.receipt)?this.writes.set(e.mutation,o):this.writes.delete(e.mutation),o}settle(e,t={}){return tP(this,e,t)}receipt(e,t={}){return this.call("receipt",Ke([[0,M.enc(e)]]),{codec:Sn,retry:!0,...t.signal?{signal:t.signal}:{}}).catch(i=>{throw La(i,"receipt",{mutationId:e})})}awaitReceipt(e,t={}){return this.call("await",Ke([[0,M.enc(e)],[1,t.timeoutMs]]),{codec:Sn,retry:!0,...t.signal?{signal:t.signal}:{}}).catch(i=>{throw La(i,"await",{mutationId:e})})}listHolds(e={}){return this.call("list_holds",null,{codec:G(Jc),retry:!0,...e.signal?{signal:e.signal}:{}})}onHolds(e){let t=this.holdsWatch;return t.listeners.add(e),t.last&&e(t.last),t.listeners.size===1&&this.refreshHolds(!0).catch(()=>{}),()=>t.listeners.delete(e)}async refreshHolds(e){e&&await this.call("subscribe_holds",null,{retry:!0}),this.emitHolds(await this.listHolds())}emitHolds(e){this.holdsWatch.last=e;for(let t of[...this.holdsWatch.listeners])t(e)}async resolveHold(e,t,i){let o=await this.call("resolve_hold",Ke([[0,M.enc(e)],[1,Xg.enc(t)],[2,i]]),{codec:Sn});return this._track(o)}listConflicts(e={}){return this.call("list_conflicts",e.record?Ke([[0,M.enc(e.record)]]):null,{codec:G(Zc),retry:!0,...e.signal?{signal:e.signal}:{}})}onConflicts(e){let t=this.conflictsWatch;return t.listeners.add(e),t.last&&e(t.last),t.listeners.size===1&&this.refreshConflicts(!0).catch(()=>{}),()=>t.listeners.delete(e)}async refreshConflicts(e){e&&await this.call("subscribe_conflicts",null,{retry:!0}),this.emitConflicts(await this.listConflicts())}emitConflicts(e){this.conflictsWatch.last=e;for(let t of[...this.conflictsWatch.listeners])t(e)}dismissConflict(e,t={}){return this.submit([{kind:"conflict_dismiss",mutation:e.mutation,record:e.conflict.id}],t)}resolveConflict(e,t,i,o={}){return this.submit([{kind:"update",id:e.conflict.id,patch:new Map([[t,Fe(i)]])},{kind:"conflict_dismiss",mutation:e.mutation,record:e.conflict.id}],o)}pendingDevices(e={}){return this.call("pending_devices",null,{codec:G(VS),retry:!0,...e.signal?{signal:e.signal}:{}})}approveDevice(e,t){return/^\d{6}$/.test(t)?this.call("approve_device",Ke([[0,M.enc(e)],[1,t]])).then(()=>{}):Promise.reject(A("invalid_request","the code is six digits","invalid_sas"))}rejectDevice(e){return this.call("reject_device",Ke([[0,M.enc(e)]])).then(()=>{})}accountKey={setup:async e=>{MP(e);let t=await this.call("account_key_setup",Ke([[0,e]]),{codec:Sn});return this._track(t)},unlock:async e=>{MP(e),await this.call("account_key_unlock",Ke([[0,e]]))},status:(e={})=>this.call("account_key_status",null,{codec:GS,retry:!0,...e.signal?{signal:e.signal}:{}})};recoveryKey={status:()=>this.call("recovery_key_status",null,{codec:KS,retry:!0}),create:()=>this.call("recovery_key_create",null,{codec:WS}),import:e=>this.call("recovery_key_import",Ke([[0,e.trim()]])).then(()=>{})};offerFence(e){this.fenceHandler=e}reportFence(e){return this.call("fence_report",ub.enc({open:e}),{retry:!0}).then(()=>{})}}});function jf(n){if(!n||typeof n!="object"||Array.isArray(n))throw Vi();return n}function FP(n){if(typeof n!="string")return!1;try{let e=new URL(n);return["http:","https:"].includes(e.protocol)&&!e.username&&!e.password}catch{return!1}}function VP(n){let e=jf(n);if(!FP(e.issuer)||typeof e.subject!="string"||!e.subject.trim()||typeof e.name!="string"||!e.name.trim())throw Vi();let t=e.account_id;if(t!==void 0){if(typeof t!="string")throw Vi();try{if(N(t).every(i=>i===0))throw Vi()}catch{throw Vi()}}return{issuer:e.issuer,subject:e.subject,name:e.name,...t===void 0?{}:{accountId:t}}}function Uf(n,e){return n.issuer===e.issuer&&n.subject===e.subject}function OT(n){return Array.isArray(n)?n.flatMap(e=>{let t=de(e,"issuer"),i=de(e,"subject");return typeof t!="string"||typeof i!="string"?[]:[{issuer:t,subject:i}]}):[]}function RT(n){let e=de(n.fields,"name"),t=de(n.fields,"identities"),i=OT(t),o=n.issues.find(s=>s.severity==="error");return o?{reason:o.message,claims:i}:typeof e!="string"||!e.trim()?{reason:"It needs a non-blank name.",claims:i}:t!==void 0&&(!Array.isArray(t)||i.length!==t.length||i.some(s=>!s.subject.trim()))?{reason:"Each account identity needs an exact issuer and subject.",claims:i}:{name:e,identities:i,claims:i}}var dw,Vi,gr,kp=I(()=>{"use strict";ve();re();un();dw=Object.freeze({id:"mdbase.person",version:"2.0.0"}),Vi=()=>A("unavailable","invalid people response","people_response");gr=class{constructor(e,t){this.client=e;this.authority=t}client;authority;check(e){if(e?.throwIfAborted(),!this.authority.isCurrent())throw A("unauthenticated","people scope changed","people_fenced")}checkReadSession(e){if(e!==this.client.currentSession()||e.closed)throw A("unavailable","people read session changed","people_fenced");let t=N(this.authority.collection),i=N(e.hello.collection);if(t.every(o=>o===0)||!t.every((o,s)=>o===i[s]))throw A("unauthenticated","people collection binding changed","people_binding")}async current(e={}){this.check(e.signal);let t=await this.authority.request("identity",e);this.check(e.signal);let i=VP(t),o=jf(t).person_settings_url;if(o===void 0)return i;if(!FP(o))throw Vi();return{...i,personSettingsUrl:o}}async members(e={}){this.check(e.signal);let t=jf(await this.authority.request("members",e));if(this.check(e.signal),!Array.isArray(t.members)||t.members.length>1e3)throw Vi();return t.members.map(i=>{let o=VP(i),s=jf(i).role;if(s!=="owner"&&s!=="editor"&&s!=="viewer")throw Vi();return{...o,role:s}})}async directory(e={}){let{members:t="if-approved",...i}=e;if(!["require","if-approved","omit"].includes(t))throw A("invalid_request","invalid members mode");this.check(i.signal);let o=async()=>{let u=await this.current(i);this.check(i.signal);let f=t==="omit"?void 0:await this.members(i).catch(h=>{if(!(t==="if-approved"&&X(h,"forbidden")&&h.reason==="people_permission_declined"))throw h});return this.check(i.signal),{account:u,members:f}},[{account:s,members:r},a]=await Promise.all([o(),this.records(i)]);this.check(i.signal),this.checkReadSession(a.session);let c=a.invalid.filter(u=>u.claims.some(f=>Uf(f,s))),l=a.people.filter(u=>u.identities.some(f=>Uf(f,s))),p=l[0],d=c.length?{status:"invalid",paths:c.map(u=>u.path)}:l.length>1?{status:"ambiguous",paths:l.map(u=>u.path)}:p?{status:"linked",person:p}:{status:"unlinked"};return{account:s,me:d,people:a.people,invalid:a.invalid.map(({claims:u,...f})=>f),...r===void 0?{}:{members:r}}}async records(e){let t=await this.client.readyForRead(e.signal);this.check(e.signal),this.checkReadSession(t);let i,o,s,r=new Set,a=new Set,c=[],l=[];for(;;){this.check(e.signal);let d=await this.client.queryContract(dw,{pageSize:128,...i?{cursor:i}:{},...e.signal?{signal:e.signal}:{}}).catch(f=>{if(!i&&!r.size&&X(f,"not_found")&&f.reason==="data_contract_not_found")return null;throw f});if(this.check(e.signal),this.checkReadSession(t),!d)return{people:c,invalid:l,session:t};let{page:u}=d;if(!u.complete)throw A("unavailable","person inventory is incomplete","people_incomplete");if(o!==void 0&&o!==u.asOf||s!==void 0&&s!==d.contractDigest)throw Vi();o=u.asOf,s=d.contractDigest;for(let[f,h]of d.records.entries()){let m=u.records[f];if(h.id!==m?.id||r.has(h.id)||!h.implementations.length)throw Vi();if(r.add(h.id),r.size>1e4)throw A("too_large","person directory exceeds its record budget","people_budget");let w=h.implementations.map(RT),b=w[0],g=w.find(_=>"reason"in _),y=w.flatMap(_=>_.claims);g&&"reason"in g?l.push({id:h.id,path:m.path,reason:g.reason,claims:y}):w.some(_=>JSON.stringify(_)!==JSON.stringify(b))?l.push({id:h.id,path:m.path,reason:"Its Person implementations project different values.",claims:y}):"name"in b&&c.push({id:h.id,path:m.path,name:b.name,identities:b.identities,typeNames:[...new Set(h.implementations.map(_=>_.typeName))].sort()})}if(!u.cursor){if(u.hasMore===!0||u.totalCount!==void 0&&u.totalCount!==r.size)throw A("unavailable","person inventory is incomplete","people_incomplete");break}if(a.has(u.cursor))throw Vi();a.add(u.cursor),i=u.cursor}let p=(d,u)=>d.path<u.path?-1:d.path>u.path?1:0;return{people:c.sort(p),invalid:l.sort(p),session:t}}}});function Sp(n){return typeof n=="string"&&TT.test(n)&&Number.isFinite(Date.parse(n))}function Pp(n){if(typeof n!="string"||!ET.test(n))throw Fi()}function HP(n){if(typeof n!="string"||!Nf.test(n))throw Fi()}function uw(n){if(typeof n!="string"||!n.length||n.length>100)throw Fi()}function fw(n){if(!n||Object.keys(n).some(e=>e!=="id"&&e!=="fireAt")||(HP(n.id),!Sp(n.fireAt)))throw Fi();return{id:n.id,fire_at:new Date(n.fireAt).toISOString()}}function Xr(n){if(!n||typeof n!="object"||Array.isArray(n))throw In();return n}function GP(n){let e=Xr(n);if(typeof e.id!="string"||!Nf.test(e.id)||typeof e.criterion_id!="string"||!e.criterion_id.length||e.criterion_id.length>100||!Sp(e.fire_at)||!Number.isSafeInteger(e.generation)||e.generation<1||!["scheduled","firing","fired","cancelled"].includes(e.status)||!Sp(e.created_at)||!Sp(e.updated_at)||e.fired_at!==null&&!Sp(e.fired_at))throw In();return{id:e.id,criterionId:e.criterion_id,fireAt:e.fire_at,generation:e.generation,status:e.status,createdAt:e.created_at,updatedAt:e.updated_at,firedAt:e.fired_at}}function hw(n,e){let t=Xr(n);if(t.namespace!==e||!Array.isArray(t.timers)||t.timers.length>xp)throw In();let i=t.timers.map(GP);if(new Set(i.map(o=>o.id)).size!==i.length||t.intent_revision!==void 0&&(!Number.isSafeInteger(t.intent_revision)||t.intent_revision<0))throw In();return{namespace:e,timers:i,...t.intent_revision===void 0?{}:{intentRevision:t.intent_revision}}}function KP(n){let{namespace:e,operationId:t,expectedRevision:i}=n;if(Pp(e),typeof t!="string"||!qT.test(t)||!Number.isSafeInteger(i)||i<0||i===Number.MAX_SAFE_INTEGER)throw Fi();return{namespace:e,operationId:t,expectedRevision:i}}function MT(n,e){let t=Xr(n),i=hw(t,e);if(!Array.isArray(t.cancelled_ids)||t.cancelled_ids.length>xp||t.cancelled_ids.some(o=>typeof o!="string"||!Nf.test(o))||new Set(t.cancelled_ids).size!==t.cancelled_ids.length)throw In();return{...i,cancelledIds:[...t.cancelled_ids]}}function WP(n,e){let t=Xr(n);if(t.protocol_version!==1||t.namespace!==e.namespace||t.operation_id!==e.operationId||t.expected_revision!==e.expectedRevision||t.committed_revision!==e.expectedRevision+1||Object.keys(t).some(r=>!["protocol_version","namespace","operation_id","expected_revision","committed_revision","result"].includes(r)))throw In();let i=Xr(t.result);if(Object.keys(i).some(r=>!["namespace","timers","cancelled_ids"].includes(r)))throw In();let o=MT(i,e.namespace),s=["id","criterion_id","fire_at","generation","status","created_at","updated_at","fired_at"];for(let r of i.timers)if(Object.keys(Xr(r)).some(a=>!s.includes(a)))throw In();if(o.cancelledIds.some(r=>o.timers.some(a=>a.id===r)))throw In();return{protocolVersion:1,...e,committedRevision:t.committed_revision,result:o}}async function LT(n){let e=globalThis.navigator?.serviceWorker;if(!e)throw A("invalid_request","Web Push needs a service worker.","timer_push_platform");return await new Promise((t,i)=>{let o=()=>i(A("cancelled","Timer request cancelled before dispatch."));if(n?.aborted)return o();n?.addEventListener("abort",o,{once:!0}),e.ready.then(t,i).finally(()=>n?.removeEventListener("abort",o))})}var ET,Nf,qT,TT,xp,Fi,In,Ka,mw=I(()=>{"use strict";re();ET=/^[A-Za-z0-9._-]{1,64}$/,Nf=/^[A-Za-z0-9._:-]{1,128}$/,qT=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,TT=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/i,xp=1e4,Fi=()=>A("invalid_request","Invalid opaque timer request."),In=()=>A("internal","Invalid control-plane timer response.","invalid_timer_response");Ka=class{constructor(e,t={}){this.port=e;this.criteria=t.criteria?.length?[...t.criteria]:void 0}port;lifetime=new AbortController;criteria;close(){this.lifetime.signal.aborted||(this.lifetime.abort(),this.port.close?.())}async run(e,t,i){let o=e.signal?AbortSignal.any([this.lifetime.signal,e.signal]):this.lifetime.signal;if(o.aborted)throw A("cancelled","Timer request cancelled before dispatch.");let s;try{s=await i({signal:o})}catch(r){let a=r&&typeof r=="object"?r.problem?.operation_outcome:void 0;throw t&&a==="unknown"?A("outcome_unknown","Timer or channel write outcome is unknown."):t&&X(r,"internal")&&r.reason==="invalid_timer_response"?A("outcome_unknown","Timer write returned an invalid response."):r}if(o.aborted)throw A(t?"outcome_unknown":"cancelled","Timer request ended before its response was observed.");return s}list(e,t={}){return Pp(e),this.run(t,!1,async i=>hw(await this.port.list(e,i),e))}put(e,t={}){Pp(e.namespace),uw(e.criterionId);let i=fw(e.timer),o=e.namespace,s=e.criterionId;return this.run(t,!0,async r=>{let a=GP(await this.port.put(o,i.id,{criterion_id:s,fire_at:i.fire_at},r));if(a.id!==i.id||a.criterionId!==s||Date.parse(a.fireAt)!==Date.parse(i.fire_at))throw In();return a})}cancel(e,t={}){if(Pp(e.namespace),HP(e.id),e.generation!==void 0&&(!Number.isSafeInteger(e.generation)||e.generation<1))throw Fi();let{namespace:i,id:o,generation:s}=e;return this.run(t,!0,async r=>{let a=Xr(await this.port.cancel(i,o,s,r));if(a.namespace!==i||a.id!==o||typeof a.cancelled!="boolean")throw In();return{namespace:i,id:o,cancelled:a.cancelled}})}reconcile(e,t={}){if(Pp(e.namespace),uw(e.criterionId),!Array.isArray(e.timers)||e.timers.length>xp)throw Fi();let i=e.timers.map(fw),o=new Map(i.map(a=>[a.id,a.fire_at]));if(o.size!==i.length)throw Fi();let s=e.namespace,r=e.criterionId;return this.run(t,!0,async a=>{let c=Xr(await this.port.reconcile(s,{criterion_id:r,timers:i},a)),l=hw(c,s);if(l.timers.length!==i.length||l.timers.some(p=>!o.has(p.id)||p.criterionId!==r||Date.parse(p.fireAt)!==Date.parse(o.get(p.id)))||!Array.isArray(c.cancelled_ids)||c.cancelled_ids.length>xp||c.cancelled_ids.some(p=>typeof p!="string"||!Nf.test(p)||o.has(p))||new Set(c.cancelled_ids).size!==c.cancelled_ids.length)throw In();return{...l,cancelledIds:c.cancelled_ids}})}reconcileWithReceipt(e,t={}){let i=KP(e),o=e.criterionId;if(uw(o),!Array.isArray(e.timers)||e.timers.length>xp)throw Fi();let s=e.timers.map(fw),r=new Map(s.map(l=>[l.id,l.fire_at]));if(r.size!==s.length)throw Fi();let a=this.port.reconcileWithReceipt;if(!a)throw A("upgrade_required","Timer port does not support original-operation recovery.","timer_operation_recovery_unavailable");let c={protocol_version:1,operation_id:i.operationId,expected_revision:i.expectedRevision};return this.run(t,!0,async l=>{let p=WP(await a.call(this.port,i.namespace,{criterion_id:o,timers:s,recovery:c},l),i);if(p.result.timers.length!==s.length||p.result.timers.some(d=>d.criterionId!==o||!r.has(d.id)||Date.parse(d.fireAt)!==Date.parse(r.get(d.id))))throw In();return p})}lookupOperation(e,t={}){let i=KP(e),o=this.port.lookupOperation;if(!o)throw A("upgrade_required","Timer port does not support original-operation recovery.","timer_operation_recovery_unavailable");return this.run(t,!0,async s=>{let r=Xr(await o.call(this.port,i.namespace,i.operationId,s));if(r.outcome==="committed"&&Object.keys(r).length===2)return{outcome:"committed",receipt:WP(r.receipt,i)};if(r.outcome==="unknown"&&r.namespace===i.namespace&&r.operation_id===i.operationId&&Object.keys(r).length===3)return{outcome:"unknown",namespace:i.namespace,operationId:i.operationId};throw In()}).catch(()=>{throw A("outcome_unknown","Original timer operation could not be recovered.")})}registerWebPush(e={}){let t=e.criteria??this.criteria;return this.run(e,!0,async i=>{let o=e.serviceWorker??await LT(i.signal);return this.port.registerWebPush({...e,...t?{criteria:[...t]}:{},serviceWorker:o,...i})})}unregisterWebPush(e,t={}){return this.run(t,!0,i=>this.port.unregisterWebPush(e,i))}registerFcm(e){let t=e.criteria??this.criteria;return this.run(e,!0,i=>this.port.registerFcm({...e,...t?{criteria:[...t]}:{},...i}))}unregisterFcm(e={}){return this.run(e,!0,t=>this.port.unregisterFcm(t))}}});function Es(n){try{let e=$f(n),t=$f(e?.error)??e,i=t?.code;if(typeof i!="string"||!VT.test(i))return null;let o=$f(t.details)?.issues,s=Array.isArray(t.paths)?t.paths:Array.isArray(o)?o.slice(0,64).map(a=>$f(a)?.path):[],r=[];for(let a of s.slice(0,64))if(typeof a=="string"&&FT.test(a)&&!r.includes(a)&&r.push(a),r.length===5)break;return Object.freeze({code:i,paths:Object.freeze(r)})}catch{return null}}function sx(n){return n?`This app's registration was rejected (${n.code==="invalid_application_manifest"?"invalid manifest":n.code.replaceAll("_"," ")}${n.paths.length?`: ${n.paths.join(", ")}`:""}).`:"This app's registration was rejected by mdbase."}var VT,FT,$f,Bf=I(()=>{"use strict";VT=/^[a-z][a-z0-9_]{0,63}$/,FT=/^(?:\/[A-Za-z0-9_-]{1,64}){1,6}$/,$f=n=>n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null});var ax,lx=I(()=>{"use strict";ax="Your account has reached its synced collection limit. Open an existing collection, delete one you own if Delete is available, or, if you're on the Free plan, upgrade to Plus from your mdbase account page."});function Ha(n){return typeof n=="string"&&KT.has(n)}function wi(n){if(n==null)return null;if(typeof n!="object"||Array.isArray(n))return Object.freeze({state:"unavailable",reason:"device_offline"});let e=n;return e.state==="available"?Object.freeze({state:"available"}):e.state==="unavailable"&&Ha(e.reason)?Object.freeze({state:"unavailable",reason:e.reason}):Object.freeze({state:"unavailable",reason:"device_offline"})}function Fn(n){let e={availability:n};return n==="collection_deleted"?new oe({code:"forbidden",message:"this collection was deleted",reason:n,recovery:"none",details:e}):n==="access_removed"?A("forbidden","this account no longer has access to this collection",{reason:n,details:e}):n==="sync_required"?A("forbidden","this collection must be set up again for this app",{reason:n,details:e}):A("unavailable",`this collection can't be opened now (${n})`,{reason:n,details:e})}var Aw,KT,To=I(()=>{"use strict";re();Aw=["device_offline","device_not_serving","desktop_update_required","old_connector_running","approval_required","sync_required","no_device_registered","access_removed","collection_migrating","collection_not_yet_migrated","collection_deleted"],KT=new Set(Aw)});function nn(n){return typeof n=="object"&&n!==null&&kw.has(n)}function YT(n,e){let t=n?.retry_after_ms,i=n?.retry_after_seconds;if(typeof t=="number"&&Number.isFinite(t)&&t>=0)return Vf(t);if(typeof i=="number"&&Number.isFinite(i)&&i>=0)return Vf(i*1e3);let o=e?.get("retry-after")?.trim();return o&&/^[0-9]{1,6}$/.test(o)?Vf(Number(o)*1e3):null}function Ff(n,e=null){if(typeof n!="string"||n.length>2048||/[\u0000-\u0020\u007f]/.test(n))return null;try{let t=new URL(n);if(t.protocol!=="https:"||t.username||t.password||t.port)return null;let i=t.hostname;return i==="mdbase.dev"||i.endsWith(".mdbase.dev")||e!==null&&t.origin===e?t.href:null}catch{return null}}function Mo(n,e=null){try{if(nn(n))return n;if(typeof n!="object"||n===null||Array.isArray(n)||Object.getPrototypeOf(n)!==Object.prototype||Object.keys(n).sort().join(",")!==JT)return null;let t=n,i=t.status,o=t.retryAfterMs;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0||i>999||t.code!==null&&Ga(t.code)===null||t.reason!==null&&Ga(t.reason)===null||o!==null&&(typeof o!="number"||!Number.isFinite(o)||o<0)||t.updateUrl!==null&&typeof t.updateUrl!="string")return null;let s=Object.freeze({status:i,code:Ga(t.code),reason:Ga(t.reason),retryAfterMs:o===null?null:Vf(o),updateUrl:Ff(t.updateUrl,e)});return kw.add(s),s}catch{return null}}function vi(n,e,t=null,i=null){let o=e&&typeof e=="object"&&!Array.isArray(e)?e.error:void 0,s=o&&typeof o=="object"&&!Array.isArray(o)?o:null,r=s?.details&&typeof s.details=="object"&&!Array.isArray(s.details)?s.details:null,a=Object.freeze({status:Number.isSafeInteger(n)?n:0,code:Ga(s?.code),reason:Ga(r?.reason),retryAfterMs:YT(r,t),updateUrl:Ff(r?.update_url,i)});return kw.add(a),a}function Ot(n){if(!n)return null;let e=[n.reason,n.code];return n.status===429&&n.code==="account_collection_quota_exceeded"?"account_collection_quota_exceeded":e.includes("collection_not_yet_migrated")?"collection_not_yet_migrated":e.includes("collection_migrating")?"collection_migrating":e.includes("account_suspended")?"account_suspended":n.status===403&&n.code==="installation_private_device_not_allowed"?"private_device_not_allowed":e.some(t=>t==="moved_to_next_runtime"||t==="collection_moved"||t==="client_update_required")||n.status===426?"update_required":null}function Lo(n){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{return}}var WT,kw,Ya,Ja,HT,GT,cx,Ga,Vf,JT,ri=I(()=>{"use strict";WT=/^[a-z][a-z0-9_]{0,63}$/,kw=new WeakSet;Ya=5e3,Ja=6e5,HT=Ya,GT=Ja,cx="https://mdbase.dev/downloads/",Ga=n=>typeof n=="string"&&WT.test(n)?n:null,Vf=n=>Math.min(GT,Math.max(HT,Math.round(n)));JT="code,reason,retryAfterMs,status,updateUrl"});function Sw(n){if(typeof n!="string")return null;if(ux(n))return n;if(Object.hasOwn(Kf,n))return Kf[n];for(let e of["readiness_","application_"]){if(!n.startsWith(e))continue;let t=n.slice(e.length);if(e==="readiness_"&&Object.hasOwn(dx,t))return dx[t];if(ux(t))return t;if(Object.hasOwn(Kf,t))return Kf[t]}return null}function aM(n){let e=de(n.details,"availability");if(Ha(e))return e;let t=_i(n.availability)??(n.state==="unavailable"?n:null);return t&&t.state==="unavailable"&&Ha(t.reason)?t.reason:null}function Pw(n,e){let t=Zr(n);if(t)return{codes:[t],retryAfterMs:null,updateUrl:null};let i=_i(n);if(!i)return null;try{if(typeof i.kind=="string"&&"problem"in i&&_i(i.problem)&&typeof _i(i.problem).code=="string")return Pw(_i(i.problem).code,e);let o=_i(i.problemDetail),s=Mo(i.server??o?.server,e),r=[s?.reason??null,s?.code??null].filter(p=>p!==null),a={retryAfterMs:s?.retryAfterMs??sM(i.retryAfterMs),updateUrl:Ff(s?.updateUrl,e),hasServer:i.server!=null||o?.server!=null};if("problem"in i||"readiness"in i||"assessment"in i){let p=Zr(i.problem)??Zr(_i(i.problem)?.code);if(p)return{codes:[...r,p],...a,refusal:Es(o?.registration)};let d=_i(i.readiness)??i,u=_i(d.assessment),f=Zr(_i(d.problem)?.code)??Zr(_i(u?.problem)?.code);if(f)return{codes:[f],...a};let h=Zr(u?.status)??Zr(i.status);return h==="incompatible"||h==="setup_required"?{codes:[h],...a}:null}let c=aM(i);if(c)return{codes:[c==="approval_required"?"device_approval_required":c],...a};if("state"in i&&(i.state==="available"||i.state==="opening"))return null;let l=[...r,Zr(i.reason),Zr(i.code)].filter(p=>p!==null);return l.length?{codes:l,...a,refusal:Es(i.details??o?.registration)}:null}catch{return null}}function gx(n){let e=n.codes[n.codes.length-1];try{for(let t of n.codes){if(yx.has(t))return{key:null,original:e};let i=Sw(t);if(i)return{key:i,original:e}}}catch{}return{key:"unknown",original:e}}function qs(n,e={}){let t=typeof e.cpOrigin=="string"?e.cpOrigin:null,i=Pw(n,t);if(!i)return null;let{key:o,original:s}=gx(i);if(o===null)return null;let[r,a,c,l,p=!1,d]=o==="unknown"?hx:o==="refused"&&!i.hasServer?iM:mx[o],u;try{let b=e.messages;u=b&&Object.hasOwn(b,o)?_i(b[o]):void 0}catch{u=void 0}let f=(b,g)=>typeof b=="string"&&b.trim()?b:g,h=typeof e.recoveryAccountLabel=="string"&&e.recoveryAccountLabel.trim().length>0&&e.recoveryAccountLabel.length<=320&&!Array.from(e.recoveryAccountLabel).some(b=>b.charCodeAt(0)<32||b.charCodeAt(0)===127)?e.recoveryAccountLabel:null,m=o==="recovery_account_mismatch"&&h?`This collection belongs to ${h}. Sign in as ${h} to continue.`:a,w=o==="recovery_account_mismatch"&&h?`Sign in as ${h}`:d??XT[c];return Object.freeze({key:o,title:f(u?.title,r),message:f(u?.message,m),action:c,actionLabel:w===null?null:f(u?.actionLabel,w),severity:l,transient:p,code:s,developerMessage:bx(o,s,i.refusal??null),retryAfterMs:i.retryAfterMs,updateUrl:c==="update_app"?i.updateUrl??cx:null})}function bx(n,e,t){return n==="application_registration_refused"?sx(t):Object.hasOwn(Wf,n)?Wf[n]:n==="unknown"?`Problem code ${e} has no user-facing copy; it is shown as a generic error.`:null}function Hf(n,e={}){let t=Pw(n,typeof e.cpOrigin=="string"?e.cpOrigin:null);if(!t)return null;for(let s of t.codes)if(Object.hasOwn(Wf,s)&&yx.has(s))return Wf[s];let{key:i,original:o}=gx(t);return i===null?null:bx(i,o,t.refusal??null)}var XT,fx,hx,ZT,QT,eM,tM,px,nM,iM,mx,Kf,dx,rM,yx,Wf,oM,Zr,_i,sM,ux,Rp=I(()=>{"use strict";Bf();lx();To();un();ri();XT={retry:"Try again",wait:null,reload:"Reload",sign_in:"Sign in",approve:"Approve",choose_collection:"Choose a collection",set_up:"Set up",update_app:"Update the app",free_space:"Manage storage",check_connection:"Try again",resolve_outcome:"Check and try again",contact_support:"Contact support",none:null},fx=["device_offline","device_not_serving","desktop_update_required","old_connector_running","sync_required","no_device_registered","access_removed","read_only","capability_missing","collection_deleted","collection_unavailable","moved_to_next_runtime","device_approval_required","collection_migrating","collection_not_yet_migrated","account_suspended","update_required","account_collection_quota_exceeded","invalid_request","invalid_record","not_found","conflict","unauthenticated","forbidden","collection_invalid","unavailable","rate_limited","quota_exceeded","too_large","outcome_unknown","internal","refused","expired","approval_window_closed","account_confirmation_required","recovery_required","installation_removed","open_failed","device_keys_unavailable","busy","open_in_another_tab","not_authorized","sign_out_pending_writes","sign_out_failed","application_popup_blocked","sign_in_window","application_not_yet_available","application_failed","application_worker_unavailable","browser_unsupported","application_storage_unavailable","storage_may_be_evicted","application_registration_unsupported","application_registration_refused","application_selection_not_approved","application_selection_invalid","installation_scope_removed","recovery_account_mismatch","assets","setup_required","incompatible","approval_required","contract_mismatch","contract_missing","implementation_missing","catalog_invalid","catalog_response","type_invalid","readiness_budget","readiness_unsupported","notifications_consent_required","timer_channel_reapproval_required","notifications_unsupported","people_unsupported","people_permission_declined","people_access","history_unsupported","configuration_conflict","configuration_unavailable","configuration_unsupported","configuration_busy_timeout","readiness_busy_timeout","setup_forbidden","setup_conflict","setup_unresolved","collection_setup_conflict","collection_setup_namespace_conflict","setup_records_forbidden","setup_changed","installed_newer","type_pack_conflict","invalid_type_pack","access_required","access_declined","access_undeclared","files_access_missing","files_scope_missing","file_read_failed","file_read_idle","collection_delete_name_mismatch","collection_delete_not_owner","collection_delete_not_found","collection_delete_frozen","collection_delete_busy","collection_delete_not_approved","collection_delete_sign_in","collection_delete_invalid","collection_delete_outcome_unknown","collection_delete_failed","wrong_secret","locked","weak_password","already_set_up","no_account_key","invalid_recovery_key","unlock_strict","unlock_unavailable","unlock_failed","private_device_limit","private_device_not_allowed"],hx=["Something went wrong","An unexpected problem occurred. Reload the app, and contact support if it keeps happening.","reload","error"],ZT=["Another step hasn't finished","The app couldn't finish this step yet. Try again, or reload if it keeps happening.","retry","warning",!0],QT=["Can't complete this request","mdbase couldn't complete this request. Try again.","retry","warning"],eM=["Update required","Update mdbase on this computer, then reload the app to try again.","update_app","warning",!1,"Update mdbase"],tM=["Choose a collection","Pick the collection you want this app to use.","choose_collection","info"],px=["Approval needed","This app needs your approval for extra access to your collection.","approve","info"],nM=["Set up this collection","This collection needs a one-time setup before the app can use it.","set_up","info"],iM=["Sign-in wasn't finished","Access wasn't approved. Sign in again when you're ready.","sign_in","info"],mx={device_offline:["Your computer isn't online","This collection is kept on your computer. Open the mdbase desktop app on a computer that has it, and this app connects as soon as it's online.","wait","info",!0],device_not_serving:["Your computer can't open this collection","Your computer is online, but mdbase there isn't serving this collection right now. Open the mdbase desktop app on that computer to see why. This app connects as soon as it can.","wait","warning",!0],desktop_update_required:["Update mdbase on your computer","The mdbase desktop app on the computer that has this collection is out of date. Update it there, then try again.","update_app","warning",!1,"Get the update"],old_connector_running:["Quit the old mdbase Connect app","The old mdbase Connect app is still running on the computer that has this collection. Quit it there (including its menu-bar or tray icon), then open the mdbase desktop app.","retry","warning"],sync_required:["Give this app access again","Access to this collection changed since you approved this app. Approve it again to keep using the collection.","approve","warning",!1,"Approve again"],no_device_registered:["Turn on sync for this collection","No computer is offering this collection to apps. Open the mdbase desktop app on the computer that has it and turn on sync. Web apps can reach a collection once sync is on.","retry","info"],installation_scope_removed:["Access was removed","This app's previous installation cannot regain access to this collection. Request access again to approve a new installation for this collection.","approve","warning",!1,"Request access again"],access_removed:["You no longer have access","You were removed from this collection, so this app can't open it. Ask its owner to add you again, or choose another collection.","choose_collection","warning"],collection_deleted:["Collection deleted","This collection was deleted, so it can't be opened any more. Choose another collection.","choose_collection","info"],collection_unavailable:["Collection not available","This collection can't be opened from this app right now. It may no longer be shared with this app, or the computer that offered it stopped. Choose another collection, or try again later.","choose_collection","warning"],moved_to_next_runtime:["mdbase was upgraded","This collection now uses the new version of mdbase. Update the app to keep using it; for a web app, reloading the page is enough. If the collection still doesn't appear, open the mdbase desktop app and turn on sync for it so web apps can reach it.","update_app","warning"],device_approval_required:["Waiting for your computer","Keep a computer with this collection running mdbase and signed in. This app connects when it is ready.","wait","info",!0],collection_not_yet_migrated:["Your collection needs an upgrade","Your data is safe. Open the latest mdbase desktop app on the computer that keeps this collection to finish upgrading it, then try again.","retry","info"],collection_migrating:["Your collection is being upgraded","Your data is safe. This usually takes a few minutes, and the app reconnects by itself when it's done.","wait","info",!0],account_suspended:["Your account is suspended","Your mdbase account has been suspended, so this app can't open your collections. Contact mdbase support for help.","contact_support","error"],update_required:eM,invalid_request:["Couldn't do that","Some of the information isn't valid. Check it and try again.","none","warning"],invalid_record:["Couldn't save that","Some fields aren't valid. Check them and try again.","none","warning"],not_found:["Not found","This item no longer exists. It may have been deleted on another device.","none","info"],conflict:["Changed somewhere else","This item was changed on another device. Review the latest version and try again.","retry","warning"],unauthenticated:["Sign in again","Your session has ended. Sign in again to continue.","sign_in","warning"],read_only:["View access only","You have view access, so changes can't be saved. Ask the collection's owner for edit access.","none","warning"],forbidden:["Access needed","This app doesn't have permission to do that. Approve access to continue.","approve","warning"],collection_invalid:["Your collection needs repair","Something in this collection isn't valid. Contact support if this keeps happening.","contact_support","error"],unavailable:QT,rate_limited:["Too many requests","Wait a moment, then try again.","retry","warning",!0],quota_exceeded:["Out of storage","Storage for this collection is full. Free up space to keep saving. If it's your collection and you're on the Free plan, you can upgrade to Plus from your mdbase account page.","free_space","error"],account_collection_quota_exceeded:["Synced collection limit reached",ax,"free_space","error",!1,"Manage collections"],too_large:["That's too large","This item is larger than mdbase allows.","none","warning"],outcome_unknown:["Not sure that worked","The connection dropped before mdbase confirmed it. Check whether it went through before trying again.","resolve_outcome","warning"],internal:hx,refused:["Sign-in didn't go through","mdbase didn't accept this sign-in. Try signing in again.","sign_in","warning"],installation_removed:["This app's access was removed","Sign out of this app on this device, then sign in to approve a new installation.","none","warning"],expired:["Sign-in timed out","The sign-in request expired. Start again to get a new one.","sign_in","warning"],approval_window_closed:["Sign-in wasn't finished","The mdbase window was closed before access was approved. Sign in again to continue.","sign_in","info"],account_confirmation_required:["Confirm your account","Confirm which mdbase account to use, then continue.","sign_in","info"],recovery_account_mismatch:["Use a different account","Sign in with the account you originally used for this collection to continue.","approve","info",!1,"Use a different account"],recovery_required:["Reload required","The app stopped to keep your data safe. Reload to continue.","reload","error"],open_failed:["Couldn't open your collection","Something went wrong while opening it. Reload the app to try again.","reload","error"],device_keys_unavailable:["Couldn't read this device's sign-in","This browser couldn't open the keys this app uses to sign in to mdbase. Reload to try again. If it keeps happening, sign out of mdbase in this app and sign in again.","reload","error"],busy:ZT,file_read_failed:["Couldn't load the file","mdbase couldn't finish downloading this file. Check your connection and try opening the collection again.","retry","warning"],file_read_idle:["File download timed out","The file download stopped making progress. Try opening the collection again.","retry","warning"],configuration_busy_timeout:["Collection setup is taking too long","The app is waiting for another setup or metadata request to finish. Try again; if it keeps happening, close other tabs of this app and reload.","retry","warning"],readiness_busy_timeout:["Collection checks are taking too long","The app couldn't get a stable view of the collection yet. Try again when the other step has finished.","retry","warning"],open_in_another_tab:["Open in another tab","This app is already open in another tab. Close that tab, or keep using it there; this tab continues by itself when it's free.","none","info",!0],not_authorized:["This app can't open this collection","This app isn't allowed to open this collection. Approve it again, or choose another collection.","approve","warning",!1,"Approve again"],sign_out_pending_writes:["Changes are still saving","Some changes haven't reached mdbase yet. Wait for them to finish, or sign out anyway and lose them on this device.","wait","warning",!1,"Wait"],sign_out_failed:["Couldn't finish signing out","This device couldn't remove all of its sign-in data. Reload the app and sign out again.","reload","error"],application_popup_blocked:["Allow pop-ups to sign in","Your browser blocked the sign-in window. Allow pop-ups for this site, then try again.","retry","warning"],sign_in_window:["Sign-in window problem","The sign-in window couldn't be opened. Try again.","retry","warning"],application_not_yet_available:["Not available yet","This app isn't available on this version of mdbase yet.","none","info"],application_failed:["The app stopped","Something inside the app stopped working. Your data is safe. Reload to continue.","reload","error"],application_worker_unavailable:["This browser can't run the app","Open the app in a current version of Chrome, Edge, Firefox or Safari.","none","error"],browser_unsupported:["This browser can't run mdbase","Update Safari to 17.4 or newer, Firefox to 130 or newer, or Chrome or Edge to 133 or newer, then open the app again.","none","error"],application_storage_unavailable:["This browser can't keep mdbase data on this device","Private browsing may be on. Open the app in a regular window so your changes can be kept safely on this device.","none","error"],storage_may_be_evicted:["Not synced yet","Some changes are only on this device. Stay online so they can sync.","check_connection","warning"],application_registration_unsupported:["This app can't connect","This version of the app isn't supported by mdbase. Update the app.","update_app","error"],application_registration_refused:["This app can't connect","This app can't connect right now. Contact the app's developer.","contact_support","error"],application_selection_not_approved:["Collection not approved","This app hasn't been given access to that collection. Approve it to continue.","approve","info"],application_selection_invalid:tM,assets:["The app couldn't load","Some of the app's files couldn't be loaded. Check your connection and reload.","reload","error"],setup_required:nM,incompatible:["This collection isn't compatible","This collection uses a format this version of the app doesn't support. Update the app.","update_app","error"],approval_required:px,capability_missing:px,contract_mismatch:["Your collection's format differs","This collection's record types don't match what this app expects. Set it up again or update the app.","set_up","warning"],contract_missing:["Set up this collection","This collection is missing record types this app needs. Set it up to continue.","set_up","info"],implementation_missing:["Set up this collection","A record type in this collection doesn't provide the fields this app needs. Set it up to continue.","set_up","info"],catalog_invalid:["A definition has a problem","A definition in this collection has an error, so the app can't open the collection safely. Fix the definition in your collection, and the app picks up the change.","none","warning"],catalog_response:["Couldn't read this collection's definitions","The app couldn't read how this collection is defined, so it didn't open it. Nothing was changed. Try again.","retry","warning"],type_invalid:["A record type isn't available","This record type has an error in its definition, so the app can't use it right now. Everything else still works. Fix the type in your collection to use it again.","none","warning"],readiness_budget:["This collection is too large to check","This collection has more definitions than the app can check at once. Contact the app's developer.","contact_support","warning"],readiness_unsupported:["Update the app","This collection uses features this version of the app can't check. Update the app to open it.","update_app","warning"],notifications_consent_required:["Allow reminders","Approve notifications so reminders can reach this device.","approve","info"],timer_channel_reapproval_required:["Allow reminders again","Approve notifications again so reminders keep reaching this device.","approve","info"],notifications_unsupported:["Reminders aren't available here","This browser or device can't receive notifications.","none","info"],people_unsupported:["Sharing isn't available here","People and sharing aren't supported for this collection yet.","none","info"],people_permission_declined:["People aren't shown","This app wasn't allowed to see who else is in this collection. Approve it again and allow people to show them here.","approve","info",!1,"Approve again"],people_access:["People can't be shown","This app can't see the people in this collection right now. Everything else still works.","none","info"],history_unsupported:["History isn't available here","Earlier versions of records in this collection can't be read here. Everything else still works.","none","info"],configuration_conflict:["Settings changed elsewhere","These settings were changed on another device. Review them and try again.","retry","warning"],configuration_unavailable:["Couldn't check this collection's setup","The app couldn't read how this collection is set up, so it didn't open it. Nothing in the collection was changed. Try again, and contact support if it keeps happening.","retry","warning"],configuration_unsupported:["This app can't set up this collection","This app's setup isn't supported by this version of mdbase. Contact the app's developer.","contact_support","warning"],setup_forbidden:["You can't set up this collection","Your access to this collection doesn't allow setting it up. Ask its owner to open it in this app first.","choose_collection","warning"],setup_conflict:["Setup needs your decision","Some things in this collection differ from what this app needs. Review them to continue.","set_up","warning",!1,"Review setup"],setup_unresolved:["Setup can't finish","This collection is missing a note format this app needs. Add or update a note type that supports that format, then try setup again.","retry","warning"],collection_setup_conflict:["Collection setup conflicts","Setting up this app would conflict with definitions already in this collection, so nothing was changed. A note type may have been renamed or customised and still use an older definition. Update or remove it, then try again.","retry","warning"],collection_setup_namespace_conflict:["A file is in the way","A file in this collection is stored where this app needs to save part of its setup, and its contents differ. Move or rename that file, then try again. Nothing was changed.","retry","warning"],setup_records_forbidden:["You can't add notes to this collection","Your access to this collection doesn't allow creating notes, which this app's setup needs. Ask its owner for more access.","choose_collection","warning"],setup_changed:["This collection changed","The collection changed while you were reviewing its setup. Review the setup again; nothing was changed yet.","set_up","info",!1,"Review again"],installed_newer:["Update the app","A newer version of this app set up this collection with changes this version can't use. Update the app to keep using the collection.","update_app","warning"],type_pack_conflict:["Setup needs your decision","Some record types already exist with different content. Review them to continue.","set_up","warning",!1,"Review setup"],invalid_type_pack:["This app's setup has a problem","Setting up this collection would leave it invalid, so nothing was changed. Contact the app's developer.","contact_support","warning"],access_required:["Allow this app to change files?","This app needs your permission before it can add or change files in this collection.","approve","info",!1,"Allow"],access_declined:["Not allowed","You chose not to allow this. Everything else in the app works as before, and you can allow it the next time you try.","none","info"],access_undeclared:["This app can't do that","This app isn't set up to change files this way. Contact the app's developer if you need it.","none","warning"],files_access_missing:["This app can't use this collection","Your access to this collection doesn't include the file changes this app needs. Ask the collection's owner for more access.","none","warning"],files_scope_missing:["This app can't use this collection","This app needs access to all files in this collection, but your access covers only some folders. Ask the collection's owner for more access.","none","warning"],collection_delete_name_mismatch:["The name doesn't match","Type the collection's current name exactly to delete it.","none","warning"],collection_delete_not_owner:["Only the owner can delete this","Ask the collection's owner to delete it.","none","info"],collection_delete_not_found:["Collection not found","This collection no longer exists, or this app can't reach it. It may already have been deleted.","none","info"],collection_delete_frozen:["Can't delete right now","Your account is being upgraded, so collections can't be deleted until that finishes. Try again later.","retry","warning"],collection_delete_busy:["mdbase is busy","Wait a moment, then try deleting again.","retry","warning",!0],collection_delete_not_approved:["This app can't delete this collection","This app doesn't have access to this collection anymore. Approve it again, then try again.","approve","warning"],collection_delete_sign_in:["Sign in again","This device's sign-in is no longer current. Sign in again, then try deleting again.","sign_in","warning"],collection_delete_invalid:["Couldn't delete the collection","Check the name you typed and try again.","none","warning"],collection_delete_outcome_unknown:["Not sure the collection was deleted","The connection dropped before mdbase confirmed. Reload your collections to check before trying again.","resolve_outcome","warning"],collection_delete_failed:["Couldn't delete the collection","Something went wrong. Try again, and contact support if it keeps happening.","retry","error"],wrong_secret:["That isn't right","The password or recovery key doesn't match. Check it and try again.","none","warning"],locked:["Too many attempts","Wait a few minutes before trying again.","wait","warning",!0],weak_password:["Choose a stronger password","That password is too easy to guess. Use a longer one, or a few unrelated words.","none","warning"],already_set_up:["Already set up","Your account key is already set up on this account.","none","info"],no_account_key:["Set up your account key","This account doesn't have an account key yet. Set one up to use Private collections.","none","info"],invalid_recovery_key:["Check the recovery key","That doesn't look like a recovery key. Check for missing or mistyped characters and try again.","none","warning"],unlock_strict:["Can't be unlocked here","This account approves each device from another device instead of using an encryption password, and this app can't do that yet. Use the mdbase desktop app on a computer that has this collection.","none","info"],unlock_unavailable:["This app can't unlock yet","This version of the app can't unlock Private collections. Update the app, then try again.","update_app","warning"],unlock_failed:["Couldn't unlock this collection","Your password or recovery key is right, but this collection didn't give this device its key. Try again. If it keeps happening, open the mdbase desktop app on a computer that has this collection.","retry","warning"],private_device_limit:["One Private collection per app","This app already keeps another Private collection on this device, and it can keep only one. Open that collection, or sign out of mdbase in this app to switch.","choose_collection","warning"],private_device_not_allowed:["This app can't keep this collection","Access to this Private collection can't be restored in this app on this server. Open it in the mdbase desktop app on a computer that has it.","none","warning"]},Kf=Object.assign(Object.create(null),{no_device_online:"device_offline",not_served:"device_not_serving",collection_moved:"moved_to_next_runtime",client_update_required:"update_required",upgrade_required:"update_required",declared_setup_unsupported:"update_required",resource_setup_unsupported:"update_required",type_packs_unsupported:"update_required",describe_definitions_unsupported:"update_required",contract_records_unsupported:"update_required",record_links_unsupported:"update_required",backlinks_unsupported:"update_required",resolve_links_unsupported:"update_required",change_entity_unsupported:"update_required",timer_operation_recovery_unavailable:"update_required",contract_query_version:"update_required",contract_query_order_unsupported:"update_required",contract_query_order_mtime_unsupported:"update_required",bases_row_properties_unsupported:"update_required",unsupported_push_version:"update_required",fenced:"busy",reconnecting:"busy",application_busy:"busy",application_fenced:"busy",application_entry_fenced:"busy",application_asset_fenced:"busy",application_connection_busy:"busy",application_connection_fenced:"busy",application_readiness_busy:"busy",application_readiness_fenced:"busy",application_registration_fenced:"busy",application_selection_busy:"busy",application_selection_fenced:"busy",application_worker_busy:"busy",application_worker_fenced:"busy",application_popup_fenced:"busy",readiness_fenced:"busy",readiness_busy:"busy",readiness_changed:"busy",configuration_busy:"busy",configuration_fenced:"busy",files_fenced:"busy",people_fenced:"busy",people_readiness_busy:"busy",people_readiness_fenced:"busy",notification_readiness_busy:"busy",notification_readiness_fenced:"busy",record_links_fenced:"busy",binding:"application_failed",response:"application_failed",application_declaration:"application_failed",application_connection_binding:"application_failed",application_popup_binding:"application_failed",application_registration_response:"application_failed",application_selection_binding:"application_failed",application_worker_binding:"application_failed",application_worker_module_binding:"application_failed",application_entry_unavailable:"application_failed",application_readiness_unavailable:"application_failed",configuration_binding:"application_failed",configuration_response:"application_failed",files_unavailable:"application_failed",application_stop_failed:"recovery_required",application_worker_stop_failed:"recovery_required",application_popup_stop_failed:"recovery_required",configuration_recovery_required:"recovery_required",application_popup_unavailable:"sign_in_window",application_registration_unavailable:"unavailable",application_registration_unknown:"unavailable",application_connection_unavailable:"unavailable",readiness_unavailable:"unavailable",grant_activation_timeout:"unavailable",relay_closed:"unavailable",pipe_closed:"unavailable",authorization_unavailable:"unavailable",grant_lease_expired:"unavailable",grant_inactive:"forbidden",connector_busy:"rate_limited",application_connection_people_unavailable:"people_access",people_unavailable:"people_access",people_response:"people_access",people_binding:"people_access",people_budget:"people_access",people_incomplete:"people_access",application_selection_empty:"application_selection_invalid",application_selection_duplicate:"application_selection_invalid",application_selection_metadata:"application_selection_invalid",application_lab_trust_unavailable:"assets",application_production_trust_unavailable:"assets",application_release_trust_unavailable:"assets",application_packaged_assets_unavailable:"assets",application_asset_fetch:"assets",grant_required:"approval_required",readiness_capability_version:"readiness_unsupported",readiness_type_invalid:"type_invalid",configuration_not_authorized:"setup_forbidden",configuration_unsupported_source_provision:"configuration_unsupported",setup_downgrade:"installed_newer",type_pack_downgrade:"installed_newer",installed_newer_major:"installed_newer",timer_push_platform:"notifications_unsupported",push_registration_missing:"notifications_consent_required"}),dx=Object.assign(Object.create(null),{budget:"readiness_budget",unsupported:"readiness_unsupported"}),rM=["application_registration_id_superseded","application_closing","cancelled","aborted"],yx=new Set(rM),Wf=Object.assign(Object.create(null),{device_offline:"Collection availability device_offline: no device serving this Private collection is connected to the relay.",device_not_serving:"Collection availability device_not_serving / relay close not_served: the device is online but is not serving this Private collection right now (paused, opening, recovering, failed, or removed on that computer). Check the collection's status in mdbase on that computer; connect with waitForDevice keeps retrying.",desktop_update_required:"Collection availability desktop_update_required: the serving device's last relay connection was refused as incompatible.",old_connector_running:"Collection availability old_connector_running: the serving device reports a legacy connector still holding its collections.",device_approval_required:"Collection availability approval_required: no device has signed an approval for this app's grant yet.",sync_required:"Collection availability sync_required: the grant no longer matches the collection's membership; run authorize() again.",no_device_registered:"Collection availability no_device_registered: Connect has no device that can serve this collection (none registered with sync on, or its device was revoked).",installation_scope_removed:"The original installation lost this collection scope. Only explicit approval of a fresh scoped installation can regain access.",private_device_not_allowed:"Connect refused a recovery sign-in's Private device access (403 installation_private_device_not_allowed): MDBASE_NEXT_PRIVATE_APP_DEVICES is off, or the registered manifest does not declare offline.replica.",access_removed:"Collection availability access_removed: the grant's account is no longer a member of the collection.",collection_deleted:"Collection availability collection_deleted: the owner deleted the collection.",collection_unavailable:"Connect problem collection_unavailable without a known reason: the collection is not offered to this app or client.",moved_to_next_runtime:"Connect problem collection_unavailable, reason moved_to_next_runtime: a legacy route was used for a collection that completed its move to mdbase-next.",people_permission_declined:"People members request refused (people_permission_declined): the person did not grant the people permission for this app.",people_access:"People request refused (people_access).",access_required:"access_required: an optional file action the person has not allowed. Call requestAccess from the user's action, then retry.",access_undeclared:"access_undeclared: the file action is not in the manifest's requirements.files.",installed_newer:"installed_newer: an installed type pack has a different major version than the one this app ships; same-major newer packs open read/write.",application_registration_id_superseded:"The declared application ID is an earlier registration ID: mdbase registers each exact manifest under its own ID, so it changes with the manifest. The SDK uses the registered ID and keeps the declared storage names. Declare the manifest's logical `id` (stable across manifest changes and origins) with pinned storage names to remove this note.",application_worker_unavailable:"application_worker_unavailable: this page cannot construct the SDK's module Worker (no Worker/MessageChannel, or a non-web origin).",browser_unsupported:"browser_unsupported: the SDK's upfront capability probe found a required browser feature missing (Web Crypto/X25519, AbortSignal.any, Web Locks, BroadcastChannel, IndexedDB, Worker/MessageChannel or crypto.randomUUID); see the MdbaseError details for the missing tokens.",application_storage_unavailable:"application_storage_unavailable: navigator.storage.getDirectory() (OPFS) is absent or rejected, as in private browsing; the local replica cannot be kept on this device.",storage_may_be_evicted:"storage_may_be_evicted: replica edits are pending for at least 30 seconds or while disconnected on nonpersistent storage (`storage_may_be_evicted` in snapshot.sync.attention); only a log-confirmed receipt counts as saved.",device_keys_unavailable:"device_keys_unavailable: this installation's device custody in IndexedDB (key encryption key, device keys or Noise vault) could not be opened or did not hold the attested device. Before attestation the SDK recreates it by itself; after attestation only signOut() and a fresh sign-in replace it.",sign_out_pending_writes:"sign_out_pending_writes: unconfirmed writes are still queued on this device; signOut({discard: true}) discards them."}),oM=/^[a-z][a-z0-9_-]{0,127}$/,Zr=n=>typeof n=="string"&&oM.test(n)?n:null,_i=n=>n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null,sM=n=>typeof n=="number"&&Number.isFinite(n)&&n>=0?Math.min(Ja,Math.max(Ya,Math.round(n))):null,ux=n=>Object.hasOwn(mx,n)});function Xa(n){if(typeof n!="string"||n.length>256)return null;let e=lM.exec(n.trim());if(!e)return null;let t=[e[1],e[2],e[3]].map(Number);if(t.some(o=>!Number.isSafeInteger(o)))return null;let i=e[4]?e[4].split(".").map(o=>/^\d+$/.test(o)?Number(o):o):[];return i.some(o=>typeof o=="number"&&!Number.isSafeInteger(o))?null:Object.freeze({major:t[0],minor:t[1],patch:t[2],prerelease:Object.freeze(i)})}function xw(n,e){let t=typeof n=="string"?Xa(n):n,i=typeof e=="string"?Xa(e):e;if(!t||!i)return null;for(let o of["major","minor","patch"])if(t[o]!==i[o])return t[o]<i[o]?-1:1;if(!t.prerelease.length&&!i.prerelease.length)return 0;if(!t.prerelease.length)return 1;if(!i.prerelease.length)return-1;for(let o=0;o<Math.max(t.prerelease.length,i.prerelease.length);o++){let s=t.prerelease[o],r=i.prerelease[o];if(s===void 0)return-1;if(r===void 0)return 1;if(s!==r)return typeof s=="number"&&typeof r=="number"?s<r?-1:1:typeof s=="number"?-1:typeof r=="number"?1:s<r?-1:1}return 0}function Ts(n,e){let t=Xa(n),i=Xa(e),o=t&&i?xw(t,i):null;return o===null?"unknown":o===0?"same":o<0?"installed_older":t.major===i.major?"installed_newer":"installed_newer_major"}var Gf,wx,lM,Yf=I(()=>{"use strict";Gf="0|[1-9]\\d*",wx=`(?:${Gf}|\\d*[a-zA-Z-][0-9a-zA-Z-]*)`,lM=new RegExp(`^v?(${Gf})\\.(${Gf})\\.(${Gf})(?:-(${wx}(?:\\.${wx})*))?(?:\\+[0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*)?$`)});function Zf(n){return n.storage.applicationNamespace===n.id?null:n.storage.applicationNamespace}function Cw(n){return Array.from(Ze(new TextEncoder().encode(n)),e=>e.toString(16).padStart(2,"0")).join("")}function _x(n,e){return e===null?`bundle:${n}`:`bundle-storage:${Cw(JSON.stringify([n,e]))}`}var Qf=I(()=>{"use strict";hr()});function He(n){if(n&&typeof n=="object")switch(n[On]){case Ki:case eo:return!0}return!1}function je(n){if(n&&typeof n=="object")switch(n[On]){case eh:case Ki:case oi:case eo:return!0}return!1}var eh,th,Ki,Iw,oi,eo,On,Wi,br,si,qe,Ae,Hi,nh,Ne=I(()=>{eh=Symbol.for("yaml.alias"),th=Symbol.for("yaml.document"),Ki=Symbol.for("yaml.map"),Iw=Symbol.for("yaml.pair"),oi=Symbol.for("yaml.scalar"),eo=Symbol.for("yaml.seq"),On=Symbol.for("yaml.node.type"),Wi=n=>!!n&&typeof n=="object"&&n[On]===eh,br=n=>!!n&&typeof n=="object"&&n[On]===th,si=n=>!!n&&typeof n=="object"&&n[On]===Ki,qe=n=>!!n&&typeof n=="object"&&n[On]===Iw,Ae=n=>!!n&&typeof n=="object"&&n[On]===oi,Hi=n=>!!n&&typeof n=="object"&&n[On]===eo;nh=n=>(Ae(n)||He(n))&&!!n.anchor});function vr(n,e){let t=kx(e);br(n)?Za(null,n.contents,t,Object.freeze([n]))===wr&&(n.contents=null):Za(null,n,t,Object.freeze([]))}function Za(n,e,t,i){let o=Sx(n,e,t,i);if(je(o)||qe(o))return Px(n,i,o),Za(n,o,t,i);if(typeof o!="symbol"){if(He(e)){i=Object.freeze(i.concat(e));for(let s=0;s<e.items.length;++s){let r=Za(s,e.items[s],t,i);if(typeof r=="number")s=r-1;else{if(r===Kn)return Kn;r===wr&&(e.items.splice(s,1),s-=1)}}}else if(qe(e)){i=Object.freeze(i.concat(e));let s=Za("key",e.key,t,i);if(s===Kn)return Kn;s===wr&&(e.key=null);let r=Za("value",e.value,t,i);if(r===Kn)return Kn;r===wr&&(e.value=null)}}return o}async function ih(n,e){let t=kx(e);br(n)?await Qa(null,n.contents,t,Object.freeze([n]))===wr&&(n.contents=null):await Qa(null,n,t,Object.freeze([]))}async function Qa(n,e,t,i){let o=await Sx(n,e,t,i);if(je(o)||qe(o))return Px(n,i,o),Qa(n,o,t,i);if(typeof o!="symbol"){if(He(e)){i=Object.freeze(i.concat(e));for(let s=0;s<e.items.length;++s){let r=await Qa(s,e.items[s],t,i);if(typeof r=="number")s=r-1;else{if(r===Kn)return Kn;r===wr&&(e.items.splice(s,1),s-=1)}}}else if(qe(e)){i=Object.freeze(i.concat(e));let s=await Qa("key",e.key,t,i);if(s===Kn)return Kn;s===wr&&(e.key=null);let r=await Qa("value",e.value,t,i);if(r===Kn)return Kn;r===wr&&(e.value=null)}}return o}function kx(n){return typeof n=="object"&&(n.Collection||n.Node||n.Value)?Object.assign({Alias:n.Node,Map:n.Node,Scalar:n.Node,Seq:n.Node},n.Value&&{Map:n.Value,Scalar:n.Value,Seq:n.Value},n.Collection&&{Map:n.Collection,Seq:n.Collection},n):n}function Sx(n,e,t,i){if(typeof t=="function")return t(n,e,i);if(si(e))return t.Map?.(n,e,i);if(Hi(e))return t.Seq?.(n,e,i);if(qe(e))return t.Pair?.(n,e,i);if(Ae(e))return t.Scalar?.(n,e,i);if(Wi(e))return t.Alias?.(n,e,i)}function Px(n,e,t){let i=e[e.length-1];if(He(i))i.items[n]=t;else if(qe(i))n==="key"?i.key=t:i.value=t;else if(br(i))i.contents=t;else{let o=Wi(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var Kn,Ax,wr,qp=I(()=>{Ne();Kn=Symbol("break visit"),Ax=Symbol("skip children"),wr=Symbol("remove node");vr.BREAK=Kn;vr.SKIP=Ax;vr.REMOVE=wr;ih.BREAK=Kn;ih.SKIP=Ax;ih.REMOVE=wr});var dM,uM,_r,Ow=I(()=>{Ne();qp();dM={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},uM=n=>n.replace(/[!,[\]{}]/g,e=>dM[e]),_r=class n{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},n.defaultYaml,e),this.tags=Object.assign({},n.defaultTags,t)}clone(){let e=new n(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new n(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:n.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},n.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:n.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},n.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),o=i.shift();switch(o){case"%TAG":{if(i.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,r]=i;return this.tags[s]=r,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let r=/^\d+\.\d+$/.test(s);return t(6,`Unsupported YAML version ${s}`,r),!1}}default:return t(0,`Unknown directive ${o}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let r=e.slice(2,-1);return r==="!"||r==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),r)}let[,i,o]=e.match(/^(.*!)([^!]*)$/s);o||t(`The ${e} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(o)}catch(r){return t(String(r)),null}return i==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,i]of Object.entries(this.tags))if(e.startsWith(i))return t+uM(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),o;if(e&&i.length>0&&je(e.contents)){let s={};vr(e.contents,(r,a)=>{je(a)&&a.tag&&(s[a.tag]=!0)}),o=Object.keys(s)}else o=[];for(let[s,r]of i)s==="!!"&&r==="tag:yaml.org,2002:"||(!e||o.some(a=>a.startsWith(r)))&&t.push(`%TAG ${s} ${r}`);return t.join(`
1
+ "use strict";var MdbaseSDK=(()=>{var qg=Object.defineProperty;var rq=Object.getOwnPropertyDescriptor;var oq=Object.getOwnPropertyNames;var sq=Object.prototype.hasOwnProperty;var I=(n,e,t)=>()=>{if(t)throw t[0];try{return n&&(e=n(n=0)),e}catch(i){throw t=[i],i}};var Ca=(n,e)=>{for(var t in e)qg(n,t,{get:e[t],enumerable:!0})},aq=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of oq(e))!sq.call(n,o)&&o!==t&&qg(n,o,{get:()=>e[o],enumerable:!(i=rq(e,o))||i.enumerable});return n};var lq=n=>aq(qg({},"__esModule",{value:!0}),n);function vo(n){return Object.prototype.hasOwnProperty.call(vu,n)}function cq(n){return vo(n)?vu[n]:"contact_support"}function A(n,e,t={}){let i=typeof t=="string"?{reason:t}:t;return new oe({code:n,recovery:vu[n],message:e,...i})}function X(n,e){return n instanceof oe&&(e===void 0||n.code===e)}var vu,oe,re=I(()=>{"use strict";vu={invalid_request:"fix_request",invalid_record:"fix_request",not_found:"refresh",conflict:"resolve_conflict",unauthenticated:"reauthorize",forbidden:"reauthorize",collection_invalid:"repair_collection",unavailable:"retry",rate_limited:"retry",quota_exceeded:"free_space",too_large:"fix_request",upgrade_required:"upgrade",outcome_unknown:"resolve_outcome",cancelled:"none",internal:"contact_support"};oe=class extends Error{code;recovery;reason;details;retryAfterMs;issues;traceId;mutationId;constructor(e,t={}){super(e.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="MdbaseError",this.code=vo(e.code)?e.code:"internal",this.recovery=vo(e.code)?e.recovery:"contact_support",e.reason!==void 0&&(this.reason=e.reason),e.details!==void 0&&(this.details=e.details),e.retryAfterMs!==void 0&&(this.retryAfterMs=e.retryAfterMs),e.issues!==void 0&&(this.issues=e.issues),e.traceId!==void 0&&(this.traceId=e.traceId),t.mutationId!==void 0&&(this.mutationId=t.mutationId)}toProblem(){let e={code:this.code,recovery:this.recovery,message:this.message};return this.reason!==void 0&&(e.reason=this.reason),this.details!==void 0&&(e.details=this.details),this.retryAfterMs!==void 0&&(e.retryAfterMs=this.retryAfterMs),this.issues!==void 0&&(e.issues=this.issues),this.traceId!==void 0&&(e.traceId=this.traceId),e}}});function hq(n){let e=n.isWellFormed;if(e)return e.call(n);for(let t=0;t<n.length;t++){let i=n.charCodeAt(t);if(i>=55296&&i<=56319){let o=n.charCodeAt(t+1);if(!(o>=56320&&o<=57343))return!1;t++}else if(i>=56320&&i<=57343)return!1}return!0}function tk(n,e){let t=typeof e=="bigint"?e:BigInt(e);if(t>=0n){if(t>pq)throw new Me("unencodable","integer above 2^64-1");n.head(0,typeof e=="number"?e:t)}else{if(t<dq)throw new Me("unencodable","integer below -2^63");let i=-1n-t;n.head(1,i<=BigInt(Number.MAX_SAFE_INTEGER)?Number(i):i)}}function mq(n,e,t){let i=[...e.entries()];ik(i.map(([o])=>o)),n.head(5,i.length);for(let[o,s]of i)typeof o=="number"?n.head(0,o):nk(n,o),Au(n,s,t+1)}function nk(n,e){if(e.length<24&&!/[^\x00-\x7f]/u.test(e))return n.shortAscii(e);if(!hq(e))throw new Me("utf8","text is not well-formed UTF-16");let t=uq.encode(e);try{n.head(3,t.length),n.bytes(t)}finally{n.wipeTemporary(t)}}function ik(n){if(n.length===0)return;if(typeof n[0]=="string"){let t=new Set;for(let i of n){if(typeof i!="string")throw new Me("mixed_map_keys");if(t.has(i))throw new Me("duplicate_key",`duplicate data map key ${JSON.stringify(i)}`);t.add(i)}return}let e;for(let t of n){if(typeof t=="string")throw new Me("mixed_map_keys");if(typeof t=="number"&&!(Number.isSafeInteger(t)&&t>=0))throw new Me("mixed_map_keys","struct map keys must be unsigned integers");let i=BigInt(t);if(i<0n)throw new Me("mixed_map_keys");if(e!==void 0&&e>=i)throw new Me("unsorted_keys");e=i}}function Au(n,e,t){if(t>Mg)throw new Me("too_deep");if(e===null)return n.byte(246);switch(typeof e){case"boolean":return n.byte(e?245:244);case"number":return Number.isSafeInteger(e)&&!Object.is(e,-0)?tk(n,e):n.float(e);case"bigint":return tk(n,e);case"string":return nk(n,e)}if(e instanceof vt)return n.float(e.value);if(e instanceof Uint8Array)return n.head(2,e.length),n.bytes(e);if(Array.isArray(e)){n.head(4,e.length);for(let i of e)Au(n,i,t+1);return}if(e instanceof Map)return mq(n,e,t);throw new Me("unencodable",`cannot encode ${Object.prototype.toString.call(e)}`)}function fe(n){let e=new _u;return Au(e,n,0),e.result()}function zn(n){let e=new _u(!0);try{return Au(e,n,0),e.result()}finally{e.buf.fill(0)}}function we(n){let e=new Tg(n),t=e.item(0);if(e.remaining!==0)throw new Me("trailing_bytes");return t}function yq(n){try{return we(n),!0}catch{return!1}}function Lg(n){let e=new Map;for(let[t,i]of n)i!==void 0&&e.set(t,i);return e}function ut(n){let e="";for(let t of n)e+=gq[t];return e}function Br(n){if(n.length%2!==0||!/^[0-9a-fA-F]*$/.test(n))throw new Error("invalid hex");let e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function jg(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!==e[t])return!1;return!0}var vt,Mg,Me,pq,dq,uq,fq,_u,Tg,gq,Je=I(()=>{"use strict";vt=class{constructor(e){this.value=e}value;valueOf(){return this.value}toJSON(){return this.value}},Mg=128,Me=class extends Error{constructor(t,i){super(i??t);this.kind=t;this.name="CborError"}kind},pq=(1n<<64n)-1n,dq=-(1n<<63n),uq=new TextEncoder,fq=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),_u=class{constructor(e=!1){this.sensitive=e}sensitive;buf=new Uint8Array(256);len=0;view=new DataView(this.buf.buffer);ensure(e){if(this.len+e<=this.buf.length)return;let t=this.buf.length*2;for(;t<this.len+e;)t*=2;let i=new Uint8Array(t);i.set(this.buf.subarray(0,this.len)),this.sensitive&&this.buf.fill(0),this.buf=i,this.view=new DataView(i.buffer)}byte(e){this.ensure(1),this.buf[this.len++]=e}bytes(e){this.ensure(e.length),this.buf.set(e,this.len),this.len+=e.length}shortAscii(e){this.ensure(1+e.length),this.buf[this.len++]=96|e.length;for(let t=0;t<e.length;t++)this.buf[this.len++]=e.charCodeAt(t)}head(e,t){let i=e<<5;if(typeof t=="number"&&t<24)this.byte(i|t);else if(typeof t=="number"&&t<=255)this.ensure(2),this.buf[this.len++]=i|24,this.buf[this.len++]=t;else if(typeof t=="number"&&t<=65535)this.ensure(3),this.buf[this.len++]=i|25,this.view.setUint16(this.len,t),this.len+=2;else if(typeof t=="number"&&t<=4294967295)this.ensure(5),this.buf[this.len++]=i|26,this.view.setUint32(this.len,t),this.len+=4;else{let o=BigInt(t);if(o<=0xffffffffn)return this.head(e,Number(o));this.ensure(9),this.buf[this.len++]=i|27,this.view.setBigUint64(this.len,o),this.len+=8}}float(e){if(!Number.isFinite(e))throw new Me("float","float must be finite");this.ensure(9),this.buf[this.len++]=251,this.view.setFloat64(this.len,e),this.len+=8}wipeTemporary(e){this.sensitive&&e.fill(0)}result(){return this.buf.slice(0,this.len)}};Tg=class{constructor(e){this.buf=e;this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}buf;pos=0;view;get remaining(){return this.buf.length-this.pos}need(e){if(e>this.remaining)throw new Me("unexpected_end")}byte(){return this.need(1),this.buf[this.pos++]}take(e){this.need(e);let t=this.buf.subarray(this.pos,this.pos+e);return this.pos+=e,t}arg(e){if(e<24)return e;switch(e){case 24:{let t=this.byte();if(t<24)throw new Me("non_canonical_head");return t}case 25:{this.need(2);let t=this.view.getUint16(this.pos);if(this.pos+=2,t<=255)throw new Me("non_canonical_head");return t}case 26:{this.need(4);let t=this.view.getUint32(this.pos);if(this.pos+=4,t<=65535)throw new Me("non_canonical_head");return t}case 27:{this.need(8);let t=this.view.getBigUint64(this.pos);if(this.pos+=8,t<=0xffffffffn)throw new Me("non_canonical_head");return t<=BigInt(Number.MAX_SAFE_INTEGER)?Number(t):t}case 31:throw new Me("indefinite");default:throw new Me("non_canonical_head","reserved additional info")}}len(e){let t=this.arg(e);if(typeof t=="bigint")throw new Me("too_long");if(t>this.remaining)throw new Me("unexpected_end");return t}item(e){if(e>Mg)throw new Me("too_deep");let t=this.byte(),i=t>>5,o=t&31;switch(i){case 0:return this.arg(o);case 1:{let s=this.arg(o);if(typeof s=="number"){let r=-1-s;return Number.isSafeInteger(r)?r:-1n-BigInt(s)}return-1n-s}case 2:return this.take(this.len(o)).slice();case 3:{let s=this.take(this.len(o));try{return fq.decode(s)}catch{throw new Me("utf8")}}case 4:{let s=this.len(o),r=new Array(s);for(let a=0;a<s;a++)r[a]=this.item(e+1);return r}case 5:{let s=this.len(o),r=[],a=[];for(let l=0;l<s;l++){let p=this.item(e+1);if(typeof p!="string"&&typeof p!="number"&&typeof p!="bigint")throw new Me("mixed_map_keys");if((typeof p=="number"||typeof p=="bigint")&&p<0)throw new Me("mixed_map_keys");r.push(p),a.push(this.item(e+1))}ik(r);let c=new Map;for(let l=0;l<s;l++){let p=r[l];if(typeof p=="bigint")throw new Me("too_long","struct key beyond 2^53");c.set(p,a[l])}return c}case 6:throw new Me("tag");default:switch(o){case 20:return!1;case 21:return!0;case 22:return null;case 27:{this.need(8);let s=this.view.getFloat64(this.pos);if(this.pos+=8,!Number.isFinite(s))throw new Me("float");return Number.isInteger(s)?new vt(s):s}case 25:case 26:throw new Me("float","float must be binary64");case 31:throw new Me("indefinite");default:throw new Me("simple")}}}};gq=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"))});function ei(n){return n===null||typeof n=="boolean"||typeof n=="number"||typeof n=="string"?n:typeof n=="bigint"?n.toString():n instanceof vt?n.value:n instanceof Uint8Array?ut(n):Array.isArray(n)?n.map(ei):Object.fromEntries([...n].map(([e,t])=>[String(e),ei(t)]))}function de(n,e){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&Object.hasOwn(n,e)?n[e]:void 0}function Fe(n){if(n==null)return null;if(typeof n!="object"||n instanceof vt)return n;if(Array.isArray(n))return n.map(Fe);if(n instanceof Map){let t=new Map;for(let[i,o]of n)t.set(i,Fe(o));return t}if(n instanceof Date)return n.toISOString();let e=new Map;for(let[t,i]of Object.entries(n))i!==void 0&&e.set(t,Fe(i));return e}var un=I(()=>{"use strict";Je()});function _o(n,e){let t=Fc;Fc=!0;try{return n.dec(e)}finally{Fc=t}}function ku(n){return{name:n.name,enc:()=>{throw new ae(n.name,"an answer is decoded, never encoded")},dec:e=>_o(n,e)}}function bq(n){return n===null?"null":n instanceof Uint8Array?"bytes":n instanceof vt?"float":Array.isArray(n)?"array":n instanceof Map?"map":typeof n=="number"?Number.isInteger(n)?"int":"float":typeof n}function $n(n,e,t){return new ae(n,`expected ${e}, found ${bq(t)}`)}function ok(n,e){return{name:e,enc:t=>{if(!(t instanceof Uint8Array)||t.length!==n)throw new ae(e,`must be ${n} bytes`);return t},dec:t=>{if(!(t instanceof Uint8Array))throw $n(e,"bytes",t);if(t.length!==n)throw new ae(e,`must be ${n} bytes`);return t}}}function N(n){if(!wq.test(n))throw new ae("uuid",`not a UUID: ${n}`);return Br(n.replace(/-/g,""))}function Wc(n){let e=ut(n);return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20,32)}`}function Su(n){let e=/^sha256:([0-9a-f]{64})$/.exec(n);if(!e)throw new ae("hash",`not a sha256: revision token: ${n}`);return Br(e[1])}function Ug(n){return`sha256:${ut(n)}`}function Kc(n,e=0){if(e>128)throw new ae("value","nesting too deep");if(n instanceof Uint8Array)throw new ae("value","byte strings are not values");if(typeof n=="bigint"){if(n>0x7fffffffffffffffn||n<-0x8000000000000000n)throw new ae("value","integer outside int64");return}if(Array.isArray(n))for(let t of n)Kc(t,e+1);else if(n instanceof Map)for(let[t,i]of n){if(typeof t!="string")throw new ae("value","map keys must be text");Kc(i,e+1)}}function G(n,e={}){let t=`[${n.name}]`;return{name:t,enc:i=>{if(e.nonEmpty&&i.length===0)throw new ae(t,"list must not be empty");return i.map(o=>n.enc(o))},dec:i=>{if(!Array.isArray(i))throw $n(t,"array",i);if(e.nonEmpty&&i.length===0)throw new ae(t,"list must not be empty");return i.map(o=>n.dec(o))}}}function Hc(n){let e=`{tstr => ${n.name}}`;return{name:e,enc:t=>{let i=new Map;for(let[o,s]of t)i.set(o,n.enc(s));return i},dec:t=>{if(!(t instanceof Map))throw $n(e,"map",t);let i=new Map;for(let[o,s]of t){if(typeof o!="string")throw new ae(e,"data map keys must be text");i.set(o,n.dec(s))}return Fc?Object.fromEntries(i):i}}}function xu(n,e,t,i,o){return{name:n,enc:s=>t(s)?e.enc(s):o.enc(s),dec:s=>i(s)?e.dec(s):o.dec(s)}}function Se(n,e,t=0){let i=new Map(e.map((o,s)=>[o,s+t]));return{name:n,values:e,enc:o=>{let s=i.get(o);if(s===void 0)throw new ae(n,`unknown value ${JSON.stringify(o)}`);return s},dec:o=>{if(typeof o=="bigint")throw new ae(n,`unknown variant ${o}`,!0);if(typeof o!="number"||!Number.isInteger(o)||o<0)throw $n(n,"uint enum",o);let s=o>=t?e[o-t]:void 0;if(s===void 0)throw new ae(n,`unknown variant ${o}`,!0);return s}}}function z(n,e){for(let t=1;t<e.length;t++)if(e[t][0]<=e[t-1][0])throw new Error(`${n}: field keys must ascend`);return{name:n,enc:t=>{let i=new Map,o=t;for(let[s,r,a,c="req"]of e){let l=o[r];if(l===void 0){if(c==="req"||c==="req1")throw new ae(n,`missing required field ${r}`);continue}if((c==="req1"||c==="opt1")&&Array.isArray(l)&&l.length===0)throw new ae(n,`${r} must not be empty`);i.set(s,a.enc(l))}return i},dec:t=>{if(!(t instanceof Map))throw $n(n,"struct map",t);let i=t;for(let s of i.keys())if(typeof s!="number")throw $n(n,"struct map",t);let o={};for(let[s,r,a,c="req"]of e){let l=i.get(s);if(l===void 0){if(c==="req"||c==="req1")throw new ae(n,`missing required key ${s} (${r})`);continue}let p=a.dec(l);if((c==="req1"||c==="opt1")&&Array.isArray(p)&&p.length===0)throw new ae(n,`${r} must not be empty`);o[r]=p}return o}}}function Gc(n,e){let t=new Map,i=new Map;for(let[o,s,r]of e){let a=z(`${n}.${s}`,r);t.set(o,[s,a]),i.set(s,[o,a])}return{name:n,enc:o=>{let s=i.get(o.kind);if(!s)throw new ae(n,`unknown kind ${JSON.stringify(o.kind)}`);let r=s[1].enc(o);return new Map([[0,s[0]],...r])},dec:o=>{if(!(o instanceof Map))throw $n(n,"struct map",o);let s=o.get(0);if(s===void 0)throw new ae(n,"missing discriminator");if(typeof s=="bigint")throw new ae(n,`unknown variant ${s}`,!0);if(typeof s!="number")throw $n(n,"uint discriminator",s);let r=t.get(s);if(!r)throw new ae(n,`unknown variant ${s}`,!0);return{kind:r[0],...r[1].dec(o)}}}}function Ng(n,e,t,i){return{name:n,enc:o=>e.enc(i(o)),dec:o=>t(e.dec(o))}}function Dg(n,e){return{name:n,enc:t=>e.map((i,o)=>i.enc(t[o])),dec:t=>{if(!Array.isArray(t))throw $n(n,"array",t);if(t.length!==e.length)throw new ae(n,"wrong number of elements");return e.map((i,o)=>i.dec(t[o]))}}}var ae,Fc,F,An,T,Ee,rk,bs,pr,wq,M,Z,Pu,Ht,Ia,ve=I(()=>{"use strict";Je();un();ae=class extends Error{constructor(t,i,o=!1){super(`${t}: ${i}`);this.ty=t;this.unknown=o;this.name="SchemaError"}ty;unknown},Fc=!1;F={name:"uint",enc:n=>{if(!Number.isSafeInteger(n)||n<0)throw new ae("uint",`not an unsigned integer: ${n}`);return n},dec:n=>{if(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0)return n;throw typeof n=="bigint"&&n>=0n?new ae("uint","value beyond 2^53 is not supported here"):$n("uint","uint",n)}},An={name:"int",enc:n=>{if(!Number.isSafeInteger(n))throw new ae("int",`not an integer: ${n}`);return n},dec:n=>{if(typeof n=="number"&&Number.isInteger(n))return n;throw $n("int","int",n)}},T={name:"tstr",enc:n=>{if(typeof n!="string")throw new ae("tstr","not a string");return n},dec:n=>{if(typeof n=="string")return n;throw $n("tstr","text",n)}},Ee={name:"bool",enc:n=>n,dec:n=>{if(typeof n=="boolean")return n;throw $n("bool","bool",n)}},rk={name:"bstr",enc:n=>n,dec:n=>{if(n instanceof Uint8Array)return n;throw $n("bstr","bytes",n)}};bs=ok(16,"b16"),pr=ok(32,"b32"),wq=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;M={name:"uuid",enc:n=>N(n),dec:n=>Wc(bs.dec(n))};Z={name:"hash",enc:n=>Su(n),dec:n=>Ug(pr.dec(n))},Pu={name:"any",enc:n=>n,dec:n=>n},Ht={name:"value",enc:n=>(Kc(n),n),dec:n=>(Kc(n),Fc?ei(n):n)},Ia={name:"value",enc:n=>Ht.enc(Fe(n)),dec:n=>(Kc(n),ei(n))}});function lk(n,e,t){if(!Array.isArray(n)||n.length!==e)throw new ae(t,`must have exactly ${e} elements`);if(F.dec(n[0])!==1)throw new ae(t,"unknown version",!0);return n}var Cu,sk,ak,Ao,zg=I(()=>{"use strict";ve();Cu={name:"attachment-uint64",enc:n=>{if(typeof n=="number")return F.enc(n);if(typeof n!="bigint"||n<0n||n>0xffffffffffffffffn)throw new ae("attachment-uint64","outside uint64");return n},dec:n=>{if(typeof n=="number")return F.dec(n);if(typeof n!="bigint"||n<0n||n>0xffffffffffffffffn)throw new ae("attachment-uint64","outside uint64");return n<=BigInt(Number.MAX_SAFE_INTEGER)?Number(n):n}},sk=8388608;ak={name:"attachment-ref-v1",enc:n=>[1,M.enc(n.collection),Cu.enc(n.keyEpoch),pr.enc(n.attachmentId),sk,Z.enc(n.manifestCipherHash)],dec:n=>{let e=lk(n,6,"attachment-ref-v1");if(F.dec(e[4])!==sk)throw new ae("attachment-ref-v1","unknown chunk profile",!0);return{collection:M.dec(e[1]),keyEpoch:Cu.dec(e[2]),attachmentId:pr.dec(e[3]),manifestCipherHash:Z.dec(e[5])}}},Ao={name:"attachment-content-v1",enc:n=>[1,ak.enc(n.reference),Z.enc(n.wholePlainHash),Cu.enc(n.totalPlainBytes)],dec:n=>{let e=lk(n,4,"attachment-content-v1");return{reference:ak.dec(e[1]),wholePlainHash:Z.dec(e[2]),totalPlainBytes:Cu.dec(e[3])}}}});function ck(n){return n.content.form==="blob"?n.content.blob.size:n.content.content.totalPlainBytes}function vq(n){return n.kind==="ordinary_attachment_continuation"||n.kind==="file_attach"||n.kind==="unindexed_markdown_put"||n.kind==="record_to_unindexed_markdown"||n.kind==="unindexed_markdown_to_record"||n.kind==="ordinary_file_to_record"}function uk(n,e){return{name:n,enc:t=>e().enc(t),dec:t=>e().dec(t)}}var Ou,Iu,pk,dk,Ru,m4,fk=I(()=>{"use strict";ve();en();zg();Ou={name:"file-content",enc:n=>n.form==="blob"?Vr.enc(n.blob):Ao.enc(n.content),dec:n=>Array.isArray(n)?{form:"attachment",content:Ao.dec(n)}:{form:"blob",blob:Vr.dec(n)}};Iu={name:"unindexed-markdown-payload-v1",enc:n=>{if(ck(n)<=1048576)throw new ae("unindexed-markdown-payload-v1","declared size must exceed record cap");return[2,1,1,Ou.enc(n.content)]},dec:n=>{let e="unindexed-markdown-payload-v1";if(!Array.isArray(n)||n.length!==4)throw new ae(e,"must have exactly four elements");if(F.dec(n[0])!==2||F.dec(n[1])!==1||F.dec(n[2])!==1)throw new ae(e,"unknown discriminator/profile/kind",!0);let t={content:Ou.dec(n[3])};if(ck(t)<=1048576)throw new ae(e,"declared size must exceed record cap");return t}},pk=xu("text",T,n=>typeof n=="string",n=>typeof n=="string",F),dk=Gc("extended-runtime-op",[[13,"file_attach",[[1,"id",M],[2,"path",T],[3,"content",Ao],[4,"ifRevision",Z,"opt"],[5,"base",Z,"opt"]]],[14,"unindexed_markdown_put",[[1,"id",M],[2,"path",T],[3,"payload",Iu],[4,"expected",Iu,"opt"]]],[15,"record_to_unindexed_markdown",[[1,"id",M],[2,"path",T],[3,"payload",Iu],[4,"priorRevision",Z]]],[16,"unindexed_markdown_to_record",[[1,"id",M],[2,"path",T],[3,"doc",pk],[4,"prior",Iu]]],[18,"ordinary_attachment_continuation",[[1,"id",M],[2,"path",T],[3,"content",Ao],[4,"prior",Ou]]],[17,"ordinary_file_to_record",[[1,"id",M],[2,"path",T],[3,"doc",pk],[4,"prior",Ou]]]]);Ru={name:"runtime-v1-op",enc:n=>vq(n)?dk.enc(n):Oa.enc(n),dec:n=>{let e=n instanceof Map?F.dec(n.get(0)):void 0;return e!==void 0&&e>=13&&e<=18?dk.dec(n):Oa.dec(n)}};m4=z("runtime-v1-mutation",[[0,"id",M],[1,"origin",M],[2,"baseSeq",F],[3,"clock",uk("op-clock",()=>ws)],[4,"seed",pr],[5,"source",Se("source",["api","external"])],[6,"ops",G(Ru,{nonEmpty:!0}),"req1"],[7,"onBehalf",M,"opt"],[8,"conflictMode",uk("conflict-mode",()=>Yc),"opt"],[9,"validatedAt",Se("level",["off","warn","error"]),"opt"],[10,"room",z("room-checkpoint",[[0,"stream",bs],[1,"state",Z]]),"opt"]])});var _b={};Ca(_b,{DESCRIBE_TYPING_MAX_PATHS:()=>tp,DESCRIBE_TYPING_MAX_TYPES:()=>ep,HOLD_REASONS:()=>Sk,HOLD_RESOLUTIONS:()=>Pk,INCIDENT_KINDS:()=>vk,MEDIA_CLASSES:()=>Ok,PUSH_CODECS:()=>kq,RECOVERY:()=>yk,ROLES:()=>bk,TEMPORAL_HINTS:()=>Ku,TRANSFER_PHASES:()=>Lk,appliedPrefix:()=>Hg,appliedPrefixParams:()=>Wg,authorRef:()=>Mu,b16:()=>bs,b32:()=>pr,backlinksResult:()=>mb,baseField:()=>Nu,blobRef:()=>Vr,bodyEdit:()=>nb,change:()=>Ik,changesResult:()=>vs,clientFrame:()=>Kr,confirmedHead:()=>ju,conflict:()=>ob,conflictEntry:()=>Zc,conflictMode:()=>Yc,conflictValue:()=>qu,describeResult:()=>bb,describeTypingResult:()=>vb,docVersion:()=>Bg,executeViewParams:()=>Rq,fenceApply:()=>db,fenceReport:()=>ub,fenceResult:()=>fb,fileChunk:()=>Du,fileInclusion:()=>ib,fileStreamFailure:()=>zu,fileView:()=>Qc,fmMap:()=>kn,grantInfo:()=>Kg,helloParams:()=>Fg,helloResult:()=>Gg,hold:()=>Jc,holdReason:()=>Yg,holdRef:()=>Jg,holdResolution:()=>Xg,incident:()=>_k,include:()=>Ra,issue:()=>Fr,linkResolution:()=>Zg,linkView:()=>Qg,listFilesResult:()=>ab,listPendingResult:()=>wb,listResourcesResult:()=>hb,listViewsResult:()=>xq,materialization:()=>Bu,mediaClass:()=>Ea,mutation:()=>Sq,newTypeFile:()=>gb,op:()=>Oa,opClock:()=>ws,openUploadParams:()=>lb,openUploadResult:()=>cb,peer:()=>jk,preflight:()=>qk,presencePush:()=>Vu,problem:()=>ti,progress:()=>Ak,publishState:()=>Ek,queryGroup:()=>tb,queryMetadata:()=>Ck,queryParams:()=>Oq,queryResult:()=>Xc,queryUpdate:()=>Uu,receipt:()=>Sn,recordState:()=>xk,recordView:()=>ko,recovery:()=>gk,resolveLinksResult:()=>yb,resourceView:()=>Fu,resyncing:()=>kk,role:()=>wk,severity:()=>Lu,submitParams:()=>rb,submitResult:()=>sb,syncStatus:()=>Wr,target:()=>Vg,temporalHint:()=>Uk,textOrBlob:()=>Eu,transferProgress:()=>$u,typingEntry:()=>Nk,uploadChunkParams:()=>pb,version:()=>Tu,viewRef:()=>eb,viewSourceDocument:()=>Cq});function Mk(n){throw new ae(n,"wrong type")}var Tu,yk,gk,Lu,Fr,ti,Kr,Fg,bk,wk,Kg,vk,_k,Ak,kk,ju,Wg,Hg,Wr,Gg,Vr,Eu,Sk,Yg,Jg,Jc,Pk,Xg,xk,Zg,Qg,Mu,kn,ko,Ra,eb,tb,Ck,Xc,Uu,Ik,vs,Ok,Ea,Yc,Nu,nb,Bg,ib,hk,mk,_q,Oa,Rk,rb,Aq,qu,ob,Ek,qk,Sn,sb,Zc,Tk,$g,Qc,ab,lb,cb,pb,Du,zu,Lk,$u,Bu,jk,Vu,db,ub,fb,kq,ws,Sq,Pq,Fu,hb,mb,yb,xq,Cq,gb,bb,Iq,wb,Vg,Oq,Rq,Ku,Uk,Nk,vb,ep,tp,en=I(()=>{"use strict";fk();zg();ve();Tu=Ng("version",Dg("version",[F,F]),([n,e])=>({major:n,minor:e}),n=>[n.major,n.minor]),yk=["fix_request","refresh","resolve_conflict","reauthorize","repair_collection","retry","free_space","upgrade","resolve_outcome","none","contact_support"],gk=Se("recovery",yk),Lu=Se("severity",["warning","error"]),Fr=z("issue",[[0,"code",T],[1,"severity",Lu],[2,"message",T],[3,"details",Ia,"opt"]]),ti=z("problem",[[0,"code",T],[1,"recovery",gk],[2,"message",T],[3,"reason",T,"opt"],[4,"details",Ia,"opt"],[5,"retryAfterMs",F,"opt"],[6,"issues",G(Fr),"opt"],[7,"traceId",T,"opt"]]),Kr=Gc("client-frame",[[0,"request",[[1,"id",F],[2,"method",T],[3,"params",Pu]]],[1,"response",[[1,"id",F],[2,"result",Pu,"opt"],[3,"problem",ti,"opt"]]],[2,"push",[[1,"type",T],[2,"payload",Pu]]]]),Fg=z("hello-params",[[0,"versions",G(Tu,{nonEmpty:!0}),"req1"],[1,"clientName",T],[2,"clientVersion",T],[3,"features",G(T),"opt"],[4,"timezone",T,"opt"]]),bk=["viewer","editor","owner"],wk=Se("role",bk),Kg=z("grant-info",[[0,"grant",M,"opt"],[1,"capabilities",G(T,{nonEmpty:!0}),"req1"],[2,"role",wk],[3,"account",M,"opt"],[4,"fileFolders",G(T),"opt"]]),vk=["upgrade_required","waiting_for_key","integrity","access_revoked","quota_exceeded","read_only","verification_mismatch","voided_items","key_inconsistent","foreign_sync_tool","gone","lost_entries","log_regressed"],_k=z("incident",[[0,"kind",Se("incident-kind",vk)],[1,"details",Ia,"opt"]]),Ak=z("progress",[[0,"done",F],[1,"total",F]]),kk=z("resyncing",[[0,"phase",Se("resync-phase",["probing","repairing","rolling_back","awaiting_control"])],[1,"positions",F]]),ju=z("confirmed-head",[[0,"seq",F],[1,"chain",Z],[2,"policyGeneration",Z],[3,"catalogGeneration",Z]]),Wg=z("applied-prefix-params",[[0,"seq",F]]),Hg=z("applied-prefix",[[0,"appliedThrough",F],[1,"seq",F],[2,"chain",Z,"opt"]]),Wr=z("sync-status",[[0,"mode",Se("sync-mode",["local_only","synced"])],[1,"confirmedThrough",F],[2,"headKnown",F],[3,"pending",F],[4,"oldestPending",An,"opt"],[5,"holds",F],[6,"unresolved",F],[7,"connection",Se("connection",["online","connecting","offline"])],[8,"installing",Ak,"opt"],[9,"incidents",G(_k)],[10,"resyncing",kk,"opt"],[11,"confirmedHead",ju,"opt"],[12,"grant",Kg,"opt"]]),Gg=z("hello-result",[[0,"version",Tu],[1,"runtimeVersion",T],[2,"sem",Tu],[3,"collection",M],[4,"grant",Kg],[5,"status",Wr],[6,"features",G(T)],[7,"headWitness",rk,"opt"]]),Vr=z("blob-ref",[[0,"plainHash",Z],[1,"size",F],[2,"blobId",pr],[3,"idEpoch",F],[4,"partSize",F]]),Eu={name:"text-or-blob",enc:n=>{if(typeof n=="string")return T.enc(n);if("form"in n){if(n.form!=="attachment")throw new ae("text-or-blob","unknown arm",!0);return[1,Ao.enc(n.content)]}return Vr.enc(n)},dec:n=>{if(typeof n=="string")return T.dec(n);if(Array.isArray(n)){if(n.length!==2)throw new ae("text-or-blob","attachment arm must have exactly two elements");if(F.dec(n[0])!==1)throw new ae("text-or-blob","unknown attachment arm",!0);return{form:"attachment",content:Ao.dec(n[1])}}return Vr.dec(n)}},Sk=["conflict","unknown_provenance","deleted_elsewhere","read_only","editor_busy","suspect_write"],Yg=Se("hold-reason",Sk),Jg=z("hold-ref",[[0,"id",M],[1,"reason",Yg]]),Jc=z("hold",[[0,"id",M],[1,"path",T],[2,"reason",Yg],[3,"since",An],[4,"base",Eu,"opt"],[5,"mine",Eu],[6,"theirs",Eu,"opt"],[7,"saves",F]]),Pk=["keep_mine","take_theirs","use","delete","keep_both"],Xg=Se("hold-resolution",Pk),xk=z("record-state",[[0,"state",Se("confirmation",["confirmed","pending"])],[1,"confirmedSeq",F],[2,"hold",Jg,"opt"],[3,"unresolved",F,"opt"]]),Zg=z("link-resolution",[[0,"kind",Se("link-kind",["record","file","ambiguous","not_found","invalid"])],[1,"target",M,"opt"],[2,"path",T,"opt"],[3,"candidates",G(T,{nonEmpty:!0}),"opt"]]),Qg=z("link-view",[[0,"raw",T],[1,"embed",Ee],[2,"resolution",Zg],[3,"field",T,"opt"]]),Mu=z("author-ref",[[0,"account",M],[1,"device",M],[2,"grant",M,"opt"],[3,"grantAccount",M,"opt"]]),kn=Hc(Ht),ko=z("record-view",[[0,"id",M],[1,"path",T],[2,"revision",Z],[3,"frontmatter",kn],[4,"effective",kn,"opt"],[5,"body",T,"opt"],[6,"document",T,"opt"],[7,"types",G(T)],[8,"state",xk],[9,"diagnostics",G(Fr),"opt"],[10,"values",kn,"opt"],[11,"mtime",An,"opt"],[12,"links",G(Qg),"opt"],[13,"createdBy",Mu,"opt"],[14,"modifiedBy",Mu,"opt"]]),Ra=z("include",[[0,"effective",Ee,"opt"],[1,"body",Ee,"opt"],[2,"document",Ee,"opt"],[3,"diagnostics",Ee,"opt"],[4,"links",Ee,"opt"]]),eb=z("view-ref",[[0,"path",T],[1,"view",T]]),tb=z("query-group",[[0,"values",kn],[1,"count",F],[2,"summaries",kn,"opt"]]),Ck=z("query-metadata",[[0,"columns",G(T),"opt"],[1,"totalCount",F,"opt"],[2,"diagnostics",G(Fr),"opt"],[3,"view",eb,"opt"],[4,"groups",G(tb),"opt"],[5,"hasMore",Ee,"opt"]]),Xc=z("query-result",[[0,"records",G(ko)],[1,"cursor",T,"opt"],[2,"complete",Ee],[3,"asOf",F],[4,"columns",G(T),"opt"],[5,"totalCount",F,"opt"],[6,"diagnostics",G(Fr),"opt"],[7,"view",eb,"opt"],[8,"groups",G(tb),"opt"],[9,"hasMore",Ee,"opt"]]),Uu=z("query-update",[[0,"sub",F],[1,"kind",Se("update-kind",["snapshot","diff","reset"])],[2,"added",G(ko),"opt"],[3,"changed",G(ko),"opt"],[4,"removed",G(M),"opt"],[5,"order",G(M),"opt"],[6,"complete",Ee],[7,"asOf",F],[8,"metadata",Ck,"opt"]]),Ik=z("change",[[0,"id",M],[1,"path",T],[2,"kind",Se("change-kind",["put","remove"])],[3,"version",F],[4,"author",Mu,"opt"],[5,"entity",Se("change-entity",["record","file"]),"opt"],[6,"types",G(T),"opt"]]),vs=z("changes-result",[[0,"changes",G(Ik)],[1,"cursor",T],[2,"reset",Ee]]),Ok=["image","audio","video","pdf","other"],Ea=Se("media-class",Ok),Yc=Se("conflict-mode",["record","reject"]),Nu={name:"base-field",enc:n=>n.observed===void 0?[n.key]:[n.key,Ht.enc(n.observed)],dec:n=>{if(!Array.isArray(n)||n.length<1||n.length>2)throw new ae("base-field","must have 1 or 2 elements");return n.length===1?{key:T.dec(n[0])}:{key:T.dec(n[0]),observed:Ht.dec(n[1])}}},nb=Dg("body-edit",[F,F,T]),Bg=z("doc-version",[[0,"path",T],[1,"doc",T]]),ib=z("file-inclusion",[[0,"include",G(Ea)],[1,"exclude",G(T),"opt"],[2,"maxSize",F,"opt"]]),hk=Hc(G(Ht)),mk=[[1,"id",M],[2,"patch",kn,"opt"],[3,"unset",G(T),"opt1"],[4,"add",hk,"opt"],[5,"remove",hk,"opt"],[6,"body",T,"opt"],[7,"bodyEdits",G(nb),"opt1"],[8,"bodyBase",Z,"opt"],[9,"bodyBaseText",T,"opt"],[10,"base",G(Nu),"opt1"],[11,"ifRevision",Z,"opt"],[12,"updateRefs",Ee,"opt"]],_q=Gc("op",[[1,"create",[[1,"id",M],[2,"path",T,"opt"],[3,"type",T,"opt"],[4,"frontmatter",kn,"opt"],[5,"body",T,"opt"],[6,"document",T,"opt"]]],[2,"update",mk],[19,"update_live",mk],[3,"document",[[1,"id",M],[2,"base",Bg,"opt"],[3,"new",Bg,"opt"],[4,"ifRevision",Z,"opt"]]],[4,"delete",[[1,"id",M],[2,"baseRevision",Z,"opt"],[3,"ifRevision",Z,"opt"]]],[5,"rename",[[1,"id",M],[2,"from",T],[3,"to",T],[4,"updateRefs",Ee],[5,"ifRevision",Z,"opt"]]],[6,"resource_put",[[1,"path",T],[2,"doc",T],[3,"baseRevision",Z,"opt"],[4,"mustNotExist",Ee,"opt"]]],[7,"resource_delete",[[1,"path",T],[2,"baseRevision",Z,"opt"]]],[8,"file_put",[[1,"id",M],[2,"path",T],[3,"blob",Vr],[4,"ifRevision",Z,"opt"],[5,"base",Z,"opt"]]],[9,"file_delete",[[1,"id",M],[2,"ifRevision",Z,"opt"],[3,"base",Z,"opt"]]],[10,"file_move",[[1,"id",M],[2,"from",T],[3,"to",T],[4,"updateRefs",Ee],[5,"ifRevision",Z,"opt"]]],[11,"conflict_dismiss",[[1,"mutation",M],[2,"record",M]]],[12,"sync_settings",[[1,"inclusion",ib]]]]),Oa=Ng("op",_q,n=>n.kind==="update_live"?{...n,kind:"update",requireLive:!0}:n,n=>n.kind==="update"&&n.requireLive?{...n,kind:"update_live"}:n),Rk=Se("level",["off","warn","error"]),rb=z("submit-params",[[0,"ops",G(Oa,{nonEmpty:!0}),"req1"],[1,"mutationId",M,"opt"],[2,"conflictMode",Yc,"opt"],[3,"timezone",T,"opt"],[4,"allowPartial",Ee,"opt"],[5,"mutationIds",G(M),"opt1"],[6,"dryRun",Ee,"opt"],[7,"include",Ra,"opt"],[8,"wait",Se("wait-for",["pending","confirmed","published"]),"opt"],[9,"validation",Rk,"opt"]]),Aq=["missing","value","text","blob","deleted"],qu={name:"conflict-value",enc:n=>{switch(n.form){case"missing":return[0];case"value":return[1,Ht.enc(n.value)];case"text":return[2,n.text];case"blob":return[3,Vr.enc(n.blob)];case"deleted":return[4]}},dec:n=>{if(!Array.isArray(n)||n.length===0)throw new ae("conflict-value","malformed conflict value");let e=n[0];if(typeof e!="number")throw new ae("conflict-value","malformed conflict value");if(e>4)throw new ae("conflict-value",`unknown variant ${e}`,!0);let t=Aq[e];if(t==="missing"||t==="deleted"){if(n.length!==1)throw new ae("conflict-value","malformed conflict value");return{form:t}}if(n.length!==2)throw new ae("conflict-value","malformed conflict value");return t==="value"?{form:t,value:Ht.dec(n[1])}:t==="text"?{form:t,text:T.dec(n[1])}:{form:t,blob:Vr.dec(n[1])}}},ob=z("conflict",[[0,"kind",Se("conflict-kind",["field","frontmatter","body","path","delete","file"],1)],[1,"id",M],[2,"field",T,"opt"],[3,"base",qu,"opt"],[4,"kept",qu],[5,"lost",qu]]),Ek=Se("publish-state",["publishing","published","not_published"]),qk=z("preflight",[[0,"rewrites",G(z("link-rewrite",[[0,"record",M],[1,"path",T],[2,"from",T],[3,"to",T],[4,"field",T,"opt"]]))],[1,"broken",G(z("broken-link",[[0,"record",M],[1,"path",T],[2,"raw",T],[3,"target",M],[4,"field",T,"opt"]]))]]),Sn=z("receipt",[[0,"mutation",M],[1,"state",Se("receipt-state",["pending","confirmed","rejected","unknown"])],[2,"seq",F,"opt"],[3,"status",Se("status",["applied","merged","conflicted"]),"opt"],[4,"conflicts",G(ob),"opt1"],[5,"records",G(ko),"opt"],[6,"problem",ti,"opt"],[7,"published",Ek,"opt"],[8,"preflight",qk,"opt"],[9,"relocatedFrom",F,"opt"]]),sb=G(Sn,{nonEmpty:!0}),Zc=z("conflict-entry",[[0,"mutation",M],[1,"seq",F],[2,"conflict",ob]]),Tk=Se("file-content-profile",["ordinary_blob","ordinary_attachment_v1","unindexed_markdown_blob","unindexed_markdown_attachment_v1"]),$g=z("file-view",[[0,"id",M],[1,"path",T],[2,"size",F],[3,"digest",Z],[4,"media",Ea],[5,"state",Se("file-state",["materialized","remote","fetching","pending_upload"])],[6,"confirmedSeq",F],[7,"hold",Jg,"opt"],[8,"mtime",An,"opt"],[9,"mediaType",T,"opt"],[10,"contentProfile",Tk,"opt"]]),Qc={...$g,dec(n){let e=n instanceof Map?n:void 0;if(e?.has(10))try{Tk.dec(e.get(10))}catch(t){if(!(t instanceof ae)||!t.unknown)throw t;let i=new Map(e);return i.delete(10),$g.dec(i)}return $g.dec(n)}},ab=z("list-files-result",[[0,"files",G(Qc)],[1,"cursor",T,"opt"],[2,"complete",Ee]]),lb=z("open-upload-params",[[0,"transfer",M],[1,"path",T],[2,"size",F],[3,"digest",Z,"opt"],[4,"fileId",M,"opt"],[5,"ifRevision",Z,"opt"],[6,"mutationId",M,"opt"]]),cb=z("open-upload-result",[[0,"transfer",M],[1,"chunkSize",F],[2,"received",G(F)],[3,"expiresAt",An],[4,"fileId",M,"opt"]]),pb=z("upload-chunk-params",[[0,"transfer",M],[1,"index",F],[2,"bytes",{name:"bstr",enc:n=>n,dec:n=>n instanceof Uint8Array?n:Mk("bstr")}]]);Du=z("file-chunk",[[0,"stream",F],[1,"offset",F],[2,"bytes",{name:"bstr",enc:n=>n,dec:n=>n instanceof Uint8Array?n:Mk("bstr")}],[3,"last",Ee]]),zu=z("file-stream-failure",[[0,"stream",F],[1,"problem",ti]]),Lk=["receiving","sealing","uploading","appending","confirmed","fetching","streaming","done"],$u=z("transfer-progress",[[0,"id",xu("transfer-id",M,n=>typeof n=="string",n=>n instanceof Uint8Array,F)],[1,"phase",Se("phase",Lk)],[2,"done",F],[3,"total",F]]),Bu=z("materialization",[[0,"mode",Se("materialize-mode",["all","on_demand"])],[1,"pinned",G(T),"opt"],[2,"media",G(Ea),"opt"],[3,"maxSize",F,"opt"]]),jk=z("peer",[[0,"session",bs],[1,"account",M,"opt"],[2,"app",T,"opt"],[3,"state",Ht],[4,"lastSeen",An]]),Vu=z("presence",[[0,"record",M],[1,"peers",G(jk)]]),db=z("fence-apply",[[0,"path",T],[1,"base",Z],[2,"edits",G(nb,{nonEmpty:!0}),"req1"],[3,"expected",Z]]),ub=z("fence-report",[[0,"open",G(z("fence-open",[[0,"path",T],[1,"dirty",Ee],[2,"buffer",Z]]))]]),fb=z("fence-result",[[0,"outcome",Se("fence-outcome",["applied","not_open","buffer_changed"])],[1,"buffer",T,"opt"]]),kq={query_update:Uu,receipt:Sn,status:Wr,holds:G(Jc),conflicts:G(Zc),presence:Vu,file_chunk:Du,file_stream_failed:zu,transfer_progress:$u,changes:vs},ws=z("op-clock",[[0,"instant",An],[1,"tz",T],[2,"localDate",T]]),Sq=z("mutation",[[0,"id",M],[1,"origin",M],[2,"baseSeq",F],[3,"clock",ws],[4,"seed",pr],[5,"source",Se("source",["api","external"])],[6,"ops",G(Oa,{nonEmpty:!0}),"req1"],[7,"onBehalf",M,"opt"],[8,"conflictMode",Yc,"opt"],[9,"validatedAt",Rk,"opt"],[10,"room",z("room-checkpoint",[[0,"stream",bs],[1,"state",Z]]),"opt"]]),Pq=Se("confirmation",["confirmed","pending"]),Fu=z("resource-view",[[0,"path",T],[1,"revision",Z],[2,"size",F],[3,"state",Pq],[4,"text",T,"opt"]]),hb=z("list-resources-result",[[0,"resources",G(Fu)],[1,"complete",Ee],[2,"cursor",T,"opt"]]),mb=z("backlinks-result",[[0,"backlinks",G(z("backlink",[[0,"record",ko],[1,"links",G(Qg,{nonEmpty:!0}),"req1"]]))],[1,"cursor",T,"opt"],[2,"complete",Ee],[3,"asOf",F]]),yb=z("resolve-links-result",[[0,"resolutions",G(Zg)],[1,"asOf",F],[2,"complete",Ee]]),xq=z("list-views-result",[[0,"sources",G(z("view-source",[[0,"record",M],[1,"id",T],[2,"name",T],[3,"source",z("view-source-ref",[[0,"path",T],[1,"format",T],[2,"revision",Z],[3,"writable",Ee]])],[4,"views",G(z("view-descriptor",[[0,"id",T],[1,"name",T],[2,"properties",G(z("view-property",[[0,"key",T],[1,"label",T,"opt"],[2,"description",T,"opt"],[3,"format",T,"opt"],[4,"hidden",Ee,"opt"]]))],[3,"presentation",Ht,"opt"]]))]]))],[1,"diagnostics",G(Fr)],[2,"complete",Ee]]),Cq=z("view-source-document",[[0,"path",T],[1,"format",T],[2,"revision",Z],[3,"document",T],[4,"record",M]]),gb=z("new-type-file",[[0,"name",T],[1,"path",T]]),bb=z("describe-result",[[0,"specVersion",T],[1,"types",G(z("type-summary",[[0,"name",T],[1,"path",T],[2,"implements",G(z("implementation",[[0,"contract",T],[1,"version",T],[2,"fields",Hc(T)],[3,"binding",Ht,"opt"],[4,"digest",Z,"opt"]]))],[3,"version",An,"opt"],[4,"revision",Z,"opt"],[5,"definition",Ht,"opt"],[6,"schema",Ht,"opt"]]))],[2,"settings",Ht],[3,"inclusion",ib],[4,"issues",G(Fr)],[5,"contracts",G(z("contract-summary",[[0,"id",T],[1,"version",T],[2,"path",T],[3,"digest",Z],[4,"contractType",T],[5,"implementedBy",G(T)],[6,"schemas",Hc(Ht),"opt"]]))]]),Iq={name:"pending-runtime-op",enc:n=>Ru.enc(n),dec:n=>Ru.dec(n)},wb=z("list-pending-result",[[0,"pending",G(z("pending-mutation",[[0,"receipt",Sn],[1,"captured",An],[2,"ops",G(Iq,{nonEmpty:!0}),"req1"]]))],[1,"next",M,"opt"]]),Vg={name:"target",enc:n=>typeof n=="string"?M.enc(n):n.path,dec:n=>typeof n=="string"?{path:n}:M.dec(n)},Oq=z("query-params",[[0,"query",Ht],[1,"include",Ra,"opt"],[2,"contract",T,"opt"]]),Rq=z("execute-view-params",[[0,"source",Vg],[1,"view",T],[2,"context",Vg,"opt"],[3,"limit",F,"opt"],[4,"offset",F,"opt"],[5,"timezone",T,"opt"],[6,"include",Ra,"opt"]]),Ku=["none","date","date_time"],Uk=Se("temporal-hint",Ku),Nk=z("typing-entry",[[0,"path",T],[1,"hint",Uk]]),vb=z("describe-typing-result",[[0,"catalogGeneration",F],[1,"fields",G(Nk)]]),ep=64,tp=256});function So(n){typeof performance<"u"&&performance.mark(n)}var Wu=I(()=>{"use strict"});function Eq(n,e=!1){return e?{h:Number(n&Hu),l:Number(n>>Dk&Hu)}:{h:Number(n>>Dk&Hu)|0,l:Number(n&Hu)|0}}function zk(n,e=!1){let t=n.length,i=new Uint32Array(t),o=new Uint32Array(t);for(let s=0;s<t;s++){let{h:r,l:a}=Eq(n[s],e);[i[s],o[s]]=[r,a]}return[i,o]}function $k(n,e,t,i){let o=Ab(t),s=kb(t);n.setUint32(e,i?s:o,i),n.setUint32(e+4,i?o:s,i)}function ni(n,e,t,i){let o=(e>>>0)+(i>>>0);return{h:n+t+(o/2**32|0)|0,l:o|0}}var Hu,Dk,Ab,kb,Sb,Pb,dr,ur,_s,As,Bk,Vk,np,ip,Fk,Kk,Wk,Hk,Gu=I(()=>{Hu=BigInt(4294967295),Dk=BigInt(32);Ab=n=>n/2**32|0,kb=n=>n>>>0;Sb=(n,e,t)=>n>>>t,Pb=(n,e,t)=>n<<32-t|e>>>t,dr=(n,e,t)=>n>>>t|e<<32-t,ur=(n,e,t)=>n<<32-t|e>>>t,_s=(n,e,t)=>n<<64-t|e>>>t-32,As=(n,e,t)=>n>>>t-32|e<<64-t,Bk=(n,e)=>e,Vk=(n,e)=>n;np=(n,e,t)=>(n>>>0)+(e>>>0)+(t>>>0),ip=(n,e,t,i)=>e+t+i+(n/2**32|0)|0,Fk=(n,e,t,i)=>(n>>>0)+(e>>>0)+(t>>>0)+(i>>>0),Kk=(n,e,t,i,o)=>e+t+i+o+(n/2**32|0)|0,Wk=(n,e,t,i,o)=>(n>>>0)+(e>>>0)+(t>>>0)+(i>>>0)+(o>>>0),Hk=(n,e,t,i,o,s)=>e+t+i+o+s+(n/2**32|0)|0});function Yu(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}function Pn(n,e=""){if(typeof n!="number")throw new TypeError(xb(e)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(xb(e)+"expected integer >= 0, got "+n);return n}function ft(n,e,t=""){if(Yu(n)&&(e===void 0||n.length===e))return n;e!==void 0&&Pn(e,"length");let i=Yu(n),o=e!==void 0?` of length ${e}`:"",s=i?`length=${n.length}`:`type=${typeof n}`,r=xb(t)+"expected Uint8Array"+o+", got "+s;throw i?new RangeError(r):new TypeError(r)}function Cb(n){return Uint8Array.from(ft(n))}function rp(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(Pn(n.outputLen),Pn(n.blockLen),n.outputLen<1||n.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}function Hr(n,e=!0){if(n.destroyed)throw new Error("hash was destroyed");if(e&&n.finished)throw new Error("digest() was already called")}function qa(n,e){ft(n,void 0,"output");let t=e.outputLen;if(!(n.length>=t))throw new RangeError('"output" expected length >= '+t)}function op(n){return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}function Po(n){return new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4))}function at(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function Ju(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Ui(n,e){return n<<32-e|n>>>e}function Zk(n){return n<<24&4278190080|n<<8&16711680|n>>>8&65280|n>>>24&255}function Tq(n){for(let e=0;e<n.length;e++)n[e]=Zk(n[e]);return n}function Ta(n){if(ft(n),Qk)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=Mq[n[t]];return e}function Jk(n){return n>=48&&n<=57?n-48:n>=65&&n<=70?n-55:n>=97&&n<=102?n-87:void 0}function Xu(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);if(Qk)try{return Uint8Array.fromHex(n)}catch(o){throw o instanceof SyntaxError?new RangeError(o.message):o}let e=n.length,t=e/2;if(e%2)throw new RangeError("hex string expected, got unpadded hex of length "+e);let i=new Uint8Array(t);for(let o=0,s=0;o<t;o++,s+=2){let r=Jk(n.charCodeAt(s)),a=Jk(n.charCodeAt(s+1));if(r===void 0||a===void 0){let c=n[s]+n[s+1];throw new RangeError('hex string expected, got non-hex character "'+c+'" at index '+s)}i[o]=r*16+a}return i}function eS(n){let e=globalThis;if(typeof e.scheduler?.yield=="function"){let t=e.scheduler.yield();return n&&t.catch(n),t}return new Promise(t=>e.setTimeout(t,0))}function Ib(n){if(typeof n!="string")throw new TypeError("string expected");let e=new TextEncoder().encode(n);try{return new Uint8Array(e)}finally{at(e)}}function Zu(n,e=""){return typeof n=="string"?Ib(n):ft(n,void 0,e)}function Ob(...n){let e=0;for(let i=0;i<n.length;i++){let o=n[i];ft(o),e+=o.length}let t=new Uint8Array(e);for(let i=0,o=0;i<n.length;i++){let s=n[i];t.set(s,o),o+=s.length}return t}function sp(n,e,t="opts"){return Yk(n,"defaults"),e!==void 0&&Yk(e,t),Object.assign(Object.create(null),n,e)}function ap(n,e={}){if(typeof n!="function")throw new TypeError('"hashCons" expected function, got type='+typeof n);e=sp({},e,"info");let t=(o,s)=>n(s).update(o).digest(),i=n(void 0);return t.outputLen=i.outputLen,t.blockLen=i.blockLen,t.canXOF=i.canXOF,t.create=o=>n(o),Object.assign(t,e),Object.freeze(t)}function tS(n=32){Pn(n,"bytesLength");let e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof e?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined");if(n>65536)throw new RangeError(`"bytesLength" expected <= 65536, got ${n}`);return e.getRandomValues(new Uint8Array(n))}var xb,qq,Yk,Xk,tn,Ni,Qk,Mq,Rb,fr=I(()=>{xb=n=>n?`"${n}" `:"";qq=(n,e)=>{if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof n)},Yk=(n,e)=>{qq(n,e);let t=Object.getPrototypeOf(n);if(t!==Object.prototype&&t!==null)throw new TypeError(`"${e}" expected plain object`);if(Object.hasOwn(n,"__proto__"))throw new TypeError(`"${e}.__proto__" is not allowed`)};Xk=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;tn=Xk?n=>n:n=>Zk(n)>>>0;Ni=Xk?n=>n:Tq,Qk=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Mq=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));Rb=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])})});function nS(n,e,t){return n&e^~n&t}function iS(n,e,t){return n&e^n&t^e&t}var lp,rS,oS,sS=I(()=>{Gu();fr();lp=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,i,o){this.blockLen=e,this.outputLen=t,this.padOffset=i,this.isLE=o,this.buffer=new Uint8Array(e),this.view=Ju(this.buffer)}update(e){Hr(this),ft(e);let{view:t,buffer:i,blockLen:o}=this,s=e.length,r=!1;for(let a=0;a<s;){let c=Math.min(o-this.pos,s-a);if(c===o){let l=Ju(e);for(;o<=s-a;a+=o)this.process(l,a);r=!0;continue}i.set(a===0&&c===s?e:e.subarray(a,a+c),this.pos),this.pos+=c,a+=c,this.pos===o&&(this.process(t,0),this.pos=0,r=!0)}return this.length+=e.length,r&&this.roundClean(),this}digestInto(e){Hr(this),qa(e,this),this.finished=!0;let{buffer:t,view:i,blockLen:o,isLE:s}=this,{pos:r}=this;t[r++]=128,t.fill(0,r),this.padOffset>o-r&&(this.process(i,0),t.fill(0)),$k(i,o-8,this.length*8,s),this.process(i,0),this.roundClean();let a=e===t?i:Ju(e),c=this.outputLen,l=c/4,p=this.get();if(c%4||l>p.length)throw new Error("invalid outputLen");for(let d=0;d<l;d++)a.setUint32(4*d,p[d],s)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let i=e.slice(0,t);return this.destroy(),i}_cloneIntoMeta(e){let{buffer:t,length:i,finished:o,destroyed:s,pos:r}=this;return e.destroyed=s,e.finished=o,e.length=i,e.pos=r,r&&e.buffer.set(t),e}clone(){return this._cloneInto()}},rS=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),oS=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209])});var Lq,xo,Eb,qb,aS,jq,Uq,Co,Io,Tb,Mb,Ze,Lb,hr=I(()=>{sS();Gu();fr();Lq=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),xo=new Uint32Array(64),Eb=class extends lp{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:i,D:o,E:s,F:r,G:a,H:c}=this;return[e,t,i,o,s,r,a,c]}set(e,t,i,o,s,r,a,c){this.A=e|0,this.B=t|0,this.C=i|0,this.D=o|0,this.E=s|0,this.F=r|0,this.G=a|0,this.H=c|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let d=0;d<16;d++,t+=4)xo[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let u=xo[d-15],f=xo[d-2],h=Ui(u,7)^Ui(u,18)^u>>>3,m=Ui(f,17)^Ui(f,19)^f>>>10;xo[d]=m+xo[d-7]+h+xo[d-16]|0}let{A:i,B:o,C:s,D:r,E:a,F:c,G:l,H:p}=this;for(let d=0;d<64;d++){let u=Ui(a,6)^Ui(a,11)^Ui(a,25),f=p+u+nS(a,c,l)+Lq[d]+xo[d]|0,m=(Ui(i,2)^Ui(i,13)^Ui(i,22))+iS(i,o,s)|0;p=l,l=c,c=a,a=r+f|0,r=s,s=o,o=i,i=f+m|0}i=i+this.A|0,o=o+this.B|0,s=s+this.C|0,r=r+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,p=p+this.H|0,this.set(i,o,s,r,a,c,l,p)}roundClean(){at(xo)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),at(this.buffer)}},qb=class extends Eb{constructor(){super(32,rS)}},aS=zk(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(n=>BigInt(n))),jq=aS[0],Uq=aS[1],Co=new Uint32Array(80),Io=new Uint32Array(80),Tb=class extends lp{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:i,Bl:o,Ch:s,Cl:r,Dh:a,Dl:c,Eh:l,El:p,Fh:d,Fl:u,Gh:f,Gl:h,Hh:m,Hl:w}=this;return[e,t,i,o,s,r,a,c,l,p,d,u,f,h,m,w]}set(e,t,i,o,s,r,a,c,l,p,d,u,f,h,m,w){this.Ah=e|0,this.Al=t|0,this.Bh=i|0,this.Bl=o|0,this.Ch=s|0,this.Cl=r|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=p|0,this.Fh=d|0,this.Fl=u|0,this.Gh=f|0,this.Gl=h|0,this.Hh=m|0,this.Hl=w|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let y=0;y<16;y++,t+=4)Co[y]=e.getUint32(t),Io[y]=e.getUint32(t+=4);for(let y=16;y<80;y++){let _=Co[y-15]|0,v=Io[y-15]|0,k=dr(_,v,1)^dr(_,v,8)^Sb(_,v,7),S=ur(_,v,1)^ur(_,v,8)^Pb(_,v,7),x=Co[y-2]|0,P=Io[y-2]|0,C=dr(x,P,19)^_s(x,P,61)^Sb(x,P,6),R=ur(x,P,19)^As(x,P,61)^Pb(x,P,6),O=Fk(S,R,Io[y-7],Io[y-16]),E=Kk(O,k,C,Co[y-7],Co[y-16]);Co[y]=E|0,Io[y]=O|0}let{Ah:i,Al:o,Bh:s,Bl:r,Ch:a,Cl:c,Dh:l,Dl:p,Eh:d,El:u,Fh:f,Fl:h,Gh:m,Gl:w,Hh:b,Hl:g}=this;for(let y=0;y<80;y++){let _=dr(d,u,14)^dr(d,u,18)^_s(d,u,41),v=ur(d,u,14)^ur(d,u,18)^As(d,u,41),k=d&f^~d&m,S=u&h^~u&w,x=Wk(g,v,S,Uq[y],Io[y]),P=Hk(x,b,_,k,jq[y],Co[y]),C=x|0,R=dr(i,o,28)^_s(i,o,34)^_s(i,o,39),O=ur(i,o,28)^As(i,o,34)^As(i,o,39),E=i&s^i&a^s&a,j=o&r^o&c^r&c;b=m|0,g=w|0,m=f|0,w=h|0,f=d|0,h=u|0,{h:d,l:u}=ni(l|0,p|0,P|0,C|0),l=a|0,p=c|0,a=s|0,c=r|0,s=i|0,r=o|0;let B=np(C,O,j);i=ip(B,P,R,E),o=B|0}({h:i,l:o}=ni(this.Ah|0,this.Al|0,i|0,o|0)),{h:s,l:r}=ni(this.Bh|0,this.Bl|0,s|0,r|0),{h:a,l:c}=ni(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:p}=ni(this.Dh|0,this.Dl|0,l|0,p|0),{h:d,l:u}=ni(this.Eh|0,this.El|0,d|0,u|0),{h:f,l:h}=ni(this.Fh|0,this.Fl|0,f|0,h|0),{h:m,l:w}=ni(this.Gh|0,this.Gl|0,m|0,w|0),{h:b,l:g}=ni(this.Hh|0,this.Hl|0,b|0,g|0),this.set(i,o,s,r,a,c,l,p,d,u,f,h,m,w,b,g)}roundClean(){at(Co,Io)}destroy(){this.destroyed=!0,at(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Mb=class extends Tb{constructor(){super(64,oS)}},Ze=ap(()=>new qb,Rb(1)),Lb=ap(()=>new Mb,Rb(3))});function cp(n){return Fe(n)}function Oo(n,e){if(n===e)return!0;if(n instanceof vt&&e instanceof vt)return Object.is(n.value,e.value)||n.value===e.value;if(typeof n=="bigint"||typeof e=="bigint")return BigInt(n)===BigInt(e);if(Array.isArray(n)&&Array.isArray(e))return n.length===e.length&&n.every((t,i)=>Oo(t,e[i]));if(n instanceof Map&&e instanceof Map){if(n.size!==e.size)return!1;let t=[...n],i=[...e];return t.every(([o,s],r)=>i[r][0]===o&&Oo(s,i[r][1]))}return!1}function Di(n){let e=typeof n=="string"?new TextEncoder().encode(n):n;return`sha256:${ut(Ze(e))}`}function Nq(n){let e=new Uint8Array(n);return globalThis.crypto.getRandomValues(e),e}function zi(n=Date.now()){let e=Nq(16);n<=Qu?(n=Qu,ks=ks+1&4095,ks===0&&(n=++Qu)):(ks=(e[6]&15)<<8|e[7],ks&=2047),Qu=n;let t=BigInt(n);for(let i=0;i<6;i++)e[i]=Number(t>>BigInt(8*(5-i))&0xffn);return e[6]=112|ks>>8&15,e[7]=ks&255,e[8]=128|e[8]&63,Wc(e)}function ef(n,e){if(n===e)return[];let t=Array.from(n),i=Array.from(e),o=0;for(;o<t.length&&o<i.length&&t[o]===i[o];)o++;let s=0;for(;s<t.length-o&&s<i.length-o&&t[t.length-1-s]===i[i.length-1-s];)s++;return[[o,t.length-s,i.slice(o,i.length-s).join("")]]}var Qu,ks,mr=I(()=>{"use strict";hr();Je();ve();un();un();un();Qu=0,ks=0});function Le(n,e=$q){if(typeof n!="string"||$i.encode(n).length>e)throw pe("bounded text required");return n}function xn(n,e){let t=F.dec(n);if(t>e)throw pe("integer exceeds bound");return t}function Dt(n,e){if(!Array.isArray(n)||n.length>e)throw pe("bounded array required");return n}function Ma(n,e){let t=Dt(n,e);if(t.length!==e)throw pe("wrong tuple length");return t}function bi(n,e){if(!(n instanceof Map))throw pe("exact struct required");let t=n;if(t.size!==e.length||e.some(i=>!t.has(i)))throw pe("exact struct required");return n}function lS(n){let e=n instanceof vt?n.value:n;if(typeof e!="number"||!Number.isFinite(e)||!(n instanceof vt)&&Number.isInteger(e))throw pe("finite binary64 required");return e}function pS(n){return n.kind==="list"?n.values.every(pS):n.kind!=="map"&&n.kind!=="duration"&&n.kind!=="error"&&n.kind!=="unavailable"}function Ps(n,e=1){if(!Number.isInteger(e)||e<1||e>32)throw pe("cell depth exceeds bound");let t=Dt(n,5),i=F.dec(t[0]),o=s=>{if(t.length!==s)throw pe("wrong tagged cell length")};switch(i){case 0:return o(1),{kind:"null"};case 1:return o(2),{kind:"boolean",value:Ee.dec(t[1])};case 2:return o(2),{kind:"number",value:lS(t[1])};case 3:return o(2),{kind:"text",value:Le(t[1])};case 4:{o(5);let s=An.dec(t[1]);if(!Number.isSafeInteger(s))throw pe("date millis exceeds JS-safe range");return{kind:"date",millis:s,display:Le(t[2]),authoritativeZone:Le(t[3]),dateOnly:Ee.dec(t[4])}}case 5:return o(3),{kind:"duration",components:Ma(t[1],8).map(lS),display:Le(t[2])};case 6:return o(2),{kind:"list",values:Dt(t[1],Ss).map(s=>Ps(s,e+1))};case 7:{if(o(2),!(t[1]instanceof Map)||t[1].size>Ss)throw pe("bounded cell data map required");let s=new Map,r=null;for(let[a,c]of t[1]){let l=Le(a),p=$i.encode(l);if(r&&Fq(r,p)>=0)throw pe("cell data map keys must ascend");r=p,s.set(l,Ps(c,e+1))}return{kind:"map",values:s}}case 8:return o(2),{kind:"error",message:Le(t[1])};case 9:return o(3),{kind:"unavailable",code:Le(t[1]),detail:Le(t[2])};default:throw pe("unknown tagged cell",!0)}}function Fq(n,e){for(let t=0;t<Math.min(n.length,e.length);t++)if(n[t]!==e[t])return n[t]-e[t];return n.length-e.length}function Kq(n){let e=new Map,t=0,i=0,o=r=>{if(++t>4096||(i+=r)>1024*1024)throw pe("summary metadata exceeds bound")},s=(r,a)=>{if(a>32)throw pe("summary value depth exceeds bound");o(128);let c=Dt(r,5),l=F.dec(c[0]);if(l===3||l===8)o($i.encode(Le(c[1])).length);else if(l===4)o($i.encode(Le(c[2])).length+$i.encode(Le(c[3])).length);else if(l===5)o($i.encode(Le(c[2])).length);else if(l===6)for(let p of Dt(c[1],Ss))s(p,a+1);else if(l===7){if(!(c[1]instanceof Map)||c[1].size>Ss)throw pe("bounded summary data map required");for(let[p,d]of c[1])o($i.encode(Le(p)).length+64),s(d,a+1)}else if(l!==0&&l!==1&&l!==2)throw pe("summary must be a tagged value",!0)};for(let r of Dt(n,64)){let a=Ma(r,2),c=Le(a[0],1024);if(c.length===0||/[\u0000-\u001f\u007f-\u009f]/u.test(c)||e.has(c))throw pe("unique nonempty summary name required");o($i.encode(c).length+64),s(a[1],1),e.set(c,Ps(a[1]))}return e}function jb(n){let e=xn(n.offset,4294967295),t=xn(n.limit,ii);if(t===0)throw pe("window limit must be positive");return{offset:e,limit:t}}function dS(n){if(!Array.isArray(n)||n.length>cS)throw pe("bounded rowProperties list required");let e=new Set,t=[],i=0;for(let o of n){if(typeof o!="string"||o.length===0)throw pe("non-empty row property name required");let s=$i.encode(o).length;if(s>Bq||e.has(o))throw pe("distinct bounded row property name required");if(i+=s,i>Vq)throw pe("row property names exceed bound");e.add(o),t.push(o)}return t}function tf(n){if(!(n.hints instanceof Map)||n.hints.size>Ss)throw pe("bounded hints map required");let e=new Map,t=0;for(let[s,r]of n.hints){if(Le(s),Le(r),t+=$i.encode(s).length+$i.encode(r).length,t>65536)throw pe("hint bytes exceed bound");e.set(s,r)}let i=new Map([[0,M.enc(n.record)],[1,Z.enc(n.sourceRevision)],[2,xn(n.ordinal,4294967295)],[3,e],[4,Le(n.captureTimezone,128)],[5,Ub]]);if(n.window!==void 0){let s=jb(n.window);i.set(6,new Map([[0,s.offset],[1,s.limit]]))}n.rowProperties!==void 0&&i.set(7,dS(n.rowProperties));let o=fe(i);if(o.length>zq)throw pe("request bytes exceed bound");return o}function uS(n){let e=bi(n,[0,1,2,3,4,5,6]);return{record:M.dec(e.get(0)),path:Le(e.get(1)),sourceRevision:Z.dec(e.get(2)),ordinal:xn(e.get(3),4294967295),name:e.get(4)===null?null:Le(e.get(4)),viewType:Le(e.get(5)),implementations:Dt(e.get(6),Ss).map(t=>{let i=bi(t,[0,1,2,3]);return{typeName:Le(i.get(0)),version:Le(i.get(1)),contractDigest:Z.dec(i.get(2)),implementationDigest:Z.dec(i.get(3))}})}}function nf(n,e,t){if(!(n instanceof Uint8Array)||!n.length||n.length>Dq)throw pe("response bytes exceed bound");let i=we(n);if(!(i instanceof Map))throw pe("result struct required");let o=i;if(o.get(0)!==1)throw pe("unknown result version",!0);if(o.has(7)){let v=bi(o,[0,7]);return{kind:"refusal",problem:ti.dec(v.get(7))}}let s=o.has(8),r=o.has(9),a=o.has(10),c=!(t==null||t===!1);if(a!==c)throw pe("rowProperties response differs from request");let l=Array.isArray(t)?new Set(dS(t)):null,p=bi(o,[0,1,2,3,4,5,6,...s?[8]:[],...r?[9]:[],...a?[10]:[]]);if(e!==void 0&&s!==(e!==null))throw pe("window response differs from request");let d=uS(p.get(1)),u=bi(p.get(2),[0,1]),f=Dt(u.get(0),64).map(v=>Le(v)),h=Dt(u.get(1),64).map(v=>{let k=bi(v,[0,1,2]),S=xn(k.get(0),63);if(S>=f.length)throw pe("unavailable column index out of bounds");return{index:S,code:Le(k.get(1)),detail:Le(k.get(2))}}),m=Dt(p.get(3),ii).map(v=>{let k=Ma(v,4),S=Dt(k[3],64);if(S.length!==f.length)throw pe("row cell count differs from columns");return{record:M.dec(k[0]),path:Le(k[1]),sourceRevision:Z.dec(k[2]),cells:S.map(x=>Ps(x))}}),w=a?(()=>{let v=Dt(p.get(10),ii);if(v.length!==m.length)throw pe("rowProperties count differs from rows");return m.map((k,S)=>{let x=Ma(v[S],2),P=Dt(x[0],Ss).map(O=>Le(O)),C=kn.dec(x[1]);if(C.size>cS)throw pe("rowProperties entry exceeds bound");let R=Object.create(null);for(let[O,E]of C){if(l&&!l.has(O))throw pe("unexpected row property in response");Object.defineProperty(R,O,{value:ei(E),enumerable:!0,writable:!0,configurable:!0})}return{...k,types:P,properties:{...R}}})})():m,b=Dt(p.get(4),ii).map(v=>{let k=Ma(v,2),S=Ps(k[0]);if(!pS(S))throw pe("group key must be a qualified scalar or list");let x=Dt(k[1],ii).map(P=>{let C=xn(P,ii-1);if(C>=w.length)throw pe("group row index out of bounds");return C});return{key:S,rowIndices:x}}),g;if(s){let v=bi(p.get(8),[0,1,2,3]),k=jb({offset:xn(v.get(0),4294967295),limit:xn(v.get(1),ii)}),S=xn(v.get(2),ii);if(w.length!==Math.min(k.limit,Math.max(S-k.offset,0)))throw pe("window row count differs from total/request");if(e!=null){let R=jb(e);if(k.offset!==R.offset||k.limit!==R.limit)throw pe("window echo differs from request")}let x=-1,P=Dt(v.get(3),ii);if(P.length!==b.length||b.some(R=>R.rowIndices.length===0))throw pe("group placements must align represented groups");let C=P.map((R,O)=>{let E=Ma(R,3),j=xn(E[0],ii-1),B=xn(E[1],ii);if(j<=x||j>=S||B===0||B>S)throw pe("group placement bounds/order invalid");x=j;let D=-1,J=Dt(E[2],ii).map(V=>{let U=xn(V,ii-1);if(U<=D||U>=B)throw pe("group row ordinal bounds/order invalid");return D=U,U});if(J.length!==b[O].rowIndices.length)throw pe("group ordinal count differs from represented rows");return{globalGroupOrdinal:j,totalGroupRows:B,rowOrdinals:J}});g={...k,totalMatchedRows:S,groupPlacements:C}}let y=ws.dec(p.get(5));if(!Number.isSafeInteger(y.instant))throw pe("clock instant exceeds JS-safe range");let _=r?Kq(p.get(9)):void 0;return{kind:"success",view:d,columns:f,unavailableColumns:h,rows:w,groups:b,clock:y,collectionRevision:Z.dec(p.get(6)),...g===void 0?{}:{window:g},..._===void 0?{}:{summaries:_}}}function fS(n){if(n==null)return null;if(!(n instanceof Uint8Array)||n.length!==32)throw pe("native discovery handle must be 32 bytes");return new Uint8Array(n)}function pp(n){let e=xn(n.limit,128);if(!e)throw pe("discovery limit must be positive");return fe(new Map([[0,n.reportUnreadable?2:1],[1,Le(n.captureTimezone,128)],[2,e],[3,fS(n.continuation)]]))}function rf(n){return fe(new Map([[0,1],[1,M.enc(n.record)],[2,Z.enc(n.sourceRevision)],[3,xn(n.ordinal,4294967295)],[4,Le(n.captureTimezone,128)]]))}function hS(n){if(!(n instanceof Uint8Array)||!n.length||n.length>1024*1024)throw pe("discovery response bytes exceed bound");let e=we(n);if(!(e instanceof Map))throw pe("discovery result struct required");let t=e;if(t.get(0)!==1)throw pe("unknown discovery result version");return t}function mS(n){let e=uS(n);if(!e.implementations.length||e.implementations.length>16)throw pe("bounded native implementation provenance required");return e}function yS(n){let e=ws.dec(n);if(!Number.isSafeInteger(e.instant))throw pe("clock instant exceeds JS-safe range");return Le(e.tz,128),Le(e.localDate,128),e}function Wq(n){let e=bi(n,[0,1,2,3,4]);return{record:M.dec(e.get(0)),path:Le(e.get(1)),sourceRevision:Z.dec(e.get(2)),reason:Le(e.get(3),128),detail:Le(e.get(4),128)}}function of(n,e=128,t=!1){let i=xn(e,128);if(!i)throw pe("discovery limit must be positive");let o=hS(n);if(o.has(7)){let l=bi(o,[0,7]);return{kind:"refusal",problem:ti.dec(l.get(7))}}let s=bi(o,t?[0,1,2,3,4,5]:[0,1,2,3,4]),r=t?Dt(s.get(5),128).map(Wq):[];for(let l=1;l<r.length;l++)if(r[l-1].record>=r[l].record)throw pe("unreadable sources must ascend by record");let a=Dt(s.get(1),i).map(mS);for(let l=1;l<a.length;l++){let p=a[l-1],d=a[l];if(p.record>d.record||p.record===d.record&&p.ordinal>=d.ordinal)throw pe("discovery source/ordinal frontier must ascend");if(p.record===d.record&&(p.path!==d.path||p.sourceRevision!==d.sourceRevision))throw pe("one source identity cannot have two revisions/paths within a page")}let c=s.get(4);if(c!==null&&!(c instanceof Uint8Array))throw pe("native discovery handle required");return{kind:"success",views:a,unreadable:r,clock:yS(s.get(2)),collectionRevision:Z.dec(s.get(3)),continuation:fS(c)}}function sf(n,e){let t=hS(n);if(t.has(7)){let r=bi(t,[0,7]);return{kind:"refusal",problem:ti.dec(r.get(7))}}let i=bi(t,[0,1,2,3,4]),o=mS(i.get(1)),s=Le(i.get(2),512*1024);if(Di(s)!==o.sourceRevision)throw pe("exact native source SHA differs from bytes");if(e&&(o.record!==M.dec(M.enc(e.record))||o.sourceRevision!==Z.dec(Z.enc(e.sourceRevision))||o.ordinal!==e.ordinal))throw pe("exact source identity/revision/ordinal differs from request");return{kind:"success",view:o,source:s,clock:yS(i.get(3)),collectionRevision:Z.dec(i.get(4))}}var Ub,Dq,zq,$q,Ss,ii,cS,Bq,Vq,$i,pe,Nb=I(()=>{"use strict";Je();ve();un();mr();en();Ub="whole-view-synthetic-policy-reference-v1",Dq=16*1024*1024,zq=128*1024,$q=4096,Ss=4096,ii=65536,cS=128,Bq=256,Vq=16*1024,$i=new TextEncoder,pe=(n,e=!1)=>new ae("app-bases-v1",n,e)});async function*bS(n,e,t={}){let i=gS(t.firstPageSize,200),o=gS(t.pageSize,1e3),s=e.window?.offset??0,r=0,a=0,c;for(;;){t.signal?.throwIfAborted();let l=await n({...e,window:{offset:s,limit:a===0?i:o}},t.signal);if(l.kind==="refusal"){yield l;return}let p=l.window?.totalMatchedRows;if(p===void 0)throw A("internal","native Bases page omitted its window");c??={revision:l.collectionRevision,total:p},r+=l.rows.length;let d=l.rows.length===0||s+l.rows.length>=p;if(yield{...l,page:a,offset:s,loaded:r,complete:d,changedSinceFirst:c.revision!==l.collectionRevision||c.total!==p},d)return;s+=l.rows.length,a+=1}}var gS,wS=I(()=>{"use strict";re();gS=(n,e)=>{if(n===void 0)return e;if(!Number.isInteger(n)||n<1||n>65536)throw A("invalid_request","page size must be 1..65536");return n}});function vS(n){if(n==="request"||n==="single_record"||n==="cross_record")return n;throw new ae("validation-tier","unknown diagnostic tier",!0)}function kS(n){if(n===void 0)return{targets:void 0,expected:void 0};if(!Array.isArray(n)||n.length>1e3)throw A("invalid_request","At most 1000 validation selections are allowed.","validation_bounds");let e=[],t=[];for(let i of Array.from(n)){if(typeof i=="string"){let s=M.dec(M.enc(i));e.push(M.enc(s)),t.push({id:s});continue}if(!i||typeof i!="object")throw A("invalid_request","Validation needs UUID, path or record selections.","validation_selection");if("id"in i){let s=M.dec(M.enc(i.id)),r=Z.dec(Z.enc(i.revision));e.push(M.enc(s)),t.push({id:s,revision:r});continue}let o=i.path;if(typeof o!="string"||!o||o.length>4096||new TextEncoder().encode(o).byteLength>4096)throw A("invalid_request","Validation paths must be nonempty and at most 4096 UTF-8 bytes.","validation_selection");e.push(o),t.push({})}return{targets:e,expected:t}}function SS(n,e){if(e&&(n.length!==e.length||n.some((t,i)=>e[i]?.id!==void 0&&e[i].id!==t.id)))throw A("internal","Validation did not return the complete selected record identities.","invalid_validation_result");if(e&&n.some((t,i)=>e[i]?.revision!==void 0&&e[i].revision!==t.revision))throw A("unavailable","The validated document differs from the selected record revision.","record_validation_stale");return n}var Hq,Gq,Yq,_S,Ro,AS,PS=I(()=>{"use strict";ve();Je();en();re();Hq={name:"validation-tier",enc:vS,dec:vS},Gq=z("validation-issue",[[0,"code",T],[1,"severity",Lu],[2,"message",T],[3,"details",Ia,"opt"],[4,"location",T,"opt"],[5,"typeName",T,"opt"],[6,"tier",Hq]]),Yq=z("record-validation",[[0,"id",M],[1,"issues",G(Gq)],[2,"path",T],[3,"revision",Z]]),_S=G(Yq),Ro=n=>new ae("record-validations",n),AS={name:"record-validations",enc:n=>_S.enc(n),dec:n=>{if(!Array.isArray(n)||n.length>1e3)throw Ro("invalid inventory");let e=0,t=0,i=[[n,0]];for(;i.length;){let[s,r]=i.pop();if(++t>65536||r>32)throw Ro("result exceeds tree bounds");if(Array.isArray(s)){if(s.length>65536)throw Ro("oversized array");for(let a of s)i.push([a,r+1])}else if(s instanceof Map){if(s.size>32768)throw Ro("oversized map");for(let[a,c]of s)i.push([a,r+1],[c,r+1])}}for(let s of n){let r=s instanceof Map?s.get(1):void 0;if(!Array.isArray(r))throw Ro("missing diagnostics");if(e+=r.length,e>4096)throw Ro("too many diagnostics")}if(fe(n).byteLength>1024*1024)throw Ro("result exceeds byte bounds");let o=_S.dec(n);for(let s of o)if(!s.path||new TextEncoder().encode(s.path).byteLength>4096)throw Ro("invalid current path");return o}}});function Jq(n){if(n.length>Eo)throw A("too_large",`frame of ${n.length} bytes exceeds ${Eo}`);let e=new Uint8Array(4+n.length);return new DataView(e.buffer).setUint32(0,n.length),e.set(n,4),e}function Db(n){return xS.has(n)}function af(n){let e=new dp,t=!1,i=null,o=[],s={get onframe(){return i},set onframe(a){if(i=a,a&&o.length)for(let c of o.splice(0))a(c)},onclose:null,send(a){if(t)throw A("unavailable","connection closed");n.write(Jq(fe(a)))},close(){t||(t=!0,n.close(),s.onclose?.())}};xS.add(s),n.ondata=a=>{try{for(let c of e.push(a)){let l=we(c);if(i)i(l);else if(o.length<1024)o.push(l);else throw A("too_large","too many frames before the session started")}}catch(c){r(c instanceof oe?c:A("internal",`invalid frame from replica: ${String(c)}`))}},n.onclose=a=>r(a);function r(a){t||(t=!0,n.close(),s.onclose?.(a))}return s}function CS(){let n=()=>({onframe:null,onclose:null,closed:!1,send(i){if(this.closed)throw A("unavailable","connection closed");let o=this.peer;queueMicrotask(()=>{o.closed||o.onframe?.(i)})},close(){if(this.closed)return;this.closed=!0,this.onclose?.();let i=this.peer;i.closed||(i.closed=!0,queueMicrotask(()=>i.onclose?.()))}}),e=n(),t=n();return e.peer=t,t.peer=e,[e,t]}var Eo,dp,xS,up=I(()=>{"use strict";Je();re();Eo=16*1024*1024,dp=class{chunks=[];head=0;buffered=0;push(e){e.length&&(this.chunks.push(e),this.buffered+=e.length);let t=[];for(;!(this.buffered<4);){let i=new DataView(this.peek(4).buffer).getUint32(0);if(i>Eo)throw A("too_large",`frame of ${i} bytes exceeds ${Eo}`);if(this.buffered<4+i)break;this.skip(4),t.push(this.take(i))}return t}peek(e){let t=new Uint8Array(e),i=0,o=this.head;for(let s of this.chunks){let r=Math.min(e-i,s.length-o);if(t.set(s.subarray(o,o+r),i),i+=r,o=0,i===e)break}return t}take(e){let t=this.peek(e);return this.skip(e),t}skip(e){for(this.buffered-=e;e>0;){let i=this.chunks[0].length-this.head;if(e<i){this.head+=e;return}e-=i,this.chunks.shift(),this.head=0}}};xS=new WeakSet});var lf,IS=I(()=>{"use strict";re();lf=class{constructor(e){this.request=e}request;tail=Promise.resolve();occupied=0;read(e,t,i,o){if(o?.aborted)return Promise.reject(A("cancelled","Bases READ cancelled"));if(this.occupied>=33)return Promise.reject(A("unavailable","Bases read queue is full","bases_read_backpressure"));let s=t.slice();this.occupied++;let r,a,c=!1,l=new Promise((u,f)=>{r=u,a=f}),p=()=>{c||(c=!0,s.fill(0),a(A("cancelled","Bases READ cancelled")))};o?.addEventListener("abort",p,{once:!0});let d=async()=>{try{if(c)return;let u=await this.request(e,s);if(!(u instanceof Uint8Array)||!u.length||u.length>i)throw u instanceof Uint8Array&&u.fill(0),A("internal","native Bases response bytes exceed bound");if(c||o?.aborted){u.fill(0),p();return}c=!0,r(u)}catch(u){c||(c=!0,a(u))}finally{s.fill(0),o?.removeEventListener("abort",p),this.occupied--}};return this.tail=this.tail.then(d,d),l}}});function OS(n,e){cf.set(n,e)}function RS(n,e){let t=cf.get(n);t&&cf.set(e,t)}function ES(n){return cf.get(n)}var cf,zb=I(()=>{"use strict";cf=new WeakMap});function pf(n){return qS.add(n),n}function fp(n){return qS.has(n)}var qS,hp=I(()=>{"use strict";qS=new WeakSet});function Bn(n,e){return X(n)?n:n instanceof ae&&n.unknown?A("upgrade_required",`${e}: ${n.message}`,{reason:"unknown_variant"}):A("internal",`${e}: ${n instanceof Error?n.message:String(n)}`)}function La(n,e,t){return new oe(Bn(n,e).toProblem(),{...t,cause:n})}var df,xs,TS,ja,Cs,Ua=I(()=>{"use strict";ve();re();up();IS();zb();hp();en();df=[{major:1,minor:4},{major:1,minor:3},{major:1,minor:2},{major:1,minor:1},{major:1,minor:0}];xs=class extends oe{constructor(e,t={}){super(Bn(e,"submit").toProblem(),{...t,cause:e})}},TS=new WeakSet,ja=n=>n instanceof oe&&TS.has(n),Cs=class n{constructor(e,t){this.port=e;this.hello=t;e.onframe=i=>this.onFrame(i),e.onclose=i=>this.onClosed(i)}port;hello;nextId=1;pending=new Map;pushHandlers=new Map;requestHandlers=new Map;closeError;closedFlag=!1;closeListeners=new Set;basesReads=new lf((e,t)=>this.request(e,new Map([[0,t]])));device;static async open(e,t,i){let o=Kr.enc({kind:"request",id:0,method:"hello",params:Fg.enc(t)}),s;try{s=await e.open(o,i)}catch(c){throw X(c)?c:A("unavailable",`cannot reach the replica (${e.description}): ${String(c)}`)}let r;try{let c=Kr.dec(s.helloResponse);if(c.kind!=="response"||c.id!==0)throw A("internal","replica answered hello with another frame");if(c.problem)throw c.problem.code==="unavailable"&&c.problem.reason==="not_serving"&&fp(e)?new oe({...c.problem,reason:"not_served"}):new oe(c.problem);r=Gg.dec(c.result??null)}catch(c){throw s.port.close(),Bn(c,"hello")}let a=new n(s.port,r);return RS(s.port,a),a.device=s.device,a}get closed(){return this.closedFlag}get error(){return this.closeError}onClose(e){return this.closedFlag?(queueMicrotask(()=>e(this.closeError)),()=>{}):(this.closeListeners.add(e),()=>this.closeListeners.delete(e))}async readAppBases(e,t){if(this.closedFlag)throw this.closeError??A("unavailable","session closed");if(t?.aborted)throw A("cancelled","Bases read cancelled");if(!(e instanceof Uint8Array)||!e.length||e.length>128*1024)throw A("invalid_request","Bases request bytes exceed bound");let i=this.port;if(typeof i.readAppBases!="function"&&!Db(i))throw A("invalid_request","this transport does not support app Bases reads",{reason:"unsupported"});let o=typeof i.readAppBases=="function"?await i.readAppBases(e,t):await this.basesReads.read("app_bases_execute_v1",e,16*1024*1024,t);try{if(t?.aborted)throw A("cancelled","Bases read cancelled");if(this.closedFlag||this.port!==i)throw this.closeError??A("unavailable","original Bases session closed");if(!(o instanceof Uint8Array)||!o.length||o.length>16*1024*1024)throw A("internal","Bases response bytes exceed bound");return o}catch(s){throw o instanceof Uint8Array&&o.fill(0),s}}async readAppBasesDiscovery(e,t,i){if(this.closedFlag)throw this.closeError??A("unavailable","session closed");if(i?.aborted)throw A("cancelled","Bases discovery cancelled");if(e!=="list-views"&&e!=="read-view-source")throw A("invalid_request","unknown native Bases read");if(!(t instanceof Uint8Array)||!t.length||t.length>128*1024)throw A("invalid_request","Bases request bytes exceed bound");let o=this.port;if(typeof o.readAppBasesDiscovery!="function"&&!Db(o))throw A("invalid_request","this transport does not support native Bases discovery",{reason:"unsupported"});let s=typeof o.readAppBasesDiscovery=="function"?await o.readAppBasesDiscovery(e,t,i):await this.basesReads.read(e==="list-views"?"app_bases_list_views_v1":"app_bases_read_view_source_v1",t,1024*1024,i);try{if(i?.aborted)throw A("cancelled","Bases discovery cancelled");if(this.closedFlag||this.port!==o)throw this.closeError??A("unavailable","original Bases session closed");if(!(s instanceof Uint8Array)||!s.length||s.length>1024*1024)throw A("internal","Bases discovery response bytes exceed bound");return s}catch(r){throw s instanceof Uint8Array&&s.fill(0),r}}async declaredSetup(e,t){if(!this.hello.features.includes("declared-collection-setup-v1"))throw A("upgrade_required","This computer needs an update to set up this app.","declared_setup_unsupported");if(!e.length||e.length>2*1024*1024)throw A("too_large","Setup request exceeds its fixed bound.");let i=await this.request("app_collection_setup_v1",new Map([[0,e]]),{signal:t});if(this.closed||t?.aborted)throw i instanceof Uint8Array&&i.fill(0),this.error??A("unavailable","Original setup session closed.");if(!(i instanceof Uint8Array)||!i.length||i.length>256*1024)throw i instanceof Uint8Array&&i.fill(0),A("internal","Invalid bounded Native setup reply.");return i}request(e,t,i={}){if(this.closedFlag)return Promise.reject(this.closeError??A("unavailable","session closed"));if(i.signal?.aborted)return Promise.reject(A("cancelled","request aborted before sending"));let o=this.nextId++;return new Promise((s,r)=>{let a=()=>{try{this.sendFrame({kind:"request",id:this.nextId++,method:"cancel",params:new Map([[0,o]])})}catch{}c.reject(A("cancelled",`${e} cancelled`))},c={resolve:l=>{c.cleanup();try{s(i.codec?i.codec.dec(l):l)}catch(p){r(Bn(p,`${e} result`))}},reject:l=>{c.cleanup(),r(l)},cleanup:()=>{this.pending.delete(o),i.signal?.removeEventListener("abort",a)}};this.pending.set(o,c),i.signal?.addEventListener("abort",a,{once:!0});try{this.sendFrame({kind:"request",id:o,method:e,params:t})}catch(l){c.reject(X(l)?l:A("unavailable",String(l)))}})}onPush(e,t){let i=this.pushHandlers.get(e);return i||this.pushHandlers.set(e,i=new Set),i.add(t),()=>i.delete(t)}handle(e,t){this.requestHandlers.set(e,t)}close(){this.port.close(),this.onClosed()}closeWith(e){this.fail(e)}sendFrame(e){this.port.send(Kr.enc(e))}onFrame(e){let t;try{t=Kr.dec(e)}catch(i){if(i instanceof ae&&i.unknown)return;this.fail(A("internal",`malformed frame from replica: ${String(i)}`));return}switch(t.kind){case"response":{let i=this.pending.get(t.id);if(!i)return;if(t.problem){let o=new oe(t.problem);TS.add(o),i.reject(o)}else i.resolve(t.result??null);return}case"push":{let i=this.pushHandlers.get(t.type);if(!i)return;for(let o of[...i])try{o(t.payload)}catch(s){queueMicrotask(()=>{throw s})}return}case"request":this.serve(t.id,t.method,t.params);return}}async serve(e,t,i){let o=this.requestHandlers.get(t),s,r;if(!o)r=A("invalid_request",`client does not serve ${t}`,{reason:"unknown_method"}).toProblem();else try{s=await o(i)}catch(a){r=(X(a)?a:A("internal",String(a))).toProblem()}if(!this.closedFlag)try{this.port.send(Kr.enc(r?{kind:"response",id:e,problem:r}:{kind:"response",id:e,result:s??null}))}catch{}}fail(e){this.port.onclose=null,this.port.close(),this.onClosed(e)}onClosed(e){if(this.closedFlag)return;this.closedFlag=!0,this.closeError=e;let t=e??A("unavailable","connection to the replica closed");for(let i of[...this.pending.values()])i.reject(t);this.pending.clear();for(let i of[...this.closeListeners])i(e);this.closeListeners.clear()}}});function LS(n,e){return X(n,"unavailable")&&n.reason==="hosted_chunk_busy"&&Date.now()<e}function jS(n,e,t){let i=Math.min(Math.max(n.retryAfterMs??1e3,250),5e3);return new Promise((o,s)=>{if(t?.aborted)return s(A("cancelled",`${e} aborted`));let a=setTimeout(()=>{t?.removeEventListener("abort",c),o()},i),c=()=>{clearTimeout(a),s(A("cancelled",`${e} aborted`))};t?.addEventListener("abort",c,{once:!0})})}function Bb(n){let{grant:e}=n;if(e.grant!==void 0&&n.version.major===1&&n.version.minor<2)return null;let t=new Set(e.capabilities),i=Zq.filter(([,s])=>t.has(s)&&(s==="collection.read"||e.role!=="viewer")).map(([s])=>s),o=e.fileFolders===void 0?Object.freeze({kind:"collection"}):Object.freeze({kind:"selected_folders",folders:Object.freeze([...e.fileFolders])});return Object.freeze({actions:Object.freeze(i),scope:o})}function DS(n,e){mp.set(n,e)}function US(n){return typeof n=="string"?M.enc(n):"id"in n?M.enc(n.id):n.path}function $b(n){if(typeof n=="string")return n;if("id"in n)return n.id;throw A("invalid_request","this operation needs a file ID; get() the file first")}function Gr(n){let e=new Map;for(let[t,i]of n)i!==void 0&&e.set(t,i);return e}async function NS(n,e,t){return n instanceof Uint8Array?n.subarray(e,t):n instanceof ArrayBuffer?new Uint8Array(n,e,t-e):new Uint8Array(await n.slice(e,t).arrayBuffer())}function Qq(n){return n instanceof Uint8Array||n instanceof ArrayBuffer?n.byteLength:n.size}var MS,uf,Xq,Zq,mp,Na,yp=I(()=>{"use strict";hr();ve();re();Ua();mr();en();MS=9e4;uf=64*1024*1024,Xq=8*1024*1024,Zq=[["list","collection.read"],["read","collection.read"],["add","records.create"],["replace","records.edit"],["move","records.edit"],["delete","records.delete"]];mp=new WeakMap;Na=class{constructor(e){this.client=e;e.onSession(t=>this.wire(t))}client;uploading=Promise.resolve();progress=new Map;streams=new Map;wired=new WeakSet;opening=0;early=new Map;earlyFailures=new Map;get grant(){let e=Bb(this.client.hello),t=mp.get(this);return e&&t?Object.freeze({...e,actions:Object.freeze(e.actions.filter(i=>i==="list"||i==="read"||t.allows(i)))}):e}watch(e,t={}){let{version:i}=this.client.hello;if(i.major!==1||i.minor<2)throw A("upgrade_required","this replica's change feed does not name files","change_entity_unsupported");return this.client.watchChanges(o=>{let s=o.changes.filter(a=>a.entity==="file"||a.entity===void 0&&a.kind==="remove");o.changes.some(a=>a.entity===void 0&&a.kind==="put")?e({changes:[],cursor:o.cursor,reset:!0}):(s.length||o.reset)&&e({changes:s,cursor:o.cursor,reset:o.reset})},t)}wire(e){this.wired.has(e)||(this.wired.add(e),e.onPush("transfer_progress",t=>{try{let i=$u.dec(t);this.progress.get(i.id)?.(i)}catch{}}),e.onPush("file_chunk",t=>{try{let i=Du.dec(t),o=this.streams.get(i.stream);if(o)o.onChunk(i);else if(this.opening>0){let s=this.early.get(i.stream)??[];s.reduce((a,c)=>a+c.bytes.length,0)+i.bytes.length<=Xq&&this.early.size<16&&(s.push(i),this.early.set(i.stream,s))}}catch{}}),e.onPush("file_stream_failed",t=>{try{let{stream:i,problem:o}=zu.dec(t),s=this.streams.get(i);s?(this.streams.delete(i),s.onEnd(new oe(o))):this.opening>0&&this.earlyFailures.size<16&&this.earlyFailures.set(i,new oe(o))}catch{}}),e.onClose(t=>{for(let i of this.streams.values())i.onEnd(t??A("unavailable","connection closed"));this.streams.clear()}))}async session(e,t=!1){let i=await(t?this.client.readyForRead(e):this.client.ready({signal:e}));return this.wire(i),i}listPage(e={}){return this.client.call("list_files",Gr([[0,e.folder],[1,e.media?.map(t=>Ea.enc(t))],[2,e.cursor],[3,e.limit]]),{codec:ab,retry:!0,...e.signal?{signal:e.signal}:{}})}async*list(e={}){let t;for(;;){let i=await this.listPage({...e,...t?{cursor:t}:{},...e.pageSize?{limit:e.pageSize}:{}});if(yield*i.files,!i.cursor)return;t=i.cursor}}get(e,t={}){return this.client.call("get_file",Gr([[0,US(e)]]),{codec:Qc,retry:!0,...t.signal?{signal:t.signal}:{}})}async upload(e,t,i={}){let o={...i},s=this.uploading.then(()=>this.uploadQueued(e,t,o));return this.uploading=s.then(()=>{},()=>{}),s}async uploadQueued(e,t,i){if(mp.get(this)?.check(i.fileId?"replace":"add"),i.signal?.aborted)throw A("cancelled","upload aborted");let o=Qq(t),s=Ze.create(),r=4*1024*1024;for(let d=0;d<o;d+=r)s.update(await NS(t,d,Math.min(o,d+r)));let a=Ug(s.digest()),c=i.transferId??zi(),l={transfer:c,path:e,size:o,digest:a,mutationId:i.mutationId??zi()};i.fileId&&(l.fileId=i.fileId),i.ifRevision&&(l.ifRevision=i.ifRevision),i.onProgress&&this.progress.set(c,i.onProgress);let p=Date.now()+MS;for(;;)try{return await this.uploadOnce(t,o,l,i)}catch(d){if(X(d,"unavailable")&&this.client.link==="reconnecting")continue;if(LS(d,p)){await jS(d,"upload",i.signal);continue}throw this.progress.delete(c),await this.abortUpload(c).catch(()=>{}),La(d,"upload",{mutationId:l.mutationId})}}async uploadOnce(e,t,i,o){let s=await this.session(o.signal),r=o.signal?{signal:o.signal}:{},a=await s.request("open_upload",lb.enc(i),{codec:cb,...r});if(a.fileId===void 0){let h=s.hello.version.minor>=1;throw A(h?"internal":"upgrade_required","the replica does not return upload file identity",{reason:h?"file_upload_identity_missing":"file_upload_identity_unsupported"})}if(a.transfer!==i.transfer||i.fileId!==void 0&&a.fileId!==i.fileId)throw A("internal","the replica returned an unrelated upload identity",{reason:"file_upload_identity_mismatch"});let c=new Set(a.received),l=Math.ceil(t/a.chunkSize),p=c.size*a.chunkSize,d=new Set;for(let h=0;h<l;h++){if(c.has(h))continue;let m=h*a.chunkSize,w=await NS(e,m,Math.min(t,m+a.chunkSize)),b=s.request("upload_chunk",pb.enc({transfer:i.transfer,index:h,bytes:w}),r).then(()=>{p+=w.length,o.onProgress?.({id:i.transfer,phase:"receiving",done:Math.min(p,t),total:t})});d.add(b),b.finally(()=>d.delete(b)).catch(()=>{}),d.size>=4&&await Promise.race(d)}await Promise.all(d);let u=await s.request("commit_upload",Gr([[0,M.enc(i.transfer)]]),{codec:ku(Sn),...r}),f=Object.assign(this.client._track(u),{fileId:a.fileId});return o.onProgress?f.confirmed.finally(()=>this.progress.delete(i.transfer)).catch(()=>{}):this.progress.delete(i.transfer),f}abortUpload(e){return this.client.call("abort_upload",Gr([[0,M.enc(e)]])).then(()=>{})}downloadStream(e,t={}){let i=null,o=null,s,r,a=new Promise((g,y)=>(s=g,r=y));a.catch(()=>{});let c=this,l=new AbortController,p=A("cancelled","file download cancelled"),d=!1,u=!1,f=!1,h=()=>{},m=()=>{i!==null&&(c.streams.delete(i),c.early.delete(i),f||(f=!0,o?.request("cancel_stream",Gr([[0,i]])).catch(()=>{})))},w=()=>{u||(d=!0,h(),r(p),l.abort(),m())},b=new ReadableStream({async start(g){let y=()=>{u||d||(w(),g.error(p))};if(h=()=>t.signal?.removeEventListener("abort",y),t.signal?.addEventListener("abort",y,{once:!0}),t.signal?.aborted){y();return}try{if(o=await c.session(l.signal,!0),d)return;let _=Gr([[0,US(e)]]);t.range&&_.set(1,[t.range[0],t.range[1]]),t.revision&&_.set(2,Z.enc(t.revision));let v=0,k=0;c.opening++;let S;try{let O=Date.now()+MS;for(;;)try{S=await o.request("read_file",_,{signal:l.signal});break}catch(E){if(!LS(E,O))throw E;await jS(E,"download",l.signal)}}finally{c.opening--}i=F.dec(S.get(0)??null);let x=c.early.get(i)??[],P=c.earlyFailures.get(i);if(c.early.delete(i),c.earlyFailures.delete(i),c.opening===0&&(c.early.clear(),c.earlyFailures.clear()),d){m(),u=!0;return}let C=Qc.dec(S.get(1)??null);s(C),v=t.range?t.range[1]:C.size;let R=O=>{d||u||(g.enqueue(O.bytes),k+=O.bytes.length,t.onProgress?.({id:i,phase:"streaming",done:k,total:v}),!(d||u)&&(o.request("ack_chunks",Gr([[0,i],[1,O.offset+O.bytes.length]])).catch(()=>{}),O.last&&!d&&!u&&(u=!0,h(),c.streams.delete(i),g.close())))};c.streams.set(i,{onChunk:R,onEnd:O=>{u=!0,h(),g.error(O??A("unavailable","stream ended"))}});for(let O of x)R(O);P&&!u&&(c.streams.delete(i),u=!0,h(),g.error(P))}catch(_){u=!0,h(),c.opening===0&&(c.early.clear(),c.earlyFailures.clear()),m(),r(_),g.error(_)}},cancel:w});return Object.assign(b,{file:a})}async download(e,t={}){let i=typeof e=="object"&&"size"in e?e:await this.get(e,t);if(i.size>uf)throw A("too_large",`file is ${i.size} bytes; use downloadStream`,{details:{limit:uf}});let o=new Uint8Array(i.size),s=0,r=this.downloadStream(i,t).getReader();for(;;){let{done:a,value:c}=await r.read();if(a)break;o.set(c,s),s+=c.length}return o.subarray(0,s)}fetch(e,t={}){return this.client.call("fetch_file",Gr([[0,M.enc($b(e))]]),{retry:!0,...t.signal?{signal:t.signal}:{}}).then(()=>{})}evict(e){return this.client.call("evict_file",Gr([[0,M.enc($b(e))]])).then(()=>{})}getMaterialization(){return this.client.call("get_materialization",null,{codec:Bu,retry:!0})}setMaterialization(e){return this.client.call("set_materialization",Bu.enc(e)).then(()=>{})}async move(e,t,i={}){mp.get(this)?.check("move");let o={kind:"file_move",id:e.id,from:e.path,to:t,updateRefs:i.updateRefs??!0};return this.client.submit([i.ifRevision?{...o,ifRevision:i.ifRevision}:o],i)}async delete(e,t={}){mp.get(this)?.check("delete");let i={kind:"file_delete",id:$b(e)};return typeof e=="object"&&"digest"in e&&(i.base=e.digest),t.ifRevision&&(i.ifRevision=t.ifRevision),this.client.submit([i],t)}}});function HS(n){return/^\d{6}$/.test(n)?`${n.slice(0,3)} ${n.slice(3)}`:n}var Vb,zS,Fb,$S,VS,BS,FS,KS,WS,Kb,eT,GS,ff=I(()=>{"use strict";ve();en();Vb=["desktop","mobile","app_runtime","cli","hosted","escrow","recovery"],zS=Se("device-kind",Vb),Fb={name:"device-kind",enc:n=>zS.enc(n),dec:n=>{try{return zS.dec(n)}catch{return"unknown"}}},$S=z("pending-device",[[0,"device",M],[1,"account",M],[2,"kind",Fb],[3,"sas",T,"opt"],[4,"exchangeReady",Ee]]),VS={...$S,enc:n=>$S.enc({...n,sas:void 0})},BS=z("approval-readiness",[[0,"device",M],[1,"sas",T,"opt"],[2,"exchangeReady",Ee]]),FS={...BS,enc:n=>BS.enc({...n,sas:void 0})},KS=z("recovery-key-status",[[0,"configured",Ee],[1,"device",M,"opt"]]),WS=z("recovery-key-created",[[0,"phrase",T],[1,"device",M]]);Kb=["idle","reading_ahead","pending_grant","keyed","refused"],eT=Se("account-key-state",Kb),GS=z("account-key-status",[[0,"state",eT],[1,"problem",ti,"opt"]])});var YS,JS,tT,nT,XS,ZS,QS=I(()=>{"use strict";ve();ff();YS=z("record-history-params",[[0,"record",M],[1,"before",F,"opt"],[2,"limit",F,"opt"]]),JS=z("record-version-params",[[0,"record",M],[1,"seq",F]]),tT=z("author-ref",[[0,"account",M],[1,"device",M],[2,"grant",M,"opt"],[3,"grantAccount",M,"opt"]]),nT=z("history-version",[[0,"seq",F],[1,"time",An],[2,"author",tT],[3,"kind",Se("version-kind",["created","edited","moved","deleted"])],[4,"path",T],[5,"revision",Z,"opt"],[6,"source",Se("source",["api","external"])],[7,"deviceKind",Fb],[8,"app",T,"opt"]]),XS=z("record-history",[[0,"versions",G(nT)],[1,"from",F],[2,"fromTime",An,"opt"],[3,"next",F,"opt"]]),ZS=z("record-version",[[0,"path",T],[1,"document",T]])});function Wb(n,e,t,i){return Object.freeze({outcome:"unknown",mutationId:n,...i?{receipt:i}:{},problem:{code:"outcome_unknown",recovery:"resolve_outcome",reason:e,message:t}})}async function tP(n,e,t={}){let i=t.signal,o,s,r;if(typeof e=="string"){s=e;try{r=await n.receipt(s,{signal:i})}catch(l){if(gp(l))throw l;return X(l,"not_found")?Object.freeze({outcome:"rejected",mutationId:s,problem:l.toProblem()}):Wb(s,"receipt_unavailable",`The write's result could not be read: ${eP(l)}`)}}else try{o=await e,s=o.mutationId,r=o.receipt}catch(l){if(!(l instanceof oe)||gp(l))throw l;if(l.mutationId===void 0)return Object.freeze({outcome:"rejected",problem:l.toProblem()});s=l.mutationId;try{r=await n.receipt(s,{signal:i})}catch(p){if(gp(p))throw p;return X(p,"not_found")?Object.freeze({outcome:"rejected",mutationId:s,problem:l.toProblem()}):Wb(s,"receipt_unavailable",`The write may have been saved: ${l.message}`)}}if(r.state==="pending")try{r=await n.awaitReceipt(s,{timeoutMs:t.timeoutMs??iT,signal:i}),o?.update(r)}catch(l){if(gp(l))throw l;r=o?.receipt??r}if(r.mutation!==s)throw new oe({code:"internal",recovery:"contact_support",message:"the replica answered with another mutation's receipt"},{mutationId:s});if(r.state==="unknown"){let l=r.problem??{code:"outcome_unknown",recovery:"resolve_outcome",message:"The write's result is not known."};return Object.freeze({outcome:"unknown",mutationId:s,receipt:r,problem:l})}if(r.state==="rejected"){let l=r.problem??{code:"internal",recovery:"contact_support",message:"The write was rejected without a reason."};return Object.freeze({outcome:"rejected",mutationId:s,receipt:r,problem:l})}let a;if(t.read){let l=t.read===!0?{}:t.read,p=r.records?.length===1?r.records[0].id:void 0,d=l.record??o?.recordId??p;if(d===void 0)throw new oe({code:"invalid_request",recovery:"fix_request",message:"settle cannot tell which record to read back; pass read.record"},{mutationId:s});try{a=await rT(n,d,l,i)}catch(u){if(gp(u))throw u;return Wb(s,"readback_failed",`The write was kept, but the record could not be read back: ${eP(u)}`,r)}}let c={mutationId:s,receipt:r,...a};return r.state==="pending"?Object.freeze({outcome:"saved_on_device",...c}):r.status==="conflicted"?Object.freeze({outcome:"conflicted",...c,conflicts:Object.freeze([...r.conflicts??[]])}):Object.freeze({outcome:"confirmed",...c})}async function rT(n,e,t,i){let o;try{o=await n.get(e,{include:t.include,signal:i})}catch(s){if(!X(s,"not_found"))throw s;return t.contract?{record:null,contractRecord:null}:{record:null}}return t.contract?{record:o,contractRecord:await n.getContract(o,t.contract,{signal:i})}:{record:o}}var iT,gp,eP,nP=I(()=>{"use strict";re();iT=3e3,gp=n=>X(n,"cancelled"),eP=n=>n instanceof Error?n.message:String(n)});async function hf(n,e,t={}){let{include:i,signal:o}=t;o?.throwIfAborted();let s=t.concurrency??8;if(!Number.isSafeInteger(s)||s<1||s>Gb)throw A("invalid_request","readMany concurrency must be 1..16","read_many_bounds");if(!Array.isArray(e)||e.length>Hb)throw A("invalid_request","readMany accepts at most 1000 record selections","read_many_bounds");let r=Array.from(e,oT),a=i?Object.freeze({...i}):void 0,c={...a?{include:a}:{},...o?{signal:o}:{}},l=new Array(r.length),p=0,d=!1,u;async function f(){for(;!d&&p<r.length;)try{o?.throwIfAborted();let h=p++,m=r[h],w=await n.get(m,c);if(o?.throwIfAborted(),d)return;if(typeof m=="string"&&w.id!==m)throw A("invalid_request","readMany readback belongs to another UUID","read_many_identity_mismatch");l[h]=w}catch(h){d||(d=!0,u=h);return}}if(await Promise.all(Array.from({length:Math.min(s,r.length)},()=>f())),d)throw u;return o?.throwIfAborted(),l}function oT(n){if(typeof n=="string")return M.dec(M.enc(n));if(!n||typeof n!="object")throw A("invalid_request","readMany needs UUID, path or record selections","read_many_selection");if("id"in n)return M.dec(M.enc(n.id));if(typeof n.path!="string"||n.path.length===0||n.path.length>4096||new TextEncoder().encode(n.path).byteLength>4096)throw A("invalid_request","readMany path must be nonempty and at most 4096 UTF-8 bytes","read_many_bounds");return Object.freeze({path:n.path})}function mf(n,e,t={}){return n.pages(e,t)}async function iP(n,e,t={}){let i=t.signal,o=t.isCurrent?.bind(t),s=()=>A("unavailable","original record link binding changed","record_links_fenced");function r(){if(i?.throwIfAborted(),o){let k=!1;try{k=o()===!0}catch{}if(!k)throw s()}}r();let a=e?.path,c=e?.field,l=k=>typeof k=="string"&&k.length>0&&k.length<=4096&&new TextEncoder().encode(k).byteLength<=4096;if(!l(a)||!l(c))throw A("invalid_request","record link path/field must be nonempty and bounded","record_links_bounds");let p=JSON.stringify(c),d=`(${p} in raw ? raw[${p}] : null)`,u=k=>`${k}.asFile() == null ? null : ${k}.asFile().file.path`,f=`${d} == null ? [] : type(${d}) == "list" ? ${d}.map(l, ${u("l")}) : [${u(d)}]`;if(new TextEncoder().encode(f).byteLength>64*1024)throw A("invalid_request","record link expression exceeds native source bound","record_links_bounds");r();let h=await n.query({where:`file.path == ${JSON.stringify(a)}`,limit:2,select:[{name:"raw",expr:d},{name:"paths",expr:f}]},i?{signal:i}:{});r();let m=()=>A("unavailable","invalid or incomplete native record link projection","record_links_response");if(h.complete!==!0||h.cursor!=null)throw m();if(h.columns===void 0)throw A("upgrade_required","native record link projection unsupported","record_links_unsupported");if(h.columns.length!==2||h.columns[0]!=="raw"||h.columns[1]!=="paths"||h.diagnostics?.some(k=>k.code==="expression_evaluation_error"))throw m();if(h.records.length===0)throw A("not_found","selected record not found","record_links_missing");if(h.records.length!==1||h.records[0].path!==a)throw m();let w=h.records[0].values;if(w===void 0)throw A("upgrade_required","native record link projection unsupported","record_links_unsupported");let b=de(w,"raw"),g=de(w,"paths");if(Object.keys(w).length!==2||b===void 0||g===void 0)throw m();let y=b===null?[]:typeof b=="string"?[b]:b;if(!Array.isArray(y)||!Array.isArray(g)||y.length!==g.length||y.length>1e3)throw m();let _=0,v=[];for(let k=0;k<y.length;k++){let S=y[k],x=g[k];if(typeof S!="string"||S.length>(1<<20)-_||x!==null&&!l(x)||(_+=new TextEncoder().encode(S).byteLength+(x===null?0:new TextEncoder().encode(x).byteLength),_>1<<20))throw m();v.push(Object.freeze({raw:S,path:x}))}return r(),Object.freeze(v)}var Hb,Gb,Yb=I(()=>{"use strict";ve();re();un();Hb=1e3,Gb=16});function Da(n,e){if((n.document?.length??0)>bp||(n.body?.length??0)>bp)throw A("invalid_request","native record exceeds the record session source budget","record_session_budget");if(e!==void 0&&n.id!==e||typeof n.document!="string"||typeof n.body!="string"||Di(n.document)!==n.revision)throw A("invalid_request","record session needs actual complete, revision-consistent source and identity","record_witness_required")}function Yr(n){return n.state.hold!==void 0||n.state.unresolved!==void 0&&n.state.unresolved!==0}function za(n){return n.state.state==="confirmed"&&!Yr(n)}function _t(n){return structuredClone(n)}function $a(n){return n instanceof oe?n.toProblem():n instanceof Error&&(n.name==="AbortError"||n.name==="TimeoutError")?A("cancelled",n.message).toProblem():A("internal",n instanceof Error?n.message:"record session failure").toProblem()}function Gt(n,e,t){return new oe({code:n,message:e,reason:t,recovery:n==="conflict"?"resolve_conflict":n==="outcome_unknown"?"resolve_outcome":"retry"})}function yf(n){return JSON.stringify(n,(e,t)=>typeof t=="bigint"?t.toString():t instanceof Uint8Array?ut(t):t).length*2}function Jb(n){if(n.length>bp)throw A("invalid_request","record session draft exceeds retained budget","record_session_budget");return new TextEncoder().encode(n).byteLength*2}function vp(n){let e=n??3e4;if(!Number.isSafeInteger(e)||e<1||e>12e4)throw A("invalid_request","record session timeout must be 1..120000ms","invalid_timeout");return e}var wp,bp,gf=I(()=>{"use strict";Je();re();mr();wp={body:!0,document:!0,effective:!0},bp=8*1024*1024});function bf(n,e,t){if(e===null)return t===n.body;let i=de(n.frontmatter,e);return i===void 0||t===void 0?i===t:Xb(Fe(i),Fe(ei(t)))}function Xb(n,e){let t=fe(n),i=fe(e);return t.length===i.length&&t.every((o,s)=>o===i[s])}function sT(n){let e=new AbortController,t=setTimeout(()=>e.abort(new DOMException("record flush timed out","TimeoutError")),n);return{signal:e.signal,clear:()=>clearTimeout(t)}}function aT(n,e){return e?new Promise((t,i)=>{let o=()=>{s(),i(A("cancelled","record flush waiter cancelled"))},s=()=>e.removeEventListener("abort",o);if(e.aborted){o();return}e.addEventListener("abort",o,{once:!0}),n.then(r=>{s(),t(r)},r=>{s(),i(r)})}):n}var wf,rP=I(()=>{"use strict";Je();re();Ua();mr();un();gf();wf=class{constructor(e,t,i){this.client=e;this.reserve=i;Da(t),this.base=_t(t),this.body=t.body,this.state=Yr(t)?"conflict":this.restState,this.publish()}client;reserve;base;body;patch=new Map;remote=null;captured=null;pendingEdits=new Map;driveGeneration=0;lastReceipt=null;state;why=null;snapshot;listeners=new Set;life=new AbortController;running=null;writing=!1;refreshRunning=null;refreshAgain=!1;timer;active=!1;idle=!1;requireLive=!1;defaultTimeout=3e4;async restore(e,t){if(this.captured){if(t&&t.mutationId!==this.captured.recovery.mutationId)throw A("invalid_request","record already owns another recovery identity","record_recovery_mismatch");return}if(t){if(t.recordId!==this.id)throw A("invalid_request","recovery belongs to another native record","record_identity_mismatch");this.captured={bound:!1,body:this.body,patch:new Map,recovery:{...t,receipt:null,write:null}}}if(!this.active&&!t&&this.base.state.state==="pending"&&!this.pendingEdits.size){let i=new Map;for(let{ops:o,receipt:s}of await this.client.pendingWrites({signal:e}))for(let r of o){if(r.kind!=="update"||r.id!==this.id)continue;let a=s.mutation;if(r.body!==void 0||r.bodyEdits?.length){let c=r.body??s.records?.find(l=>l.id===this.id)?.body??this.base.body;i.set(null,{mutation:a,value:c})}for(let[c,l]of Object.entries(r.patch??{}))i.set(c,{mutation:a,value:Fe(l)});for(let c of r.unset??[])i.set(c,{mutation:a,value:void 0})}this.charge(this.body,this.patch,this.base,this.remote,this.lastReceipt,this.captured,i),this.pendingEdits=i}e?.throwIfAborted(),this.captured&&(this.state="recovery",this.why=Gt("outcome_unknown","recover the original native mutation before another edit","record_recovery_required").toProblem(),this.publish())}get id(){return this.base.id}get dirty(){return this.body!==this.base.body||this.patch.size>0}get restState(){return!this.pendingEdits.size&&za(this.base)?"saved":"saved_on_device"}get retained(){return this.dirty||this.captured!==null||this.pendingEdits.size>0||!za(this.base)}getSnapshot=()=>this.snapshot;subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));resume(e){this.active||(this.life=new AbortController,this.active=!0),this.requireLive=e.requireLive??!1,this.defaultTimeout=vp(e.timeoutMs),this.idle=e.autosave?e.autosave.idleMs:!1,this.schedule()}suspend(){this.active=!1,this.clearTimer(),this.life.abort()}ensure(){if(!this.active)throw A("cancelled","record lease has been released")}setBody=e=>{if(this.ensure(),typeof e!="string")throw A("invalid_request","record body must be text");this.charge(e,this.patch),this.body=e,this.edited()};patchFrontmatter=e=>{this.ensure();let t=new Map(this.patch);for(let[i,o]of e instanceof Map?e:Object.entries(e)){let s=o===void 0?void 0:we(fe(Fe(o))),r=Object.hasOwn(this.base.frontmatter,i)?Fe(this.base.frontmatter[i]):void 0;!this.captured?.patch.has(i)&&(s===void 0&&r===void 0||s!==void 0&&r!==void 0&&Xb(s,r))?t.delete(i):t.set(i,s)}this.charge(this.body,t),this.patch=t,this.edited()};edited(){!this.captured&&this.state!=="conflict"&&this.state!=="deleted"&&(this.state=this.dirty?"unsaved":this.restState,this.why=null),this.publish(),this.schedule()}charge(e=this.body,t=this.patch,i=this.base,o=this.remote,s=this.lastReceipt,r=this.captured,a=this.pendingEdits){let c=yf(i)+Jb(e)+fe(new Map([...t].map(([l,p])=>[l,p??null]))).byteLength*2;o&&(c+=yf(o)),r&&(c+=Jb(r.body)+fe(new Map([...r.patch].map(([l,p])=>[l,p??null]))).byteLength*2);for(let[l,p]of a)c+=fe([l,p.mutation,p.value??null]).byteLength*2;s&&(c+=yf(s)),this.reserve(c)}publish(){this.charge();let e=new Map(Object.entries(this.base.frontmatter));for(let[t,i]of this.patch)i===void 0?e.delete(t):e.set(t,ei(i));this.snapshot=Object.freeze({state:this.state,body:this.body,frontmatter:structuredClone(Object.fromEntries(e)),record:_t(this.base),remote:this.remote?_t(this.remote):null,dirty:this.dirty,problem:this.why,lastReceipt:this.lastReceipt?_t(this.lastReceipt):null,recovery:this.captured?Object.freeze({...this.captured.recovery}):null});for(let t of[...this.listeners])try{t()}catch{}}clearTimer(){this.timer!==void 0&&clearTimeout(this.timer),this.timer=void 0}schedule(){this.clearTimer(),this.active&&this.idle!==!1&&this.dirty&&this.state==="unsaved"&&!this.running&&(this.timer=setTimeout(()=>{this.timer=void 0,this.flush().catch(()=>{})},this.idle))}async read(e){let t=await this.client.get(this.id,{include:wp,signal:e});return e.throwIfAborted(),Da(t,this.id),t}async readWithReceipts(e){let t=new Map;for(;;){let i=await this.read(e);if(this.captured)return{current:i,receipts:t};let o=t.size;for(let[s,{mutation:r,value:a}]of this.pendingEdits){let c=bf(i,s,a);if(!za(i)&&c)continue;if(!t.has(r)){let p=await this.client.receipt(r,{signal:e});if(e.throwIfAborted(),p.mutation!==r)throw Gt("outcome_unknown","native receipt changed identity","mutation_identity_mismatch");t.set(r,p)}let l=t.get(r);if(l.state==="unknown"||l.state==="pending"&&!c)throw Gt("outcome_unknown","the projection does not qualify this device write yet","unqualified_readback")}if(t.size===o)return{current:i,receipts:t}}}reconcilePending(e,t){if(!t.size)return;let i=new Map(this.pendingEdits),o=new Map(this.patch),s=this.body!==this.base.body,r=s?this.body:e.body,a=!1;for(let[l,{mutation:p,value:d}]of this.pendingEdits){let u=t.get(p);!u||u.state==="pending"||u.state==="unknown"||(i.delete(l),!(u.state!=="rejected"&&u.status!=="conflicted"||bf(e,l,d))&&(a=!0,l===null?s||(r=d):o.has(l)||o.set(l,d)))}let c=this.lastReceipt&&(t.get(this.lastReceipt.mutation)??this.lastReceipt);if(a){for(let[p,d]of o)bf(e,p,d)&&o.delete(p);let l=r!==e.body||o.size>0;this.charge(r,o,e,l?e:null,c,this.captured,i),this.base=_t(e),this.remote=l?_t(e):null,this.body=r,this.patch=o,l&&(this.state="conflict",this.why=Gt("conflict","a device write was refused at head","record_session_conflict").toProblem())}else this.charge(this.body,this.patch,this.base,this.remote,c,this.captured,i);this.pendingEdits=i,this.lastReceipt=c}refresh=()=>{if(!this.active)return Promise.resolve();if(this.refreshRunning)return this.refreshAgain=!0,this.refreshRunning;let e=this.life.signal;return this.refreshRunning=(async()=>{do{this.refreshAgain=!1;let t=this.driveGeneration;try{let{current:i,receipts:o}=await this.readWithReceipts(e);if(t!==this.driveGeneration){this.refreshAgain=!0;continue}if(this.captured||this.running){this.captured&&!this.running&&this.start(!1,{}).catch(()=>{});continue}this.reconcilePending(i,o),this.charge(this.body,this.patch,this.base,i),this.dirty?(i.revision!==this.base.revision||Yr(i))&&(this.remote=_t(i),this.state="conflict",this.why=Gt("conflict","record changed while this draft was open","record_session_conflict").toProblem()):(this.base=_t(i),this.body=i.body,this.remote=null,this.state=Yr(i)?"conflict":this.restState,this.why=null),this.publish()}catch(i){if(e.aborted)return;if(t!==this.driveGeneration||this.running){this.refreshAgain=!this.running;continue}this.why=$a(i),this.state=this.why.code==="not_found"?"deleted":this.captured?"recovery":"error",this.publish()}}while(this.refreshAgain&&!e.aborted)})().finally(()=>{this.refreshRunning=null}),this.refreshRunning};observerProblem(e){this.active&&(this.why=e,this.state=this.captured?"recovery":"error",this.publish())}flush=(e={})=>(this.ensure(),this.clearTimer(),this.start(!0,e));start(e,t){let i=vp(t.timeoutMs??this.defaultTimeout),o=sT(i),s=AbortSignal.any([...t.signal?[t.signal]:[],o.signal]),r=this.running;if(r&&(this.writing||!e))return aT(r,s).finally(o.clear);let a=AbortSignal.any([this.life.signal,s]),c={until:Date.now()+i,margin:Math.min(2e3,Math.floor(i/4))},l=()=>(this.driveGeneration++,this.drive(a,c,e)),p=(r?r.then(l,l):l()).finally(()=>{this.driveGeneration++,o.clear(),this.running===p&&(this.running=null,this.writing=!1,this.schedule())});return this.running=p,this.writing=e,p}async drive(e,t,i){try{for(;;){if(e.throwIfAborted(),this.captured){await this.settle(e,t);continue}if(!i)return this.restState==="saved"?{ok:!0,record:_t(this.base)}:{ok:!0,record:_t(this.base),saved:"on_device"};let{current:o,receipts:s}=await this.readWithReceipts(e);if(this.reconcilePending(o,s),Yr(o))throw this.charge(this.body,this.patch,this.base,o),this.remote=_t(o),Gt("conflict","native hold/unresolved edits require native resolution before saving","native_protection_resolution_required");if(this.state==="deleted")throw Gt("conflict","the original record was deleted","record_deleted");if(!this.dirty)return this.charge(o.body,this.patch,o,null),this.base=_t(o),this.body=o.body,this.remote=null,this.state=this.restState,this.why=null,this.publish(),this.restState==="saved"?{ok:!0,record:_t(o)}:{ok:!0,record:_t(o),saved:"on_device"};if(o.revision!==this.base.revision||this.state==="conflict")throw this.charge(this.body,this.patch,this.base,o),this.remote=_t(o),Gt("conflict","explicitly resolve the current native revision before saving","record_session_conflict");Da(this.base,this.id),this.base=_t(o);let r=this.body,a=new Map(this.patch),c=zi(),l={bound:!0,body:r,patch:a,recovery:{mutationId:c,recordId:this.id,baseRevision:this.base.revision,receipt:null,write:null}};this.charge(this.body,this.patch,this.base,this.remote,this.lastReceipt,l),this.captured=l,this.state="saving",this.why=null,this.publish();let p={ifRevision:this.base.revision};this.requireLive&&(p.requireLive=!0),r!==this.base.body&&(p.body=r);let d=new Map,u=[];for(let[h,m]of a)m===void 0?u.push(h):d.set(h,m);d.size&&(p.patch=d),u.length&&(p.unset=u);let f;try{f=await this.client.update(_t(this.base),p,{mutationId:c,include:wp,conflictMode:"reject",signal:e})}catch(h){throw h instanceof xs&&(this.captured=null),h}if(e.throwIfAborted(),f.mutationId!==c)throw Gt("outcome_unknown","native write changed its original mutation identity","mutation_identity_mismatch");this.captured.recovery={...this.captured.recovery,write:f,receipt:f.receipt},this.publish()}}catch(o){if(this.why=$a(o),!this.captured&&this.why.code==="conflict"&&!this.remote)try{let s=await this.read(e);this.charge(this.body,this.patch,this.base,s),this.remote=_t(s)}catch(s){this.why=$a(s)}return this.state=this.captured?"recovery":this.why.code==="conflict"?"conflict":this.why.code==="not_found"?"deleted":this.why.code==="outcome_unknown"?"recovery":"error",this.publish(),{ok:!1,problem:this.why}}}async settle(e,t){let i=this.captured,o=i.recovery,s=await this.client.awaitReceipt(o.mutationId,{timeoutMs:Math.max(1,t.until-Date.now()-t.margin),signal:e});if(e.throwIfAborted(),s.mutation!==o.mutationId)throw Gt("outcome_unknown","native receipt belongs to another mutation","mutation_identity_mismatch");let r=s.records?.find(m=>m.id===o.recordId),a=r!==void 0;if(s.records?.length&&!a||!i.bound&&s.state==="confirmed"&&!a)throw Gt("outcome_unknown","receipt does not bind the original native record identity","receipt_record_witness_required");if(a&&(i.bound=!0),this.charge(this.body,this.patch,this.base,this.remote,s),this.lastReceipt=s,i.recovery={...o,receipt:s},this.publish(),s.state==="unknown")throw Gt("outcome_unknown","original native mutation is not settled; no resubmit","record_receipt_pending");if(s.state==="rejected"||s.status==="conflicted")throw this.captured=null,s.problem?new oe(s.problem):Gt("conflict","original mutation conflicted","record_session_conflict");let c=await this.read(e),l=s.state==="pending",p=new Map(this.pendingEdits),d=new Map(i.patch);i.body!==this.base.body&&d.set(null,i.body);for(let[m,w]of d)l?p.set(m,{mutation:s.mutation,value:w}):p.delete(m);if(l?Yr(c)||[...d].some(([m,w])=>!bf(c,m,w)):!za(c))throw Gt("outcome_unknown","record readback does not qualify the native receipt","unqualified_readback");let u=this.body===i.body,f=r?.revision!==void 0&&c.revision===r.revision,h=!l&&!u&&!f&&c.body!==i.body&&c.body!==this.body;this.charge(this.body,this.patch,c,h?c:null,s,null,p),this.pendingEdits=p;for(let[m,w]of i.patch){let b=this.patch.get(m);this.patch.has(m)&&(w===void 0?b===void 0:b!==void 0&&Xb(w,b))&&this.patch.delete(m)}if(this.base=_t(c),u&&(this.body=c.body),this.captured=null,this.remote=h?_t(c):null,h)throw Gt("conflict","record body changed while saving an earlier draft","record_session_conflict");this.state=this.dirty?"unsaved":this.restState,this.why=null,this.publish()}resolve=e=>{if(this.ensure(),this.captured||this.running)throw Gt("outcome_unknown","recover the original mutation before resolving or preparing another","record_recovery_required");let t=this.remote;if(!t||!za(t))throw Gt("conflict","a confirmed unprotected native record is required for resolution","native_protection_resolution_required");let i="body"in e?e.body:e.keep==="theirs"||this.body===this.base.body?t.body:this.body,o="keep"in e&&e.keep==="theirs"?new Map:this.patch;this.charge(i,o,t,null),this.base=_t(t),this.body=i,this.patch=o,this.remote=null,this.state=this.dirty?"unsaved":"saved",this.why=null,this.publish(),this.schedule()}}});var vf,oP=I(()=>{"use strict";re();ve();rP();gf();vf=class{constructor(e){this.client=e}client;slots=new Map;bytes=0;closed=!1;opening=Promise.resolve();watch=null;offWatch=null;offStatus=null;open(e,t={}){let i={...t,autosave:t.autosave?{...t.autosave}:t.autosave,...t.recovery?{recovery:{...t.recovery}}:{}};if(i.recovery&&(i.recovery={...i.recovery,mutationId:M.dec(M.enc(i.recovery.mutationId)),recordId:M.dec(M.enc(i.recovery.recordId))},i.recovery.baseRevision!==null&&Z.enc(i.recovery.baseRevision)),vp(i.timeoutMs),i.autosave&&(!Number.isSafeInteger(i.autosave.idleMs)||i.autosave.idleMs<1||i.autosave.idleMs>12e4))throw A("invalid_request","record autosave idleMs must be 1..120000","invalid_autosave");let o=typeof e=="string"?e:"id"in e?e.id:{path:e.path},s=this.opening.catch(()=>{}).then(()=>this.acquire(o,i));return this.opening=s.then(()=>{},()=>{}),s}async acquire(e,t){if(this.closed)throw A("unavailable","record sessions client closed");t.signal?.throwIfAborted();let i=await this.client.get(e,{include:wp,signal:t.signal});if(t.signal?.throwIfAborted(),this.closed)throw A("unavailable","record sessions client closed");Da(i);let o=typeof e=="string"?e:"id"in e?e.id:void 0,s=o===void 0?void 0:M.dec(M.enc(o));if(s!==void 0&&s!==i.id)throw A("invalid_request","record open readback changed the requested UUID","record_identity_mismatch");let r=JSON.stringify([t.autosave?t.autosave.idleMs:!1,t.timeoutMs??3e4,t.requireLive??!1]),a=this.slots.get(i.id);if(a&&a.leases>0&&a.policy!==r)throw A("invalid_request","active record leases must use the same editing policy","record_lease_policy");if(a)await a.session.restore(t.signal,t.recovery),t.signal?.throwIfAborted();else{if(this.slots.size>=64)throw A("invalid_request","retained record sessions exceed 64; settle drafts before opening more","record_session_budget");a={session:null,leases:0,bytes:0,policy:r};let h=a;try{a.session=new wf(this.client,i,m=>{let w=this.bytes-h.bytes+m;if(w>bp)throw A("invalid_request","record session retained data exceeds 8MiB","record_session_budget");this.bytes=w,h.bytes=m}),await a.session.restore(t.signal,t.recovery),t.signal?.throwIfAborted()}catch(m){throw this.bytes-=h.bytes,m}this.slots.set(i.id,a)}a.leases++,a.policy=r,a.session.resume(t),this.startWatch();let c=a,l=!1,p=new Set,d=()=>{if(l)throw A("cancelled","record lease released")},u=Object.freeze({getSnapshot:c.session.getSnapshot,subscribe:h=>{d();let m=c.session.subscribe(h);return p.add(m),()=>{p.delete(m),m()}},setBody:h=>{d(),c.session.setBody(h)},patchFrontmatter:h=>{d(),c.session.patchFrontmatter(h)},resolve:h=>{d(),c.session.resolve(h)},flush:h=>(d(),c.session.flush(h))}),f=()=>{if(!l){l=!0,t.signal?.removeEventListener("abort",f);for(let h of p)h();p.clear(),--c.leases===0&&(c.session.suspend(),c.session.retained||(this.bytes-=c.bytes,this.slots.delete(i.id))),[...this.slots.values()].some(h=>h.leases>0)||this.stopWatch()}};return t.signal?.addEventListener("abort",f,{once:!0}),t.signal?.aborted&&(f(),t.signal.throwIfAborted()),c.session.refresh(),Object.freeze({session:u,release:f})}startWatch(){if(this.watch)return;let e=this.client.watchChanges(i=>{for(let[o,s]of this.slots)s.leases>0&&(i.reset||i.changes.some(r=>r.id===o))&&s.session.refresh()});this.watch=e;let t=-1;this.offStatus=this.client.onStatus(i=>{let o=i.pending<t;if(t=i.pending,o&&this.watch===e)for(let s of this.slots.values())s.leases>0&&s.session.refresh()}),this.offWatch=e.subscribe((i,o)=>{if(this.watch===e){if(i==="active")for(let s of this.slots.values())s.leases>0&&s.session.refresh();else if(o)for(let s of this.slots.values())s.leases>0&&s.session.observerProblem(o.toProblem())}}),e.ready.catch(i=>{if(this.watch===e)for(let o of this.slots.values())o.leases>0&&o.session.observerProblem($a(i))})}stopWatch(){this.offWatch?.(),this.offWatch=null,this.offStatus?.(),this.offStatus=null;let e=this.watch;this.watch=null,e?.()}dispose(){this.closed=!0,this.stopWatch();for(let e of this.slots.values())e.session.suspend()}}});function lT(n,e){let t=Bi(de(n,"properties")),i=[];for(let o of _f(de(e,"select"))){let s=Bi(o),r=Cn(o),a=s?Cn(de(s,"name")):r?.slice(r.lastIndexOf(".")+1);if(!a)continue;let c=Bi(de(t,s||!r?a:r))??Bi(de(t,a)),l={key:a},p=Cn(de(s,"label"))??Cn(de(c,"label")),d=Cn(de(s,"description"))??Cn(de(c,"description")),u=Cn(de(c,"format")),f=de(c,"hidden");p!==void 0&&(l.label=p),d!==void 0&&(l.description=d),u!==void 0&&(l.format=u),typeof f=="boolean"&&(l.hidden=f),i.push(l)}return i}async function cP(n,e={}){let{folder:t,signal:i}=e,o=[],s=[],r=t?t.replace(/\/?$/,"/"):"",a,c=!0;do{let l;try{l=await n.queryContract(_p,{...a?{cursor:a}:{},...i?{signal:i}:{}})}catch(p){if(X(p,"not_found")&&p.reason==="data_contract_not_found")return{sources:o,diagnostics:s,complete:!0};throw p}c&&=l.page.complete,l.records.forEach((p,d)=>{let u=l.page.records[d];if(!u.path.startsWith(r))return;let f=p.implementations[0],h=f?.issues.find(g=>g.severity==="error");if(!f||h){s.push(sP("invalid_view",h?.message??"View record does not implement mdbase.view.",u.path));return}let m=f.fields,w=[],b=new Set;for(let g of _f(de(m,"views"))){let y=Bi(g),_=Cn(de(y,"id")),v=Cn(de(y,"name"));if(!y||!_||!v)continue;if(b.has(_)){s.push(sP("invalid_view","View record contains duplicate named-view IDs.",u.path));return}b.add(_);let k={id:_,name:v,properties:lT(m,y)},S=de(y,"presentation");S!==void 0&&(k.presentation=S),w.push(k)}o.push({record:u.id,id:Cn(de(m,"id"))??u.path,name:Cn(de(m,"name"))??u.path,source:{path:u.path,format:_p.id,revision:u.revision,writable:!0},views:w})}),a=l.page.cursor}while(a);return o.sort((l,p)=>l.source.path<p.source.path?-1:l.source.path>p.source.path?1:0),{sources:o,diagnostics:s,complete:c}}async function pP(n,e,t,i={}){let o=i.signal,s=await n.getContract(e,_p,{signal:o}).catch(v=>aP(v,lP(e))),r=s.fields,a=s.path,c=_f(de(r,"views")).map(Bi),l=c.map(v=>Cn(de(v,"id")));if(new Set(l).size!==l.length)throw A("invalid_request","View record contains duplicate named-view IDs.","invalid_view");let p=c[l.indexOf(t)];if(!p)throw A("not_found",`named view '${t}' was not found`,"view_not_found");let d=Bi(de(r,"query")),u=new Map,f=de(p,"types")??de(d,"types");f!==void 0&&u.set("types",f);let h=[Cn(de(d,"where")),Cn(de(p,"where"))].filter(v=>!!v);h.length&&u.set("where",h.length===2?`(${h[0]}) && (${h[1]})`:h[0]);let m=new Map(Object.entries(Bi(de(d,"projections"))??{}));for(let[v,k]of Object.entries(Bi(de(p,"projections"))??{})){let S=m.get(v);if(S!==void 0&&Af(S)!==Af(k))throw A("invalid_request",`Projection '${v}' has conflicting definitions.`,"invalid_view");m.set(v,k)}m.size&&u.set("projections",Object.fromEntries(m));for(let v of["select","order_by","group_by","summaries","limit","offset","include_body","frontmatter_mode"]){let k=de(p,v);k!==void 0&&u.set(v,k)}let w=de(r,"summary_functions");w!==void 0&&u.set("summary_functions",w),i.limit!==void 0&&u.set("limit",i.limit),i.offset!==void 0&&u.set("offset",i.offset),i.timezone!==void 0&&u.set("timezone",i.timezone);let b=Bi(de(Bi(de(p,"context")??de(d,"context")),"this")),g=Cn(de(b,"on_missing"))??"view",y=i.context;if(y===void 0&&g==="error")throw A("invalid_request","This named view requires an invocation context.","context_required");if(y===void 0&&g==="view"&&(y={path:a}),y!==void 0){let v=_f(de(b,"types")).filter(S=>typeof S=="string"),k=typeof y=="string"?void 0:y.path;if(v.length||k===void 0){let S=await n.get(y,{signal:o});if(k=S.path,v.length&&!S.types.some(x=>v.some(P=>P.toLowerCase()===x.toLowerCase())))throw A("invalid_request","The invocation context does not match an allowed context type.","context_type_mismatch")}u.set("context",{this:{path:k}})}return{...await n.query(Object.fromEntries(u),{include:i.include,signal:o}),view:{path:a,view:t}}}async function dP(n,e,t={}){let i=t.signal,o=await n.getContract(e,_p,{signal:i}).catch(r=>aP(r,lP(e))),s=await n.get(o.id,{include:{document:!0},signal:i});if(s.revision!==o.revision||typeof s.document!="string")throw A("unavailable","saved view source changed while it was read","view_source_changed");return{path:s.path,format:_p.id,revision:s.revision,document:s.document,record:s.id}}function Af(n){return Array.isArray(n)?`[${n.map(Af).join(",")}]`:n!==null&&typeof n=="object"?`{${Object.keys(n).sort().map(e=>`${JSON.stringify(e)}:${Af(n[e])}`).join(",")}}`:JSON.stringify(n)}var _p,Bi,_f,Cn,sP,aP,lP,uP=I(()=>{"use strict";re();un();_p=Object.freeze({id:"mdbase.view",version:"1.0.0"}),Bi=n=>n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0,_f=n=>Array.isArray(n)?n:[],Cn=n=>typeof n=="string"?n:void 0,sP=(n,e,t)=>({code:n,severity:"warning",message:e,details:{path:t}}),aP=(n,e)=>{throw X(n,"not_found")?A("not_found",`saved view source '${e}' was not found`,"view_not_found"):n},lP=n=>typeof n=="string"?n:n.path});function Jr(n){return A("invalid_request",n,"view_source_witness_required")}function Zb(n){try{M.enc(n)}catch{throw Jr("view source writes need their original record and mutation UUIDs")}}function fP(n){if(!n||typeof n.path!="string"||n.path.length===0||typeof n.document!="string")throw Jr("view source update needs the complete RecordView read with document included");Zb(n.id);try{Z.enc(n.revision)}catch{throw Jr("view source needs its original source revision")}if(Di(n.document)!==n.revision)throw Jr("view source document differs from its captured revision")}function hP(n){return Zb(n?.mutationId),{...n,include:{...n.include,document:!0}}}async function kf(n,e,t={}){let i=typeof e=="string"?e:"id"in e?e.id:void 0,o=i===void 0?void 0:M.dec(M.enc(i)),s=await n.get(e,{include:{...t.include,document:!0},signal:t.signal});if(fP(s),o!==void 0&&s.id!==o)throw Jr("view source readback belongs to another record");return s}function Sf(n,e,t){if(Zb(e?.id),typeof e.path!="string"||e.path.length===0||typeof e.document!="string")throw Jr("view source create needs the exact path and complete source document");let i={id:e.id,path:e.path,document:e.document};return e.type!==void 0&&(i.type=e.type),n.create(i,hP(t))}function Pf(n,e,t,i){fP(e);let o=e.state;if(!o||o.state!=="pending"&&o.state!=="confirmed"||!Number.isSafeInteger(o.confirmedSeq)||o.confirmedSeq<0)throw Jr("view source update needs actual native record state, not inferred confirmation");if(o.hold!==void 0||o.unresolved!==void 0&&o.unresolved!==0)throw Jr("resolve the original view source hold or unresolved mutation before replacing its document");if(typeof t!="string")throw Jr("view source update needs complete source text");return n.replaceDocument(e,t,{...hP(i),ifRevision:e.revision})}var Qb=I(()=>{"use strict";ve();re();mr()});var mP,yP,gP=I(()=>{"use strict";ve();en();mP=z("contract-record-v1",[[0,"version",F],[1,"id",M],[2,"path",T],[3,"revision",Z],[4,"type",T],[5,"fields",kn],[6,"contractDigest",Z],[7,"implementationDigest",Z]]),yP=z("contract-write-plan-v1",[[0,"version",F],[1,"type",T],[2,"patch",kn],[3,"unset",G(T)],[4,"base",G(Nu)],[5,"contractDigest",Z],[6,"implementationDigest",Z],[7,"id",M,"opt"],[8,"path",T,"opt"],[9,"revision",Z,"opt"]])});var bP,wP=I(()=>{"use strict";ve();en();bP=z("contract-query-v1",[[0,"version",F],[1,"page",Xc],[2,"records",G(z("contract-query-record",[[0,"id",M],[1,"implementations",G(z("contract-projection",[[0,"typeName",T],[1,"fields",kn],[2,"issues",G(Fr)]]))]]))],[3,"contractDigest",Z]])});var xf,vP=I(()=>{"use strict";xf=class{byId=new Map;order=[];cached=[];complete=!1;asOf=0;stale=!0;metadata;get records(){return this.cached??=this.order.map(e=>this.byId.get(e)).filter(Boolean)}get(e){return this.byId.get(e)}markStale(){this.stale=!0,this.metadata=void 0}apply(e){switch(e.kind){case"reset":this.stale=!0;break;case"snapshot":{this.byId.clear(),this.order=[];for(let t of e.added??[])this.byId.has(t.id)||this.order.push(t.id),this.byId.set(t.id,t);e.order&&this.reorder(e.order),this.stale=!1;break}case"diff":{if(e.removed?.length){let t=new Set(e.removed);for(let i of t)this.byId.delete(i);this.order=this.order.filter(i=>!t.has(i))}for(let t of e.changed??[])this.byId.has(t.id)||this.order.push(t.id),this.byId.set(t.id,t);for(let t of e.added??[])this.byId.has(t.id)||this.order.push(t.id),this.byId.set(t.id,t);e.order&&this.reorder(e.order);break}}this.metadata=e.kind==="reset"||this.stale?void 0:e.metadata,this.complete=e.complete,this.asOf=e.asOf,this.cached=null}reorder(e){let t=new Set,i=[];for(let o of e)this.byId.has(o)&&!t.has(o)&&(t.add(o),i.push(o));for(let o of this.order)t.has(o)||i.push(o);this.order=i}}});function _P(n){return n instanceof oe?n.recovery==="retry"?!0:n.code==="invalid_request"&&(n.reason==="cursor_stale"||n.reason==="cursor_expired")||n.code==="conflict"&&n.reason==="collection_changed":!1}var cT,pT,dT,ew,uT,fT,AP,hT,mT,Ba,tw=I(()=>{"use strict";re();cT=1e3,pT=500,dT=8,ew=250,uT=3e4;fT=n=>n instanceof oe?n.toProblem():{code:"internal",recovery:"contact_support",message:n instanceof Error?n.message:String(n)},AP=n=>n.replace(/[A-Z]/g,e=>e.toLowerCase()),hT=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),mT=(n,e)=>n.revision===e.revision&&n.path===e.path&&n.state.state===e.state.state&&n.state.hold?.id===e.state.hold?.id&&n.state.unresolved===e.state.unresolved&&hT(n.types,e.types),Ba=class{constructor(e,t={}){this.client=e;this.signal=t.signal,this.pending=e.status.pending,this.types=t.types?.length?[...t.types]:void 0,this.folded=this.types?.map(AP),this.include=t.include?{...t.include}:void 0,this.ready=new Promise((i,o)=>{this.resolveReady=i,this.rejectReady=o}),this.ready.catch(()=>{}),this.offStatus=e.onStatus(i=>{let o=i.pending<this.pending;if(this.pending=i.pending,!!o){for(let s of this.byId.values())s.state.state==="pending"&&this.queued.add(s.id);this.work()}}),this.startWatch(),this.signal?.addEventListener("abort",this.abort,{once:!0}),this.signal?.aborted&&this.close()}client;ready;resolveReady;rejectReady;lifetime=new AbortController;listeners=new Set;types;folded;include;byId=new Map;view=Object.freeze({records:Object.freeze([]),state:"loading",problem:null});touched=!1;state="loading";problem=null;watch;offWatch=()=>{};offStatus;abort=()=>this.close();cursor;queued=new Set;loaded=!1;dirty=!0;working=!1;timer;again;delay=ew;pending;signal;getSnapshot=()=>this.view;get(e){return this.byId.get(e)}subscribe=e=>(this.state!=="closed"&&this.listeners.add(e),()=>{this.listeners.delete(e)});reload(){return this.state==="closed"?Promise.reject(A("cancelled","record set closed")):(this.dirty=!0,this.delay=ew,this.state==="failed"&&(this.problem=null,this.publish(this.loaded?"stale":"loading"),(this.watch.state==="failed"||this.watch.state==="closed")&&this.startWatch()),new Promise((e,t)=>{let i=this.subscribe(()=>{this.state==="current"&&!this.dirty?(i(),e()):(this.state==="failed"||this.state==="closed")&&(i(),t(new oe(this.problem??{code:"cancelled",recovery:"none",message:"record set closed"})))});this.resume()}))}close(){this.state!=="closed"&&(this.lifetime.abort(),this.cancelRetry(),this.signal?.removeEventListener("abort",this.abort),this.offStatus(),this.offWatch(),this.watch(),this.rejectReady(A("cancelled","record set closed")),this.publish("closed"),this.listeners.clear())}startWatch(){this.offWatch();let e=this.client.watchChanges(t=>{this.watch===e&&this.changed(t)},{cursor:this.cursor});this.watch=e,this.cursor===void 0&&(this.dirty=!0),this.offWatch=e.subscribe((t,i)=>{if(!(this.watch!==e||this.state==="closed"||this.state==="failed")){if(t==="active"){this.work();return}if(t==="stale"){this.loaded&&this.publish("stale");return}if(t==="closed"){this.close();return}t==="failed"&&(i&&_P(i)&&this.client.link!=="closed"?this.retry(i,()=>this.startWatch()):this.fail(i??A("unavailable","the change watch stopped")))}})}changed(e){this.cursor=e.cursor,e.reset&&(this.dirty=!0);for(let t of e.changes)t.entity!=="file"&&(t.kind==="put"&&this.types&&t.types&&!this.byId.has(t.id)&&!this.member(t.types)||t.kind==="remove"&&!this.byId.has(t.id)||this.queued.add(t.id));this.work()}member(e){return!this.folded||e.some(t=>this.folded.includes(AP(t)))}async work(){if(!(this.working||this.timer!==void 0)){this.working=!0;try{for(;this.state!=="closed"&&this.state!=="failed"&&this.watch.state==="active"&&(this.dirty||this.queued.size);){if(!this.dirty&&this.queued.size<=pT)await this.reread();else if(!await this.load()){this.retry(null,()=>{this.work()});return}this.delay=ew}}catch(e){if(this.state==="closed"||X(e,"cancelled"))return;_P(e)?this.retry(e,()=>{this.work()}):this.fail(e);return}finally{this.working=!1}this.state==="closed"||this.state==="failed"||this.watch.state!=="active"||(this.problem=null,this.publish("current"),this.resolveReady())}}retry(e,t){this.problem=e?.toProblem()??null,this.publish(this.loaded?"stale":"loading");let i=this.delay;this.delay=Math.min(i*2,uT),clearTimeout(this.timer),this.again=t,this.timer=setTimeout(()=>this.resume(),i)}resume(){clearTimeout(this.timer),this.timer=void 0;let e=this.again??(()=>{this.work()});this.again=void 0,this.state!=="closed"&&e()}cancelRetry(){clearTimeout(this.timer),this.timer=void 0,this.again=void 0}fail(e){this.cancelRetry(),this.problem=fT(e),this.rejectReady(e instanceof oe?e:new oe(this.problem)),this.publish("failed")}async load(){let e=this.lifetime.signal;this.dirty=!1,this.queued.clear(),this.publish(this.loaded?"stale":"loading");let t=new Map,i=!0;try{let r={...this.types?{types:[...this.types]}:{},limit:cT};for await(let a of this.client.pages(r,{include:this.include,signal:e})){for(let c of a.records)t.set(c.id,c);i&&=a.complete,this.loaded||this.apply(a.records.map(c=>({record:c})),this.state)}}catch(r){throw this.dirty=!0,r}let o=[...t.values()].map(r=>({record:r})),s=[...this.byId.keys()].filter(r=>!t.has(r)).map(r=>({id:r}));return this.loaded||=i,i||(this.dirty=!0),this.apply([...o,...s],this.state),i}async reread(){let e=this.lifetime.signal,t=[...this.queued];this.queued.clear();let i=new Array(t.length),o=0;try{await Promise.all(Array.from({length:Math.min(dT,t.length)},async()=>{for(;o<t.length;){let s=o++;i[s]=await this.client.find(t[s],{include:this.include,signal:e})}}))}catch(s){for(let r of t)this.queued.add(r);throw s}this.apply(t.map((s,r)=>i[r]&&this.member(i[r].types)?{record:i[r]}:{id:s}),this.state)}apply(e,t){let i=[];for(let o of e){let s="record"in o?o.record.id:o.id,r=this.byId.get(s);"record"in o?(this.byId.set(s,o.record),r?mT(r,o.record)||i.push({kind:"put",record:o.record,previous:r}):i.push({kind:"put",record:o.record})):r&&(this.byId.delete(s),i.push({kind:"remove",previous:r}))}this.touched||=e.length>0,this.publish(t,i)}publish(e,t=[]){if(this.state==="closed")return;let i=e==="current"?null:this.problem;if(!(!this.touched&&e===this.state&&i===this.view.problem)){this.state=e,this.view=Object.freeze({records:this.touched?Object.freeze([...this.byId.values()]):this.view.records,state:e,problem:i}),this.touched=!1;for(let o of[...this.listeners])try{o(t)}catch{}}}}});var kP,yT,Va,nw=I(()=>{"use strict";ve();re();mr();en();kP=4096,yT=100,Va=class{constructor(e){this.client=e;e.onSession(async t=>{this.wire(t);for(let[i,o]of this.joined)await t.request("presence_join",this.params(i,o.state));for(let i of this.watchers.keys())await t.request("subscribe_presence",new Map([[0,M.enc(i)]]))})}client;joined=new Map;watchers=new Map;wired=new WeakSet;wire(e){this.wired.has(e)||(this.wired.add(e),e.onPush("presence",t=>{try{let i=_o(Vu,t);for(let o of this.watchers.get(i.record)??[])o(i.peers)}catch{}}))}params(e,t){return new Map([[0,M.enc(e)],[1,t]])}check(e){if(JSON.stringify(e,(i,o)=>typeof o=="bigint"?o.toString():o instanceof Map?[...o]:o).length>kP)throw A("too_large","presence state over 4 KiB",{details:{limit:kP}})}async join(e,t){let i=Fe(t);this.check(i),this.joined.set(e,{state:i,last:Date.now(),timer:null});let o=await this.client.ready();this.wire(o),await o.request("presence_join",this.params(e,i))}update(e,t){let i=this.joined.get(e);if(!i)throw A("invalid_request","join the record's presence first");if(i.state=Fe(t),this.check(i.state),i.timer)return;let o=Math.max(0,i.last+yT-Date.now());i.timer=setTimeout(()=>{i.timer=null,i.last=Date.now(),this.joined.get(e)===i&&this.client.call("presence_update",this.params(e,i.state)).catch(()=>{})},o)}async leave(e){let t=this.joined.get(e);t?.timer&&clearTimeout(t.timer),this.joined.delete(e),await this.client.call("presence_leave",new Map([[0,M.enc(e)]])).catch(()=>{})}subscribe(e,t){let i=this.watchers.get(e),o=!i;return i||this.watchers.set(e,i=new Set),i.add(t),o&&this.client.ready().then(s=>(this.wire(s),s.request("subscribe_presence",new Map([[0,M.enc(e)]])))).catch(()=>{}),()=>{i.delete(t),i.size===0&&this.watchers.delete(e)}}}});function SP(n){try{let e=we(n);if(!(e instanceof Map))return null;let t=e.get(2),i=e.get(3);return!(t instanceof Uint8Array)||typeof i!="number"?null:{device:ut(t),seq:i}}catch{return null}}function bT(n){return n.replace(/-/g,"").toLowerCase()}function PP(n,e,t){if(!t)return;let i=SP(e);if(!i||bT(t)!==i.device)return;let o=iw.get(n);o||iw.set(n,o=new Map);let s=o.get(i.device);if(!s){if(o.size>=gT)return;o.set(i.device,s=new Map)}let r="self",a=s.get(r);(!a||a[0]<i.seq)&&s.set(r,[i.seq,e])}function xP(n,e){let t=e?SP(e)?.device:void 0,i=[];for(let[o,s]of iw.get(n)??[])if(o!==t)for(let[,r]of s.values())i.push(r);return i}var gT,iw,CP=I(()=>{"use strict";Je();gT=64,iw=new Map});function Vn(n,e){return e===void 0?{}:{[n]:e}}function rw(n){let e=Is(n);return{id:it(e.id),version:it(e.version),digest:it(e.digest),installedBy:it(e.installed_by),resources:(Array.isArray(e.resources)?e.resources:[]).map(t=>{let i=Is(t);return{source:it(i.source),target:it(i.target),kind:it(i.kind),mode:it(i.mode),digest:it(i.digest),...Vn("originDigest",it(i.origin_digest))}})}}function AT(n){let e=Is(n),t=e.upgrade_baseline===void 0?void 0:Is(e.upgrade_baseline),i=t&&(typeof t.version=="number"?t.version:typeof t.version=="string"?Number(t.version):void 0);return{source:it(e.source)??"",target:it(e.target),kind:it(e.kind),mode:it(e.mode),action:it(e.action),...Vn("digest",it(e.digest)),...Vn("currentDigest",it(e.current_digest)),...Vn("installedDigest",it(e.installed_digest)),...Vn("adoptedFromDigest",it(e.adopted_from_digest)),...Vn("upgradeBaseline",t&&{digest:it(t.digest),...Vn("version",i)}),...Vn("reason",it(e.reason))}}function kT(n,e){return e?n.installedDigest!==void 0?`${n.target} was changed after this pack installed it. Review it, then adopt it to replace it with this pack's version.`:`${n.target} already exists with different content. Review it, then adopt it to let this pack manage it.`:n.reason?`${n.target} can't be changed: ${n.reason}.`:`${n.target} can't be changed by this pack.`}function OP(n,e,t){let i=Is(n),o=(Array.isArray(i.resources)?i.resources:[]).map(AT),s=rw(i.desired),r=new Set(s.resources.map(h=>h.target)),a=Object.fromEntries(_T.map(h=>[h,o.filter(m=>m.action===h).map(m=>m.target)])),c={},l=o.filter(h=>h.action==="conflict").map(h=>{let m=h.mode==="managed"&&h.currentDigest!==void 0&&r.has(h.target);return m&&(c[h.target]=h.currentDigest),{target:h.target,kind:h.kind,...Vn("reason",h.reason),message:kT(h,m),...Vn("adoptable",m?{digest:h.currentDigest}:void 0)}}),p=it(i.status),d=Array.isArray(i.issues)?i.issues.map(Is):[],u;if(i.definitions_manage!==!0)u={code:"forbidden",message:"This app doesn't have permission to change the collection's types."};else if(p==="downgrade"){let h=i.current===void 0?"a newer version":`version ${rw(i.current).version}`;u={code:"type_pack_downgrade",message:`${s.id} ${h} is installed; ${s.version} is older.`}}else if(l.length){let h=l.length;u={code:"type_pack_conflict",message:Object.keys(c).length===h?`${h===1?"A type already exists":`${h} types already exist`} with different content. Review and adopt ${h===1?"it":"them"} to continue.`:l.map(m=>m.message).join(" ")}}else(d.length||i.applicable!==!0)&&(u={code:"invalid_type_pack",message:`This pack would leave the collection invalid: ${it(d[0]?.message)??"the staged types do not validate"}.`});let f=Is(i.lock);return Object.freeze({status:p,canApply:i.applicable===!0&&u===void 0,digest:it(i.assessment_digest),summary:a,conflicts:l,adoptable:c,resources:o,...Vn("current",i.current===void 0?void 0:rw(i.current)),desired:s,lock:{target:it(f.target),action:it(f.action),digest:it(f.digest)},...Vn("refusal",u),pack:e,options:t})}function IP(n){return n&&Object.keys(n).length?Fe(n):void 0}function ST(n){return n==null?!1:Array.isArray(n)?n.length>0:typeof n=="object"&&Object.keys(n).length>0}async function RP(n,e,t,i){if(ST(t.contractSetups))throw A("invalid_request","Contract setup during type pack install is not supported yet.","type_pack_contract_setups_unsupported");let o=new Map([["manifest",Fe(e.manifest)],["resources",e.resources.map(c=>new Map([["source",c.source],["document",c.document]]))]]);e.provides!==void 0&&o.set("provides",Fe(e.provides));let s=new Map([[0,1],[1,o],[2,t.installedBy]]),r=IP(t.adopt);r!==void 0&&s.set(3,r),t.preserveSeedTargets?.length&&s.set(4,[...t.preserveSeedTargets]);let a=IP(t.targetOverrides);a!==void 0&&s.set(5,a),t.allowDowngrade&&s.set(6,!0),i!==void 0&&s.set(7,Z.enc(i));try{let c=await n.call("plan_type_pack_v1",s,{codec:vT,retry:!0,...t.signal?{signal:t.signal}:{}});if(c.version!==1)throw A("upgrade_required","unsupported type pack plan","type_packs_unsupported");return c}catch(c){throw X(c,"invalid_request")&&c.reason==="unknown_method"?A("upgrade_required","This collection's replica can't install type packs yet.","type_packs_unsupported"):c}}async function EP(n,e,t){return OP((await RP(n,e,t)).assessment,e,t)}async function qP(n,e,t={}){if(e.refusal)throw A(PT[e.refusal.code],e.refusal.message,e.refusal.code);let i=t.signal?{...e.options,signal:t.signal}:e.options,o=await RP(n,e.pack,i,e.digest),s=OP(o.assessment,e.pack,e.options),r=o.writes??[];if(!r.length)return{outcome:"already_current",receipt:s.desired};let a=r.map(p=>p.doc===void 0?{kind:"resource_delete",path:p.path,...Vn("baseRevision",p.baseRevision)}:{kind:"resource_put",path:p.path,doc:p.doc,...Vn("baseRevision",p.baseRevision),...p.mustNotExist?{mustNotExist:!0}:{}}),c=await n.submit(a,t),l=c.receipt;if(l.state==="rejected"||l.state==="unknown")throw new oe(l.problem??(l.state==="unknown"?{code:"outcome_unknown",recovery:"resolve_outcome",message:"The type pack install outcome is unknown."}:{code:"internal",recovery:"contact_support",message:"The type pack install was rejected."}),{mutationId:l.mutation});if(t.dryRun)return{outcome:"preview",receipt:s.desired,write:c};if(l.status==="conflicted"||(l.conflicts?.length??0)>0)throw new oe({code:"conflict",recovery:"resolve_conflict",reason:"type_pack_conflict",message:"The type pack install has a conflict. Resolve it before continuing."},{mutationId:l.mutation});return{outcome:l.state==="confirmed"?"applied":"pending",receipt:s.desired,write:c}}var wT,vT,_T,Is,it,PT,TP=I(()=>{"use strict";ve();re();mr();wT=z("type-pack-write-v1",[[0,"path",T],[1,"doc",T,"opt"],[2,"baseRevision",Z,"opt"],[3,"mustNotExist",Ee]]),vT=z("type-pack-plan-v1",[[0,"version",F],[1,"assessment",Ht],[2,"writes",G(wT),"opt"]]),_T=["create","update","delete","adopt","unchanged","preserve","conflict"],Is=n=>n&&typeof n=="object"&&!Array.isArray(n)?n:{},it=n=>typeof n=="string"?n:void 0;PT={forbidden:"forbidden",type_pack_conflict:"conflict",type_pack_downgrade:"conflict",invalid_type_pack:"invalid_request",type_pack_contract_setups_unsupported:"invalid_request"}});function If(){let n=new Map;return{list:async()=>[...n.values()],put:async e=>{n.set(e.mutationId,e)},remove:async e=>{n.delete(e)}}}var ow,Ap,Cf,sw=I(()=>{"use strict";re();ow=n=>[...new Set(n.flatMap(e=>{let t=e,i=t.id??t.record;return typeof i=="string"?[i]:[]}))],Ap=(n,e,t,i,o=Date.now())=>i?{mutationId:n,records:e,createdAt:o,state:t,problem:i}:{mutationId:n,records:e,createdAt:o,state:t},Cf=class{constructor(e,t){this.store=e;this.native=t}store;native;entries=new Map;listeners=new Set;snapshot=null;io=Promise.resolve();deferred=!1;restored=!1;checking=!1;getSnapshot=()=>{let e=[...this.entries.values()];return this.snapshot??={pending:e.filter(t=>t.state==="pending"),rejected:e.filter(t=>t.state==="rejected"),saveState:this.stateOf(),restored:this.restored}};subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});stateOf(e){let t=!1;for(let i of this.entries.values())if(!(e!==void 0&&!i.records.includes(e))){if(i.state==="rejected")return"rejected";t=!0}return t?this.deferred?"saved_on_device":"saving":"saved"}async acknowledge(e){this.entries.get(e)?.state==="rejected"&&await this.drop(e)}get pendingCount(){return this.getSnapshot().pending.length}setDeferred(e){e!==this.deferred&&(this.deferred=e,this.changed())}begin(e,t){return this.set(Ap(e,ow(t),"pending"))}observe(e){let t=this.entries.get(e.mutation),i=t?.records??(e.records??[]).map(o=>o.id);e.state==="confirmed"?t&&this.drop(e.mutation):e.state==="pending"?t||this.set(Ap(e.mutation,i,"pending")):t?.state!=="rejected"&&this.set(Ap(e.mutation,i,"rejected",e.problem??(e.state==="unknown"?{code:"outcome_unknown",recovery:"resolve_outcome",message:"mutation unknown"}:{code:"internal",recovery:"contact_support",message:"mutation rejected"}),t?.createdAt))}async restore(){try{let[e,t]=await Promise.all([this.store.list().catch(()=>[]),this.native.pendingWrites().catch(()=>null)]);for(let o of t??[])this.entries.has(o.receipt.mutation)||this.entries.set(o.receipt.mutation,Ap(o.receipt.mutation,ow(o.ops),"pending"));for(let o of e)(o.state==="rejected"||!this.entries.has(o.mutationId))&&this.entries.set(o.mutationId,o);this.changed();let i=new Set(t?.map(o=>o.receipt.mutation));t&&await Promise.all(e.filter(o=>o.state==="pending"&&!i.has(o.mutationId)).map(o=>this.settle(o.mutationId)))}finally{this.restored=!0,this.changed()}}async recheck(){if(!this.checking){this.checking=!0;try{for(let e of this.getSnapshot().pending)await this.settle(e.mutationId)}finally{this.checking=!1}}}async adopt(){let e=await this.native.pendingWrites().catch(()=>null),t=!1;for(let i of e??[])this.entries.has(i.receipt.mutation)||(this.entries.set(i.receipt.mutation,Ap(i.receipt.mutation,ow(i.ops),"pending")),t=!0);t&&this.changed()}async settle(e){try{this.observe(await this.native.receipt(e))}catch(t){X(t,"not_found")&&this.entries.get(e)?.state==="pending"&&await this.drop(e)}}set(e){return this.entries.set(e.mutationId,e),this.changed(),this.persist(()=>this.entries.get(e.mutationId)===e?this.store.put(e):void 0)}drop(e){return this.entries.delete(e),this.changed(),this.persist(()=>this.entries.has(e)?void 0:this.store.remove(e))}persist(e){return this.io=this.io.then(e).catch(()=>{})}changed(){this.snapshot=null;for(let e of[...this.listeners])try{e()}catch{}}}});var Mf={};Ca(Mf,{LiveQuery:()=>Fa,MdbaseClient:()=>yr,Write:()=>Os,connect:()=>pw});function Ef(n){return n instanceof vt?new vt(n.value):n instanceof Date?new Date(n):Array.isArray(n)?n.map(e=>Ef(e)):n instanceof Map?new Map([...n].map(([e,t])=>[e,Ef(t)])):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Ef(t)])):n}function Of(n){return typeof n=="string"?M.enc(n):"id"in n&&typeof n.id=="string"?M.enc(n.id):n.path}function Rf(n){if(typeof n=="string")return n;if("id"in n)return n.id;throw A("invalid_request","this operation needs a record ID, not a path; get() the record first")}function qf(n){return n?Ra.enc(n):void 0}function MP(n){if(!(n instanceof Uint8Array)||n.length!==32)throw A("invalid_request","the account secret is 32 bytes","account_secret_length")}function Ke(n){let e=new Map;for(let[t,i]of n)i!==void 0&&e.set(t,i);return e}function zP(n){return n.catch(e=>{throw X(e,"invalid_request")&&e.reason==="unknown_method"?A("upgrade_required","This collection's replica has no record history.","history_unsupported"):e})}function lw(n,e){let t=n.grant;return!e||t.grant===e.grant&&t.role===e.role&&Oo(t.capabilities,e.capabilities)&&Oo(t.fileFolders??null,e.fileFolders??null)?n:{...n,grant:e}}async function $P(n,e){if(typeof e!="string"||!e)throw A("invalid_request","intent must be a non-empty string");let t=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`mdbase-intent/1\0${n}\0${e}`))),i=o=>{let s=t.slice(o,o+16);return s[6]=128|s[6]&15,s[8]=128|s[8]&63,Wc(s)};return[i(0),i(16)]}function cw(n){return n.state==="pending"||n.state==="confirmed"&&n.published==="publishing"}function Tf(n,e){let t=e.published;return t==="published"||t==="not_published"||n.published===void 0&&t!==void 0?{...n,published:t}:n}function pw(n){return yr.connect(n)}var aw,xT,LP,jP,UP,NP,DP,Os,Fa,CT,yr,Rs=I(()=>{"use strict";Wu();Je();Nb();wS();ve();PS();re();yp();QS();nP();Yb();oP();uP();Qb();gP();wP();vP();tw();nw();CP();Ua();hp();TP();mr();ff();en();sw();ve();en();aw=1e3,xT=new Set(["no_device_online","not_served","device_not_serving"]);LP="validate-page-v1",jP="bases-discovery-unreadable-v1",UP="bases-row-properties-v1",NP="contract-query-order-v1",DP="contract-query-order-mtime-v1";Os=class{constructor(e){this.receipt=e;this.confirmed=new Promise((t,i)=>this.settle={resolve:t,reject:i}),this.published=new Promise((t,i)=>this.settlePublished={resolve:t,reject:i}),this.confirmed.catch(()=>{}),this.published.catch(()=>{}),this.update(e)}receipt;listeners=new Set;settle;settlePublished;confirmed;published;recordId;get mutationId(){return this.receipt.mutation}get records(){return this.receipt.records??[]}get state(){return this.receipt.state}onReceipt(e){return this.listeners.add(e),()=>this.listeners.delete(e)}update(e){let t=e.records||!this.receipt.records?e:{...e,records:this.receipt.records};t=Tf(t,this.receipt),this.receipt=t;for(let i of[...this.listeners])i(this.receipt);if(e.state==="rejected"||e.state==="unknown"){let i=new oe(e.problem??{code:e.state==="unknown"?"outcome_unknown":"internal",recovery:e.state==="unknown"?"resolve_outcome":"contact_support",message:`mutation ${e.state}`},{mutationId:e.mutation});this.settle.reject(i),this.settlePublished.reject(i)}else{let i=this.receipt.published;(i==="published"||i==="not_published"||e.state==="confirmed"&&i===void 0)&&this.settlePublished.resolve(this.receipt),e.state==="confirmed"&&this.settle.resolve(this.receipt)}}},Fa=class{constructor(e,t,i){this.client=e;this.query=t;this.include=i;this.ready=new Promise((o,s)=>(this.readyResolve=o,this.readyReject=s)),this.ready.catch(()=>{})}client;query;include;result=new xf;listeners=new Set;subId=null;closedFlag=!1;ready;readyResolve;readyReject;error=null;get records(){return this.result.records}get complete(){return this.result.complete}get asOf(){return this.result.asOf}get stale(){return this.result.stale}get metadata(){return this.result.metadata}get closed(){return this.closedFlag}get(e){return this.result.get(e)}subscribe(e){return this.listeners.add(e),e(this,null),()=>this.listeners.delete(e)}async setQuery(e,t={}){let{include:i=this.include}=t;this.query=e,this.include=i,this.result.markStale(),this.emit(null),await this.client._resubscribeLive(this)}close(){this.closedFlag||(this.closedFlag=!0,this.result.markStale(),this.client._closeLive(this),this.listeners.clear())}_params(){return Ke([[0,Fe(this.query)],[1,qf(this.include)]])}_setSub(e){this.subId=e}get _sub(){return this.subId}_apply(e){this.closedFlag||(this.result.apply(e),e.kind==="snapshot"&&(this.error=null,this.readyResolve()),this.emit(e))}_markStale(){this.result.markStale(),this.emit(null)}_fail(e,t){this.error=e,t&&this.readyReject(e),this.emit(null)}emit(e){for(let t of[...this.listeners])t(this,e)}},CT=new Set(["get","query","query_contract_v1","subscribe","changes","backlinks","list_resources","get_resource","describe","describe_typing","list_files","get_file","read_file","list_holds","list_conflicts","validate","new_type_file","get_contract_v1","map_contract_write_v1","plan_type_pack_v1","record_history","record_version"]),yr=class n{constructor(e,t){this.opts=e;this.session=t,this.collectionId=t.hello.collection,this.lastStatus=t.hello.status,this.currentHello=lw(t.hello,t.hello.status.grant),this.fenceReads=fp(e.connector),this.readFloor=t.hello.status.confirmedThrough,this.files=new Na(this),this.presence=new Va(this),this.writeLedger=new Cf(e.ledger??If(),{receipt:i=>this.receipt(i),pendingWrites:()=>this.pendingWrites()}),this.attach(t),t.request("subscribe_status",null).catch(()=>{}),e.ledger&&this.startLedger()}opts;session;linkState="open";linkError=null;linkListeners=new Set;lastStatus;currentHello;statusListeners=new Set;lives=new Set;livesBySub=new Map;subscribing=0;early=new Map;writes=new Map;unclaimed=new Map;reconnectWaiters=[];restorers=[];fenceHandler=null;fenceReads;readFloor;readFencedAt=null;readFenceWaiters=[];closing=!1;collectionId;holdsWatch={listeners:new Set,last:null};conflictsWatch={listeners:new Set,last:null};files;presence;writeLedger;ledgerStarted=!1;queryAnswered=!1;transportDeferred=!1;get ledger(){return this.startLedger(),this.writeLedger}startLedger(){if(this.ledgerStarted)return;this.ledgerStarted=!0;let e=-1;this.onStatus(t=>{let i=e>t.pending;e=t.pending,this.updateDeferred(),i?this.writeLedger.recheck():t.pending>this.writeLedger.pendingCount&&this.writeLedger.adopt()}),this.onLink(()=>this.updateDeferred()),this.writeLedger.restore()}updateDeferred(){this.writeLedger.setDeferred(this.transportDeferred||this.linkState!=="open"||this.lastStatus.connection==="offline")}setTransportDeferred(e){this.transportDeferred=e,this.ledgerStarted&&this.updateDeferred()}static async connect(e){let t=fp(e.connector);t&&(e={...e});let i=e.reconnect&&e.reconnect.minDelayMs||1e3,o=e.signal,s,r,a,c=()=>e.signal?.aborted||!a?A("cancelled","connect aborted"):a;try{for(;;)try{let l=o,p=await new Promise((d,u)=>{let f=()=>u(c());if(l?.aborted){f();return}l?.addEventListener("abort",f,{once:!0}),Cs.open(e.connector,n.helloParams(e),l).then(h=>{if(l?.removeEventListener("abort",f),l?.aborted){try{h.close()}catch{}u(c())}else d(h)},h=>{l?.removeEventListener("abort",f),u(h)})});if(o?.aborted)throw p.close(),c();return new n(e,p)}catch(l){if(o?.aborted)throw c();let p=t&&X(l,"unavailable")&&(l.reason==="grant_lease_expired"||l.reason==="authorization_unavailable");if(!(p||e.waitForDevice&&X(l,"unavailable")&&xT.has(l.reason??"")))throw l;p&&!s&&(s=new AbortController,a=A("unavailable","The approved grant did not become live within 30 seconds",{reason:"grant_activation_timeout",details:l.toProblem().details}),o=e.signal?AbortSignal.any([e.signal,s.signal]):s.signal,r=setTimeout(()=>s.abort(),3e4)),e.onWaiting?.(l),await new Promise((d,u)=>{let f=()=>{clearTimeout(m),o?.removeEventListener("abort",h)},h=()=>{f(),u(c())},m=setTimeout(()=>{f(),d()},p?Math.min(1e3,i):i);o?.aborted?h():o?.addEventListener("abort",h,{once:!0})}),i=Math.min(15e3,i*2)}}finally{clearTimeout(r)}}static helloParams(e){let t=e.timezone??Intl.DateTimeFormat().resolvedOptions().timeZone;return{versions:df,clientName:e.app.name,clientVersion:e.app.version,features:[...new Set([...e.features??[],"declared-collection-setup-v1","file-stream-failure-v1",LP,jP,UP,NP,DP])],...t?{timezone:t}:{}}}get hello(){return this.currentSession(),this.currentHello}get collection(){return this.collectionId}get link(){return this.linkState}get linkProblem(){return this.linkError}onLink(e){return this.linkListeners.add(e),()=>this.linkListeners.delete(e)}close(){this.closing=!0,this.recordSessions.dispose(),this.session?.close(),this.setLink("closed"),this.wakeReadFence()}get readFenced(){return this.readFencedAt!==null}async readFence(e){if(this.fenceReads){for(;this.readFencedAt!==null;){if(this.linkState==="closed")throw this.linkError??A("unavailable","client closed");if(e?.aborted)throw A("cancelled","aborted while the replica catches up");await new Promise(t=>{let i=()=>{e?.removeEventListener("abort",i);let o=this.readFenceWaiters.indexOf(i);o>=0&&this.readFenceWaiters.splice(o,1),t()};this.readFenceWaiters.push(i),e?.addEventListener("abort",i,{once:!0})})}if(this.linkState==="closed")throw this.linkError??A("unavailable","client closed");if(e?.aborted)throw A("cancelled","aborted while the replica catches up")}}async readyForRead(e,t=!1){if(!this.fenceReads)return t?this.currentSession():this.ready({signal:e});for(;;){let i=t?this.currentSession():await this.ready({signal:e});if(await this.readFence(e),i===this.session&&!i.closed&&this.readFencedAt===null)return i;t&&this.currentSession()}}wakeReadFence(){for(let e of this.readFenceWaiters.splice(0))e()}noteReplica(e){if(!this.fenceReads)return;let t=e.hello.status.confirmedThrough<this.readFloor;this.readFencedAt=t?this.readFloor:null,t||this.wakeReadFence()}noteReceipt(e){this.ledgerStarted&&this.writeLedger.observe(e),this.fenceReads&&this.readFencedAt===null&&e.state==="confirmed"&&e.seq!==void 0&&(this.readFloor=Math.max(this.readFloor,e.seq))}currentSession(){if(!this.session||this.session.closed)throw this.linkState==="closed"&&this.linkError?this.linkError:A("unavailable","not connected to the replica",{reason:"reconnecting"});return this.session}async ready(e={}){let t=e.signal;for(;;){if(this.linkState==="closed")throw this.linkError??A("unavailable","client closed");if(this.session&&!this.session.closed)return this.session;if(t?.aborted)throw A("cancelled","aborted while reconnecting");await new Promise(i=>{this.reconnectWaiters.push(i),t?.addEventListener("abort",()=>i(),{once:!0})})}}async call(e,t,i={}){let o=i.codec,s=this.fenceReads&&CT.has(e),r=!1;for(;;){let a=s?await this.readyForRead(i.signal,!i.retry):i.retry?await this.ready({signal:i.signal}):this.currentSession();try{let c=await a.request(e,t,{...i.signal?{signal:i.signal}:{},...o?{codec:ku(o)}:{}});if(s&&(a!==this.session||a.closed||this.closing)){if(i.retry&&!this.closing)continue;throw A("unavailable","the session changed during the read",{reason:"reconnecting"})}return a===this.session&&!a.closed&&!this.closing&&o===Sn&&(e==="receipt"||e==="await")&&this.noteReceipt(c),c}catch(c){let l=X(c,"unavailable")&&a.closed;if(!(i.retry&&l&&this.opts.reconnect!==!1&&!this.closing))throw r&&ja(c)?new oe(c.toProblem(),{cause:c}):c;r=!0}}}onSession(e){this.restorers.push(e)}relayWitnesses(e){let t=e.hello.headWitness;t&&PP(this.collectionId,t,e.device);let i=xP(this.collectionId,t);i.length&&e.request("report_witnesses",Ke([[0,i]])).catch(()=>{})}get authenticatedDevice(){return this.currentSession().device}get headWitness(){return this.session?.hello.headWitness}attach(e){this.relayWitnesses(e),e.onPush("query_update",t=>{if(this.fenceReads&&this.session!==e)return;let i;try{i=_o(Uu,t)}catch{return}let o=this.livesBySub.get(i.sub);if(o)o._apply(i);else if(this.subscribing>0){let s=this.early.get(i.sub)??[];s.length<64&&this.early.size<64&&(s.push(i),this.early.set(i.sub,s))}}),e.onPush("receipt",t=>{try{let i=_o(Sn,t);this.session===e&&this.noteReceipt(i);let o=this.writes.get(i.mutation);if(o)o.update(i),cw(o.receipt)||this.writes.delete(i.mutation);else{let s=this.unclaimed.get(i.mutation);this.unclaimed.set(i.mutation,s?Tf(i,s):i),this.unclaimed.size>256&&this.unclaimed.delete(this.unclaimed.keys().next().value)}}catch{}}),e.onPush("status",t=>{if(this.session===e)try{this.setStatus(Wr.dec(t))}catch{}}),e.onPush("holds",t=>{try{this.emitHolds(G(Jc).dec(t))}catch{}}),e.onPush("conflicts",t=>{try{this.emitConflicts(_o(G(Zc),t))}catch{}}),e.onPush("closed",t=>{let i;try{i=new oe(ti.dec(t))}catch{i=A("unauthenticated","the replica closed the session")}e.closeWith(i)}),e.handle("fence_apply",async t=>{if(!this.fenceHandler)throw A("invalid_request","this client offers no fence",{reason:"unknown_method"});return fb.enc(await this.fenceHandler(db.dec(t)))}),e.onClose(t=>this.onSessionClosed(e,t))}onSessionClosed(e,t){if(this.session===e){for(let i of this.lives)i._setSub(null),i._markStale();if(this.livesBySub.clear(),this.early.clear(),this.closing||this.opts.reconnect===!1){this.setLink("closed",t??null);return}if(t&&(t.code==="unauthenticated"||t.code==="upgrade_required"||t.code==="forbidden")){this.setLink("closed",t);return}this.setLink("reconnecting",t??null),this.reconnectLoop()}}async reconnectLoop(){let e=this.opts.reconnect||{},t=e.minDelayMs??250,i=e.maxDelayMs??15e3,o=t;for(;!this.closing;)try{let s=await Cs.open(this.opts.connector,n.helloParams(this.opts));if(this.closing){s.close();return}if(s.hello.collection!==this.collectionId)throw s.close(),A("invalid_request","reconnected to a different collection");this.session=s,this.currentHello=lw(s.hello,s.hello.status.grant),this.attach(s),this.noteReplica(s),this.setStatus(s.hello.status),this.setLink("open");for(let r of this.reconnectWaiters.splice(0))r();await this.restore(s);return}catch(s){if(X(s)&&["unauthenticated","forbidden","upgrade_required"].includes(s.code)){this.setLink("closed",s);return}X(s)&&this.setLink("reconnecting",s);let r=X(s)?s.retryAfterMs??0:0;await new Promise(a=>setTimeout(a,Math.max(r,o*(.5+Math.random()/2)))),o=Math.min(i,o*2)}}async restore(e){let t=[];t.push(e.request("subscribe_status",null).catch(()=>{})),this.holdsWatch.listeners.size&&t.push(this.refreshHolds(!0).catch(()=>{})),this.conflictsWatch.listeners.size&&t.push(this.refreshConflicts(!0).catch(()=>{}));for(let i of this.lives)t.push(this._resubscribeLive(i,!1,e).catch(()=>{}));for(let[i,o]of this.writes)t.push(this.awaitReceipt(i).then(s=>{o.update(s),cw(o.receipt)||this.writes.delete(i)}).catch(()=>{}));for(let i of this.restorers)t.push(Promise.resolve(i(e)).catch(()=>{}));await Promise.all(t)}setLink(e,t=null){if(this.linkState!=="closed"&&(e==="closed"&&this.fenceReads&&queueMicrotask(()=>this.wakeReadFence()),!(this.linkState===e&&this.linkError?.reason===t?.reason))){if(this.linkState=e,this.linkError=e==="open"?null:t,e==="closed")for(let i of this.reconnectWaiters.splice(0))i();for(let i of[...this.linkListeners])i(e,this.linkError)}}get status(){return this.lastStatus}async getStatus(){if(!this.fenceReads){let e=await this.call("get_status",null,{codec:Wr,retry:!0});return this.setStatus(e),e}for(;;){let e=await this.ready(),t;try{t=await e.request("get_status",null,{codec:Wr})}catch(i){if(X(i,"unavailable")&&e.closed&&!this.closing&&this.opts.reconnect!==!1)continue;throw i}if(e!==this.session||e.closed){if(this.closing)throw A("unavailable","client closed");continue}return this.setStatus(t),t}}async appliedPrefix(e,t={}){let i=Wg.enc({seq:e}),o=await this.call("applied_prefix",i,{codec:Hg,retry:!1,...t.signal?{signal:t.signal}:{}});if(o.seq!==e||o.chain!==void 0&&(e===0||o.appliedThrough<e))throw A("invalid_request","applied_prefix: inconsistent historical proof","prefix_response");return o}onStatus(e){return this.statusListeners.add(e),e(this.lastStatus),()=>this.statusListeners.delete(e)}setStatus(e){this.fenceReads&&(this.readFencedAt!==null&&e.confirmedThrough>=this.readFencedAt&&(this.readFencedAt=null,this.wakeReadFence()),this.readFencedAt===null&&(this.readFloor=Math.max(this.readFloor,e.confirmedThrough))),this.lastStatus=e,this.currentHello=lw(this.currentHello,e.grant);for(let t of[...this.statusListeners])t(e)}async describe(e={}){let t=await this.call("describe",e.definitions?Ke([[0,!0]]):null,{codec:bb,retry:!0,...e.signal?{signal:e.signal}:{}});if(e.definitions&&(t.types.some(i=>i.definition===void 0)||t.contracts.some(i=>i.schemas===void 0)))throw A("upgrade_required","this replica does not describe definitions","describe_definitions_unsupported");return t}async createType(e,t={}){let{name:i,path:o}=await this.call("new_type_file",Ke([[0,e]]),{codec:gb,retry:!0,...t.signal?{signal:t.signal}:{}}),s=await this.resources.put(o,e,{...t,mustNotExist:!0});return{name:i,path:o,write:s}}describeTyping(e,t,i={}){let o=(s,r)=>Array.isArray(s)&&s.length<=r&&s.every(a=>typeof a=="string"&&a.length>0&&a.length<=1024);return!o(e,ep)||!o(t,tp)?Promise.reject(A("invalid_request","describe_typing: at most 64 types and 256 non-empty paths","typing_bounds")):this.call("describe_typing",Ke([[0,[...e]],[1,[...t]]]),{codec:vb,retry:!0,...i.signal?{signal:i.signal}:{}}).then(s=>{if(s.fields.length!==t.length||s.fields.some((r,a)=>r.path!==t[a]))throw A("internal","describe_typing answered for different paths","invalid_typing_response");return s})}get(e,t={}){return this.call("get",Ke([[0,Of(e)],[1,qf(t.include)]]),{codec:ko,retry:!0,...t.signal?{signal:t.signal}:{}})}async getContract(e,t,i={}){let o=await this.contractCall("get_contract_v1",Ke([[0,1],[1,Of(e)],[2,t.id],[3,t.version],[4,t.type]]),s=>_o(mP,s),i.signal);if(o.version!==1)throw A("upgrade_required","unsupported contract record","contract_records_unsupported");return{id:o.id,path:o.path,revision:o.revision,fields:o.fields,contract:{id:t.id,version:t.version,digest:o.contractDigest,type:o.type,implementationDigest:o.implementationDigest}}}async contractPlan(e,t,i,o,s,r=!1){let a=await this.contractCall("map_contract_write_v1",Ke([[0,1],[1,e.id],[2,e.version],[3,e.type],[4,t===void 0?void 0:Of(t)],[5,i],[6,o?.length?o:void 0],[7,r?!0:void 0]]),yP.dec,s);if(a.version!==1)throw A("upgrade_required","unsupported contract write plan","contract_records_unsupported");return a}async contractCall(e,t,i,o){let s;try{s=await this.call(e,t,{retry:!0,...o?{signal:o}:{}})}catch(r){throw X(r,"invalid_request")&&r.reason==="unknown_method"?A("upgrade_required","this replica does not serve contract-scoped records","contract_records_unsupported"):r}try{return i(s)}catch(r){throw Bn(r,`${e} result`)}}readMany(e,t={}){return hf(this,e,t)}async find(e,t={}){try{return await this.get(e,t)}catch(i){if(X(i,"not_found"))return null;throw i}}query(e,t={}){return this.call("query",Ke([[0,Fe(e)],[1,qf(t.include)],[2,t.contract]]),{codec:Xc,retry:!0,...t.signal?{signal:t.signal}:{}}).then(i=>this.firstQueryResult(i))}firstQueryResult(e){return this.queryAnswered||(this.queryAnswered=!0,So("mdbase:query:first-result")),e}async queryContract(e,t={}){let i=t.pageSize??128;if(!Number.isInteger(i)||i<1||!e.id||e.id.length>1024||!e.version||e.version.length>128||t.where!==void 0&&(!t.where||t.where.length>4096))throw A("invalid_request","invalid contract page selection");let o,s=!1;if(t.orderBy!==void 0){if(!Array.isArray(t.orderBy)||t.orderBy.length<1||t.orderBy.length>8)throw A("invalid_request","invalid contract order_by","invalid_query");let p=[];for(let d of t.orderBy){if(!d||typeof d!="object"||Array.isArray(d))throw A("invalid_request","invalid contract order_by term","invalid_query");if(Object.keys(d).some(f=>f!=="field"&&f!=="direction")||typeof d.field!="string"||!d.field||d.field.length>256||d.direction!==void 0&&d.direction!=="asc"&&d.direction!=="desc")throw A("invalid_request","invalid contract order_by term","invalid_query");d.field==="file.mtime"&&(s=!0),p.push(d.direction===void 0?{field:d.field}:{field:d.field,direction:d.direction})}o=Fe(p)}let r=await this.readyForRead(t.signal),a=r.hello.features.includes(NP);if(o!==void 0&&!a)throw A("upgrade_required","This replica does not support ordered contract queries.","contract_query_order_unsupported");if(s&&!r.hello.features.includes(DP))throw A("upgrade_required","This replica does not support ordering contract queries by file.mtime.","contract_query_order_mtime_unsupported");let c=Math.min(i,a?1e3:128),l=await this.call("query_contract_v1",Ke([[0,1],[1,e.id],[2,e.version],[3,c],[4,t.cursor],[5,t.where],[6,o]]),{codec:bP,retry:!0,...t.signal?{signal:t.signal}:{}});if(l.version!==1)throw A("upgrade_required","unsupported contract query result","contract_query_version");if(l.records.length!==l.page.records.length||l.records.some((p,d)=>p.id!==l.page.records[d]?.id))throw A("unavailable","invalid contract query record binding","contract_query_response");return this.firstQueryResult(l)}backlinks(e,t={}){return this.call("backlinks",Ke([[0,Of(e)],[1,qf(t.include)],[2,t.limit],[3,t.cursor]]),{codec:mb,retry:!0,...t.signal?{signal:t.signal}:{}}).catch(i=>{throw X(i,"invalid_request")&&i.reason==="unknown_method"?A("upgrade_required","This collection's replica can't list backlinks yet.","backlinks_unsupported"):i})}resolveLinks(e,t,i={}){return this.call("resolve_links",Ke([[0,e],[1,[...t]]]),{codec:yb,retry:!0,...i.signal?{signal:i.signal}:{}}).catch(o=>{throw X(o,"invalid_request")&&o.reason==="unknown_method"?A("upgrade_required","This collection's replica can't resolve links yet.","resolve_links_unsupported"):o})}history={list:(e,t={})=>zP(this.call("record_history",YS.enc({record:e,before:t.before,limit:t.limit}),{codec:XS,retry:!0,...t.signal?{signal:t.signal}:{}})),version:(e,t,i={})=>zP(this.call("record_version",JS.enc({record:e,seq:t}),{codec:ZS,retry:!0,...i.signal?{signal:i.signal}:{}}))};resources={get:(e,t={})=>this.call("get_resource",Ke([[0,e]]),{codec:Fu,retry:!0,...t.signal?{signal:t.signal}:{}}),list:(e={})=>this.call("list_resources",Ke([[0,e.folder],[1,e.text],[2,e.cursor],[3,e.limit]]),{codec:hb,retry:!0,...e.signal?{signal:e.signal}:{}}),put:(e,t,i={})=>i.baseRevision&&i.mustNotExist?Promise.reject(A("invalid_request","baseRevision and mustNotExist are exclusive")):this.submit([{kind:"resource_put",path:e,doc:t,...i.baseRevision?{baseRevision:i.baseRevision}:{},...i.mustNotExist?{mustNotExist:!0}:{}}],i),delete:(e,t={})=>this.submit([{kind:"resource_delete",path:e,...t.baseRevision?{baseRevision:t.baseRevision}:{}}],t)};typePacks=Object.freeze({plan:(e,t)=>EP(this,e,t),apply:(e,t)=>qP(this,e,t)});recordSessions=new vf(this);records=Object.freeze({open:(e,t)=>this.recordSessions.open(e,t)});views={createSource:(e,t)=>Sf(this,e,t),updateSource:(e,t,i)=>Pf(this,e,t,i),getSourceRecord:(e,t={})=>kf(this,e,t),list:(e={})=>cP(this,e),execute:(e,t,i={})=>pP(this,e,t,i),readSource:(e,t={})=>dP(this,e,t)};async pendingWrites(e={}){let t=e.signal,i=[],o;for(;;){let s=await this.call("list_pending",Ke([[0,o?M.enc(o):void 0]]),{codec:wb,retry:!0,...t?{signal:t}:{}});if(i.push(...s.pending),!s.next)return i;o=s.next}}async preflightRename(e,t,i={}){return this.preflight({kind:"rename",id:e.id,from:e.path,to:t,updateRefs:i.updateRefs??!0})}async preflightDelete(e){return this.preflight({kind:"delete",id:Rf(e)})}async preflight(e){let t=(await this.submit([e],{dryRun:!0})).receipt;if(t.state==="rejected")throw new oe(t.problem);return t.preflight??{rewrites:[],broken:[]}}async*pages(e,t={}){let{include:i,signal:o,onReset:s}=t,r=Ef(e);r.limit===void 0&&(r.limit=500);let a=i?{...i}:void 0,c={...a?{include:a}:{},...o?{signal:o}:{}},l=r.cursor,p=!1,d=0;for(delete r.cursor;;){o?.throwIfAborted();let u;try{u=await this.query(l!==void 0?{...r,cursor:l}:{...r},c)}catch(f){if(!s||p||!X(f,"invalid_request")||f.recovery!=="fix_request"||f.reason!=="cursor_expired"&&f.reason!=="cursor_stale")throw f;o?.throwIfAborted(),await s({reason:f.reason,error:f,pagesYielded:d,...o?{signal:o}:{}}),o?.throwIfAborted(),p=!0,l=void 0,d=0;continue}if(o?.throwIfAborted(),u.hasMore&&!u.cursor)throw A("invalid_request","Query requires offset paging","query_cursor_required");if(yield u,d++,!u.cursor)return;l=u.cursor}}queryPages(e,t={}){return mf(this,e,t)}recordSet(e={}){return new Ba(this,e)}live(e,t={}){let i=new Fa(this,e,t.include);return this.lives.add(i),i.ready.then(()=>{this.firstQueryResult(void 0)},()=>{}),this._resubscribeLive(i,!0),i}async _resubscribeLive(e,t=!1,i){let o=e._sub;o!==null&&(this.livesBySub.delete(o),e._setSub(null),this.call("unsubscribe",Ke([[0,o]])).catch(()=>{}));try{let s=await this.readyForRead();if(this.fenceReads&&(e.closed||i&&i!==s))return;this.subscribing++;let r;try{let c=await s.request("subscribe",e._params());r=F.dec(c.get(0)??null)}finally{this.subscribing--}let a=this.early.get(r)??[];if(this.early.delete(r),this.subscribing===0&&this.early.clear(),e.closed||this.fenceReads&&(s!==this.session||s.closed)){s.request("unsubscribe",Ke([[0,r]])).catch(()=>{});return}e._setSub(r),this.livesBySub.set(r,e);for(let c of a)e._apply(c)}catch(s){let r=Bn(s,"subscribe");X(r,"unavailable")&&this.linkState==="reconnecting"||e._fail(r,t)}}_closeLive(e){this.lives.delete(e);let t=e._sub;t!==null&&(this.livesBySub.delete(t),this.call("unsubscribe",Ke([[0,t]])).catch(()=>{}))}changes(e={}){return this.call("changes",Ke([[0,e.cursor??null],[1,e.limit]]),{codec:vs,retry:!0,...e.signal?{signal:e.signal}:{}})}watchChanges(e,t={}){let i=t.cursor,o=!1,s=0,r="starting",a=null,c=null,l=null,p=null,d=null,u=()=>{},f,h,m=new Promise((C,R)=>{f=C,h=R});m.catch(()=>{});let w=new Set,b=C=>{try{C(r,a)}catch{}},g=(C,R=null)=>{r=C,a=R;for(let O of[...w])b(O)},y=()=>{p?.(),p=null,d?.(),d=null;let C=l;l=null,u(),u=()=>{},C?.abort(),c=null},_=()=>{this.restorers=this.restorers.filter(C=>C!==S),x()},v=C=>{o||(o=!0,s++,y(),_(),h(C),g("failed",C),w.clear())},k=()=>{r!=="closed"&&(o=!0,s++,y(),_(),h(A("cancelled","change watch closed")),g("closed"),w.clear())},S=async C=>{if(o||C.closed||C!==this.session||c===C)return;s++,y(),c=C;let R=s,O=()=>!o&&R===s&&!C.closed&&C===this.session;l=new AbortController;let E=l.signal;try{await this.readFence(E)}catch(V){O()&&v(Bn(V,"changes watch"));return}if(!O())return;let j=!0,B=[],D=0;u=()=>{B.length=0,D=0};let J=V=>{if(O()){i=V.cursor;try{e(V)}catch{}}};if(d=C.onClose(V=>{if(o||R!==s)return;s++,y();let U=V??A("unavailable","change watch session closed");h(U),g("stale",U)}),p=C.onPush("changes",V=>{if(O())try{let U=vs.dec(V);if(!j){J(U);return}let ce=64+U.cursor.length*2+U.changes.reduce((ee,te)=>ee+384+te.path.length*2,0);if(B.length>=16||D+ce>1024*1024){v(A("unavailable","change watch startup buffer exceeded"));return}D+=ce,B.push(U)}catch(U){v(Bn(U,"changes push"))}}),g("starting"),!!O())try{let V=await C.request("changes",Ke([[0,i??null],[1,aw],[2,!0]]),{codec:vs,signal:E});for(;;){if(!O()||(i=V.cursor,(V.changes.length||V.reset)&&J(V),!O()))return;if(V.changes.length<aw)break;u(),V=await C.request("changes",Ke([[0,i],[1,aw]]),{codec:vs,signal:E})}for(;B.length&&O();)J(B.shift());if(u(),j=!1,!O())return;g("active"),O()&&f()}catch(V){O()&&v(Bn(V,"changes watch"))}},x=this.onLink((C,R)=>{C==="closed"&&(R?v(R):k())});this.onSession(S),this.ready().then(S).catch(C=>v(Bn(C,"changes watch")));let P=Object.assign(k,{ready:m,subscribe:C=>(r!=="closed"&&r!=="failed"&&w.add(C),b(C),()=>{w.delete(C)})});return Object.defineProperties(P,{state:{get:()=>r},error:{get:()=>a},cursor:{get:()=>i}}),Object.freeze(P)}async validate(e={}){let t=e.signal;t?.throwIfAborted();let{targets:i,expected:o}=kS(e.refs),s=a=>this.call("validate",a,{codec:AS,retry:!0,...t?{signal:t}:{}});if(i!==void 0||!this.hello.features.includes(LP)){let a=await s(Ke([[0,i]]));return t?.throwIfAborted(),SS(a,o)}let r=[];for(let a;;){let c=await s(Ke([[1,new Map(a===void 0?[]:[[0,M.enc(a)]])]]));t?.throwIfAborted();let l=c[c.length-1];if(l===void 0)return r;r.push(...c),a=l.id}}async executeAppBases(e,t={}){let i=t.signal,o=e.window===void 0?null:{...e.window},s=e.rowProperties===void 0?void 0:[...e.rowProperties],r=tf({...e,...o===null?{}:{window:o},...s===void 0?{}:{rowProperties:s}}),a=await this.readyForRead(i);if(s!==void 0&&!a.hello.features.includes(UP))throw A("upgrade_required","This replica does not support projected Bases row properties.","bases_row_properties_unsupported");let c=await a.readAppBases(r,i);if(a!==this.session||a.closed||this.readFencedAt!==null)throw A("unavailable","original Bases session is no longer current");try{return nf(c,o,s??null)}catch(l){throw Bn(l,"app Bases result")}}executeAppBasesPages(e,t={}){return bS((i,o)=>this.executeAppBases(i,o?{signal:o}:{}),e,t)}async listAppBasesViews(e,t={}){let i=t.signal,o=e.limit;pp(e);let s=await this.readyForRead(i),r=e.reportUnreadable===!0&&s.hello.features.includes(jP),a=pp({...e,reportUnreadable:r}),c=await s.readAppBasesDiscovery("list-views",a,i);try{if(s!==this.session||s.closed||this.readFencedAt!==null)throw A("unavailable","original Bases session is no longer current");return of(c,o,r)}catch(l){throw Bn(l,"app Bases discovery")}finally{c.fill(0)}}async readAppBasesViewSource(e,t={}){let i=t.signal,o={...e},s=rf(o),r=await this.readyForRead(i),a=await r.readAppBasesDiscovery("read-view-source",s,i);try{if(r!==this.session||r.closed||this.readFencedAt!==null)throw A("unavailable","original Bases session is no longer current");return sf(a,o)}catch(c){throw Bn(c,"app Bases exact source")}finally{a.fill(0)}}async submit(e,t={}){if(this.hello.version.minor>=3&&this.hello.grant.role==="viewer")throw new xs(A("forbidden","You have view access, so changes can't be saved.","read_only"));t.intent!==void 0&&t.mutationId===void 0&&(t={...t,mutationId:(await $P(this.collectionId,t.intent))[0]});let i=t.mutationId??zi(),o={ops:e,mutationId:i};t.conflictMode&&(o.conflictMode=t.conflictMode),t.timezone&&(o.timezone=t.timezone),t.dryRun&&(o.dryRun=!0),t.include&&(o.include=t.include),t.wait&&(o.wait=t.wait),t.validation&&(o.validation=t.validation),t.dryRun||(this.startLedger(),await this.writeLedger.begin(i,e));let s;try{let r=await this.call("submit",rb.enc(o),{codec:sb,retry:!0,...t.signal?{signal:t.signal}:{}});if(r.length!==1)throw A("internal","submit answered without exactly one receipt","invalid_submit_response");s=r[0]}catch(r){throw t.dryRun?r:(this.writeLedger.settle(i),ja(r)&&["invalid_request","invalid_record","not_found","conflict","unauthenticated","forbidden","collection_invalid","rate_limited","too_large","upgrade_required"].includes(r.code)?new xs(r,{mutationId:i}):La(r,"submit",{mutationId:i}))}return t.dryRun?new Os(s):this._track(s)}async record(e,t){return Object.assign(await this.submit([e],t),{recordId:e.id})}create(e,t={}){if(t.intent!==void 0&&t.mutationId===void 0)return $P(this.collectionId,t.intent).then(([o,s])=>this.create({...e,id:e.id??s},{...t,mutationId:o}));if(e.contract)return this.createThroughContract(e,e.contract,t);let i={kind:"create",id:e.id??zi()};return e.path!==void 0&&(i.path=e.path),e.type!==void 0&&(i.type=e.type),e.frontmatter!==void 0&&(i.frontmatter=cp(e.frontmatter)),e.body!==void 0&&(i.body=e.body),e.document!==void 0&&(i.document=e.document),this.record(i,t)}async createThroughContract(e,t,i){if(e.document!==void 0)throw A("invalid_request","a contract create takes frontmatter fields, not a document");if(e.type!==void 0&&t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())throw A("invalid_request","the create type and contract type must name the same type");let o=t.type===void 0&&e.type!==void 0?{...t,type:e.type}:t,s=await this.contractPlan(o,void 0,cp(e.frontmatter??{}),void 0,i.signal),r={kind:"create",id:e.id??zi(),type:s.type,frontmatter:s.patch};return e.path!==void 0&&(r.path=e.path),e.body!==void 0&&(r.body=e.body),this.record(r,i)}update(e,t,i={}){return t.contract?this.updateThroughContract(e,t,t.contract,i):this.record(this.updateOp(e,t),i)}async updateThroughContract(e,t,i,o){if(t.add||t.remove)throw A("invalid_request","a contract update takes only patch, unset, body and ifRevision");let s=await this.contractPlan(i,e,t.patch?cp(t.patch):void 0,t.unset,o.signal,t.promote),r=typeof e=="object"&&"frontmatter"in e?e:s.id,a=this.updateOp(r,{body:t.body,bodyEdits:t.bodyEdits,bodyBase:t.bodyBase}),c={kind:"update",id:s.id};return a.body!==void 0&&(c.body=a.body),a.bodyEdits&&(c.bodyEdits=a.bodyEdits),a.bodyBase!==void 0&&(c.bodyBase=a.bodyBase),s.patch.size&&(c.patch=s.patch),s.unset.length&&(c.unset=s.unset),s.base.length&&(c.base=s.base),t.requireLive&&(c.requireLive=!0),t.updateRefs!==void 0&&(c.updateRefs=t.updateRefs),t.ifRevision&&(c.ifRevision=t.ifRevision),this.record(c,o)}updateOp(e,t){if(t.contract||t.promote)throw A("invalid_request","contract updates are mapped by the replica; use update()");let i={kind:"update",id:Rf(e)},o=typeof e=="object"&&"frontmatter"in e?e:null;if(t.requireLive&&(i.requireLive=!0),t.updateRefs!==void 0&&(i.updateRefs=t.updateRefs),t.patch&&(i.patch=cp(t.patch)),t.unset?.length&&(i.unset=t.unset),t.add&&(i.add=new Map(Object.entries(t.add).map(([s,r])=>[s,r.map(Fe)]))),t.remove&&(i.remove=new Map(Object.entries(t.remove).map(([s,r])=>[s,r.map(Fe)]))),t.ifRevision&&(i.ifRevision=t.ifRevision),t.bodyEdits?.length){i.bodyEdits=t.bodyEdits;let s=t.bodyBase??(o?.body!==void 0?Di(o.body):void 0);if(!s)throw A("invalid_request","bodyEdits need bodyBase (or a RecordView read with its body)");i.bodyBase=s}else if(t.body!==void 0)if(o?.body!==void 0&&t.bodyBase===void 0){let s=ef(o.body,t.body);s.length&&(i.bodyEdits=s,i.bodyBase=Di(o.body))}else i.body=t.body,t.bodyBase&&(i.bodyBase=t.bodyBase);if(o){let s=[],r=[...i.patch?.keys()??[],...i.unset??[]];for(let a of new Set(r)){let c=Object.hasOwn(o.frontmatter,a)?o.frontmatter[a]:void 0;s.push(c===void 0?{key:a}:{key:a,observed:Fe(c)})}s.length&&(i.base=s)}if(o&&i.patch){for(let[s,r]of[...i.patch]){let a=Object.hasOwn(o.frontmatter,s)?o.frontmatter[s]:void 0;a!==void 0&&Oo(Fe(a),r)&&(i.patch.delete(s),i.base=i.base?.filter(c=>c.key!==s))}i.patch.size===0&&delete i.patch,i.base?.length===0&&delete i.base}return i}replaceDocument(e,t,i={}){let o=typeof e=="object"&&"path"in e&&"revision"in e?e:null,s={kind:"document",id:Rf(e),new:{path:o?.path??"",doc:t}};if(!o)throw A("invalid_request","replaceDocument needs the RecordView it was edited from");return o.document!==void 0&&(s.base={path:o.path,doc:o.document}),i.ifRevision&&(s.ifRevision=i.ifRevision),this.record(s,i)}delete(e,t={}){if(t.contract){let{contract:o,...s}=t;return this.contractPlan(o,e,void 0,void 0,t.signal).then(r=>{let a={kind:"delete",id:r.id,baseRevision:r.revision};return s.ifRevision&&(a.ifRevision=s.ifRevision),this.record(a,s)})}let i={kind:"delete",id:Rf(e)};return typeof e=="object"&&"revision"in e&&(i.baseRevision=e.revision),t.ifRevision&&(i.ifRevision=t.ifRevision),this.record(i,t)}rename(e,t,i={}){if(i.contract){let{contract:s,...r}=i;return this.contractPlan(s,e.id,void 0,void 0,i.signal).then(a=>this.rename({...e,id:a.id,path:a.path},t,r))}let o={kind:"rename",id:e.id,from:e.path,to:t,updateRefs:i.updateRefs??!0};return i.ifRevision&&(o.ifRevision=i.ifRevision),this.record(o,i)}_track(e){this.noteReceipt(e);let t=e,i=this.unclaimed.get(e.mutation);i&&(this.unclaimed.delete(e.mutation),t=Tf(e,i),(e.state==="pending"||e.state==="confirmed"&&(i.state==="rejected"||i.state==="unknown"))&&(t=Tf({...e,...i},t)));let o=this.writes.get(e.mutation);return o?o.update(t):o=new Os(t),cw(o.receipt)?this.writes.set(e.mutation,o):this.writes.delete(e.mutation),o}settle(e,t={}){return tP(this,e,t)}receipt(e,t={}){return this.call("receipt",Ke([[0,M.enc(e)]]),{codec:Sn,retry:!0,...t.signal?{signal:t.signal}:{}}).catch(i=>{throw La(i,"receipt",{mutationId:e})})}awaitReceipt(e,t={}){return this.call("await",Ke([[0,M.enc(e)],[1,t.timeoutMs]]),{codec:Sn,retry:!0,...t.signal?{signal:t.signal}:{}}).catch(i=>{throw La(i,"await",{mutationId:e})})}listHolds(e={}){return this.call("list_holds",null,{codec:G(Jc),retry:!0,...e.signal?{signal:e.signal}:{}})}onHolds(e){let t=this.holdsWatch;return t.listeners.add(e),t.last&&e(t.last),t.listeners.size===1&&this.refreshHolds(!0).catch(()=>{}),()=>t.listeners.delete(e)}async refreshHolds(e){e&&await this.call("subscribe_holds",null,{retry:!0}),this.emitHolds(await this.listHolds())}emitHolds(e){this.holdsWatch.last=e;for(let t of[...this.holdsWatch.listeners])t(e)}async resolveHold(e,t,i){let o=await this.call("resolve_hold",Ke([[0,M.enc(e)],[1,Xg.enc(t)],[2,i]]),{codec:Sn});return this._track(o)}listConflicts(e={}){return this.call("list_conflicts",e.record?Ke([[0,M.enc(e.record)]]):null,{codec:G(Zc),retry:!0,...e.signal?{signal:e.signal}:{}})}onConflicts(e){let t=this.conflictsWatch;return t.listeners.add(e),t.last&&e(t.last),t.listeners.size===1&&this.refreshConflicts(!0).catch(()=>{}),()=>t.listeners.delete(e)}async refreshConflicts(e){e&&await this.call("subscribe_conflicts",null,{retry:!0}),this.emitConflicts(await this.listConflicts())}emitConflicts(e){this.conflictsWatch.last=e;for(let t of[...this.conflictsWatch.listeners])t(e)}dismissConflict(e,t={}){return this.submit([{kind:"conflict_dismiss",mutation:e.mutation,record:e.conflict.id}],t)}resolveConflict(e,t,i,o={}){return this.submit([{kind:"update",id:e.conflict.id,patch:new Map([[t,Fe(i)]])},{kind:"conflict_dismiss",mutation:e.mutation,record:e.conflict.id}],o)}pendingDevices(e={}){return this.call("pending_devices",null,{codec:G(VS),retry:!0,...e.signal?{signal:e.signal}:{}})}approveDevice(e,t){return/^\d{6}$/.test(t)?this.call("approve_device",Ke([[0,M.enc(e)],[1,t]])).then(()=>{}):Promise.reject(A("invalid_request","the code is six digits","invalid_sas"))}rejectDevice(e){return this.call("reject_device",Ke([[0,M.enc(e)]])).then(()=>{})}accountKey={setup:async e=>{MP(e);let t=await this.call("account_key_setup",Ke([[0,e]]),{codec:Sn});return this._track(t)},unlock:async e=>{MP(e),await this.call("account_key_unlock",Ke([[0,e]]))},status:(e={})=>this.call("account_key_status",null,{codec:GS,retry:!0,...e.signal?{signal:e.signal}:{}})};recoveryKey={status:()=>this.call("recovery_key_status",null,{codec:KS,retry:!0}),create:()=>this.call("recovery_key_create",null,{codec:WS}),import:e=>this.call("recovery_key_import",Ke([[0,e.trim()]])).then(()=>{})};offerFence(e){this.fenceHandler=e}reportFence(e){return this.call("fence_report",ub.enc({open:e}),{retry:!0}).then(()=>{})}}});function jf(n){if(!n||typeof n!="object"||Array.isArray(n))throw Vi();return n}function FP(n){if(typeof n!="string")return!1;try{let e=new URL(n);return["http:","https:"].includes(e.protocol)&&!e.username&&!e.password}catch{return!1}}function VP(n){let e=jf(n);if(!FP(e.issuer)||typeof e.subject!="string"||!e.subject.trim()||typeof e.name!="string"||!e.name.trim())throw Vi();let t=e.account_id;if(t!==void 0){if(typeof t!="string")throw Vi();try{if(N(t).every(i=>i===0))throw Vi()}catch{throw Vi()}}return{issuer:e.issuer,subject:e.subject,name:e.name,...t===void 0?{}:{accountId:t}}}function Uf(n,e){return n.issuer===e.issuer&&n.subject===e.subject}function OT(n){return Array.isArray(n)?n.flatMap(e=>{let t=de(e,"issuer"),i=de(e,"subject");return typeof t!="string"||typeof i!="string"?[]:[{issuer:t,subject:i}]}):[]}function RT(n){let e=de(n.fields,"name"),t=de(n.fields,"identities"),i=OT(t),o=n.issues.find(s=>s.severity==="error");return o?{reason:o.message,claims:i}:typeof e!="string"||!e.trim()?{reason:"It needs a non-blank name.",claims:i}:t!==void 0&&(!Array.isArray(t)||i.length!==t.length||i.some(s=>!s.subject.trim()))?{reason:"Each account identity needs an exact issuer and subject.",claims:i}:{name:e,identities:i,claims:i}}var dw,Vi,gr,kp=I(()=>{"use strict";ve();re();un();dw=Object.freeze({id:"mdbase.person",version:"2.0.0"}),Vi=()=>A("unavailable","invalid people response","people_response");gr=class{constructor(e,t){this.client=e;this.authority=t}client;authority;check(e){if(e?.throwIfAborted(),!this.authority.isCurrent())throw A("unauthenticated","people scope changed","people_fenced")}checkReadSession(e){if(e!==this.client.currentSession()||e.closed)throw A("unavailable","people read session changed","people_fenced");let t=N(this.authority.collection),i=N(e.hello.collection);if(t.every(o=>o===0)||!t.every((o,s)=>o===i[s]))throw A("unauthenticated","people collection binding changed","people_binding")}async current(e={}){this.check(e.signal);let t=await this.authority.request("identity",e);this.check(e.signal);let i=VP(t),o=jf(t).person_settings_url;if(o===void 0)return i;if(!FP(o))throw Vi();return{...i,personSettingsUrl:o}}async members(e={}){this.check(e.signal);let t=jf(await this.authority.request("members",e));if(this.check(e.signal),!Array.isArray(t.members)||t.members.length>1e3)throw Vi();return t.members.map(i=>{let o=VP(i),s=jf(i).role;if(s!=="owner"&&s!=="editor"&&s!=="viewer")throw Vi();return{...o,role:s}})}async directory(e={}){let{members:t="if-approved",...i}=e;if(!["require","if-approved","omit"].includes(t))throw A("invalid_request","invalid members mode");this.check(i.signal);let o=async()=>{let u=await this.current(i);this.check(i.signal);let f=t==="omit"?void 0:await this.members(i).catch(h=>{if(!(t==="if-approved"&&X(h,"forbidden")&&h.reason==="people_permission_declined"))throw h});return this.check(i.signal),{account:u,members:f}},[{account:s,members:r},a]=await Promise.all([o(),this.records(i)]);this.check(i.signal),this.checkReadSession(a.session);let c=a.invalid.filter(u=>u.claims.some(f=>Uf(f,s))),l=a.people.filter(u=>u.identities.some(f=>Uf(f,s))),p=l[0],d=c.length?{status:"invalid",paths:c.map(u=>u.path)}:l.length>1?{status:"ambiguous",paths:l.map(u=>u.path)}:p?{status:"linked",person:p}:{status:"unlinked"};return{account:s,me:d,people:a.people,invalid:a.invalid.map(({claims:u,...f})=>f),...r===void 0?{}:{members:r}}}async records(e){let t=await this.client.readyForRead(e.signal);this.check(e.signal),this.checkReadSession(t);let i,o,s,r=new Set,a=new Set,c=[],l=[];for(;;){this.check(e.signal);let d=await this.client.queryContract(dw,{pageSize:128,...i?{cursor:i}:{},...e.signal?{signal:e.signal}:{}}).catch(f=>{if(!i&&!r.size&&X(f,"not_found")&&f.reason==="data_contract_not_found")return null;throw f});if(this.check(e.signal),this.checkReadSession(t),!d)return{people:c,invalid:l,session:t};let{page:u}=d;if(!u.complete)throw A("unavailable","person inventory is incomplete","people_incomplete");if(o!==void 0&&o!==u.asOf||s!==void 0&&s!==d.contractDigest)throw Vi();o=u.asOf,s=d.contractDigest;for(let[f,h]of d.records.entries()){let m=u.records[f];if(h.id!==m?.id||r.has(h.id)||!h.implementations.length)throw Vi();if(r.add(h.id),r.size>1e4)throw A("too_large","person directory exceeds its record budget","people_budget");let w=h.implementations.map(RT),b=w[0],g=w.find(_=>"reason"in _),y=w.flatMap(_=>_.claims);g&&"reason"in g?l.push({id:h.id,path:m.path,reason:g.reason,claims:y}):w.some(_=>JSON.stringify(_)!==JSON.stringify(b))?l.push({id:h.id,path:m.path,reason:"Its Person implementations project different values.",claims:y}):"name"in b&&c.push({id:h.id,path:m.path,name:b.name,identities:b.identities,typeNames:[...new Set(h.implementations.map(_=>_.typeName))].sort()})}if(!u.cursor){if(u.hasMore===!0||u.totalCount!==void 0&&u.totalCount!==r.size)throw A("unavailable","person inventory is incomplete","people_incomplete");break}if(a.has(u.cursor))throw Vi();a.add(u.cursor),i=u.cursor}let p=(d,u)=>d.path<u.path?-1:d.path>u.path?1:0;return{people:c.sort(p),invalid:l.sort(p),session:t}}}});function Sp(n){return typeof n=="string"&&TT.test(n)&&Number.isFinite(Date.parse(n))}function Pp(n){if(typeof n!="string"||!ET.test(n))throw Fi()}function HP(n){if(typeof n!="string"||!Nf.test(n))throw Fi()}function uw(n){if(typeof n!="string"||!n.length||n.length>100)throw Fi()}function fw(n){if(!n||Object.keys(n).some(e=>e!=="id"&&e!=="fireAt")||(HP(n.id),!Sp(n.fireAt)))throw Fi();return{id:n.id,fire_at:new Date(n.fireAt).toISOString()}}function Xr(n){if(!n||typeof n!="object"||Array.isArray(n))throw In();return n}function GP(n){let e=Xr(n);if(typeof e.id!="string"||!Nf.test(e.id)||typeof e.criterion_id!="string"||!e.criterion_id.length||e.criterion_id.length>100||!Sp(e.fire_at)||!Number.isSafeInteger(e.generation)||e.generation<1||!["scheduled","firing","fired","cancelled"].includes(e.status)||!Sp(e.created_at)||!Sp(e.updated_at)||e.fired_at!==null&&!Sp(e.fired_at))throw In();return{id:e.id,criterionId:e.criterion_id,fireAt:e.fire_at,generation:e.generation,status:e.status,createdAt:e.created_at,updatedAt:e.updated_at,firedAt:e.fired_at}}function hw(n,e){let t=Xr(n);if(t.namespace!==e||!Array.isArray(t.timers)||t.timers.length>xp)throw In();let i=t.timers.map(GP);if(new Set(i.map(o=>o.id)).size!==i.length||t.intent_revision!==void 0&&(!Number.isSafeInteger(t.intent_revision)||t.intent_revision<0))throw In();return{namespace:e,timers:i,...t.intent_revision===void 0?{}:{intentRevision:t.intent_revision}}}function KP(n){let{namespace:e,operationId:t,expectedRevision:i}=n;if(Pp(e),typeof t!="string"||!qT.test(t)||!Number.isSafeInteger(i)||i<0||i===Number.MAX_SAFE_INTEGER)throw Fi();return{namespace:e,operationId:t,expectedRevision:i}}function MT(n,e){let t=Xr(n),i=hw(t,e);if(!Array.isArray(t.cancelled_ids)||t.cancelled_ids.length>xp||t.cancelled_ids.some(o=>typeof o!="string"||!Nf.test(o))||new Set(t.cancelled_ids).size!==t.cancelled_ids.length)throw In();return{...i,cancelledIds:[...t.cancelled_ids]}}function WP(n,e){let t=Xr(n);if(t.protocol_version!==1||t.namespace!==e.namespace||t.operation_id!==e.operationId||t.expected_revision!==e.expectedRevision||t.committed_revision!==e.expectedRevision+1||Object.keys(t).some(r=>!["protocol_version","namespace","operation_id","expected_revision","committed_revision","result"].includes(r)))throw In();let i=Xr(t.result);if(Object.keys(i).some(r=>!["namespace","timers","cancelled_ids"].includes(r)))throw In();let o=MT(i,e.namespace),s=["id","criterion_id","fire_at","generation","status","created_at","updated_at","fired_at"];for(let r of i.timers)if(Object.keys(Xr(r)).some(a=>!s.includes(a)))throw In();if(o.cancelledIds.some(r=>o.timers.some(a=>a.id===r)))throw In();return{protocolVersion:1,...e,committedRevision:t.committed_revision,result:o}}async function LT(n){let e=globalThis.navigator?.serviceWorker;if(!e)throw A("invalid_request","Web Push needs a service worker.","timer_push_platform");return await new Promise((t,i)=>{let o=()=>i(A("cancelled","Timer request cancelled before dispatch."));if(n?.aborted)return o();n?.addEventListener("abort",o,{once:!0}),e.ready.then(t,i).finally(()=>n?.removeEventListener("abort",o))})}var ET,Nf,qT,TT,xp,Fi,In,Ka,mw=I(()=>{"use strict";re();ET=/^[A-Za-z0-9._-]{1,64}$/,Nf=/^[A-Za-z0-9._:-]{1,128}$/,qT=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,TT=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/i,xp=1e4,Fi=()=>A("invalid_request","Invalid opaque timer request."),In=()=>A("internal","Invalid control-plane timer response.","invalid_timer_response");Ka=class{constructor(e,t={}){this.port=e;this.criteria=t.criteria?.length?[...t.criteria]:void 0}port;lifetime=new AbortController;criteria;close(){this.lifetime.signal.aborted||(this.lifetime.abort(),this.port.close?.())}async run(e,t,i){let o=e.signal?AbortSignal.any([this.lifetime.signal,e.signal]):this.lifetime.signal;if(o.aborted)throw A("cancelled","Timer request cancelled before dispatch.");let s;try{s=await i({signal:o})}catch(r){let a=r&&typeof r=="object"?r.problem?.operation_outcome:void 0;throw t&&a==="unknown"?A("outcome_unknown","Timer or channel write outcome is unknown."):t&&X(r,"internal")&&r.reason==="invalid_timer_response"?A("outcome_unknown","Timer write returned an invalid response."):r}if(o.aborted)throw A(t?"outcome_unknown":"cancelled","Timer request ended before its response was observed.");return s}list(e,t={}){return Pp(e),this.run(t,!1,async i=>hw(await this.port.list(e,i),e))}put(e,t={}){Pp(e.namespace),uw(e.criterionId);let i=fw(e.timer),o=e.namespace,s=e.criterionId;return this.run(t,!0,async r=>{let a=GP(await this.port.put(o,i.id,{criterion_id:s,fire_at:i.fire_at},r));if(a.id!==i.id||a.criterionId!==s||Date.parse(a.fireAt)!==Date.parse(i.fire_at))throw In();return a})}cancel(e,t={}){if(Pp(e.namespace),HP(e.id),e.generation!==void 0&&(!Number.isSafeInteger(e.generation)||e.generation<1))throw Fi();let{namespace:i,id:o,generation:s}=e;return this.run(t,!0,async r=>{let a=Xr(await this.port.cancel(i,o,s,r));if(a.namespace!==i||a.id!==o||typeof a.cancelled!="boolean")throw In();return{namespace:i,id:o,cancelled:a.cancelled}})}reconcile(e,t={}){if(Pp(e.namespace),uw(e.criterionId),!Array.isArray(e.timers)||e.timers.length>xp)throw Fi();let i=e.timers.map(fw),o=new Map(i.map(a=>[a.id,a.fire_at]));if(o.size!==i.length)throw Fi();let s=e.namespace,r=e.criterionId;return this.run(t,!0,async a=>{let c=Xr(await this.port.reconcile(s,{criterion_id:r,timers:i},a)),l=hw(c,s);if(l.timers.length!==i.length||l.timers.some(p=>!o.has(p.id)||p.criterionId!==r||Date.parse(p.fireAt)!==Date.parse(o.get(p.id)))||!Array.isArray(c.cancelled_ids)||c.cancelled_ids.length>xp||c.cancelled_ids.some(p=>typeof p!="string"||!Nf.test(p)||o.has(p))||new Set(c.cancelled_ids).size!==c.cancelled_ids.length)throw In();return{...l,cancelledIds:c.cancelled_ids}})}reconcileWithReceipt(e,t={}){let i=KP(e),o=e.criterionId;if(uw(o),!Array.isArray(e.timers)||e.timers.length>xp)throw Fi();let s=e.timers.map(fw),r=new Map(s.map(l=>[l.id,l.fire_at]));if(r.size!==s.length)throw Fi();let a=this.port.reconcileWithReceipt;if(!a)throw A("upgrade_required","Timer port does not support original-operation recovery.","timer_operation_recovery_unavailable");let c={protocol_version:1,operation_id:i.operationId,expected_revision:i.expectedRevision};return this.run(t,!0,async l=>{let p=WP(await a.call(this.port,i.namespace,{criterion_id:o,timers:s,recovery:c},l),i);if(p.result.timers.length!==s.length||p.result.timers.some(d=>d.criterionId!==o||!r.has(d.id)||Date.parse(d.fireAt)!==Date.parse(r.get(d.id))))throw In();return p})}lookupOperation(e,t={}){let i=KP(e),o=this.port.lookupOperation;if(!o)throw A("upgrade_required","Timer port does not support original-operation recovery.","timer_operation_recovery_unavailable");return this.run(t,!0,async s=>{let r=Xr(await o.call(this.port,i.namespace,i.operationId,s));if(r.outcome==="committed"&&Object.keys(r).length===2)return{outcome:"committed",receipt:WP(r.receipt,i)};if(r.outcome==="unknown"&&r.namespace===i.namespace&&r.operation_id===i.operationId&&Object.keys(r).length===3)return{outcome:"unknown",namespace:i.namespace,operationId:i.operationId};throw In()}).catch(()=>{throw A("outcome_unknown","Original timer operation could not be recovered.")})}registerWebPush(e={}){let t=e.criteria??this.criteria;return this.run(e,!0,async i=>{let o=e.serviceWorker??await LT(i.signal);return this.port.registerWebPush({...e,...t?{criteria:[...t]}:{},serviceWorker:o,...i})})}unregisterWebPush(e,t={}){return this.run(t,!0,i=>this.port.unregisterWebPush(e,i))}registerFcm(e){let t=e.criteria??this.criteria;return this.run(e,!0,i=>this.port.registerFcm({...e,...t?{criteria:[...t]}:{},...i}))}unregisterFcm(e={}){return this.run(e,!0,t=>this.port.unregisterFcm(t))}}});function Es(n){try{let e=$f(n),t=$f(e?.error)??e,i=t?.code;if(typeof i!="string"||!VT.test(i))return null;let o=$f(t.details)?.issues,s=Array.isArray(t.paths)?t.paths:Array.isArray(o)?o.slice(0,64).map(a=>$f(a)?.path):[],r=[];for(let a of s.slice(0,64))if(typeof a=="string"&&FT.test(a)&&!r.includes(a)&&r.push(a),r.length===5)break;return Object.freeze({code:i,paths:Object.freeze(r)})}catch{return null}}function sx(n){return n?`This app's registration was rejected (${n.code==="invalid_application_manifest"?"invalid manifest":n.code.replaceAll("_"," ")}${n.paths.length?`: ${n.paths.join(", ")}`:""}).`:"This app's registration was rejected by mdbase."}var VT,FT,$f,Bf=I(()=>{"use strict";VT=/^[a-z][a-z0-9_]{0,63}$/,FT=/^(?:\/[A-Za-z0-9_-]{1,64}){1,6}$/,$f=n=>n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null});var ax,lx=I(()=>{"use strict";ax="Your account has reached its synced collection limit. Open an existing collection, delete one you own if Delete is available, or, if you're on the Free plan, upgrade to Plus from your mdbase account page."});function Ha(n){return typeof n=="string"&&KT.has(n)}function wi(n){if(n==null)return null;if(typeof n!="object"||Array.isArray(n))return Object.freeze({state:"unavailable",reason:"device_offline"});let e=n;return e.state==="available"?Object.freeze({state:"available"}):e.state==="unavailable"&&Ha(e.reason)?Object.freeze({state:"unavailable",reason:e.reason}):Object.freeze({state:"unavailable",reason:"device_offline"})}function Fn(n){let e={availability:n};return n==="collection_deleted"?new oe({code:"forbidden",message:"this collection was deleted",reason:n,recovery:"none",details:e}):n==="access_removed"?A("forbidden","this account no longer has access to this collection",{reason:n,details:e}):n==="sync_required"?A("forbidden","this collection must be set up again for this app",{reason:n,details:e}):A("unavailable",`this collection can't be opened now (${n})`,{reason:n,details:e})}var Aw,KT,To=I(()=>{"use strict";re();Aw=["device_offline","device_not_serving","desktop_update_required","old_connector_running","approval_required","sync_required","no_device_registered","access_removed","collection_migrating","collection_not_yet_migrated","collection_deleted"],KT=new Set(Aw)});function nn(n){return typeof n=="object"&&n!==null&&kw.has(n)}function YT(n,e){let t=n?.retry_after_ms,i=n?.retry_after_seconds;if(typeof t=="number"&&Number.isFinite(t)&&t>=0)return Vf(t);if(typeof i=="number"&&Number.isFinite(i)&&i>=0)return Vf(i*1e3);let o=e?.get("retry-after")?.trim();return o&&/^[0-9]{1,6}$/.test(o)?Vf(Number(o)*1e3):null}function Ff(n,e=null){if(typeof n!="string"||n.length>2048||/[\u0000-\u0020\u007f]/.test(n))return null;try{let t=new URL(n);if(t.protocol!=="https:"||t.username||t.password||t.port)return null;let i=t.hostname;return i==="mdbase.dev"||i.endsWith(".mdbase.dev")||e!==null&&t.origin===e?t.href:null}catch{return null}}function Mo(n,e=null){try{if(nn(n))return n;if(typeof n!="object"||n===null||Array.isArray(n)||Object.getPrototypeOf(n)!==Object.prototype||Object.keys(n).sort().join(",")!==JT)return null;let t=n,i=t.status,o=t.retryAfterMs;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0||i>999||t.code!==null&&Ga(t.code)===null||t.reason!==null&&Ga(t.reason)===null||o!==null&&(typeof o!="number"||!Number.isFinite(o)||o<0)||t.updateUrl!==null&&typeof t.updateUrl!="string")return null;let s=Object.freeze({status:i,code:Ga(t.code),reason:Ga(t.reason),retryAfterMs:o===null?null:Vf(o),updateUrl:Ff(t.updateUrl,e)});return kw.add(s),s}catch{return null}}function vi(n,e,t=null,i=null){let o=e&&typeof e=="object"&&!Array.isArray(e)?e.error:void 0,s=o&&typeof o=="object"&&!Array.isArray(o)?o:null,r=s?.details&&typeof s.details=="object"&&!Array.isArray(s.details)?s.details:null,a=Object.freeze({status:Number.isSafeInteger(n)?n:0,code:Ga(s?.code),reason:Ga(r?.reason),retryAfterMs:YT(r,t),updateUrl:Ff(r?.update_url,i)});return kw.add(a),a}function Ot(n){if(!n)return null;let e=[n.reason,n.code];return n.status===429&&n.code==="account_collection_quota_exceeded"?"account_collection_quota_exceeded":e.includes("collection_not_yet_migrated")?"collection_not_yet_migrated":e.includes("collection_migrating")?"collection_migrating":e.includes("account_suspended")?"account_suspended":n.status===403&&n.code==="installation_private_device_not_allowed"?"private_device_not_allowed":e.some(t=>t==="moved_to_next_runtime"||t==="collection_moved"||t==="client_update_required")||n.status===426?"update_required":null}function Lo(n){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{return}}var WT,kw,Ya,Ja,HT,GT,cx,Ga,Vf,JT,ri=I(()=>{"use strict";WT=/^[a-z][a-z0-9_]{0,63}$/,kw=new WeakSet;Ya=5e3,Ja=6e5,HT=Ya,GT=Ja,cx="https://mdbase.dev/downloads/",Ga=n=>typeof n=="string"&&WT.test(n)?n:null,Vf=n=>Math.min(GT,Math.max(HT,Math.round(n)));JT="code,reason,retryAfterMs,status,updateUrl"});function Sw(n){if(typeof n!="string")return null;if(ux(n))return n;if(Object.hasOwn(Kf,n))return Kf[n];for(let e of["readiness_","application_"]){if(!n.startsWith(e))continue;let t=n.slice(e.length);if(e==="readiness_"&&Object.hasOwn(dx,t))return dx[t];if(ux(t))return t;if(Object.hasOwn(Kf,t))return Kf[t]}return null}function aM(n){let e=de(n.details,"availability");if(Ha(e))return e;let t=_i(n.availability)??(n.state==="unavailable"?n:null);return t&&t.state==="unavailable"&&Ha(t.reason)?t.reason:null}function Pw(n,e){let t=Zr(n);if(t)return{codes:[t],retryAfterMs:null,updateUrl:null};let i=_i(n);if(!i)return null;try{if(typeof i.kind=="string"&&"problem"in i&&_i(i.problem)&&typeof _i(i.problem).code=="string")return Pw(_i(i.problem).code,e);let o=_i(i.problemDetail),s=Mo(i.server??o?.server,e),r=[s?.reason??null,s?.code??null].filter(p=>p!==null),a={retryAfterMs:s?.retryAfterMs??sM(i.retryAfterMs),updateUrl:Ff(s?.updateUrl,e),hasServer:i.server!=null||o?.server!=null};if("problem"in i||"readiness"in i||"assessment"in i){let p=Zr(i.problem)??Zr(_i(i.problem)?.code);if(p)return{codes:[...r,p],...a,refusal:Es(o?.registration)};let d=_i(i.readiness)??i,u=_i(d.assessment),f=Zr(_i(d.problem)?.code)??Zr(_i(u?.problem)?.code);if(f)return{codes:[f],...a};let h=Zr(u?.status)??Zr(i.status);return h==="incompatible"||h==="setup_required"?{codes:[h],...a}:null}let c=aM(i);if(c)return{codes:[c==="approval_required"?"device_approval_required":c],...a};if("state"in i&&(i.state==="available"||i.state==="opening"))return null;let l=[...r,Zr(i.reason),Zr(i.code)].filter(p=>p!==null);return l.length?{codes:l,...a,refusal:Es(i.details??o?.registration)}:null}catch{return null}}function gx(n){let e=n.codes[n.codes.length-1];try{for(let t of n.codes){if(yx.has(t))return{key:null,original:e};let i=Sw(t);if(i)return{key:i,original:e}}}catch{}return{key:"unknown",original:e}}function qs(n,e={}){let t=typeof e.cpOrigin=="string"?e.cpOrigin:null,i=Pw(n,t);if(!i)return null;let{key:o,original:s}=gx(i);if(o===null)return null;let[r,a,c,l,p=!1,d]=o==="unknown"?hx:o==="refused"&&!i.hasServer?iM:mx[o],u;try{let b=e.messages;u=b&&Object.hasOwn(b,o)?_i(b[o]):void 0}catch{u=void 0}let f=(b,g)=>typeof b=="string"&&b.trim()?b:g,h=typeof e.recoveryAccountLabel=="string"&&e.recoveryAccountLabel.trim().length>0&&e.recoveryAccountLabel.length<=320&&!Array.from(e.recoveryAccountLabel).some(b=>b.charCodeAt(0)<32||b.charCodeAt(0)===127)?e.recoveryAccountLabel:null,m=o==="recovery_account_mismatch"&&h?`This collection belongs to ${h}. Sign in as ${h} to continue.`:a,w=o==="recovery_account_mismatch"&&h?`Sign in as ${h}`:d??XT[c];return Object.freeze({key:o,title:f(u?.title,r),message:f(u?.message,m),action:c,actionLabel:w===null?null:f(u?.actionLabel,w),severity:l,transient:p,code:s,developerMessage:bx(o,s,i.refusal??null),retryAfterMs:i.retryAfterMs,updateUrl:c==="update_app"?i.updateUrl??cx:null})}function bx(n,e,t){return n==="application_registration_refused"?sx(t):Object.hasOwn(Wf,n)?Wf[n]:n==="unknown"?`Problem code ${e} has no user-facing copy; it is shown as a generic error.`:null}function Hf(n,e={}){let t=Pw(n,typeof e.cpOrigin=="string"?e.cpOrigin:null);if(!t)return null;for(let s of t.codes)if(Object.hasOwn(Wf,s)&&yx.has(s))return Wf[s];let{key:i,original:o}=gx(t);return i===null?null:bx(i,o,t.refusal??null)}var XT,fx,hx,ZT,QT,eM,tM,px,nM,iM,mx,Kf,dx,rM,yx,Wf,oM,Zr,_i,sM,ux,Rp=I(()=>{"use strict";Bf();lx();To();un();ri();XT={retry:"Try again",wait:null,reload:"Reload",sign_in:"Sign in",approve:"Approve",choose_collection:"Choose a collection",set_up:"Set up",update_app:"Update the app",free_space:"Manage storage",check_connection:"Try again",resolve_outcome:"Check and try again",contact_support:"Contact support",none:null},fx=["device_offline","device_not_serving","desktop_update_required","old_connector_running","sync_required","no_device_registered","access_removed","read_only","capability_missing","collection_deleted","collection_unavailable","moved_to_next_runtime","device_approval_required","collection_migrating","collection_not_yet_migrated","account_suspended","update_required","account_collection_quota_exceeded","invalid_request","invalid_record","not_found","conflict","unauthenticated","forbidden","collection_invalid","unavailable","rate_limited","quota_exceeded","too_large","outcome_unknown","internal","refused","expired","approval_window_closed","account_confirmation_required","recovery_required","installation_removed","open_failed","device_keys_unavailable","busy","open_in_another_tab","not_authorized","sign_out_pending_writes","sign_out_failed","application_popup_blocked","sign_in_window","application_not_yet_available","application_failed","application_worker_unavailable","browser_unsupported","application_storage_unavailable","storage_may_be_evicted","application_registration_unsupported","application_registration_refused","application_selection_not_approved","application_selection_invalid","installation_scope_removed","recovery_account_mismatch","assets","setup_required","incompatible","approval_required","contract_mismatch","contract_missing","implementation_missing","catalog_invalid","catalog_response","type_invalid","readiness_budget","readiness_unsupported","notifications_consent_required","timer_channel_reapproval_required","notifications_unsupported","people_unsupported","people_permission_declined","people_access","history_unsupported","configuration_conflict","configuration_unavailable","configuration_unsupported","configuration_busy_timeout","readiness_busy_timeout","setup_forbidden","setup_conflict","setup_unresolved","collection_setup_conflict","collection_setup_namespace_conflict","setup_records_forbidden","setup_changed","installed_newer","type_pack_conflict","invalid_type_pack","access_required","access_declined","access_undeclared","files_access_missing","files_scope_missing","file_read_failed","file_read_idle","collection_delete_name_mismatch","collection_delete_not_owner","collection_delete_not_found","collection_delete_frozen","collection_delete_busy","collection_delete_not_approved","collection_delete_sign_in","collection_delete_invalid","collection_delete_outcome_unknown","collection_delete_failed","wrong_secret","locked","weak_password","already_set_up","no_account_key","invalid_recovery_key","unlock_strict","unlock_unavailable","unlock_failed","private_device_limit","private_device_not_allowed"],hx=["Something went wrong","An unexpected problem occurred. Reload the app, and contact support if it keeps happening.","reload","error"],ZT=["Another step hasn't finished","The app couldn't finish this step yet. Try again, or reload if it keeps happening.","retry","warning",!0],QT=["Can't complete this request","mdbase couldn't complete this request. Try again.","retry","warning"],eM=["Update required","Update mdbase on this computer, then reload the app to try again.","update_app","warning",!1,"Update mdbase"],tM=["Choose a collection","Pick the collection you want this app to use.","choose_collection","info"],px=["Approval needed","This app needs your approval for extra access to your collection.","approve","info"],nM=["Set up this collection","This collection needs a one-time setup before the app can use it.","set_up","info"],iM=["Sign-in wasn't finished","Access wasn't approved. Sign in again when you're ready.","sign_in","info"],mx={device_offline:["Your computer isn't online","This collection is kept on your computer. Open the mdbase desktop app on a computer that has it, and this app connects as soon as it's online.","wait","info",!0],device_not_serving:["Your computer can't open this collection","Your computer is online, but mdbase there isn't serving this collection right now. Open the mdbase desktop app on that computer to see why. This app connects as soon as it can.","wait","warning",!0],desktop_update_required:["Update mdbase on your computer","The mdbase desktop app on the computer that has this collection is out of date. Update it there, then try again.","update_app","warning",!1,"Get the update"],old_connector_running:["Quit the old mdbase Connect app","The old mdbase Connect app is still running on the computer that has this collection. Quit it there (including its menu-bar or tray icon), then open the mdbase desktop app.","retry","warning"],sync_required:["Give this app access again","Access to this collection changed since you approved this app. Approve it again to keep using the collection.","approve","warning",!1,"Approve again"],no_device_registered:["Turn on sync for this collection","No computer is offering this collection to apps. Open the mdbase desktop app on the computer that has it and turn on sync. Web apps can reach a collection once sync is on.","retry","info"],installation_scope_removed:["Access was removed","This app's previous installation cannot regain access to this collection. Request access again to approve a new installation for this collection.","approve","warning",!1,"Request access again"],access_removed:["You no longer have access","You were removed from this collection, so this app can't open it. Ask its owner to add you again, or choose another collection.","choose_collection","warning"],collection_deleted:["Collection deleted","This collection was deleted, so it can't be opened any more. Choose another collection.","choose_collection","info"],collection_unavailable:["Collection not available","This collection can't be opened from this app right now. It may no longer be shared with this app, or the computer that offered it stopped. Choose another collection, or try again later.","choose_collection","warning"],moved_to_next_runtime:["mdbase was upgraded","This collection now uses the new version of mdbase. Update the app to keep using it; for a web app, reloading the page is enough. If the collection still doesn't appear, open the mdbase desktop app and turn on sync for it so web apps can reach it.","update_app","warning"],device_approval_required:["Waiting for your computer","Keep a computer with this collection running mdbase and signed in. This app connects when it is ready.","wait","info",!0],collection_not_yet_migrated:["Your collection needs an upgrade","Your data is safe. Open the latest mdbase desktop app on the computer that keeps this collection to finish upgrading it, then try again.","retry","info"],collection_migrating:["Your collection is being upgraded","Your data is safe. This usually takes a few minutes, and the app reconnects by itself when it's done.","wait","info",!0],account_suspended:["Your account is suspended","Your mdbase account has been suspended, so this app can't open your collections. Contact mdbase support for help.","contact_support","error"],update_required:eM,invalid_request:["Couldn't do that","Some of the information isn't valid. Check it and try again.","none","warning"],invalid_record:["Couldn't save that","Some fields aren't valid. Check them and try again.","none","warning"],not_found:["Not found","This item no longer exists. It may have been deleted on another device.","none","info"],conflict:["Changed somewhere else","This item was changed on another device. Review the latest version and try again.","retry","warning"],unauthenticated:["Sign in again","Your session has ended. Sign in again to continue.","sign_in","warning"],read_only:["View access only","You have view access, so changes can't be saved. Ask the collection's owner for edit access.","none","warning"],forbidden:["Access needed","This app doesn't have permission to do that. Approve access to continue.","approve","warning"],collection_invalid:["Your collection needs repair","Something in this collection isn't valid. Contact support if this keeps happening.","contact_support","error"],unavailable:QT,rate_limited:["Too many requests","Wait a moment, then try again.","retry","warning",!0],quota_exceeded:["Out of storage","Storage for this collection is full. Free up space to keep saving. If it's your collection and you're on the Free plan, you can upgrade to Plus from your mdbase account page.","free_space","error"],account_collection_quota_exceeded:["Synced collection limit reached",ax,"free_space","error",!1,"Manage collections"],too_large:["That's too large","This item is larger than mdbase allows.","none","warning"],outcome_unknown:["Not sure that worked","The connection dropped before mdbase confirmed it. Check whether it went through before trying again.","resolve_outcome","warning"],internal:hx,refused:["Sign-in didn't go through","mdbase didn't accept this sign-in. Try signing in again.","sign_in","warning"],installation_removed:["This app's access was removed","Sign out of this app on this device, then sign in to approve a new installation.","none","warning"],expired:["Sign-in timed out","The sign-in request expired. Start again to get a new one.","sign_in","warning"],approval_window_closed:["Sign-in wasn't finished","The mdbase window was closed before access was approved. Sign in again to continue.","sign_in","info"],account_confirmation_required:["Confirm your account","Confirm which mdbase account to use, then continue.","sign_in","info"],recovery_account_mismatch:["Use a different account","Sign in with the account you originally used for this collection to continue.","approve","info",!1,"Use a different account"],recovery_required:["Reload required","The app stopped to keep your data safe. Reload to continue.","reload","error"],open_failed:["Couldn't open your collection","Something went wrong while opening it. Reload the app to try again.","reload","error"],device_keys_unavailable:["Couldn't read this device's sign-in","This browser couldn't open the keys this app uses to sign in to mdbase. Reload to try again. If it keeps happening, sign out of mdbase in this app and sign in again.","reload","error"],busy:ZT,file_read_failed:["Couldn't load the file","mdbase couldn't finish downloading this file. Check your connection and try opening the collection again.","retry","warning"],file_read_idle:["File download timed out","The file download stopped making progress. Try opening the collection again.","retry","warning"],configuration_busy_timeout:["Collection setup is taking too long","The app is waiting for another setup or metadata request to finish. Try again; if it keeps happening, close other tabs of this app and reload.","retry","warning"],readiness_busy_timeout:["Collection checks are taking too long","The app couldn't get a stable view of the collection yet. Try again when the other step has finished.","retry","warning"],open_in_another_tab:["Open in another tab","This app is already open in another tab. Close that tab, or keep using it there; this tab continues by itself when it's free.","none","info",!0],not_authorized:["This app can't open this collection","This app isn't allowed to open this collection. Approve it again, or choose another collection.","approve","warning",!1,"Approve again"],sign_out_pending_writes:["Changes are still saving","Some changes haven't reached mdbase yet. Wait for them to finish, or sign out anyway and lose them on this device.","wait","warning",!1,"Wait"],sign_out_failed:["Couldn't finish signing out","This device couldn't remove all of its sign-in data. Reload the app and sign out again.","reload","error"],application_popup_blocked:["Allow pop-ups to sign in","Your browser blocked the sign-in window. Allow pop-ups for this site, then try again.","retry","warning"],sign_in_window:["Sign-in window problem","The sign-in window couldn't be opened. Try again.","retry","warning"],application_not_yet_available:["Not available yet","This app isn't available on this version of mdbase yet.","none","info"],application_failed:["The app stopped","Something inside the app stopped working. Your data is safe. Reload to continue.","reload","error"],application_worker_unavailable:["This browser can't run the app","Open the app in a current version of Chrome, Edge, Firefox or Safari.","none","error"],browser_unsupported:["This browser can't run mdbase","Update Safari to 17.4 or newer, Firefox to 130 or newer, or Chrome or Edge to 133 or newer, then open the app again.","none","error"],application_storage_unavailable:["This browser can't keep mdbase data on this device","Private browsing may be on. Open the app in a regular window so your changes can be kept safely on this device.","none","error"],storage_may_be_evicted:["Not synced yet","Some changes are only on this device. Stay online so they can sync.","check_connection","warning"],application_registration_unsupported:["This app can't connect","This version of the app isn't supported by mdbase. Update the app.","update_app","error"],application_registration_refused:["This app can't connect","This app can't connect right now. Contact the app's developer.","contact_support","error"],application_selection_not_approved:["Collection not approved","This app hasn't been given access to that collection. Approve it to continue.","approve","info"],application_selection_invalid:tM,assets:["The app couldn't load","Some of the app's files couldn't be loaded. Check your connection and reload.","reload","error"],setup_required:nM,incompatible:["This collection isn't compatible","This collection uses a format this version of the app doesn't support. Update the app.","update_app","error"],approval_required:px,capability_missing:px,contract_mismatch:["Your collection's format differs","This collection's record types don't match what this app expects. Set it up again or update the app.","set_up","warning"],contract_missing:["Set up this collection","This collection is missing record types this app needs. Set it up to continue.","set_up","info"],implementation_missing:["Set up this collection","A record type in this collection doesn't provide the fields this app needs. Set it up to continue.","set_up","info"],catalog_invalid:["A definition has a problem","A definition in this collection has an error, so the app can't open the collection safely. Fix the definition in your collection, and the app picks up the change.","none","warning"],catalog_response:["Couldn't read this collection's definitions","The app couldn't read how this collection is defined, so it didn't open it. Nothing was changed. Try again.","retry","warning"],type_invalid:["A record type isn't available","This record type has an error in its definition, so the app can't use it right now. Everything else still works. Fix the type in your collection to use it again.","none","warning"],readiness_budget:["This collection is too large to check","This collection has more definitions than the app can check at once. Contact the app's developer.","contact_support","warning"],readiness_unsupported:["Update the app","This collection uses features this version of the app can't check. Update the app to open it.","update_app","warning"],notifications_consent_required:["Allow reminders","Approve notifications so reminders can reach this device.","approve","info"],timer_channel_reapproval_required:["Allow reminders again","Approve notifications again so reminders keep reaching this device.","approve","info"],notifications_unsupported:["Reminders aren't available here","This browser or device can't receive notifications.","none","info"],people_unsupported:["Sharing isn't available here","People and sharing aren't supported for this collection yet.","none","info"],people_permission_declined:["People aren't shown","This app wasn't allowed to see who else is in this collection. Approve it again and allow people to show them here.","approve","info",!1,"Approve again"],people_access:["People can't be shown","This app can't see the people in this collection right now. Everything else still works.","none","info"],history_unsupported:["History isn't available here","Earlier versions of records in this collection can't be read here. Everything else still works.","none","info"],configuration_conflict:["Settings changed elsewhere","These settings were changed on another device. Review them and try again.","retry","warning"],configuration_unavailable:["Couldn't check this collection's setup","The app couldn't read how this collection is set up, so it didn't open it. Nothing in the collection was changed. Try again, and contact support if it keeps happening.","retry","warning"],configuration_unsupported:["This app can't set up this collection","This app's setup isn't supported by this version of mdbase. Contact the app's developer.","contact_support","warning"],setup_forbidden:["You can't set up this collection","Your access to this collection doesn't allow setting it up. Ask its owner to open it in this app first.","choose_collection","warning"],setup_conflict:["Setup needs your decision","Some things in this collection differ from what this app needs. Review them to continue.","set_up","warning",!1,"Review setup"],setup_unresolved:["Setup can't finish","This collection is missing a note format this app needs. Add or update a note type that supports that format, then try setup again.","retry","warning"],collection_setup_conflict:["Collection setup conflicts","Setting up this app would conflict with definitions already in this collection, so nothing was changed. A note type may have been renamed or customised and still use an older definition. Update or remove it, then try again.","retry","warning"],collection_setup_namespace_conflict:["A file is in the way","A file in this collection is stored where this app needs to save part of its setup, and its contents differ. Move or rename that file, then try again. Nothing was changed.","retry","warning"],setup_records_forbidden:["You can't add notes to this collection","Your access to this collection doesn't allow creating notes, which this app's setup needs. Ask its owner for more access.","choose_collection","warning"],setup_changed:["This collection changed","The collection changed while you were reviewing its setup. Review the setup again; nothing was changed yet.","set_up","info",!1,"Review again"],installed_newer:["Update the app","A newer version of this app set up this collection with changes this version can't use. Update the app to keep using the collection.","update_app","warning"],type_pack_conflict:["Setup needs your decision","Some record types already exist with different content. Review them to continue.","set_up","warning",!1,"Review setup"],invalid_type_pack:["This app's setup has a problem","Setting up this collection would leave it invalid, so nothing was changed. Contact the app's developer.","contact_support","warning"],access_required:["Allow this app to change files?","This app needs your permission before it can add or change files in this collection.","approve","info",!1,"Allow"],access_declined:["Not allowed","You chose not to allow this. Everything else in the app works as before, and you can allow it the next time you try.","none","info"],access_undeclared:["This app can't do that","This app isn't set up to change files this way. Contact the app's developer if you need it.","none","warning"],files_access_missing:["This app can't use this collection","Your access to this collection doesn't include the file changes this app needs. Ask the collection's owner for more access.","none","warning"],files_scope_missing:["This app can't use this collection","This app needs access to all files in this collection, but your access covers only some folders. Ask the collection's owner for more access.","none","warning"],collection_delete_name_mismatch:["The name doesn't match","Type the collection's current name exactly to delete it.","none","warning"],collection_delete_not_owner:["Only the owner can delete this","Ask the collection's owner to delete it.","none","info"],collection_delete_not_found:["Collection not found","This collection no longer exists, or this app can't reach it. It may already have been deleted.","none","info"],collection_delete_frozen:["Can't delete right now","Your account is being upgraded, so collections can't be deleted until that finishes. Try again later.","retry","warning"],collection_delete_busy:["mdbase is busy","Wait a moment, then try deleting again.","retry","warning",!0],collection_delete_not_approved:["This app can't delete this collection","This app doesn't have access to this collection anymore. Approve it again, then try again.","approve","warning"],collection_delete_sign_in:["Sign in again","This device's sign-in is no longer current. Sign in again, then try deleting again.","sign_in","warning"],collection_delete_invalid:["Couldn't delete the collection","Check the name you typed and try again.","none","warning"],collection_delete_outcome_unknown:["Not sure the collection was deleted","The connection dropped before mdbase confirmed. Reload your collections to check before trying again.","resolve_outcome","warning"],collection_delete_failed:["Couldn't delete the collection","Something went wrong. Try again, and contact support if it keeps happening.","retry","error"],wrong_secret:["That isn't right","The password or recovery key doesn't match. Check it and try again.","none","warning"],locked:["Too many attempts","Wait a few minutes before trying again.","wait","warning",!0],weak_password:["Choose a stronger password","That password is too easy to guess. Use a longer one, or a few unrelated words.","none","warning"],already_set_up:["Already set up","Your account key is already set up on this account.","none","info"],no_account_key:["Set up your account key","This account doesn't have an account key yet. Set one up to use Private collections.","none","info"],invalid_recovery_key:["Check the recovery key","That doesn't look like a recovery key. Check for missing or mistyped characters and try again.","none","warning"],unlock_strict:["Can't be unlocked here","This account approves each device from another device instead of using an encryption password, and this app can't do that yet. Use the mdbase desktop app on a computer that has this collection.","none","info"],unlock_unavailable:["This app can't unlock yet","This version of the app can't unlock Private collections. Update the app, then try again.","update_app","warning"],unlock_failed:["Couldn't unlock this collection","Your password or recovery key is right, but this collection didn't give this device its key. Try again. If it keeps happening, open the mdbase desktop app on a computer that has this collection.","retry","warning"],private_device_limit:["One Private collection per app","This app already keeps another Private collection on this device, and it can keep only one. Open that collection, or sign out of mdbase in this app to switch.","choose_collection","warning"],private_device_not_allowed:["This app can't keep this collection","Access to this Private collection can't be restored in this app on this server. Open it in the mdbase desktop app on a computer that has it.","none","warning"]},Kf=Object.assign(Object.create(null),{no_device_online:"device_offline",not_served:"device_not_serving",collection_moved:"moved_to_next_runtime",client_update_required:"update_required",upgrade_required:"update_required",declared_setup_unsupported:"update_required",resource_setup_unsupported:"update_required",type_packs_unsupported:"update_required",describe_definitions_unsupported:"update_required",contract_records_unsupported:"update_required",record_links_unsupported:"update_required",backlinks_unsupported:"update_required",resolve_links_unsupported:"update_required",change_entity_unsupported:"update_required",timer_operation_recovery_unavailable:"update_required",contract_query_version:"update_required",contract_query_order_unsupported:"update_required",contract_query_order_mtime_unsupported:"update_required",bases_row_properties_unsupported:"update_required",unsupported_push_version:"update_required",fenced:"busy",reconnecting:"busy",application_busy:"busy",application_fenced:"busy",application_entry_fenced:"busy",application_asset_fenced:"busy",application_connection_busy:"busy",application_connection_fenced:"busy",application_readiness_busy:"busy",application_readiness_fenced:"busy",application_registration_fenced:"busy",application_selection_busy:"busy",application_selection_fenced:"busy",application_worker_busy:"busy",application_worker_fenced:"busy",application_popup_fenced:"busy",readiness_fenced:"busy",readiness_busy:"busy",readiness_changed:"busy",configuration_busy:"busy",configuration_fenced:"busy",files_fenced:"busy",people_fenced:"busy",people_readiness_busy:"busy",people_readiness_fenced:"busy",notification_readiness_busy:"busy",notification_readiness_fenced:"busy",record_links_fenced:"busy",binding:"application_failed",response:"application_failed",application_declaration:"application_failed",application_connection_binding:"application_failed",application_popup_binding:"application_failed",application_registration_response:"application_failed",application_selection_binding:"application_failed",application_worker_binding:"application_failed",application_worker_module_binding:"application_failed",application_entry_unavailable:"application_failed",application_readiness_unavailable:"application_failed",configuration_binding:"application_failed",configuration_response:"application_failed",files_unavailable:"application_failed",application_stop_failed:"recovery_required",application_worker_stop_failed:"recovery_required",application_popup_stop_failed:"recovery_required",configuration_recovery_required:"recovery_required",application_popup_unavailable:"sign_in_window",application_registration_unavailable:"unavailable",application_registration_unknown:"unavailable",application_connection_unavailable:"unavailable",readiness_unavailable:"unavailable",grant_activation_timeout:"unavailable",relay_closed:"unavailable",pipe_closed:"unavailable",authorization_unavailable:"unavailable",grant_lease_expired:"unavailable",grant_inactive:"forbidden",connector_busy:"rate_limited",application_connection_people_unavailable:"people_access",people_unavailable:"people_access",people_response:"people_access",people_binding:"people_access",people_budget:"people_access",people_incomplete:"people_access",application_selection_empty:"application_selection_invalid",application_selection_duplicate:"application_selection_invalid",application_selection_metadata:"application_selection_invalid",application_lab_trust_unavailable:"assets",application_production_trust_unavailable:"assets",application_release_trust_unavailable:"assets",application_packaged_assets_unavailable:"assets",application_asset_fetch:"assets",grant_required:"approval_required",readiness_capability_version:"readiness_unsupported",readiness_type_invalid:"type_invalid",configuration_not_authorized:"setup_forbidden",configuration_unsupported_source_provision:"configuration_unsupported",setup_downgrade:"installed_newer",type_pack_downgrade:"installed_newer",installed_newer_major:"installed_newer",timer_push_platform:"notifications_unsupported",push_registration_missing:"notifications_consent_required"}),dx=Object.assign(Object.create(null),{budget:"readiness_budget",unsupported:"readiness_unsupported"}),rM=["application_registration_id_superseded","application_closing","cancelled","aborted"],yx=new Set(rM),Wf=Object.assign(Object.create(null),{device_offline:"Collection availability device_offline: no device serving this Private collection is connected to the relay.",device_not_serving:"Collection availability device_not_serving / relay close not_served: the device is online but is not serving this Private collection right now (paused, opening, recovering, failed, or removed on that computer). Check the collection's status in mdbase on that computer; connect with waitForDevice keeps retrying.",desktop_update_required:"Collection availability desktop_update_required: the serving device's last relay connection was refused as incompatible.",old_connector_running:"Collection availability old_connector_running: the serving device reports a legacy connector still holding its collections.",device_approval_required:"Collection availability approval_required: no device has signed an approval for this app's grant yet.",sync_required:"Collection availability sync_required: the grant no longer matches the collection's membership; run authorize() again.",no_device_registered:"Collection availability no_device_registered: Connect has no device that can serve this collection (none registered with sync on, or its device was revoked).",installation_scope_removed:"The original installation lost this collection scope. Only explicit approval of a fresh scoped installation can regain access.",private_device_not_allowed:"Connect refused a recovery sign-in's Private device access (403 installation_private_device_not_allowed): MDBASE_NEXT_PRIVATE_APP_DEVICES is off, or the registered manifest does not declare offline.replica.",access_removed:"Collection availability access_removed: the grant's account is no longer a member of the collection.",collection_deleted:"Collection availability collection_deleted: the owner deleted the collection.",collection_unavailable:"Connect problem collection_unavailable without a known reason: the collection is not offered to this app or client.",moved_to_next_runtime:"Connect problem collection_unavailable, reason moved_to_next_runtime: a legacy route was used for a collection that completed its move to mdbase-next.",people_permission_declined:"People members request refused (people_permission_declined): the person did not grant the people permission for this app.",people_access:"People request refused (people_access).",access_required:"access_required: an optional file action the person has not allowed. Call requestAccess from the user's action, then retry.",access_undeclared:"access_undeclared: the file action is not in the manifest's requirements.files.",installed_newer:"installed_newer: an installed type pack has a different major version than the one this app ships; same-major newer packs open read/write.",application_registration_id_superseded:"The declared application ID is an earlier registration ID: mdbase registers each exact manifest under its own ID, so it changes with the manifest. The SDK uses the registered ID and keeps the declared storage names. Declare the manifest's logical `id` (stable across manifest changes and origins) with pinned storage names to remove this note.",application_worker_unavailable:"application_worker_unavailable: this page cannot construct the SDK's module Worker (no Worker/MessageChannel, or a non-web origin).",browser_unsupported:"browser_unsupported: the SDK's upfront capability probe found a required browser feature missing (Web Crypto/X25519, AbortSignal.any, Web Locks, BroadcastChannel, IndexedDB, Worker/MessageChannel or crypto.randomUUID); see the MdbaseError details for the missing tokens.",application_storage_unavailable:"application_storage_unavailable: navigator.storage.getDirectory() (OPFS) is absent or rejected, as in private browsing; the local replica cannot be kept on this device.",storage_may_be_evicted:"storage_may_be_evicted: replica edits are pending for at least 30 seconds or while disconnected on nonpersistent storage (`storage_may_be_evicted` in snapshot.sync.attention); only a log-confirmed receipt counts as saved.",device_keys_unavailable:"device_keys_unavailable: this installation's device custody in IndexedDB (key encryption key, device keys or Noise vault) could not be opened or did not hold the attested device. Before attestation the SDK recreates it by itself; after attestation only signOut() and a fresh sign-in replace it.",sign_out_pending_writes:"sign_out_pending_writes: unconfirmed writes are still queued on this device; signOut({discard: true}) discards them."}),oM=/^[a-z][a-z0-9_-]{0,127}$/,Zr=n=>typeof n=="string"&&oM.test(n)?n:null,_i=n=>n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null,sM=n=>typeof n=="number"&&Number.isFinite(n)&&n>=0?Math.min(Ja,Math.max(Ya,Math.round(n))):null,ux=n=>Object.hasOwn(mx,n)});function Xa(n){if(typeof n!="string"||n.length>256)return null;let e=lM.exec(n.trim());if(!e)return null;let t=[e[1],e[2],e[3]].map(Number);if(t.some(o=>!Number.isSafeInteger(o)))return null;let i=e[4]?e[4].split(".").map(o=>/^\d+$/.test(o)?Number(o):o):[];return i.some(o=>typeof o=="number"&&!Number.isSafeInteger(o))?null:Object.freeze({major:t[0],minor:t[1],patch:t[2],prerelease:Object.freeze(i)})}function xw(n,e){let t=typeof n=="string"?Xa(n):n,i=typeof e=="string"?Xa(e):e;if(!t||!i)return null;for(let o of["major","minor","patch"])if(t[o]!==i[o])return t[o]<i[o]?-1:1;if(!t.prerelease.length&&!i.prerelease.length)return 0;if(!t.prerelease.length)return 1;if(!i.prerelease.length)return-1;for(let o=0;o<Math.max(t.prerelease.length,i.prerelease.length);o++){let s=t.prerelease[o],r=i.prerelease[o];if(s===void 0)return-1;if(r===void 0)return 1;if(s!==r)return typeof s=="number"&&typeof r=="number"?s<r?-1:1:typeof s=="number"?-1:typeof r=="number"?1:s<r?-1:1}return 0}function Ts(n,e){let t=Xa(n),i=Xa(e),o=t&&i?xw(t,i):null;return o===null?"unknown":o===0?"same":o<0?"installed_older":t.major===i.major?"installed_newer":"installed_newer_major"}var Gf,wx,lM,Yf=I(()=>{"use strict";Gf="0|[1-9]\\d*",wx=`(?:${Gf}|\\d*[a-zA-Z-][0-9a-zA-Z-]*)`,lM=new RegExp(`^v?(${Gf})\\.(${Gf})\\.(${Gf})(?:-(${wx}(?:\\.${wx})*))?(?:\\+[0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*)?$`)});function Zf(n){return n.storage.applicationNamespace===n.id?null:n.storage.applicationNamespace}function Cw(n){return Array.from(Ze(new TextEncoder().encode(n)),e=>e.toString(16).padStart(2,"0")).join("")}function _x(n,e){return e===null?`bundle:${n}`:`bundle-storage:${Cw(JSON.stringify([n,e]))}`}var Qf=I(()=>{"use strict";hr()});function He(n){if(n&&typeof n=="object")switch(n[On]){case Ki:case eo:return!0}return!1}function je(n){if(n&&typeof n=="object")switch(n[On]){case eh:case Ki:case oi:case eo:return!0}return!1}var eh,th,Ki,Iw,oi,eo,On,Wi,br,si,qe,Ae,Hi,nh,Ne=I(()=>{eh=Symbol.for("yaml.alias"),th=Symbol.for("yaml.document"),Ki=Symbol.for("yaml.map"),Iw=Symbol.for("yaml.pair"),oi=Symbol.for("yaml.scalar"),eo=Symbol.for("yaml.seq"),On=Symbol.for("yaml.node.type"),Wi=n=>!!n&&typeof n=="object"&&n[On]===eh,br=n=>!!n&&typeof n=="object"&&n[On]===th,si=n=>!!n&&typeof n=="object"&&n[On]===Ki,qe=n=>!!n&&typeof n=="object"&&n[On]===Iw,Ae=n=>!!n&&typeof n=="object"&&n[On]===oi,Hi=n=>!!n&&typeof n=="object"&&n[On]===eo;nh=n=>(Ae(n)||He(n))&&!!n.anchor});function vr(n,e){let t=kx(e);br(n)?Za(null,n.contents,t,Object.freeze([n]))===wr&&(n.contents=null):Za(null,n,t,Object.freeze([]))}function Za(n,e,t,i){let o=Sx(n,e,t,i);if(je(o)||qe(o))return Px(n,i,o),Za(n,o,t,i);if(typeof o!="symbol"){if(He(e)){i=Object.freeze(i.concat(e));for(let s=0;s<e.items.length;++s){let r=Za(s,e.items[s],t,i);if(typeof r=="number")s=r-1;else{if(r===Kn)return Kn;r===wr&&(e.items.splice(s,1),s-=1)}}}else if(qe(e)){i=Object.freeze(i.concat(e));let s=Za("key",e.key,t,i);if(s===Kn)return Kn;s===wr&&(e.key=null);let r=Za("value",e.value,t,i);if(r===Kn)return Kn;r===wr&&(e.value=null)}}return o}async function ih(n,e){let t=kx(e);br(n)?await Qa(null,n.contents,t,Object.freeze([n]))===wr&&(n.contents=null):await Qa(null,n,t,Object.freeze([]))}async function Qa(n,e,t,i){let o=await Sx(n,e,t,i);if(je(o)||qe(o))return Px(n,i,o),Qa(n,o,t,i);if(typeof o!="symbol"){if(He(e)){i=Object.freeze(i.concat(e));for(let s=0;s<e.items.length;++s){let r=await Qa(s,e.items[s],t,i);if(typeof r=="number")s=r-1;else{if(r===Kn)return Kn;r===wr&&(e.items.splice(s,1),s-=1)}}}else if(qe(e)){i=Object.freeze(i.concat(e));let s=await Qa("key",e.key,t,i);if(s===Kn)return Kn;s===wr&&(e.key=null);let r=await Qa("value",e.value,t,i);if(r===Kn)return Kn;r===wr&&(e.value=null)}}return o}function kx(n){return typeof n=="object"&&(n.Collection||n.Node||n.Value)?Object.assign({Alias:n.Node,Map:n.Node,Scalar:n.Node,Seq:n.Node},n.Value&&{Map:n.Value,Scalar:n.Value,Seq:n.Value},n.Collection&&{Map:n.Collection,Seq:n.Collection},n):n}function Sx(n,e,t,i){if(typeof t=="function")return t(n,e,i);if(si(e))return t.Map?.(n,e,i);if(Hi(e))return t.Seq?.(n,e,i);if(qe(e))return t.Pair?.(n,e,i);if(Ae(e))return t.Scalar?.(n,e,i);if(Wi(e))return t.Alias?.(n,e,i)}function Px(n,e,t){let i=e[e.length-1];if(He(i))i.items[n]=t;else if(qe(i))n==="key"?i.key=t:i.value=t;else if(br(i))i.contents=t;else{let o=Wi(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var Kn,Ax,wr,qp=I(()=>{Ne();Kn=Symbol("break visit"),Ax=Symbol("skip children"),wr=Symbol("remove node");vr.BREAK=Kn;vr.SKIP=Ax;vr.REMOVE=wr;ih.BREAK=Kn;ih.SKIP=Ax;ih.REMOVE=wr});var dM,uM,_r,Ow=I(()=>{Ne();qp();dM={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},uM=n=>n.replace(/[!,[\]{}]/g,e=>dM[e]),_r=class n{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},n.defaultYaml,e),this.tags=Object.assign({},n.defaultTags,t)}clone(){let e=new n(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new n(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:n.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},n.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:n.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},n.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),o=i.shift();switch(o){case"%TAG":{if(i.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[s,r]=i;return this.tags[s]=r,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[s]=i;if(s==="1.1"||s==="1.2")return this.yaml.version=s,!0;{let r=/^\d+\.\d+$/.test(s);return t(6,`Unsupported YAML version ${s}`,r),!1}}default:return t(0,`Unknown directive ${o}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let r=e.slice(2,-1);return r==="!"||r==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),r)}let[,i,o]=e.match(/^(.*!)([^!]*)$/s);o||t(`The ${e} tag has no suffix`);let s=this.tags[i];if(s)try{return s+decodeURIComponent(o)}catch(r){return t(String(r)),null}return i==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,i]of Object.entries(this.tags))if(e.startsWith(i))return t+uM(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),o;if(e&&i.length>0&&je(e.contents)){let s={};vr(e.contents,(r,a)=>{je(a)&&a.tag&&(s[a.tag]=!0)}),o=Object.keys(s)}else o=[];for(let[s,r]of i)s==="!!"&&r==="tag:yaml.org,2002:"||(!e||o.some(a=>a.startsWith(r)))&&t.push(`%TAG ${s} ${r}`);return t.join(`
2
2
  `)}};_r.defaultYaml={explicit:!1,version:"1.2"};_r.defaultTags={"!!":"tag:yaml.org,2002:"}});function rh(n){if(/[\x00-\x19\s,[\]{}]/.test(n)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(n)}`;throw new Error(t)}return!0}function Rw(n){let e=new Set;return vr(n,{Value(t,i){i.anchor&&e.add(i.anchor)}}),e}function Ew(n,e){for(let t=1;;++t){let i=`${n}${t}`;if(!e.has(i))return i}}function xx(n,e){let t=[],i=new Map,o=null;return{onAnchor:s=>{t.push(s),o??(o=Rw(n));let r=Ew(e,o);return o.add(r),r},setAnchors:()=>{for(let s of t){let r=i.get(s);if(typeof r=="object"&&r.anchor&&(Ae(r.node)||He(r.node)))r.node.anchor=r.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=s,a}}},sourceObjects:i}}var oh=I(()=>{Ne();qp()});function jo(n,e,t,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let o=0,s=i.length;o<s;++o){let r=i[o],a=jo(n,i,String(o),r);a===void 0?delete i[o]:a!==r&&(i[o]=a)}else if(i instanceof Map)for(let o of Array.from(i.keys())){let s=i.get(o),r=jo(n,i,o,s);r===void 0?i.delete(o):r!==s&&i.set(o,r)}else if(i instanceof Set)for(let o of Array.from(i)){let s=jo(n,i,o,o);s===void 0?i.delete(o):s!==o&&(i.delete(o),i.add(s))}else for(let[o,s]of Object.entries(i)){let r=jo(n,i,o,s);r===void 0?delete i[o]:r!==s&&(i[o]=r)}return n.call(e,t,i)}var qw=I(()=>{});function zt(n,e,t){if(Array.isArray(n))return n.map((i,o)=>zt(i,String(o),t));if(n&&typeof n.toJSON=="function"){if(!t||!nh(n))return n.toJSON(e,t);let i={aliasCount:0,count:1,res:void 0};t.anchors.set(n,i),t.onCreate=s=>{i.res=s,delete t.onCreate};let o=n.toJSON(e,t);return t.onCreate&&t.onCreate(o),o}return typeof n=="bigint"&&!t?.keep?Number(n):n}var Uo=I(()=>{Ne()});var No,sh=I(()=>{qw();Ne();Uo();No=class{constructor(e){Object.defineProperty(this,On,{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:i,onAnchor:o,reviver:s}={}){if(!br(e))throw new TypeError("A document argument is required");let r={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=zt(this,"",r);if(typeof o=="function")for(let{count:c,res:l}of r.anchors.values())o(l,c);return typeof s=="function"?jo(s,{"":a},"",a):a}}});function ah(n,e,t){if(Wi(e)){let i=e.resolve(n),o=t&&i&&t.get(i);return o?o.count*o.aliasCount:0}else if(He(e)){let i=0;for(let o of e.items){let s=ah(n,o,t);s>i&&(i=s)}return i}else if(qe(e)){let i=ah(n,e.key,t),o=ah(n,e.value,t);return Math.max(i,o)}return 1}var to,Tp=I(()=>{oh();qp();Ne();sh();Uo();to=class extends No{constructor(e){super(eh),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 i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],vr(e,{Node:(s,r)=>{(Wi(r)||nh(r))&&i.push(r)}}),t&&(t.aliasResolveCache=i));let o;for(let s of i){if(s===this)break;s.anchor===this.source&&(o=s)}if(o&&t){let{anchors:s,doc:r,maxAliasCount:a}=t,c=s.get(o);if(c||(zt(o,null,t),c=s.get(o)),c?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(c.count+=1,c.aliasCount===0&&(c.aliasCount=ah(r,o,s)),c.count*c.aliasCount>a)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}}return o}toJSON(e,t){if(!t)return{source:this.source};let i=this.resolve(t.doc,t);if(!i){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(o)}return t.anchors.get(i).res}toString(e,t,i){let o=`*${this.source}`;if(e){if(rh(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`${o} `}return o}}});var lh,le,Mt=I(()=>{Ne();sh();Uo();lh=n=>!n||typeof n!="function"&&typeof n!="object",le=class extends No{constructor(e){super(oi),this.value=e}toJSON(e,t){return t?.keep?this.value:zt(this.value,e,t)}toString(){return String(this.value)}};le.BLOCK_FOLDED="BLOCK_FOLDED";le.BLOCK_LITERAL="BLOCK_LITERAL";le.PLAIN="PLAIN";le.QUOTE_DOUBLE="QUOTE_DOUBLE";le.QUOTE_SINGLE="QUOTE_SINGLE"});function hM(n,e,t){if(e){let i=t.filter(s=>s.tag===e),o=i.find(s=>!s.format)??i[0];if(!o)throw new Error(`Tag ${e} not found`);return o}return t.find(i=>i.identify?.(n)&&!i.format)}function no(n,e,t){if(br(n)&&(n=n.contents),je(n))return n;if(qe(n)){let d=t.schema[Ki].createNode?.(t.schema,null,t);return d.items.push(n),d}(n instanceof String||n instanceof Number||n instanceof Boolean||typeof BigInt<"u"&&n instanceof BigInt)&&(n=n.valueOf());let{aliasDuplicateObjects:i,onAnchor:o,onTagObj:s,schema:r,sourceObjects:a}=t,c;if(i&&n&&typeof n=="object"){if(c=a.get(n),c)return c.anchor??(c.anchor=o(n)),new to(c.anchor);c={anchor:null,node:null},a.set(n,c)}e?.startsWith("!!")&&(e=fM+e.slice(2));let l=hM(n,e,r.tags);if(!l){if(n&&typeof n.toJSON=="function"&&(n=n.toJSON()),!n||typeof n!="object"){let d=new le(n);return c&&(c.node=d),d}l=n instanceof Map?r[Ki]:Symbol.iterator in Object(n)?r[eo]:r[Ki]}s&&(s(l),delete t.onTagObj);let p=l?.createNode?l.createNode(t.schema,n,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,n,t):new le(n);return e?p.tag=e:l.default||(p.tag=l.tag),c&&(c.node=p),p}var fM,Mp=I(()=>{Tp();Ne();Mt();fM="tag:yaml.org,2002:"});function Lp(n,e,t){let i=t;for(let o=e.length-1;o>=0;--o){let s=e[o];if(typeof s=="number"&&Number.isInteger(s)&&s>=0){let r=[];r[s]=i,i=r}else i=new Map([[s,i]])}return no(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:n,sourceObjects:new Map})}var tl,el,ch=I(()=>{Mp();Ne();sh();tl=n=>n==null||typeof n=="object"&&!!n[Symbol.iterator]().next().done,el=class extends No{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(i=>je(i)||qe(i)?i.clone(e):i),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(tl(e))this.add(t);else{let[i,...o]=e,s=this.get(i,!0);if(He(s))s.addIn(o,t);else if(s===void 0&&this.schema)this.set(i,Lp(this.schema,o,t));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${o}`)}}deleteIn(e){let[t,...i]=e;if(i.length===0)return this.delete(t);let o=this.get(t,!0);if(He(o))return o.deleteIn(i);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${i}`)}getIn(e,t){let[i,...o]=e,s=this.get(i,!0);return o.length===0?!t&&Ae(s)?s.value:s:He(s)?s.getIn(o,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!qe(t))return!1;let i=t.value;return i==null||e&&Ae(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[t,...i]=e;if(i.length===0)return this.has(t);let o=this.get(t,!0);return He(o)?o.hasIn(i):!1}setIn(e,t){let[i,...o]=e;if(o.length===0)this.set(i,t);else{let s=this.get(i,!0);if(He(s))s.setIn(o,t);else if(s===void 0&&this.schema)this.set(i,Lp(this.schema,o,t));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${o}`)}}}});function Ai(n,e){return/^\n+$/.test(n)?n.substring(1):e?n.replace(/^(?! *$)/gm,e):n}var Cx,Ar,jp=I(()=>{Cx=n=>n.replace(/^(?!$)(?: $)?/gm,"#");Ar=(n,e,t)=>n.endsWith(`
3
3
  `)?Ai(t,e):t.includes(`
4
4
  `)?`