@mdbase-dev/sdk 0.1.0-beta.158 → 0.1.0-beta.159
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -6
- package/dist/app-host/web-sign-in-session.js +2 -2
- package/dist/app-host/web-sign-in-session.js.map +1 -1
- package/dist/application/asset-pins.json +4 -4
- package/dist/application/entry.js +10 -1
- package/dist/application/entry.js.map +1 -1
- package/dist/application/worker.js +9 -6
- package/dist/browser/mdbase-sdk.js +24 -13
- package/dist/browser/mdbase-sdk.min.js +2 -2
- package/dist/client.js +3 -0
- package/dist/client.js.map +1 -1
- package/dist/describe-error.d.ts +1 -1
- package/dist/describe-error.js +3 -3
- package/dist/describe-error.js.map +1 -1
- package/dist/native/provenance.json +5 -5
- package/dist/native/runtime.wasm +0 -0
- package/dist/thin-client.d.ts +2 -2
- package/dist/thin-client.js +2 -2
- package/package.json +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var MdbaseSDK=(()=>{var Qh=Object.defineProperty;var MI=Object.getOwnPropertyDescriptor;var LI=Object.getOwnPropertyNames;var jI=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 ls=(n,e)=>{for(var t in e)Qh(n,t,{get:e[t],enumerable:!0})},NI=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of LI(e))!jI.call(n,o)&&o!==t&&Qh(n,o,{get:()=>e[o],enumerable:!(i=MI(e,o))||i.enumerable});return n};var UI=n=>NI(Qh({},"__esModule",{value:!0}),n);function FI(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 nv(n,e){let t=typeof e=="bigint"?e:BigInt(e);if(t>=0n){if(t>DI)throw new Ie("unencodable","integer above 2^64-1");n.head(0,typeof e=="number"?e:t)}else{if(t<$I)throw new Ie("unencodable","integer below -2^63");let i=-1n-t;n.head(1,i<=BigInt(Number.MAX_SAFE_INTEGER)?Number(i):i)}}function VI(n,e,t){let i=[...e.entries()];rv(i.map(([o])=>o)),n.head(5,i.length);for(let[o,s]of i)typeof o=="number"?n.head(0,o):iv(n,o),vp(n,s,t+1)}function iv(n,e){if(!FI(e))throw new Ie("utf8","text is not well-formed UTF-16");let t=zI.encode(e);try{n.head(3,t.length),n.bytes(t)}finally{n.wipeTemporary(t)}}function rv(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 Ie("mixed_map_keys");if(t.has(i))throw new Ie("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 Ie("mixed_map_keys");if(typeof t=="number"&&!(Number.isSafeInteger(t)&&t>=0))throw new Ie("mixed_map_keys","struct map keys must be unsigned integers");let i=BigInt(t);if(i<0n)throw new Ie("mixed_map_keys");if(e!==void 0&&e>=i)throw new Ie("unsorted_keys");e=i}}function vp(n,e,t){if(t>tm)throw new Ie("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)?nv(n,e):n.float(e);case"bigint":return nv(n,e);case"string":return iv(n,e)}if(e instanceof yt)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)vp(n,i,t+1);return}if(e instanceof Map)return VI(n,e,t);throw new Ie("unencodable",`cannot encode ${Object.prototype.toString.call(e)}`)}function pe(n){let e=new wp;return vp(e,n,0),e.result()}function qn(n){let e=new wp(!0);try{return vp(e,n,0),e.result()}finally{e.buf.fill(0)}}function ue(n){let e=new em(n),t=e.item(0);if(e.remaining!==0)throw new Ie("trailing_bytes");return t}function KI(n){try{return ue(n),!0}catch{return!1}}function WI(n){let e=new Map;for(let[t,i]of n)i!==void 0&&e.set(t,i);return e}function ri(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return e}function cs(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 HI(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 yt,tm,Ie,DI,$I,zI,BI,wp,em,Je=I(()=>{"use strict";yt=class{constructor(e){this.value=e}value;valueOf(){return this.value}toJSON(){return this.value}},tm=128,Ie=class extends Error{constructor(t,i){super(i??t);this.kind=t;this.name="CborError"}kind},DI=(1n<<64n)-1n,$I=-(1n<<63n),zI=new TextEncoder,BI=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),wp=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}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 Ie("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)}};em=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 Ie("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 Ie("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 Ie("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 Ie("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 Ie("non_canonical_head");return t<=BigInt(Number.MAX_SAFE_INTEGER)?Number(t):t}case 31:throw new Ie("indefinite");default:throw new Ie("non_canonical_head","reserved additional info")}}len(e){let t=this.arg(e);if(typeof t=="bigint")throw new Ie("too_long");if(t>this.remaining)throw new Ie("unexpected_end");return t}item(e){if(e>tm)throw new Ie("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 BI.decode(s)}catch{throw new Ie("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 c=this.item(e+1);if(typeof c!="string"&&typeof c!="number"&&typeof c!="bigint")throw new Ie("mixed_map_keys");if((typeof c=="number"||typeof c=="bigint")&&c<0)throw new Ie("mixed_map_keys");r.push(c),a.push(this.item(e+1))}rv(r);let p=new Map;for(let l=0;l<s;l++){let c=r[l];if(typeof c=="bigint")throw new Ie("too_long","struct key beyond 2^53");p.set(c,a[l])}return p}case 6:throw new Ie("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 Ie("float");return Number.isInteger(s)?new yt(s):s}case 25:case 26:throw new Ie("float","float must be binary64");case 31:throw new Ie("indefinite");default:throw new Ie("simple")}}}}});function GI(n){return n===null?"null":n instanceof Uint8Array?"bytes":n instanceof yt?"float":Array.isArray(n)?"array":n instanceof Map?"map":typeof n=="number"?Number.isInteger(n)?"int":"float":typeof n}function ln(n,e,t){return new ne(n,`expected ${e}, found ${GI(t)}`)}function sv(n,e){return{name:e,enc:t=>{if(!(t instanceof Uint8Array)||t.length!==n)throw new ne(e,`must be ${n} bytes`);return t},dec:t=>{if(!(t instanceof Uint8Array))throw ln(e,"bytes",t);if(t.length!==n)throw new ne(e,`must be ${n} bytes`);return t}}}function U(n){if(!YI.test(n))throw new ne("uuid",`not a UUID: ${n}`);return cs(n.replace(/-/g,""))}function yl(n){let e=ri(n);return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20,32)}`}function Ap(n){let e=/^sha256:([0-9a-f]{64})$/.exec(n);if(!e)throw new ne("hash",`not a sha256: revision token: ${n}`);return cs(e[1])}function nm(n){return`sha256:${ri(n)}`}function _p(n,e=0){if(e>128)throw new ne("value","nesting too deep");if(n instanceof Uint8Array)throw new ne("value","byte strings are not values");if(typeof n=="bigint"){if(n>0x7fffffffffffffffn||n<-0x8000000000000000n)throw new ne("value","integer outside int64");return}if(Array.isArray(n))for(let t of n)_p(t,e+1);else if(n instanceof Map)for(let[t,i]of n){if(typeof t!="string")throw new ne("value","map keys must be text");_p(i,e+1)}}function F(n,e={}){let t=`[${n.name}]`;return{name:t,enc:i=>{if(e.nonEmpty&&i.length===0)throw new ne(t,"list must not be empty");return i.map(o=>n.enc(o))},dec:i=>{if(!Array.isArray(i))throw ln(t,"array",i);if(e.nonEmpty&&i.length===0)throw new ne(t,"list must not be empty");return i.map(o=>n.dec(o))}}}function gl(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 ln(e,"map",t);let i=new Map;for(let[o,s]of t){if(typeof o!="string")throw new ne(e,"data map keys must be text");i.set(o,n.dec(s))}return i}}}function Sp(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 Pe(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 ne(n,`unknown value ${JSON.stringify(o)}`);return s},dec:o=>{if(typeof o=="bigint")throw new ne(n,`unknown variant ${o}`,!0);if(typeof o!="number"||!Number.isInteger(o)||o<0)throw ln(n,"uint enum",o);let s=o>=t?e[o-t]:void 0;if(s===void 0)throw new ne(n,`unknown variant ${o}`,!0);return s}}}function N(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,p="req"]of e){let l=o[r];if(l===void 0){if(p==="req"||p==="req1")throw new ne(n,`missing required field ${r}`);continue}if((p==="req1"||p==="opt1")&&Array.isArray(l)&&l.length===0)throw new ne(n,`${r} must not be empty`);i.set(s,a.enc(l))}return i},dec:t=>{if(!(t instanceof Map))throw ln(n,"struct map",t);let i=t;for(let s of i.keys())if(typeof s!="number")throw ln(n,"struct map",t);let o={};for(let[s,r,a,p="req"]of e){let l=i.get(s);if(l===void 0){if(p==="req"||p==="req1")throw new ne(n,`missing required key ${s} (${r})`);continue}let c=a.dec(l);if((p==="req1"||p==="opt1")&&Array.isArray(c)&&c.length===0)throw new ne(n,`${r} must not be empty`);o[r]=c}return o}}}function bl(n,e){let t=new Map,i=new Map;for(let[o,s,r]of e){let a=N(`${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 ne(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 ln(n,"struct map",o);let s=o.get(0);if(s===void 0)throw new ne(n,"missing discriminator");if(typeof s=="bigint")throw new ne(n,`unknown variant ${s}`,!0);if(typeof s!="number")throw ln(n,"uint discriminator",s);let r=t.get(s);if(!r)throw new ne(n,`unknown variant ${s}`,!0);return{kind:r[0],...r[1].dec(o)}}}}function av(n,e,t,i){return{name:n,enc:o=>e.enc(i(o)),dec:o=>t(e.dec(o))}}function im(n,e){return{name:n,enc:t=>e.map((i,o)=>i.enc(t[o])),dec:t=>{if(!Array.isArray(t))throw ln(n,"array",t);if(t.length!==e.length)throw new ne(n,"wrong number of elements");return e.map((i,o)=>i.dec(t[o]))}}}var ne,B,Tn,R,Oe,ov,uo,Ii,YI,T,H,kp,at,ge=I(()=>{"use strict";Je();ne=class extends Error{constructor(t,i,o=!1){super(`${t}: ${i}`);this.ty=t;this.unknown=o;this.name="SchemaError"}ty;unknown};B={name:"uint",enc:n=>{if(!Number.isSafeInteger(n)||n<0)throw new ne("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 ne("uint","value beyond 2^53 is not supported here"):ln("uint","uint",n)}},Tn={name:"int",enc:n=>{if(!Number.isSafeInteger(n))throw new ne("int",`not an integer: ${n}`);return n},dec:n=>{if(typeof n=="number"&&Number.isInteger(n))return n;throw ln("int","int",n)}},R={name:"tstr",enc:n=>{if(typeof n!="string")throw new ne("tstr","not a string");return n},dec:n=>{if(typeof n=="string")return n;throw ln("tstr","text",n)}},Oe={name:"bool",enc:n=>n,dec:n=>{if(typeof n=="boolean")return n;throw ln("bool","bool",n)}},ov={name:"bstr",enc:n=>n,dec:n=>{if(n instanceof Uint8Array)return n;throw ln("bstr","bytes",n)}};uo=sv(16,"b16"),Ii=sv(32,"b32"),YI=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;T={name:"uuid",enc:n=>U(n),dec:n=>yl(uo.dec(n))};H={name:"hash",enc:n=>Ap(n),dec:n=>nm(Ii.dec(n))},kp={name:"any",enc:n=>n,dec:n=>n},at={name:"value",enc:n=>(_p(n),n),dec:n=>(_p(n),n)}});function Sr(n){return Object.prototype.hasOwnProperty.call(Pp,n)}function JI(n){return Sr(n)?Pp[n]:"contact_support"}function A(n,e,t={}){let i=typeof t=="string"?{reason:t}:t;return new se({code:n,recovery:Pp[n],message:e,...i})}function oe(n,e){return n instanceof se&&(e===void 0||n.code===e)}var Pp,se,ie=I(()=>{"use strict";Pp={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"};se=class extends Error{code;recovery;reason;details;retryAfterMs;issues;traceId;mutationId;mutationIds;constructor(e,t={}){super(e.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="MdbaseError",this.code=Sr(e.code)?e.code:"internal",this.recovery=Sr(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);let i=t.mutationIds?Object.freeze([...t.mutationIds]):void 0,o=t.mutationId??i?.[0];o!==void 0&&(this.mutationId=o),i!==void 0&&(this.mutationIds=i)}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 pv(n,e,t){if(!Array.isArray(n)||n.length!==e)throw new ne(t,`must have exactly ${e} elements`);if(B.dec(n[0])!==1)throw new ne(t,"unknown version",!0);return n}var xp,lv,cv,Pr,rm=I(()=>{"use strict";ge();xp={name:"attachment-uint64",enc:n=>{if(typeof n=="number")return B.enc(n);if(typeof n!="bigint"||n<0n||n>0xffffffffffffffffn)throw new ne("attachment-uint64","outside uint64");return n},dec:n=>{if(typeof n=="number")return B.dec(n);if(typeof n!="bigint"||n<0n||n>0xffffffffffffffffn)throw new ne("attachment-uint64","outside uint64");return n<=BigInt(Number.MAX_SAFE_INTEGER)?Number(n):n}},lv=8388608;cv={name:"attachment-ref-v1",enc:n=>[1,T.enc(n.collection),xp.enc(n.keyEpoch),Ii.enc(n.attachmentId),lv,H.enc(n.manifestCipherHash)],dec:n=>{let e=pv(n,6,"attachment-ref-v1");if(B.dec(e[4])!==lv)throw new ne("attachment-ref-v1","unknown chunk profile",!0);return{collection:T.dec(e[1]),keyEpoch:xp.dec(e[2]),attachmentId:Ii.dec(e[3]),manifestCipherHash:H.dec(e[5])}}},Pr={name:"attachment-content-v1",enc:n=>[1,cv.enc(n.reference),H.enc(n.wholePlainHash),xp.enc(n.totalPlainBytes)],dec:n=>{let e=pv(n,4,"attachment-content-v1");return{reference:cv.dec(e[1]),wholePlainHash:H.dec(e[2]),totalPlainBytes:xp.dec(e[3])}}}});function dv(n){return n.content.form==="blob"?n.content.blob.size:n.content.content.totalPlainBytes}function XI(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 hv(n,e){return{name:n,enc:t=>e().enc(t),dec:t=>e().dec(t)}}var Ip,Cp,uv,fv,Op,vM,mv=I(()=>{"use strict";ge();At();rm();Ip={name:"file-content",enc:n=>n.form==="blob"?Xi.enc(n.blob):Pr.enc(n.content),dec:n=>Array.isArray(n)?{form:"attachment",content:Pr.dec(n)}:{form:"blob",blob:Xi.dec(n)}};Cp={name:"unindexed-markdown-payload-v1",enc:n=>{if(dv(n)<=1048576)throw new ne("unindexed-markdown-payload-v1","declared size must exceed record cap");return[2,1,1,Ip.enc(n.content)]},dec:n=>{let e="unindexed-markdown-payload-v1";if(!Array.isArray(n)||n.length!==4)throw new ne(e,"must have exactly four elements");if(B.dec(n[0])!==2||B.dec(n[1])!==1||B.dec(n[2])!==1)throw new ne(e,"unknown discriminator/profile/kind",!0);let t={content:Ip.dec(n[3])};if(dv(t)<=1048576)throw new ne(e,"declared size must exceed record cap");return t}},uv=Sp("text",R,n=>typeof n=="string",n=>typeof n=="string",B),fv=bl("extended-runtime-op",[[13,"file_attach",[[1,"id",T],[2,"path",R],[3,"content",Pr],[4,"ifRevision",H,"opt"],[5,"base",H,"opt"]]],[14,"unindexed_markdown_put",[[1,"id",T],[2,"path",R],[3,"payload",Cp],[4,"expected",Cp,"opt"]]],[15,"record_to_unindexed_markdown",[[1,"id",T],[2,"path",R],[3,"payload",Cp],[4,"priorRevision",H]]],[16,"unindexed_markdown_to_record",[[1,"id",T],[2,"path",R],[3,"doc",uv],[4,"prior",Cp]]],[18,"ordinary_attachment_continuation",[[1,"id",T],[2,"path",R],[3,"content",Pr],[4,"prior",Ip]]],[17,"ordinary_file_to_record",[[1,"id",T],[2,"path",R],[3,"doc",uv],[4,"prior",Ip]]]]);Op={name:"runtime-v1-op",enc:n=>XI(n)?fv.enc(n):ps.enc(n),dec:n=>{let e=n instanceof Map?B.dec(n.get(0)):void 0;return e!==void 0&&e>=13&&e<=18?fv.dec(n):ps.dec(n)}};vM=N("runtime-v1-mutation",[[0,"id",T],[1,"origin",T],[2,"baseSeq",B],[3,"clock",hv("op-clock",()=>fo)],[4,"seed",Ii],[5,"source",Pe("source",["api","external"])],[6,"ops",F(Op,{nonEmpty:!0}),"req1"],[7,"onBehalf",T,"opt"],[8,"conflictMode",hv("conflict-mode",()=>wl),"opt"],[9,"validatedAt",Pe("level",["off","warn","error"]),"opt"],[10,"room",N("room-checkpoint",[[0,"stream",uo],[1,"state",H]]),"opt"]])});var Nm={};ls(Nm,{DESCRIBE_TYPING_MAX_PATHS:()=>Pl,DESCRIBE_TYPING_MAX_TYPES:()=>Sl,HOLD_REASONS:()=>Pv,HOLD_RESOLUTIONS:()=>xv,INCIDENT_KINDS:()=>_v,MEDIA_CLASSES:()=>Ev,PUSH_CODECS:()=>QI,RECOVERY:()=>gv,ROLES:()=>wv,TEMPORAL_HINTS:()=>Vp,TRANSFER_PHASES:()=>jv,appliedPrefix:()=>dm,appliedPrefixParams:()=>pm,authorRef:()=>Tp,b16:()=>uo,b32:()=>Ii,backlinksResult:()=>qm,baseField:()=>Np,blobRef:()=>Xi,bodyEdit:()=>wm,change:()=>Rv,changesResult:()=>us,clientFrame:()=>Qi,confirmedHead:()=>Lp,conflict:()=>Am,conflictEntry:()=>Al,conflictMode:()=>wl,conflictValue:()=>Ep,describeResult:()=>Mm,describeTypingResult:()=>jm,docVersion:()=>sm,executeViewParams:()=>sO,fenceApply:()=>Im,fenceReport:()=>Om,fenceResult:()=>Rm,fileChunk:()=>Up,fileInclusion:()=>vm,fileStreamFailure:()=>Dp,fileView:()=>kl,fmMap:()=>_n,grantInfo:()=>cm,helloParams:()=>lm,helloResult:()=>um,hold:()=>vl,holdReason:()=>fm,holdRef:()=>hm,holdResolution:()=>mm,incident:()=>Av,include:()=>ds,issue:()=>Zi,linkResolution:()=>Iv,linkView:()=>ym,listFilesResult:()=>Sm,listPendingResult:()=>Lm,listResourcesResult:()=>Em,listViewsResult:()=>nO,materialization:()=>zp,mediaClass:()=>fs,mutation:()=>eO,newTypeFile:()=>Tm,op:()=>ps,opClock:()=>fo,openUploadParams:()=>Pm,openUploadResult:()=>xm,peer:()=>Nv,preflight:()=>Tv,presencePush:()=>Bp,problem:()=>An,progress:()=>kv,publishState:()=>qv,queryGroup:()=>bm,queryMetadata:()=>Ov,queryParams:()=>oO,queryResult:()=>_l,queryUpdate:()=>jp,receipt:()=>kt,recordState:()=>Cv,recordView:()=>Mn,recovery:()=>bv,resourceView:()=>Fp,resyncing:()=>Sv,role:()=>vv,severity:()=>Mp,submitParams:()=>_m,submitResult:()=>km,syncStatus:()=>er,target:()=>am,temporalHint:()=>Uv,textOrBlob:()=>Rp,transferProgress:()=>$p,typingEntry:()=>Dv,uploadChunkParams:()=>Cm,version:()=>qp,viewRef:()=>gm,viewSourceDocument:()=>iO});function Lv(n){throw new ne(n,"wrong type")}var qp,gv,bv,Mp,Zi,An,Qi,lm,wv,vv,cm,_v,Av,kv,Sv,Lp,pm,dm,er,um,Xi,Rp,Pv,fm,hm,vl,xv,mm,Cv,Iv,ym,Tp,_n,Mn,ds,gm,bm,Ov,_l,jp,Rv,us,Ev,fs,wl,Np,wm,sm,vm,yv,ps,_m,ZI,Ep,Am,qv,Tv,kt,km,Al,Mv,om,kl,Sm,Pm,xm,Cm,Up,Dp,jv,$p,zp,Nv,Bp,Im,Om,Rm,QI,fo,eO,tO,Fp,Em,qm,nO,iO,Tm,Mm,rO,Lm,am,oO,sO,Vp,Uv,Dv,jm,Sl,Pl,At=I(()=>{"use strict";mv();rm();ge();qp=av("version",im("version",[B,B]),([n,e])=>({major:n,minor:e}),n=>[n.major,n.minor]),gv=["fix_request","refresh","resolve_conflict","reauthorize","repair_collection","retry","free_space","upgrade","resolve_outcome","none","contact_support"],bv=Pe("recovery",gv),Mp=Pe("severity",["warning","error"]),Zi=N("issue",[[0,"code",R],[1,"severity",Mp],[2,"message",R],[3,"details",at,"opt"]]),An=N("problem",[[0,"code",R],[1,"recovery",bv],[2,"message",R],[3,"reason",R,"opt"],[4,"details",at,"opt"],[5,"retryAfterMs",B,"opt"],[6,"issues",F(Zi),"opt"],[7,"traceId",R,"opt"]]),Qi=bl("client-frame",[[0,"request",[[1,"id",B],[2,"method",R],[3,"params",kp]]],[1,"response",[[1,"id",B],[2,"result",kp,"opt"],[3,"problem",An,"opt"]]],[2,"push",[[1,"type",R],[2,"payload",kp]]]]),lm=N("hello-params",[[0,"versions",F(qp,{nonEmpty:!0}),"req1"],[1,"clientName",R],[2,"clientVersion",R],[3,"features",F(R),"opt"],[4,"timezone",R,"opt"]]),wv=["viewer","editor","owner"],vv=Pe("role",wv),cm=N("grant-info",[[0,"grant",T,"opt"],[1,"capabilities",F(R,{nonEmpty:!0}),"req1"],[2,"role",vv],[3,"account",T,"opt"],[4,"fileFolders",F(R),"opt"]]),_v=["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"],Av=N("incident",[[0,"kind",Pe("incident-kind",_v)],[1,"details",at,"opt"]]),kv=N("progress",[[0,"done",B],[1,"total",B]]),Sv=N("resyncing",[[0,"phase",Pe("resync-phase",["probing","repairing","rolling_back","awaiting_control"])],[1,"positions",B]]),Lp=N("confirmed-head",[[0,"seq",B],[1,"chain",H],[2,"policyGeneration",H],[3,"catalogGeneration",H]]),pm=N("applied-prefix-params",[[0,"seq",B]]),dm=N("applied-prefix",[[0,"appliedThrough",B],[1,"seq",B],[2,"chain",H,"opt"]]),er=N("sync-status",[[0,"mode",Pe("sync-mode",["local_only","synced"])],[1,"confirmedThrough",B],[2,"headKnown",B],[3,"pending",B],[4,"oldestPending",Tn,"opt"],[5,"holds",B],[6,"unresolved",B],[7,"connection",Pe("connection",["online","connecting","offline"])],[8,"installing",kv,"opt"],[9,"incidents",F(Av)],[10,"resyncing",Sv,"opt"],[11,"confirmedHead",Lp,"opt"],[12,"grant",cm,"opt"]]),um=N("hello-result",[[0,"version",qp],[1,"runtimeVersion",R],[2,"sem",qp],[3,"collection",T],[4,"grant",cm],[5,"status",er],[6,"features",F(R)],[7,"headWitness",ov,"opt"]]),Xi=N("blob-ref",[[0,"plainHash",H],[1,"size",B],[2,"blobId",Ii],[3,"idEpoch",B],[4,"partSize",B]]),Rp={name:"text-or-blob",enc:n=>{if(typeof n=="string")return R.enc(n);if("form"in n){if(n.form!=="attachment")throw new ne("text-or-blob","unknown arm",!0);return[1,Pr.enc(n.content)]}return Xi.enc(n)},dec:n=>{if(typeof n=="string")return R.dec(n);if(Array.isArray(n)){if(n.length!==2)throw new ne("text-or-blob","attachment arm must have exactly two elements");if(B.dec(n[0])!==1)throw new ne("text-or-blob","unknown attachment arm",!0);return{form:"attachment",content:Pr.dec(n[1])}}return Xi.dec(n)}},Pv=["conflict","unknown_provenance","deleted_elsewhere","read_only","editor_busy","suspect_write"],fm=Pe("hold-reason",Pv),hm=N("hold-ref",[[0,"id",T],[1,"reason",fm]]),vl=N("hold",[[0,"id",T],[1,"path",R],[2,"reason",fm],[3,"since",Tn],[4,"base",Rp,"opt"],[5,"mine",Rp],[6,"theirs",Rp,"opt"],[7,"saves",B]]),xv=["keep_mine","take_theirs","use","delete","keep_both"],mm=Pe("hold-resolution",xv),Cv=N("record-state",[[0,"state",Pe("confirmation",["confirmed","pending"])],[1,"confirmedSeq",B],[2,"hold",hm,"opt"],[3,"unresolved",B,"opt"]]),Iv=N("link-resolution",[[0,"kind",Pe("link-kind",["record","file","ambiguous","not_found","invalid"])],[1,"target",T,"opt"],[2,"path",R,"opt"]]),ym=N("link-view",[[0,"raw",R],[1,"embed",Oe],[2,"resolution",Iv],[3,"field",R,"opt"]]),Tp=N("author-ref",[[0,"account",T],[1,"device",T],[2,"grant",T,"opt"],[3,"grantAccount",T,"opt"]]),_n=gl(at),Mn=N("record-view",[[0,"id",T],[1,"path",R],[2,"revision",H],[3,"frontmatter",_n],[4,"effective",_n,"opt"],[5,"body",R,"opt"],[6,"document",R,"opt"],[7,"types",F(R)],[8,"state",Cv],[9,"diagnostics",F(Zi),"opt"],[10,"values",_n,"opt"],[11,"mtime",Tn,"opt"],[12,"links",F(ym),"opt"],[13,"createdBy",Tp,"opt"],[14,"modifiedBy",Tp,"opt"]]),ds=N("include",[[0,"effective",Oe,"opt"],[1,"body",Oe,"opt"],[2,"document",Oe,"opt"],[3,"diagnostics",Oe,"opt"],[4,"links",Oe,"opt"]]),gm=N("view-ref",[[0,"path",R],[1,"view",R]]),bm=N("query-group",[[0,"values",_n],[1,"count",B],[2,"summaries",_n,"opt"]]),Ov=N("query-metadata",[[0,"columns",F(R),"opt"],[1,"totalCount",B,"opt"],[2,"diagnostics",F(Zi),"opt"],[3,"view",gm,"opt"],[4,"groups",F(bm),"opt"],[5,"hasMore",Oe,"opt"]]),_l=N("query-result",[[0,"records",F(Mn)],[1,"cursor",R,"opt"],[2,"complete",Oe],[3,"asOf",B],[4,"columns",F(R),"opt"],[5,"totalCount",B,"opt"],[6,"diagnostics",F(Zi),"opt"],[7,"view",gm,"opt"],[8,"groups",F(bm),"opt"],[9,"hasMore",Oe,"opt"]]),jp=N("query-update",[[0,"sub",B],[1,"kind",Pe("update-kind",["snapshot","diff","reset"])],[2,"added",F(Mn),"opt"],[3,"changed",F(Mn),"opt"],[4,"removed",F(T),"opt"],[5,"order",F(T),"opt"],[6,"complete",Oe],[7,"asOf",B],[8,"metadata",Ov,"opt"]]),Rv=N("change",[[0,"id",T],[1,"path",R],[2,"kind",Pe("change-kind",["put","remove"])],[3,"version",B],[4,"author",Tp,"opt"],[5,"entity",Pe("change-entity",["record","file"]),"opt"],[6,"types",F(R),"opt"]]),us=N("changes-result",[[0,"changes",F(Rv)],[1,"cursor",R],[2,"reset",Oe]]),Ev=["image","audio","video","pdf","other"],fs=Pe("media-class",Ev),wl=Pe("conflict-mode",["record","reject"]),Np={name:"base-field",enc:n=>n.observed===void 0?[n.key]:[n.key,at.enc(n.observed)],dec:n=>{if(!Array.isArray(n)||n.length<1||n.length>2)throw new ne("base-field","must have 1 or 2 elements");return n.length===1?{key:R.dec(n[0])}:{key:R.dec(n[0]),observed:at.dec(n[1])}}},wm=im("body-edit",[B,B,R]),sm=N("doc-version",[[0,"path",R],[1,"doc",R]]),vm=N("file-inclusion",[[0,"include",F(fs)],[1,"exclude",F(R),"opt"],[2,"maxSize",B,"opt"]]),yv=gl(F(at)),ps=bl("op",[[1,"create",[[1,"id",T],[2,"path",R,"opt"],[3,"type",R,"opt"],[4,"frontmatter",_n,"opt"],[5,"body",R,"opt"],[6,"document",R,"opt"]]],[2,"update",[[1,"id",T],[2,"patch",_n,"opt"],[3,"unset",F(R),"opt1"],[4,"add",yv,"opt"],[5,"remove",yv,"opt"],[6,"body",R,"opt"],[7,"bodyEdits",F(wm),"opt1"],[8,"bodyBase",H,"opt"],[9,"bodyBaseText",R,"opt"],[10,"base",F(Np),"opt1"],[11,"ifRevision",H,"opt"],[12,"updateRefs",Oe,"opt"]]],[3,"document",[[1,"id",T],[2,"base",sm,"opt"],[3,"new",sm,"opt"],[4,"ifRevision",H,"opt"]]],[4,"delete",[[1,"id",T],[2,"baseRevision",H,"opt"],[3,"ifRevision",H,"opt"]]],[5,"rename",[[1,"id",T],[2,"from",R],[3,"to",R],[4,"updateRefs",Oe],[5,"ifRevision",H,"opt"]]],[6,"resource_put",[[1,"path",R],[2,"doc",R],[3,"baseRevision",H,"opt"],[4,"mustNotExist",Oe,"opt"]]],[7,"resource_delete",[[1,"path",R],[2,"baseRevision",H,"opt"]]],[8,"file_put",[[1,"id",T],[2,"path",R],[3,"blob",Xi],[4,"ifRevision",H,"opt"],[5,"base",H,"opt"]]],[9,"file_delete",[[1,"id",T],[2,"ifRevision",H,"opt"],[3,"base",H,"opt"]]],[10,"file_move",[[1,"id",T],[2,"from",R],[3,"to",R],[4,"updateRefs",Oe],[5,"ifRevision",H,"opt"]]],[11,"conflict_dismiss",[[1,"mutation",T],[2,"record",T]]],[12,"sync_settings",[[1,"inclusion",vm]]]]),_m=N("submit-params",[[0,"ops",F(ps,{nonEmpty:!0}),"req1"],[1,"mutationId",T,"opt"],[2,"conflictMode",wl,"opt"],[3,"timezone",R,"opt"],[4,"allowPartial",Oe,"opt"],[5,"mutationIds",F(T),"opt1"],[6,"dryRun",Oe,"opt"],[7,"include",ds,"opt"],[8,"wait",Pe("wait-for",["pending","confirmed","published"]),"opt"]]),ZI=["missing","value","text","blob","deleted"],Ep={name:"conflict-value",enc:n=>{switch(n.form){case"missing":return[0];case"value":return[1,at.enc(n.value)];case"text":return[2,n.text];case"blob":return[3,Xi.enc(n.blob)];case"deleted":return[4]}},dec:n=>{if(!Array.isArray(n)||n.length===0)throw new ne("conflict-value","malformed conflict value");let e=n[0];if(typeof e!="number")throw new ne("conflict-value","malformed conflict value");if(e>4)throw new ne("conflict-value",`unknown variant ${e}`,!0);let t=ZI[e];if(t==="missing"||t==="deleted"){if(n.length!==1)throw new ne("conflict-value","malformed conflict value");return{form:t}}if(n.length!==2)throw new ne("conflict-value","malformed conflict value");return t==="value"?{form:t,value:at.dec(n[1])}:t==="text"?{form:t,text:R.dec(n[1])}:{form:t,blob:Xi.dec(n[1])}}},Am=N("conflict",[[0,"kind",Pe("conflict-kind",["field","frontmatter","body","path","delete","file"],1)],[1,"id",T],[2,"field",R,"opt"],[3,"base",Ep,"opt"],[4,"kept",Ep],[5,"lost",Ep]]),qv=Pe("publish-state",["publishing","published","not_published"]),Tv=N("preflight",[[0,"rewrites",F(N("link-rewrite",[[0,"record",T],[1,"path",R],[2,"from",R],[3,"to",R],[4,"field",R,"opt"]]))],[1,"broken",F(N("broken-link",[[0,"record",T],[1,"path",R],[2,"raw",R],[3,"target",T],[4,"field",R,"opt"]]))]]),kt=N("receipt",[[0,"mutation",T],[1,"state",Pe("receipt-state",["pending","confirmed","rejected","unknown"])],[2,"seq",B,"opt"],[3,"status",Pe("status",["applied","merged","conflicted"]),"opt"],[4,"conflicts",F(Am),"opt1"],[5,"records",F(Mn),"opt"],[6,"problem",An,"opt"],[7,"published",qv,"opt"],[8,"preflight",Tv,"opt"],[9,"relocatedFrom",B,"opt"]]),km=F(kt,{nonEmpty:!0}),Al=N("conflict-entry",[[0,"mutation",T],[1,"seq",B],[2,"conflict",Am]]),Mv=Pe("file-content-profile",["ordinary_blob","ordinary_attachment_v1","unindexed_markdown_blob","unindexed_markdown_attachment_v1"]),om=N("file-view",[[0,"id",T],[1,"path",R],[2,"size",B],[3,"digest",H],[4,"media",fs],[5,"state",Pe("file-state",["materialized","remote","fetching","pending_upload"])],[6,"confirmedSeq",B],[7,"hold",hm,"opt"],[8,"mtime",Tn,"opt"],[9,"mediaType",R,"opt"],[10,"contentProfile",Mv,"opt"]]),kl={...om,dec(n){let e=n instanceof Map?n:void 0;if(e?.has(10))try{Mv.dec(e.get(10))}catch(t){if(!(t instanceof ne)||!t.unknown)throw t;let i=new Map(e);return i.delete(10),om.dec(i)}return om.dec(n)}},Sm=N("list-files-result",[[0,"files",F(kl)],[1,"cursor",R,"opt"],[2,"complete",Oe]]),Pm=N("open-upload-params",[[0,"transfer",T],[1,"path",R],[2,"size",B],[3,"digest",H,"opt"],[4,"fileId",T,"opt"],[5,"ifRevision",H,"opt"],[6,"mutationId",T,"opt"]]),xm=N("open-upload-result",[[0,"transfer",T],[1,"chunkSize",B],[2,"received",F(B)],[3,"expiresAt",Tn],[4,"fileId",T,"opt"]]),Cm=N("upload-chunk-params",[[0,"transfer",T],[1,"index",B],[2,"bytes",{name:"bstr",enc:n=>n,dec:n=>n instanceof Uint8Array?n:Lv("bstr")}]]);Up=N("file-chunk",[[0,"stream",B],[1,"offset",B],[2,"bytes",{name:"bstr",enc:n=>n,dec:n=>n instanceof Uint8Array?n:Lv("bstr")}],[3,"last",Oe]]),Dp=N("file-stream-failure",[[0,"stream",B],[1,"problem",An]]),jv=["receiving","sealing","uploading","appending","confirmed","fetching","streaming","done"],$p=N("transfer-progress",[[0,"id",Sp("transfer-id",T,n=>typeof n=="string",n=>n instanceof Uint8Array,B)],[1,"phase",Pe("phase",jv)],[2,"done",B],[3,"total",B]]),zp=N("materialization",[[0,"mode",Pe("materialize-mode",["all","on_demand"])],[1,"pinned",F(R),"opt"],[2,"media",F(fs),"opt"],[3,"maxSize",B,"opt"]]),Nv=N("peer",[[0,"session",uo],[1,"account",T,"opt"],[2,"app",R,"opt"],[3,"state",at],[4,"lastSeen",Tn]]),Bp=N("presence",[[0,"record",T],[1,"peers",F(Nv)]]),Im=N("fence-apply",[[0,"path",R],[1,"base",H],[2,"edits",F(wm,{nonEmpty:!0}),"req1"],[3,"expected",H]]),Om=N("fence-report",[[0,"open",F(N("fence-open",[[0,"path",R],[1,"dirty",Oe],[2,"buffer",H]]))]]),Rm=N("fence-result",[[0,"outcome",Pe("fence-outcome",["applied","not_open","buffer_changed"])],[1,"buffer",R,"opt"]]),QI={query_update:jp,receipt:kt,status:er,holds:F(vl),conflicts:F(Al),presence:Bp,file_chunk:Up,file_stream_failed:Dp,transfer_progress:$p,changes:us},fo=N("op-clock",[[0,"instant",Tn],[1,"tz",R],[2,"localDate",R]]),eO=N("mutation",[[0,"id",T],[1,"origin",T],[2,"baseSeq",B],[3,"clock",fo],[4,"seed",Ii],[5,"source",Pe("source",["api","external"])],[6,"ops",F(ps,{nonEmpty:!0}),"req1"],[7,"onBehalf",T,"opt"],[8,"conflictMode",wl,"opt"],[9,"validatedAt",Pe("level",["off","warn","error"]),"opt"],[10,"room",N("room-checkpoint",[[0,"stream",uo],[1,"state",H]]),"opt"]]),tO=Pe("confirmation",["confirmed","pending"]),Fp=N("resource-view",[[0,"path",R],[1,"revision",H],[2,"size",B],[3,"state",tO],[4,"text",R,"opt"]]),Em=N("list-resources-result",[[0,"resources",F(Fp)],[1,"complete",Oe],[2,"cursor",R,"opt"]]),qm=N("backlinks-result",[[0,"backlinks",F(N("backlink",[[0,"record",Mn],[1,"links",F(ym,{nonEmpty:!0}),"req1"]]))],[1,"cursor",R,"opt"],[2,"complete",Oe],[3,"asOf",B]]),nO=N("list-views-result",[[0,"sources",F(N("view-source",[[0,"record",T],[1,"id",R],[2,"name",R],[3,"source",N("view-source-ref",[[0,"path",R],[1,"format",R],[2,"revision",H],[3,"writable",Oe]])],[4,"views",F(N("view-descriptor",[[0,"id",R],[1,"name",R],[2,"properties",F(N("view-property",[[0,"key",R],[1,"label",R,"opt"],[2,"description",R,"opt"],[3,"format",R,"opt"],[4,"hidden",Oe,"opt"]]))],[3,"presentation",at,"opt"]]))]]))],[1,"diagnostics",F(Zi)],[2,"complete",Oe]]),iO=N("view-source-document",[[0,"path",R],[1,"format",R],[2,"revision",H],[3,"document",R],[4,"record",T]]),Tm=N("new-type-file",[[0,"name",R],[1,"path",R]]),Mm=N("describe-result",[[0,"specVersion",R],[1,"types",F(N("type-summary",[[0,"name",R],[1,"path",R],[2,"implements",F(N("implementation",[[0,"contract",R],[1,"version",R],[2,"fields",gl(R)],[3,"binding",at,"opt"],[4,"digest",H,"opt"]]))],[3,"version",Tn,"opt"],[4,"revision",H,"opt"],[5,"definition",at,"opt"],[6,"schema",at,"opt"]]))],[2,"settings",at],[3,"inclusion",vm],[4,"issues",F(Zi)],[5,"contracts",F(N("contract-summary",[[0,"id",R],[1,"version",R],[2,"path",R],[3,"digest",H],[4,"contractType",R],[5,"implementedBy",F(R)],[6,"schemas",gl(at),"opt"]]))]]),rO={name:"pending-runtime-op",enc:n=>Op.enc(n),dec:n=>Op.dec(n)},Lm=N("list-pending-result",[[0,"pending",F(N("pending-mutation",[[0,"receipt",kt],[1,"captured",Tn],[2,"ops",F(rO,{nonEmpty:!0}),"req1"]]))],[1,"next",T,"opt"]]),am={name:"target",enc:n=>typeof n=="string"?T.enc(n):n.path,dec:n=>typeof n=="string"?{path:n}:T.dec(n)},oO=N("query-params",[[0,"query",at],[1,"include",ds,"opt"],[2,"contract",R,"opt"]]),sO=N("execute-view-params",[[0,"source",am],[1,"view",R],[2,"context",am,"opt"],[3,"limit",B,"opt"],[4,"offset",B,"opt"],[5,"timezone",R,"opt"],[6,"include",ds,"opt"]]),Vp=["none","date","date_time"],Uv=Pe("temporal-hint",Vp),Dv=N("typing-entry",[[0,"path",R],[1,"hint",Uv]]),jm=N("describe-typing-result",[[0,"catalogGeneration",B],[1,"fields",F(Dv)]]),Sl=64,Pl=256});function $v(n,e,t,i){let o=aO(t),s=lO(t);n.setUint32(e,i?s:o,i),n.setUint32(e+4,i?o:s,i)}var aO,lO,zv=I(()=>{aO=n=>n/2**32|0,lO=n=>n>>>0});function Kp(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}function ho(n,e=""){if(typeof n!="number")throw new TypeError(Um(e)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(Um(e)+"expected integer >= 0, got "+n);return n}function tr(n,e,t=""){if(Kp(n)&&(e===void 0||n.length===e))return n;e!==void 0&&ho(e,"length");let i=Kp(n),o=e!==void 0?` of length ${e}`:"",s=i?`length=${n.length}`:`type=${typeof n}`,r=Um(t)+"expected Uint8Array"+o+", got "+s;throw i?new RangeError(r):new TypeError(r)}function Vv(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(ho(n.outputLen),ho(n.blockLen),n.outputLen<1||n.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}function hs(n,e=!0){if(n.destroyed)throw new Error("hash was destroyed");if(e&&n.finished)throw new Error("digest() was already called")}function Wp(n,e){tr(n,void 0,"output");let t=e.outputLen;if(!(n.length>=t))throw new RangeError('"output" expected length >= '+t)}function ms(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function Hp(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function oi(n,e){return n<<32-e|n>>>e}function ys(n){if(tr(n),Kv)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=pO[n[t]];return e}function Fv(n){return n>=48&&n<=57?n-48:n>=65&&n<=70?n-55:n>=97&&n<=102?n-87:void 0}function Dm(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);if(Kv)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=Fv(n.charCodeAt(s)),a=Fv(n.charCodeAt(s+1));if(r===void 0||a===void 0){let p=n[s]+n[s+1];throw new RangeError('hex string expected, got non-hex character "'+p+'" at index '+s)}i[o]=r*16+a}return i}function Wv(n){if(typeof n!="string")throw new TypeError("string expected");let e=new TextEncoder().encode(n);try{return new Uint8Array(e)}finally{ms(e)}}function dO(n,e,t="opts"){return Bv(n,"defaults"),e!==void 0&&Bv(e,t),Object.assign(Object.create(null),n,e)}function Hv(n,e={}){if(typeof n!="function")throw new TypeError('"hashCons" expected function, got type='+typeof n);e=dO({},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 Gv(n=32){ho(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 Um,cO,Bv,Kv,pO,Yv,gs=I(()=>{Um=n=>n?`"${n}" `:"";cO=(n,e)=>{if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof n)},Bv=(n,e)=>{cO(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`)};Kv=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",pO=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));Yv=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])})});function Jv(n,e,t){return n&e^~n&t}function Xv(n,e,t){return n&e^n&t^e&t}var Gp,Zv,Qv=I(()=>{zv();gs();Gp=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=Hp(this.buffer)}update(e){hs(this),tr(e);let{view:t,buffer:i,blockLen:o}=this,s=e.length,r=!1;for(let a=0;a<s;){let p=Math.min(o-this.pos,s-a);if(p===o){let l=Hp(e);for(;o<=s-a;a+=o)this.process(l,a);r=!0;continue}i.set(a===0&&p===s?e:e.subarray(a,a+p),this.pos),this.pos+=p,a+=p,this.pos===o&&(this.process(t,0),this.pos=0,r=!0)}return this.length+=e.length,r&&this.roundClean(),this}digestInto(e){hs(this),Wp(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)),$v(i,o-8,this.length*8,s),this.process(i,0),this.roundClean();let a=e===t?i:Hp(e),p=this.outputLen,l=p/4,c=this.get();if(p%4||l>c.length)throw new Error("invalid outputLen");for(let d=0;d<l;d++)a.setUint32(4*d,c[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()}},Zv=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});var uO,xr,$m,zm,it,Cr=I(()=>{Qv();gs();uO=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]),xr=new Uint32Array(64),$m=class extends Gp{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:p}=this;return[e,t,i,o,s,r,a,p]}set(e,t,i,o,s,r,a,p){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=p|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)xr[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let u=xr[d-15],f=xr[d-2],h=oi(u,7)^oi(u,18)^u>>>3,m=oi(f,17)^oi(f,19)^f>>>10;xr[d]=m+xr[d-7]+h+xr[d-16]|0}let{A:i,B:o,C:s,D:r,E:a,F:p,G:l,H:c}=this;for(let d=0;d<64;d++){let u=oi(a,6)^oi(a,11)^oi(a,25),f=c+u+Jv(a,p,l)+uO[d]+xr[d]|0,m=(oi(i,2)^oi(i,13)^oi(i,22))+Xv(i,o,s)|0;c=l,l=p,p=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,p=p+this.F|0,l=l+this.G|0,c=c+this.H|0,this.set(i,o,s,r,a,p,l,c)}roundClean(){ms(xr)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ms(this.buffer)}},zm=class extends $m{constructor(){super(32,Zv)}},it=Hv(()=>new zm,Yv(1))});function ut(n){if(n==null)return null;if(typeof n!="object"||n instanceof yt)return n;if(Array.isArray(n))return n.map(ut);if(n instanceof Map){let t=new Map;for(let[i,o]of n)t.set(i,ut(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,ut(i));return e}function xl(n){return ut(n)}function bs(n){if(n===null||typeof n=="boolean"||typeof n=="number"||typeof n=="string")return n;if(typeof n=="bigint")return n.toString();if(n instanceof yt)return n.value;if(n instanceof Uint8Array)return ri(n);if(Array.isArray(n))return n.map(bs);let e={};for(let[t,i]of n)e[String(t)]=bs(i);return e}function Ir(n,e){if(n===e)return!0;if(n instanceof yt&&e instanceof yt)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)=>Ir(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&&Ir(s,i[r][1]))}return!1}function si(n){let e=typeof n=="string"?new TextEncoder().encode(n):n;return`sha256:${ri(it(e))}`}function fO(n){let e=new Uint8Array(n);return globalThis.crypto.getRandomValues(e),e}function Ln(n=Date.now()){let e=fO(16);n<=Yp?(n=Yp,mo=mo+1&4095,mo===0&&(n=++Yp)):(mo=(e[6]&15)<<8|e[7],mo&=2047),Yp=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|mo>>8&15,e[7]=mo&255,e[8]=128|e[8]&63,yl(e)}function Jp(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 Yp,mo,Oi=I(()=>{"use strict";Cr();Je();ge();Yp=0,mo=0});function je(n,e=yO){if(typeof n!="string"||Ri.encode(n).length>e)throw fe("bounded text required");return n}function Yt(n,e){let t=B.dec(n);if(t>e)throw fe("integer exceeds bound");return t}function $t(n,e){if(!Array.isArray(n)||n.length>e)throw fe("bounded array required");return n}function Cl(n,e){let t=$t(n,e);if(t.length!==e)throw fe("wrong tuple length");return t}function ai(n,e){if(!(n instanceof Map))throw fe("exact struct required");let t=n;if(t.size!==e.length||e.some(i=>!t.has(i)))throw fe("exact struct required");return n}function e_(n){let e=n instanceof yt?n.value:n;if(typeof e!="number"||!Number.isFinite(e)||!(n instanceof yt)&&Number.isInteger(e))throw fe("finite binary64 required");return e}function t_(n){return n.kind==="list"?n.values.every(t_):n.kind!=="map"&&n.kind!=="duration"&&n.kind!=="error"&&n.kind!=="unavailable"}function yo(n,e=1){if(!Number.isInteger(e)||e<1||e>32)throw fe("cell depth exceeds bound");let t=$t(n,5),i=B.dec(t[0]),o=s=>{if(t.length!==s)throw fe("wrong tagged cell length")};switch(i){case 0:return o(1),{kind:"null"};case 1:return o(2),{kind:"boolean",value:Oe.dec(t[1])};case 2:return o(2),{kind:"number",value:e_(t[1])};case 3:return o(2),{kind:"text",value:je(t[1])};case 4:{o(5);let s=Tn.dec(t[1]);if(!Number.isSafeInteger(s))throw fe("date millis exceeds JS-safe range");return{kind:"date",millis:s,display:je(t[2]),authoritativeZone:je(t[3]),dateOnly:Oe.dec(t[4])}}case 5:return o(3),{kind:"duration",components:Cl(t[1],8).map(e_),display:je(t[2])};case 6:return o(2),{kind:"list",values:$t(t[1],ws).map(s=>yo(s,e+1))};case 7:{if(o(2),!(t[1]instanceof Map)||t[1].size>ws)throw fe("bounded cell data map required");let s=new Map,r=null;for(let[a,p]of t[1]){let l=je(a),c=Ri.encode(l);if(r&&gO(r,c)>=0)throw fe("cell data map keys must ascend");r=c,s.set(l,yo(p,e+1))}return{kind:"map",values:s}}case 8:return o(2),{kind:"error",message:je(t[1])};case 9:return o(3),{kind:"unavailable",code:je(t[1]),detail:je(t[2])};default:throw fe("unknown tagged cell",!0)}}function gO(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 bO(n){let e=new Map,t=0,i=0,o=r=>{if(++t>4096||(i+=r)>1024*1024)throw fe("summary metadata exceeds bound")},s=(r,a)=>{if(a>32)throw fe("summary value depth exceeds bound");o(128);let p=$t(r,5),l=B.dec(p[0]);if(l===3||l===8)o(Ri.encode(je(p[1])).length);else if(l===4)o(Ri.encode(je(p[2])).length+Ri.encode(je(p[3])).length);else if(l===5)o(Ri.encode(je(p[2])).length);else if(l===6)for(let c of $t(p[1],ws))s(c,a+1);else if(l===7){if(!(p[1]instanceof Map)||p[1].size>ws)throw fe("bounded summary data map required");for(let[c,d]of p[1])o(Ri.encode(je(c)).length+64),s(d,a+1)}else if(l!==0&&l!==1&&l!==2)throw fe("summary must be a tagged value",!0)};for(let r of $t(n,64)){let a=Cl(r,2),p=je(a[0],1024);if(p.length===0||/[\u0000-\u001f\u007f-\u009f]/u.test(p)||e.has(p))throw fe("unique nonempty summary name required");o(Ri.encode(p).length+64),s(a[1],1),e.set(p,yo(a[1]))}return e}function Bm(n){let e=Yt(n.offset,4294967295),t=Yt(n.limit,jn);if(t===0)throw fe("window limit must be positive");return{offset:e,limit:t}}function Xp(n){if(!(n.hints instanceof Map)||n.hints.size>ws)throw fe("bounded hints map required");let e=new Map,t=0;for(let[s,r]of n.hints){if(je(s),je(r),t+=Ri.encode(s).length+Ri.encode(r).length,t>65536)throw fe("hint bytes exceed bound");e.set(s,r)}let i=new Map([[0,T.enc(n.record)],[1,H.enc(n.sourceRevision)],[2,Yt(n.ordinal,4294967295)],[3,e],[4,je(n.captureTimezone,128)],[5,Fm]]);if(n.window!==void 0){let s=Bm(n.window);i.set(6,new Map([[0,s.offset],[1,s.limit]]))}let o=pe(i);if(o.length>mO)throw fe("request bytes exceed bound");return o}function n_(n){let e=ai(n,[0,1,2,3,4,5,6]);return{record:T.dec(e.get(0)),path:je(e.get(1)),sourceRevision:H.dec(e.get(2)),ordinal:Yt(e.get(3),4294967295),name:e.get(4)===null?null:je(e.get(4)),viewType:je(e.get(5)),implementations:$t(e.get(6),ws).map(t=>{let i=ai(t,[0,1,2,3]);return{typeName:je(i.get(0)),version:je(i.get(1)),contractDigest:H.dec(i.get(2)),implementationDigest:H.dec(i.get(3))}})}}function Zp(n,e){if(!(n instanceof Uint8Array)||!n.length||n.length>hO)throw fe("response bytes exceed bound");let t=ue(n);if(!(t instanceof Map))throw fe("result struct required");let i=t;if(i.get(0)!==1)throw fe("unknown result version",!0);if(i.has(7)){let b=ai(i,[0,7]);return{kind:"refusal",problem:An.dec(b.get(7))}}let o=i.has(8),s=i.has(9),r=ai(i,[0,1,2,3,4,5,6,...o?[8]:[],...s?[9]:[]]);if(e!==void 0&&o!==(e!==null))throw fe("window response differs from request");let a=n_(r.get(1)),p=ai(r.get(2),[0,1]),l=$t(p.get(0),64).map(b=>je(b)),c=$t(p.get(1),64).map(b=>{let w=ai(b,[0,1,2]),g=Yt(w.get(0),63);if(g>=l.length)throw fe("unavailable column index out of bounds");return{index:g,code:je(w.get(1)),detail:je(w.get(2))}}),d=$t(r.get(3),jn).map(b=>{let w=Cl(b,4),g=$t(w[3],64);if(g.length!==l.length)throw fe("row cell count differs from columns");return{record:T.dec(w[0]),path:je(w[1]),sourceRevision:H.dec(w[2]),cells:g.map(y=>yo(y))}}),u=$t(r.get(4),jn).map(b=>{let w=Cl(b,2),g=yo(w[0]);if(!t_(g))throw fe("group key must be a qualified scalar or list");let y=$t(w[1],jn).map(v=>{let _=Yt(v,jn-1);if(_>=d.length)throw fe("group row index out of bounds");return _});return{key:g,rowIndices:y}}),f;if(o){let b=ai(r.get(8),[0,1,2,3]),w=Bm({offset:Yt(b.get(0),4294967295),limit:Yt(b.get(1),jn)}),g=Yt(b.get(2),jn);if(d.length!==Math.min(w.limit,Math.max(g-w.offset,0)))throw fe("window row count differs from total/request");if(e!=null){let k=Bm(e);if(w.offset!==k.offset||w.limit!==k.limit)throw fe("window echo differs from request")}let y=-1,v=$t(b.get(3),jn);if(v.length!==u.length||u.some(k=>k.rowIndices.length===0))throw fe("group placements must align represented groups");let _=v.map((k,S)=>{let x=Cl(k,3),P=Yt(x[0],jn-1),C=Yt(x[1],jn);if(P<=y||P>=g||C===0||C>g)throw fe("group placement bounds/order invalid");y=P;let E=-1,O=$t(x[2],jn).map(L=>{let z=Yt(L,jn-1);if(z<=E||z>=C)throw fe("group row ordinal bounds/order invalid");return E=z,z});if(O.length!==u[S].rowIndices.length)throw fe("group ordinal count differs from represented rows");return{globalGroupOrdinal:P,totalGroupRows:C,rowOrdinals:O}});f={...w,totalMatchedRows:g,groupPlacements:_}}let h=fo.dec(r.get(5));if(!Number.isSafeInteger(h.instant))throw fe("clock instant exceeds JS-safe range");let m=s?bO(r.get(9)):void 0;return{kind:"success",view:a,columns:l,unavailableColumns:c,rows:d,groups:u,clock:h,collectionRevision:H.dec(r.get(6)),...f===void 0?{}:{window:f},...m===void 0?{}:{summaries:m}}}function i_(n){if(n==null)return null;if(!(n instanceof Uint8Array)||n.length!==32)throw fe("native discovery handle must be 32 bytes");return new Uint8Array(n)}function Qp(n){let e=Yt(n.limit,128);if(!e)throw fe("discovery limit must be positive");return pe(new Map([[0,1],[1,je(n.captureTimezone,128)],[2,e],[3,i_(n.continuation)]]))}function ed(n){return pe(new Map([[0,1],[1,T.enc(n.record)],[2,H.enc(n.sourceRevision)],[3,Yt(n.ordinal,4294967295)],[4,je(n.captureTimezone,128)]]))}function r_(n){if(!(n instanceof Uint8Array)||!n.length||n.length>1024*1024)throw fe("discovery response bytes exceed bound");let e=ue(n);if(!(e instanceof Map))throw fe("discovery result struct required");let t=e;if(t.get(0)!==1)throw fe("unknown discovery result version");return t}function o_(n){let e=n_(n);if(!e.implementations.length||e.implementations.length>16)throw fe("bounded native implementation provenance required");return e}function s_(n){let e=fo.dec(n);if(!Number.isSafeInteger(e.instant))throw fe("clock instant exceeds JS-safe range");return je(e.tz,128),je(e.localDate,128),e}function td(n,e=128){let t=Yt(e,128);if(!t)throw fe("discovery limit must be positive");let i=r_(n);if(i.has(7)){let a=ai(i,[0,7]);return{kind:"refusal",problem:An.dec(a.get(7))}}let o=ai(i,[0,1,2,3,4]),s=$t(o.get(1),t).map(o_);for(let a=1;a<s.length;a++){let p=s[a-1],l=s[a];if(p.record>l.record||p.record===l.record&&p.ordinal>=l.ordinal)throw fe("discovery source/ordinal frontier must ascend");if(p.record===l.record&&(p.path!==l.path||p.sourceRevision!==l.sourceRevision))throw fe("one source identity cannot have two revisions/paths within a page")}let r=o.get(4);if(r!==null&&!(r instanceof Uint8Array))throw fe("native discovery handle required");return{kind:"success",views:s,clock:s_(o.get(2)),collectionRevision:H.dec(o.get(3)),continuation:i_(r)}}function nd(n,e){let t=r_(n);if(t.has(7)){let r=ai(t,[0,7]);return{kind:"refusal",problem:An.dec(r.get(7))}}let i=ai(t,[0,1,2,3,4]),o=o_(i.get(1)),s=je(i.get(2),512*1024);if(si(s)!==o.sourceRevision)throw fe("exact native source SHA differs from bytes");if(e&&(o.record!==T.dec(T.enc(e.record))||o.sourceRevision!==H.dec(H.enc(e.sourceRevision))||o.ordinal!==e.ordinal))throw fe("exact source identity/revision/ordinal differs from request");return{kind:"success",view:o,source:s,clock:s_(i.get(3)),collectionRevision:H.dec(i.get(4))}}var Fm,hO,mO,yO,ws,jn,Ri,fe,Vm=I(()=>{"use strict";Je();ge();Oi();At();Fm="whole-view-synthetic-policy-reference-v1",hO=16*1024*1024,mO=128*1024,yO=4096,ws=4096,jn=65536,Ri=new TextEncoder,fe=(n,e=!1)=>new ne("app-bases-v1",n,e)});async function*l_(n,e,t={}){let i=a_(t.firstPageSize,200),o=a_(t.pageSize,1e3),s=e.window?.offset??0,r=0,a=0,p;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 c=l.window?.totalMatchedRows;if(c===void 0)throw A("internal","native Bases page omitted its window");p??={revision:l.collectionRevision,total:c},r+=l.rows.length;let d=l.rows.length===0||s+l.rows.length>=c;if(yield{...l,page:a,offset:s,loaded:r,complete:d,changedSinceFirst:p.revision!==l.collectionRevision||p.total!==c},d)return;s+=l.rows.length,a+=1}}var a_,c_=I(()=>{"use strict";ie();a_=(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 p_(n){if(n==="request"||n==="single_record"||n==="cross_record")return n;throw new ne("validation-tier","unknown diagnostic tier",!0)}function f_(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=T.dec(T.enc(i));e.push(T.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=T.dec(T.enc(i.id)),r=H.dec(H.enc(i.revision));e.push(T.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 h_(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 wO,vO,_O,d_,Or,u_,m_=I(()=>{"use strict";ge();Je();At();ie();wO={name:"validation-tier",enc:p_,dec:p_},vO=N("validation-issue",[[0,"code",R],[1,"severity",Mp],[2,"message",R],[3,"details",at,"opt"],[4,"location",R,"opt"],[5,"typeName",R,"opt"],[6,"tier",wO]]),_O=N("record-validation",[[0,"id",T],[1,"issues",F(vO)],[2,"path",R],[3,"revision",H]]),d_=F(_O),Or=n=>new ne("record-validations",n),u_={name:"record-validations",enc:n=>d_.enc(n),dec:n=>{if(!Array.isArray(n)||n.length>1e3)throw Or("invalid inventory");let e=0,t=0,i=[[n,0]];for(;i.length;){let[s,r]=i.pop();if(++t>65536||r>32)throw Or("result exceeds tree bounds");if(Array.isArray(s)){if(s.length>65536)throw Or("oversized array");for(let a of s)i.push([a,r+1])}else if(s instanceof Map){if(s.size>32768)throw Or("oversized map");for(let[a,p]of s)i.push([a,r+1],[p,r+1])}}for(let s of n){let r=s instanceof Map?s.get(1):void 0;if(!Array.isArray(r))throw Or("missing diagnostics");if(e+=r.length,e>4096)throw Or("too many diagnostics")}if(pe(n).byteLength>1024*1024)throw Or("result exceeds byte bounds");let o=d_.dec(n);for(let s of o)if(!s.path||new TextEncoder().encode(s.path).byteLength>4096)throw Or("invalid current path");return o}}});function AO(n){if(n.length>Rr)throw A("too_large",`frame of ${n.length} bytes exceeds ${Rr}`);let e=new Uint8Array(4+n.length);return new DataView(e.buffer).setUint32(0,n.length),e.set(n,4),e}function Km(n){return y_.has(n)}function id(n){let e=new Il,t=!1,i=null,o=[],s={get onframe(){return i},set onframe(a){if(i=a,a&&o.length)for(let p of o.splice(0))a(p)},onclose:null,send(a){if(t)throw A("unavailable","connection closed");n.write(AO(pe(a)))},close(){t||(t=!0,n.close(),s.onclose?.())}};y_.add(s),n.ondata=a=>{try{for(let p of e.push(a)){let l=ue(p);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(p){r(p instanceof se?p:A("internal",`invalid frame from replica: ${String(p)}`))}},n.onclose=a=>r(a);function r(a){t||(t=!0,n.close(),s.onclose?.(a))}return s}function g_(){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 Rr,Il,y_,Ol=I(()=>{"use strict";Je();ie();Rr=16*1024*1024,Il=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>Rr)throw A("too_large",`frame of ${i} bytes exceeds ${Rr}`);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}}};y_=new WeakSet});var rd,b_=I(()=>{"use strict";ie();rd=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,p=!1,l=new Promise((u,f)=>{r=u,a=f}),c=()=>{p||(p=!0,s.fill(0),a(A("cancelled","Bases READ cancelled")))};o?.addEventListener("abort",c,{once:!0});let d=async()=>{try{if(p)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(p||o?.aborted){u.fill(0),c();return}p=!0,r(u)}catch(u){p||(p=!0,a(u))}finally{s.fill(0),o?.removeEventListener("abort",c),this.occupied--}};return this.tail=this.tail.then(d,d),l}}});function w_(n,e){od.set(n,e)}function v_(n,e){let t=od.get(n);t&&od.set(e,t)}function __(n){return od.get(n)}var od,Wm=I(()=>{"use strict";od=new WeakMap});function Nn(n,e){return oe(n)?n:n instanceof ne&&n.unknown?A("upgrade_required",`${e}: ${n.message}`,{reason:"unknown_variant"}):A("internal",`${e}: ${n instanceof Error?n.message:String(n)}`)}function vs(n,e,t){return new se(Nn(n,e).toProblem(),{...t,cause:n})}var sd,A_,Hm,go,Rl=I(()=>{"use strict";ge();ie();Ol();b_();Wm();At();sd=[{major:1,minor:3},{major:1,minor:2},{major:1,minor:1},{major:1,minor:0}];A_=new WeakSet,Hm=n=>n instanceof se&&A_.has(n),go=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 rd((e,t)=>this.request(e,new Map([[0,t]])));device;static async open(e,t,i){let o=Qi.enc({kind:"request",id:0,method:"hello",params:lm.enc(t)}),s;try{s=await e.open(o,i)}catch(p){throw oe(p)?p:A("unavailable",`cannot reach the replica (${e.description}): ${String(p)}`)}let r;try{let p=Qi.dec(s.helloResponse);if(p.kind!=="response"||p.id!==0)throw A("internal","replica answered hello with another frame");if(p.problem)throw new se(p.problem);r=um.dec(p.result??null)}catch(p){throw s.port.close(),Nn(p,"hello")}let a=new n(s.port,r);return v_(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"&&!Km(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"&&!Km(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{}p.reject(A("cancelled",`${e} cancelled`))},p={resolve:l=>{p.cleanup();try{s(i.codec?i.codec.dec(l):l)}catch(c){r(Nn(c,`${e} result`))}},reject:l=>{p.cleanup(),r(l)},cleanup:()=>{this.pending.delete(o),i.signal?.removeEventListener("abort",a)}};this.pending.set(o,p),i.signal?.addEventListener("abort",a,{once:!0});try{this.sendFrame({kind:"request",id:o,method:e,params:t})}catch(l){p.reject(oe(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(Qi.enc(e))}onFrame(e){let t;try{t=Qi.dec(e)}catch(i){if(i instanceof ne&&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 se(t.problem);A_.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=(oe(a)?a:A("internal",String(a))).toProblem()}if(!this.closedFlag)try{this.port.send(Qi.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 S_(n,e){return oe(n,"unavailable")&&n.reason==="hosted_chunk_busy"&&Date.now()<e}function P_(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",p),o()},i),p=()=>{clearTimeout(a),s(A("cancelled",`${e} aborted`))};t?.addEventListener("abort",p,{once:!0})})}function Ym(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=SO.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 I_(n,e){El.set(n,e)}function x_(n){return typeof n=="string"?T.enc(n):"id"in n?T.enc(n.id):n.path}function Gm(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 nr(n){let e=new Map;for(let[t,i]of n)i!==void 0&&e.set(t,i);return e}async function C_(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 PO(n){return n instanceof Uint8Array||n instanceof ArrayBuffer?n.byteLength:n.size}var k_,ad,kO,SO,El,_s,ql=I(()=>{"use strict";Cr();ge();ie();Rl();Oi();At();k_=9e4;ad=64*1024*1024,kO=8*1024*1024,SO=[["list","collection.read"],["read","collection.read"],["add","records.create"],["replace","records.edit"],["move","records.edit"],["delete","records.delete"]];El=new WeakMap;_s=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=Ym(this.client.hello),t=El.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(t.cursor,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})})}wire(e){this.wired.has(e)||(this.wired.add(e),e.onPush("transfer_progress",t=>{try{let i=$p.dec(t);this.progress.get(i.id)?.(i)}catch{}}),e.onPush("file_chunk",t=>{try{let i=Up.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,p)=>a+p.bytes.length,0)+i.bytes.length<=kO&&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}=Dp.dec(t),s=this.streams.get(i);s?(this.streams.delete(i),s.onEnd(new se(o))):this.opening>0&&this.earlyFailures.size<16&&this.earlyFailures.set(i,new se(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(e));return this.wire(i),i}listPage(e={}){return this.client.call("list_files",nr([[0,e.folder],[1,e.media?.map(t=>fs.enc(t))],[2,e.cursor],[3,e.limit]]),{codec:Sm,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",nr([[0,x_(e)]]),{codec:kl,retry:!0,...t?{signal:t}:{}})}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(El.get(this)?.check(i.fileId?"replace":"add"),i.signal?.aborted)throw A("cancelled","upload aborted");let o=PO(t),s=it.create(),r=4*1024*1024;for(let d=0;d<o;d+=r)s.update(await C_(t,d,Math.min(o,d+r)));let a=nm(s.digest()),p=i.transferId??Ln(),l={transfer:p,path:e,size:o,digest:a,mutationId:i.mutationId??Ln()};i.fileId&&(l.fileId=i.fileId),i.ifRevision&&(l.ifRevision=i.ifRevision),i.onProgress&&this.progress.set(p,i.onProgress);let c=Date.now()+k_;for(;;)try{return await this.uploadOnce(t,o,l,i)}catch(d){if(oe(d,"unavailable")&&this.client.link==="reconnecting")continue;if(S_(d,c)){await P_(d,"upload",i.signal);continue}throw this.progress.delete(p),await this.abortUpload(p).catch(()=>{}),vs(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",Pm.enc(i),{codec:xm,...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 p=new Set(a.received),l=Math.ceil(t/a.chunkSize),c=p.size*a.chunkSize,d=new Set;for(let h=0;h<l;h++){if(p.has(h))continue;let m=h*a.chunkSize,b=await C_(e,m,Math.min(t,m+a.chunkSize)),w=s.request("upload_chunk",Cm.enc({transfer:i.transfer,index:h,bytes:b}),r).then(()=>{c+=b.length,o.onProgress?.({id:i.transfer,phase:"receiving",done:Math.min(c,t),total:t})});d.add(w),w.finally(()=>d.delete(w)).catch(()=>{}),d.size>=4&&await Promise.race(d)}await Promise.all(d);let u=await s.request("commit_upload",nr([[0,T.enc(i.transfer)]]),{codec:kt,...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",nr([[0,T.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 p=this,l=new AbortController,c=A("cancelled","file download cancelled"),d=!1,u=!1,f=!1,h=()=>{},m=()=>{i!==null&&(p.streams.delete(i),p.early.delete(i),f||(f=!0,o?.request("cancel_stream",nr([[0,i]])).catch(()=>{})))},b=()=>{u||(d=!0,h(),r(c),l.abort(),m())},w=new ReadableStream({async start(g){let y=()=>{u||d||(b(),g.error(c))};if(h=()=>t.signal?.removeEventListener("abort",y),t.signal?.addEventListener("abort",y,{once:!0}),t.signal?.aborted){y();return}try{if(o=await p.session(l.signal,!0),d)return;let v=nr([[0,x_(e)]]);t.range&&v.set(1,[t.range[0],t.range[1]]),t.revision&&v.set(2,H.enc(t.revision));let _=0,k=0;p.opening++;let S;try{let O=Date.now()+k_;for(;;)try{S=await o.request("read_file",v,{signal:l.signal});break}catch(L){if(!S_(L,O))throw L;await P_(L,"download",l.signal)}}finally{p.opening--}i=B.dec(S.get(0)??null);let x=p.early.get(i)??[],P=p.earlyFailures.get(i);if(p.early.delete(i),p.earlyFailures.delete(i),p.opening===0&&(p.early.clear(),p.earlyFailures.clear()),d){m(),u=!0;return}let C=kl.dec(S.get(1)??null);s(C),_=t.range?t.range[1]:C.size;let E=O=>{d||u||(g.enqueue(O.bytes),k+=O.bytes.length,t.onProgress?.({id:i,phase:"streaming",done:k,total:_}),!(d||u)&&(o.request("ack_chunks",nr([[0,i],[1,O.offset+O.bytes.length]])).catch(()=>{}),O.last&&!d&&!u&&(u=!0,h(),p.streams.delete(i),g.close())))};p.streams.set(i,{onChunk:E,onEnd:O=>{u=!0,h(),g.error(O??A("unavailable","stream ended"))}});for(let O of x)E(O);P&&!u&&(p.streams.delete(i),u=!0,h(),g.error(P))}catch(v){u=!0,h(),p.opening===0&&(p.early.clear(),p.earlyFailures.clear()),m(),r(v),g.error(v)}},cancel:b});return Object.assign(w,{file:a})}async download(e,t={}){let i=typeof e=="object"&&"size"in e?e:await this.get(e,t.signal);if(i.size>ad)throw A("too_large",`file is ${i.size} bytes; use downloadStream`,{details:new Map([["limit",ad]])});let o=new Uint8Array(i.size),s=0,r=this.downloadStream(i,t).getReader();for(;;){let{done:a,value:p}=await r.read();if(a)break;o.set(p,s),s+=p.length}return o.subarray(0,s)}fetch(e,t){return this.client.call("fetch_file",nr([[0,T.enc(Gm(e))]]),{retry:!0,...t?{signal:t}:{}}).then(()=>{})}evict(e){return this.client.call("evict_file",nr([[0,T.enc(Gm(e))]])).then(()=>{})}getMaterialization(){return this.client.call("get_materialization",null,{codec:zp,retry:!0})}setMaterialization(e){return this.client.call("set_materialization",zp.enc(e)).then(()=>{})}async move(e,t,i={}){El.get(this)?.check("move");let o={kind:"file_move",id:e.id,from:e.path,to:t,updateRefs:i.updateRefs??!0},[s]=await this.client.submit([i.ifRevision?{...o,ifRevision:i.ifRevision}:o],i);return s}async delete(e,t={}){El.get(this)?.check("delete");let i={kind:"file_delete",id:Gm(e)};typeof e=="object"&&"digest"in e&&(i.base=e.digest),t.ifRevision&&(i.ifRevision=t.ifRevision);let[o]=await this.client.submit([i],t);return o}}});async function ld(n,e,t,i,o={}){i?.throwIfAborted();let s=o.concurrency??8;if(!Number.isSafeInteger(s)||s<1||s>Xm)throw A("invalid_request","readMany concurrency must be 1..16","read_many_bounds");if(!Array.isArray(e)||e.length>Jm)throw A("invalid_request","readMany accepts at most 1000 record selections","read_many_bounds");let r=Array.from(e,xO),a=t?Object.freeze({...t}):void 0,p=new Array(r.length),l=0,c=!1,d;async function u(){for(;!c&&l<r.length;)try{i?.throwIfAborted();let f=l++,h=r[f],m=await n.get(h,a,i);if(i?.throwIfAborted(),c)return;if(typeof h=="string"&&m.id!==h)throw A("invalid_request","readMany readback belongs to another UUID","read_many_identity_mismatch");p[f]=m}catch(f){c||(c=!0,d=f);return}}if(await Promise.all(Array.from({length:Math.min(s,r.length)},()=>u())),c)throw d;return i?.throwIfAborted(),p}function xO(n){if(typeof n=="string")return T.dec(T.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 T.dec(T.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 cd(n,e,t,i,o={}){return n.pages(e,t,i,o)}async function O_(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,p=e?.field,l=k=>typeof k=="string"&&k.length>0&&k.length<=4096&&new TextEncoder().encode(k).byteLength<=4096;if(!l(a)||!l(p))throw A("invalid_request","record link path/field must be nonempty and bounded","record_links_bounds");let c=JSON.stringify(p),d=`(${c} in raw ? raw[${c}] : 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}]},void 0,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 b=h.records[0].values;if(b===void 0)throw A("upgrade_required","native record link projection unsupported","record_links_unsupported");if(!(b instanceof Map)||b.size!==2||!b.has("raw")||!b.has("paths"))throw m();let w=b.get("raw"),g=b.get("paths"),y=w===null?[]:typeof w=="string"?[w]:w;if(!Array.isArray(y)||!Array.isArray(g)||y.length!==g.length||y.length>1e3)throw m();let v=0,_=[];for(let k=0;k<y.length;k++){let S=y[k],x=g[k];if(typeof S!="string"||S.length>(1<<20)-v||x!==null&&!l(x)||(v+=new TextEncoder().encode(S).byteLength+(x===null?0:new TextEncoder().encode(x).byteLength),v>1<<20))throw m();_.push(Object.freeze({raw:S,path:x}))}return r(),Object.freeze(_)}var Jm,Xm,Zm=I(()=>{"use strict";ge();ie();Jm=1e3,Xm=16});function As(n,e){if((n.document?.length??0)>Tl||(n.body?.length??0)>Tl)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"||si(n.document)!==n.revision)throw A("invalid_request","record session needs actual complete, revision-consistent source and identity","record_witness_required")}function bo(n){return n.state.hold!==void 0||n.state.unresolved!==void 0&&n.state.unresolved!==0}function wo(n){return n.state.state==="confirmed"&&!bo(n)}function Tt(n){return Mn.dec(ue(pe(Mn.enc(n))))}function Ll(n){return n instanceof se?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 cn(n,e,t){return new se({code:n,message:e,reason:t,recovery:n==="conflict"?"resolve_conflict":n==="outcome_unknown"?"resolve_outcome":"retry"})}function Qm(n){return pe(Mn.enc(n)).byteLength*2}function ey(n){if(n.length>Tl)throw A("invalid_request","record session draft exceeds retained budget","record_session_budget");return new TextEncoder().encode(n).byteLength*2}function jl(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 Ml,Tl,ty=I(()=>{"use strict";Je();ie();Oi();At();Ml={body:!0,document:!0,effective:!0},Tl=8*1024*1024});function Nl(n){return wo(n)?"saved":"saved_on_device"}function R_(n,e){let t=pe(n),i=pe(e);return t.length===i.length&&t.every((o,s)=>o===i[s])}function CO(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 IO(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 pd,E_=I(()=>{"use strict";Je();ie();Oi();At();ty();pd=class{constructor(e,t,i){this.client=e;this.reserve=i;As(t),this.base=Tt(t),this.body=t.body,this.state=bo(t)?"conflict":Nl(t),this.publish()}client;reserve;base;body;patch=new Map;remote=null;captured=null;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;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}}}e?.throwIfAborted(),this.captured&&(this.state="recovery",this.why=cn("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 retained(){return this.dirty||this.captured!==null||!wo(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.defaultTimeout=jl(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:ue(pe(ut(o))),r=this.base.frontmatter.get(i);!this.captured?.patch.has(i)&&(s===void 0&&r===void 0||s!==void 0&&r!==void 0&&R_(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":Nl(this.base),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){let a=Qm(i)+ey(e)+pe(new Map([...t].map(([p,l])=>[p,l??null]))).byteLength*2;o&&(a+=Qm(o)),r&&(a+=ey(r.body)+pe(new Map([...r.patch].map(([p,l])=>[p,l??null]))).byteLength*2),s&&(a+=pe(kt.enc(s)).byteLength*2),this.reserve(a)}publish(){this.charge();let e=new Map(this.base.frontmatter);for(let[t,i]of this.patch)i===void 0?e.delete(t):e.set(t,i);this.snapshot=Object.freeze({state:this.state,body:this.body,frontmatter:ue(pe(e)),record:Tt(this.base),remote:this.remote?Tt(this.remote):null,dirty:this.dirty,problem:this.why,lastReceipt:this.lastReceipt?kt.dec(ue(pe(kt.enc(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,Ml,e);return e.throwIfAborted(),As(t,this.id),t}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;try{let t=await this.read(e);if(this.captured||this.running){this.captured&&!this.running&&this.start(!1,{}).catch(()=>{});continue}this.charge(this.body,this.patch,this.base,t),this.dirty?(t.revision!==this.base.revision||bo(t))&&(this.remote=Tt(t),this.state="conflict",this.why=cn("conflict","record changed while this draft was open","record_session_conflict").toProblem()):(this.base=Tt(t),this.body=t.body,this.remote=null,this.state=bo(t)?"conflict":Nl(t),this.why=null),this.publish()}catch(t){if(e.aborted)return;this.why=Ll(t),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=jl(t.timeoutMs??this.defaultTimeout),o=CO(i),s=AbortSignal.any([...t.signal?[t.signal]:[],o.signal]),r=this.running;if(r&&(this.writing||!e))return IO(r,s).finally(o.clear);let a=AbortSignal.any([this.life.signal,s]),p={until:Date.now()+i,margin:Math.min(2e3,Math.floor(i/4))},l=()=>this.drive(a,p,e),c=(r?r.then(l,l):l()).finally(()=>{o.clear(),this.running===c&&(this.running=null,this.writing=!1,this.schedule())});return this.running=c,this.writing=e,c}async drive(e,t,i){try{for(;;){if(e.throwIfAborted(),this.captured){await this.settle(e,t);continue}if(!i)return wo(this.base)?{ok:!0,record:Tt(this.base)}:{ok:!0,record:Tt(this.base),saved:"on_device"};let o=await this.read(e);if(bo(o))throw this.charge(this.body,this.patch,this.base,o),this.remote=Tt(o),cn("conflict","native hold/unresolved edits require native resolution before saving","native_protection_resolution_required");if(this.state==="deleted")throw cn("conflict","the original record was deleted","record_deleted");if(!this.dirty)return this.charge(o.body,this.patch,o,null),this.base=Tt(o),this.body=o.body,this.remote=null,this.state=Nl(o),this.why=null,this.publish(),wo(o)?{ok:!0,record:Tt(o)}:{ok:!0,record:Tt(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=Tt(o),cn("conflict","explicitly resolve the current native revision before saving","record_session_conflict");As(this.base,this.id),this.base=Tt(o);let s=this.body,r=new Map(this.patch),a=Ln(),p={bound:!0,body:s,patch:r,recovery:{mutationId:a,recordId:this.id,baseRevision:this.base.revision,receipt:null,write:null}};this.charge(this.body,this.patch,this.base,this.remote,this.lastReceipt,p),this.captured=p,this.state="saving",this.why=null,this.publish();let l={ifRevision:this.base.revision};s!==this.base.body&&(l.body=s);let c=new Map,d=[];for(let[f,h]of r)h===void 0?d.push(f):c.set(f,h);c.size&&(l.patch=c),d.length&&(l.unset=d);let u=await this.client.update(Tt(this.base),l,{mutationId:a,include:Ml,conflictMode:"reject",signal:e});if(e.throwIfAborted(),u.mutationId!==a)throw cn("outcome_unknown","native write changed its original mutation identity","mutation_identity_mismatch");this.captured.recovery={...this.captured.recovery,write:u,receipt:u.receipt},this.publish()}}catch(o){return this.why=Ll(o),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,Math.max(1,t.until-Date.now()-t.margin),e);if(e.throwIfAborted(),s.mutation!==o.mutationId)throw cn("outcome_unknown","native receipt belongs to another mutation","mutation_identity_mismatch");let r=s.records?.some(c=>c.id===o.recordId)??!1;if(s.records?.length&&!r||!i.bound&&s.state==="confirmed"&&!r)throw cn("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 cn("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 se(s.problem):cn("conflict","original mutation conflicted","record_session_conflict");let a=await this.read(e);if(s.state==="pending"?bo(a):!wo(a))throw cn("outcome_unknown","confirmed receipt has pending/protected current readback","unqualified_readback");this.charge(this.body,this.patch,a,null);let l=this.body===i.body;for(let[c,d]of i.patch){let u=this.patch.get(c);this.patch.has(c)&&(d===void 0?u===void 0:u!==void 0&&R_(d,u))&&this.patch.delete(c)}this.base=Tt(a),l&&(this.body=a.body),this.captured=null,this.remote=null,this.state=this.dirty?"unsaved":Nl(a),this.why=null,this.publish()}resolve=e=>{if(this.ensure(),this.captured||this.running)throw cn("outcome_unknown","recover the original mutation before resolving or preparing another","record_recovery_required");let t=this.remote;if(!t||!wo(t))throw cn("conflict","a confirmed unprotected native record is required for resolution","native_protection_resolution_required");let i="body"in e?e.body:e.keep==="theirs"?t.body:this.body,o="keep"in e&&e.keep==="theirs"?new Map:this.patch;this.charge(i,o,t,null),this.base=Tt(t),this.body=i,this.patch=o,this.remote=null,this.state=this.dirty?"unsaved":"saved",this.why=null,this.publish(),this.schedule()}}});var dd,q_=I(()=>{"use strict";ie();ge();E_();ty();dd=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:T.dec(T.enc(i.recovery.mutationId)),recordId:T.dec(T.enc(i.recovery.recordId))},i.recovery.baseRevision!==null&&H.enc(i.recovery.baseRevision)),jl(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,Ml,t.signal);if(t.signal?.throwIfAborted(),this.closed)throw A("unavailable","record sessions client closed");As(i);let o=typeof e=="string"?e:"id"in e?e.id:void 0,s=o===void 0?void 0:T.dec(T.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]),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 autosave 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 pd(this.client,i,m=>{let b=this.bytes-h.bytes+m;if(b>Tl)throw A("invalid_request","record session retained data exceeds 8MiB","record_session_budget");this.bytes=b,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 p=a,l=!1,c=new Set,d=()=>{if(l)throw A("cancelled","record lease released")},u=Object.freeze({getSnapshot:p.session.getSnapshot,subscribe:h=>{d();let m=p.session.subscribe(h);return c.add(m),()=>{c.delete(m),m()}},setBody:h=>{d(),p.session.setBody(h)},patchFrontmatter:h=>{d(),p.session.patchFrontmatter(h)},resolve:h=>{d(),p.session.resolve(h)},flush:h=>(d(),p.session.flush(h))}),f=()=>{if(!l){l=!0,t.signal?.removeEventListener("abort",f);for(let h of c)h();c.clear(),--p.leases===0&&(p.session.suspend(),p.session.retained||(this.bytes-=p.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()),p.session.refresh(),Object.freeze({session:u,release:f})}startWatch(){if(this.watch)return;let e=this.client.watchChanges(void 0,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(Ll(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 OO(n,e){let t=li(n.get("properties")),i=[],o=Array.isArray(e.get("select"))?e.get("select"):[];for(let s of o){let r=li(s),a=Jt(s),p=r?Jt(r.get("name")):a?.slice(a.lastIndexOf(".")+1);if(!p)continue;let l=li(t?.get(r||!a?p:a))??li(t?.get(p)),c={key:p},d=Jt(r?.get("label"))??Jt(l?.get("label")),u=Jt(r?.get("description"))??Jt(l?.get("description")),f=Jt(l?.get("format")),h=l?.get("hidden");d!==void 0&&(c.label=d),u!==void 0&&(c.description=u),f!==void 0&&(c.format=f),typeof h=="boolean"&&(c.hidden=h),i.push(c)}return i}async function j_(n,e,t){let i=[],o=[],s=e?e.replace(/\/?$/,"/"):"",r,a=!0;do{let p;try{p=await n.queryContract(Ul,{...r?{cursor:r}:{},...t?{signal:t}:{}})}catch(l){if(oe(l,"not_found")&&l.reason==="data_contract_not_found")return{sources:i,diagnostics:o,complete:!0};throw l}a&&=p.page.complete,p.records.forEach((l,c)=>{let d=p.page.records[c];if(!d.path.startsWith(s))return;let u=l.implementations[0],f=u?.issues.find(w=>w.severity==="error");if(!u||f){o.push(T_("invalid_view",f?.message??"View record does not implement mdbase.view.",d.path));return}let h=u.fields,m=[],b=new Set;for(let w of Array.isArray(h.get("views"))?h.get("views"):[]){let g=li(w),y=Jt(g?.get("id")),v=Jt(g?.get("name"));if(!g||!y||!v)continue;if(b.has(y)){o.push(T_("invalid_view","View record contains duplicate named-view IDs.",d.path));return}b.add(y);let _={id:y,name:v,properties:OO(h,g)};g.has("presentation")&&(_.presentation=g.get("presentation")),m.push(_)}i.push({record:d.id,id:Jt(h.get("id"))??d.path,name:Jt(h.get("name"))??d.path,source:{path:d.path,format:Ul.id,revision:d.revision,writable:!0},views:m})}),r=p.page.cursor}while(r);return i.sort((p,l)=>p.source.path<l.source.path?-1:p.source.path>l.source.path?1:0),{sources:i,diagnostics:o,complete:a}}async function N_(n,e,t,i={}){let o=i.signal,s=await n.getContract(e,Ul,o).catch(v=>M_(v,L_(e))),r=s.fields,a=s.path,p=Array.isArray(r.get("views"))?r.get("views").map(li):[],l=p.map(v=>Jt(v?.get("id")));if(new Set(l).size!==l.length)throw A("invalid_request","View record contains duplicate named-view IDs.","invalid_view");let c=p[l.indexOf(t)];if(!c)throw A("not_found",`named view '${t}' was not found`,"view_not_found");let d=li(r.get("query"))??new Map,u=new Map,f=c.get("types")??d.get("types");f!==void 0&&u.set("types",f);let h=[Jt(d.get("where")),Jt(c.get("where"))].filter(v=>!!v);h.length&&u.set("where",h.length===2?`(${h[0]}) && (${h[1]})`:h[0]);let m=new Map(li(d.get("projections")));for(let[v,_]of li(c.get("projections"))??[]){let k=m.get(v);if(k!==void 0&&ud(k)!==ud(_))throw A("invalid_request",`Projection '${v}' has conflicting definitions.`,"invalid_view");m.set(v,_)}m.size&&u.set("projections",m);for(let v of["select","order_by","group_by","summaries","limit","offset","include_body","frontmatter_mode"])c.has(v)&&u.set(v,c.get(v));r.has("summary_functions")&&u.set("summary_functions",r.get("summary_functions")),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=li(li(c.get("context")??d.get("context"))?.get("this")),w=Jt(b?.get("on_missing"))??"view",g=i.context;if(g===void 0&&w==="error")throw A("invalid_request","This named view requires an invocation context.","context_required");if(g===void 0&&w==="view"&&(g={path:a}),g!==void 0){let v=Array.isArray(b?.get("types"))?b.get("types").filter(k=>typeof k=="string"):[],_=typeof g=="string"?void 0:g.path;if(v.length||_===void 0){let k=await n.get(g,void 0,o);if(_=k.path,v.length&&!k.types.some(S=>v.some(x=>x.toLowerCase()===S.toLowerCase())))throw A("invalid_request","The invocation context does not match an allowed context type.","context_type_mismatch")}u.set("context",new Map([["this",new Map([["path",_]])]]))}return{...await n.query(u,i.include,o),view:{path:a,view:t}}}async function U_(n,e,t){let i=await n.getContract(e,Ul,t).catch(s=>M_(s,L_(e))),o=await n.get(i.id,{document:!0},t);if(o.revision!==i.revision||typeof o.document!="string")throw A("unavailable","saved view source changed while it was read","view_source_changed");return{path:o.path,format:Ul.id,revision:o.revision,document:o.document,record:o.id}}function ud(n){return n instanceof Map?`{${[...n].map(([e,t])=>[JSON.stringify(String(e)),ud(t)]).sort((e,t)=>e[0]<t[0]?-1:1).map(([e,t])=>`${e}:${t}`).join(",")}}`:Array.isArray(n)?`[${n.map(ud).join(",")}]`:typeof n=="bigint"?`${n}n`:JSON.stringify(n instanceof Uint8Array?[...n]:n)}var Ul,li,Jt,T_,M_,L_,D_=I(()=>{"use strict";ie();Ul=Object.freeze({id:"mdbase.view",version:"1.0.0"}),li=n=>n instanceof Map?n:void 0,Jt=n=>typeof n=="string"?n:void 0,T_=(n,e,t)=>({code:n,severity:"warning",message:e,details:new Map([["path",t]])}),M_=(n,e)=>{throw oe(n,"not_found")?A("not_found",`saved view source '${e}' was not found`,"view_not_found"):n},L_=n=>typeof n=="string"?n:n.path});function ir(n){return A("invalid_request",n,"view_source_witness_required")}function ny(n){try{T.enc(n)}catch{throw ir("view source writes need their original record and mutation UUIDs")}}function $_(n){if(!n||typeof n.path!="string"||n.path.length===0||typeof n.document!="string")throw ir("view source update needs the complete RecordView read with document included");ny(n.id);try{H.enc(n.revision)}catch{throw ir("view source needs its original source revision")}if(si(n.document)!==n.revision)throw ir("view source document differs from its captured revision")}function z_(n){return ny(n?.mutationId),{...n,include:{...n.include,document:!0}}}async function fd(n,e,t={}){let i=typeof e=="string"?e:"id"in e?e.id:void 0,o=i===void 0?void 0:T.dec(T.enc(i)),s=await n.get(e,{...t.include,document:!0},t.signal);if($_(s),o!==void 0&&s.id!==o)throw ir("view source readback belongs to another record");return s}function hd(n,e,t){if(ny(e?.id),typeof e.path!="string"||e.path.length===0||typeof e.document!="string")throw ir("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,z_(t))}function md(n,e,t,i){$_(e);let o=e.state;if(!o||o.state!=="pending"&&o.state!=="confirmed"||!Number.isSafeInteger(o.confirmedSeq)||o.confirmedSeq<0)throw ir("view source update needs actual native record state, not inferred confirmation");if(o.hold!==void 0||o.unresolved!==void 0&&o.unresolved!==0)throw ir("resolve the original view source hold or unresolved mutation before replacing its document");if(typeof t!="string")throw ir("view source update needs complete source text");return n.replaceDocument(e,t,{...z_(i),ifRevision:e.revision})}var iy=I(()=>{"use strict";ge();ie();Oi()});var B_,F_,V_=I(()=>{"use strict";ge();At();B_=N("contract-record-v1",[[0,"version",B],[1,"id",T],[2,"path",R],[3,"revision",H],[4,"type",R],[5,"fields",_n],[6,"contractDigest",H],[7,"implementationDigest",H]]),F_=N("contract-write-plan-v1",[[0,"version",B],[1,"type",R],[2,"patch",_n],[3,"unset",F(R)],[4,"base",F(Np)],[5,"contractDigest",H],[6,"implementationDigest",H],[7,"id",T,"opt"],[8,"path",R,"opt"],[9,"revision",H,"opt"]])});var K_,W_=I(()=>{"use strict";ge();At();K_=N("contract-query-v1",[[0,"version",B],[1,"page",_l],[2,"records",F(N("contract-query-record",[[0,"id",T],[1,"implementations",F(N("contract-projection",[[0,"typeName",R],[1,"fields",_n],[2,"issues",F(Zi)]]))]]))],[3,"contractDigest",H]])});var yd,H_=I(()=>{"use strict";yd=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}}});var G_,RO,ks,ry=I(()=>{"use strict";ge();ie();Oi();At();G_=4096,RO=100,ks=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,T.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=Bp.dec(t);for(let o of this.watchers.get(i.record)??[])o(i.peers)}catch{}}))}params(e,t){return new Map([[0,T.enc(e)],[1,t]])}check(e){if(JSON.stringify(e,(i,o)=>typeof o=="bigint"?o.toString():o instanceof Map?[...o]:o).length>G_)throw A("too_large","presence state over 4 KiB",{details:new Map([["limit",G_]])})}async join(e,t){let i=ut(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=ut(t),this.check(i.state),i.timer)return;let o=Math.max(0,i.last+RO-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,T.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,T.enc(e)]])))).catch(()=>{}),()=>{i.delete(t),i.size===0&&this.watchers.delete(e)}}}});function Y_(n){try{let e=ue(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:ri(t),seq:i}}catch{return null}}function qO(n){return n.replace(/-/g,"").toLowerCase()}function J_(n,e,t){if(!t)return;let i=Y_(e);if(!i||qO(t)!==i.device)return;let o=oy.get(n);o||oy.set(n,o=new Map);let s=o.get(i.device);if(!s){if(o.size>=EO)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 X_(n,e){let t=e?Y_(e)?.device:void 0,i=[];for(let[o,s]of oy.get(n)??[])if(o!==t)for(let[,r]of s.values())i.push(r);return i}var EO,oy,Z_=I(()=>{"use strict";Je();EO=64,oy=new Map});function gd(n){return Q_.add(n),n}function sy(n){return Q_.has(n)}var Q_,bd=I(()=>{"use strict";Q_=new WeakSet});function pn(n,e){return e===void 0?{}:{[n]:e}}function ay(n){let e=vo(n);return{id:Ke(e.id),version:Ke(e.version),digest:Ke(e.digest),installedBy:Ke(e.installed_by),resources:(Array.isArray(e.resources)?e.resources:[]).map(t=>{let i=vo(t);return{source:Ke(i.source),target:Ke(i.target),kind:Ke(i.kind),mode:Ke(i.mode),digest:Ke(i.digest),...pn("originDigest",Ke(i.origin_digest))}})}}function jO(n){let e=vo(n),t=e.upgrade_baseline===void 0?void 0:vo(e.upgrade_baseline),i=t&&(typeof t.version=="number"?t.version:typeof t.version=="string"?Number(t.version):void 0);return{source:Ke(e.source)??"",target:Ke(e.target),kind:Ke(e.kind),mode:Ke(e.mode),action:Ke(e.action),...pn("digest",Ke(e.digest)),...pn("currentDigest",Ke(e.current_digest)),...pn("installedDigest",Ke(e.installed_digest)),...pn("adoptedFromDigest",Ke(e.adopted_from_digest)),...pn("upgradeBaseline",t&&{digest:Ke(t.digest),...pn("version",i)}),...pn("reason",Ke(e.reason))}}function NO(n,e){return e?`${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 tA(n,e,t){let i=vo(bs(n)),o=(Array.isArray(i.resources)?i.resources:[]).map(jO),s=Object.fromEntries(LO.map(f=>[f,o.filter(h=>h.action===f).map(h=>h.target)])),r={},a=o.filter(f=>f.action==="conflict").map(f=>{let h=f.mode==="managed"&&f.currentDigest!==void 0&&f.installedDigest===void 0;return h&&(r[f.target]=f.currentDigest),{target:f.target,kind:f.kind,...pn("reason",f.reason),message:NO(f,h),...pn("adoptable",h?{digest:f.currentDigest}:void 0)}}),p=Ke(i.status),l=Array.isArray(i.issues)?i.issues.map(vo):[],c=ay(i.desired),d;if(i.definitions_manage!==!0)d={code:"forbidden",message:"This app doesn't have permission to change the collection's types."};else if(p==="downgrade"){let f=i.current===void 0?"a newer version":`version ${ay(i.current).version}`;d={code:"type_pack_downgrade",message:`${c.id} ${f} is installed; ${c.version} is older.`}}else if(a.length){let f=a.length;d={code:"type_pack_conflict",message:Object.keys(r).length===f?`${f===1?"A type already exists":`${f} types already exist`} with different content. Review and adopt ${f===1?"it":"them"} to continue.`:a.map(h=>h.message).join(" ")}}else(l.length||i.applicable!==!0)&&(d={code:"invalid_type_pack",message:`This pack would leave the collection invalid: ${Ke(l[0]?.message)??"the staged types do not validate"}.`});let u=vo(i.lock);return Object.freeze({status:p,canApply:i.applicable===!0&&d===void 0,digest:Ke(i.assessment_digest),summary:s,conflicts:a,adoptable:r,resources:o,...pn("current",i.current===void 0?void 0:ay(i.current)),desired:c,lock:{target:Ke(u.target),action:Ke(u.action),digest:Ke(u.digest)},...pn("refusal",d),pack:e,options:t})}function eA(n){return n&&Object.keys(n).length?ut(n):void 0}function UO(n){return n==null?!1:Array.isArray(n)?n.length>0:typeof n=="object"&&Object.keys(n).length>0}async function nA(n,e,t,i){if(UO(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",ut(e.manifest)],["resources",e.resources.map(p=>new Map([["source",p.source],["document",p.document]]))]]);e.provides!==void 0&&o.set("provides",ut(e.provides));let s=new Map([[0,1],[1,o],[2,t.installedBy]]),r=eA(t.adopt);r!==void 0&&s.set(3,r),t.preserveSeedTargets?.length&&s.set(4,[...t.preserveSeedTargets]);let a=eA(t.targetOverrides);a!==void 0&&s.set(5,a),t.allowDowngrade&&s.set(6,!0),i!==void 0&&s.set(7,H.enc(i));try{let p=await n.call("plan_type_pack_v1",s,{codec:MO,retry:!0,...t.signal?{signal:t.signal}:{}});if(p.version!==1)throw A("upgrade_required","unsupported type pack plan","type_packs_unsupported");return p}catch(p){throw oe(p,"invalid_request")&&p.reason==="unknown_method"?A("upgrade_required","This collection's replica can't install type packs yet.","type_packs_unsupported"):p}}async function iA(n,e,t){return tA((await nA(n,e,t)).assessment,e,t)}async function rA(n,e,t={}){if(e.refusal)throw A(DO[e.refusal.code],e.refusal.message,e.refusal.code);let i=t.signal?{...e.options,signal:t.signal}:e.options,o=await nA(n,e.pack,i,e.digest),s=tA(o.assessment,e.pack,e.options),r=o.writes??[];if(!r.length)return{outcome:"already_current",receipt:s.desired};let a=r.map(c=>c.doc===void 0?{kind:"resource_delete",path:c.path,...pn("baseRevision",c.baseRevision)}:{kind:"resource_put",path:c.path,doc:c.doc,...pn("baseRevision",c.baseRevision),...c.mustNotExist?{mustNotExist:!0}:{}}),p=(await n.submit(a,{...t,allowPartial:!1}))[0],l=p.receipt;if(l.state==="rejected"||l.state==="unknown")throw new se(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:p};if(l.status==="conflicted"||(l.conflicts?.length??0)>0)throw new se({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:p}}var TO,MO,LO,vo,Ke,DO,oA=I(()=>{"use strict";ge();ie();Oi();TO=N("type-pack-write-v1",[[0,"path",R],[1,"doc",R,"opt"],[2,"baseRevision",H,"opt"],[3,"mustNotExist",Oe]]),MO=N("type-pack-plan-v1",[[0,"version",B],[1,"assessment",at],[2,"writes",F(TO),"opt"]]),LO=["create","update","delete","adopt","unchanged","preserve","conflict"],vo=n=>n&&typeof n=="object"&&!Array.isArray(n)?n:{},Ke=n=>typeof n=="string"?n:void 0;DO={forbidden:"forbidden",type_pack_conflict:"conflict",type_pack_downgrade:"conflict",invalid_type_pack:"invalid_request",type_pack_contract_setups_unsupported:"invalid_request"}});function fA(n){return/^\d{6}$/.test(n)?`${n.slice(0,3)} ${n.slice(3)}`:n}var ly,sA,$O,aA,cA,lA,pA,dA,uA,cy,zO,hA,py=I(()=>{"use strict";ge();At();ly=["desktop","mobile","app_runtime","cli","hosted","escrow","recovery"],sA=Pe("device-kind",ly),$O={name:"device-kind",enc:n=>sA.enc(n),dec:n=>{try{return sA.dec(n)}catch{return"unknown"}}},aA=N("pending-device",[[0,"device",T],[1,"account",T],[2,"kind",$O],[3,"sas",R,"opt"],[4,"exchangeReady",Oe]]),cA={...aA,enc:n=>aA.enc({...n,sas:void 0})},lA=N("approval-readiness",[[0,"device",T],[1,"sas",R,"opt"],[2,"exchangeReady",Oe]]),pA={...lA,enc:n=>lA.enc({...n,sas:void 0})},dA=N("recovery-key-status",[[0,"configured",Oe],[1,"device",T,"opt"]]),uA=N("recovery-key-created",[[0,"phrase",R],[1,"device",T]]);cy=["idle","reading_ahead","pending_grant","keyed","refused"],zO=Pe("account-key-state",cy),hA=N("account-key-status",[[0,"state",zO],[1,"problem",An,"opt"]])});function vd(){let n=new Map;return{list:async()=>[...n.values()],put:async e=>{n.set(e.mutationId,e)},remove:async e=>{n.delete(e)}}}var dy,Dl,wd,uy=I(()=>{"use strict";ie();dy=n=>[...new Set(n.flatMap(e=>{let t=e,i=t.id??t.record;return typeof i=="string"?[i]:[]}))],Dl=(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},wd=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 Promise.all(e.map((i,o)=>this.set(Dl(i,dy(e.length===1?t:[t[o]]),"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(Dl(e.mutation,i,"pending")):t?.state!=="rejected"&&this.set(Dl(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,Dl(o.receipt.mutation,dy(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,Dl(i.receipt.mutation,dy(i.ops),"pending")),t=!0);t&&this.changed()}settleAll(e){return Promise.all(e.map(t=>this.settle(t)))}async settle(e){try{this.observe(await this.native.receipt(e))}catch(t){oe(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 xd={};ls(xd,{LiveQuery:()=>Ss,MdbaseClient:()=>Ei,Write:()=>_o,connect:()=>my});function kd(n){return n instanceof yt?new yt(n.value):n instanceof Date?new Date(n):Array.isArray(n)?n.map(e=>kd(e)):n instanceof Map?new Map([...n].map(([e,t])=>[e,kd(t)])):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,kd(t)])):n}function _d(n){return typeof n=="string"?T.enc(n):"id"in n&&typeof n.id=="string"?T.enc(n.id):n.path}function Ad(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 Sd(n){return n?ds.enc(n):void 0}function mA(n){if(!(n instanceof Uint8Array)||n.length!==32)throw A("invalid_request","the account secret is 32 bytes","account_secret_length")}function Be(n){let e=new Map;for(let[t,i]of n)i!==void 0&&e.set(t,i);return e}function fy(n,e){let t=n.grant;return!e||t.grant===e.grant&&t.role===e.role&&Ir(t.capabilities,e.capabilities)&&Ir(t.fileFolders??null,e.fileFolders??null)?n:{...n,grant:e}}async function yA(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,yl(s)};return[i(0),i(16)]}function hy(n){return n.state==="pending"||n.state==="confirmed"&&n.published==="publishing"}function Pd(n,e){let t=e.published;return t==="published"||t==="not_published"||n.published===void 0&&t!==void 0?{...n,published:t}:n}function my(n){return Ei.connect(n)}var _o,Ss,BO,Ei,Ps=I(()=>{"use strict";Je();Vm();c_();ge();m_();ie();ql();Zm();q_();D_();iy();V_();W_();H_();ry();Z_();Rl();bd();oA();Oi();py();At();uy();At();_o=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;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=Pd(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 se(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)}}},Ss=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 yd;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=this.include){this.query=e,this.include=t,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 Be([[0,ut(this.query)],[1,Sd(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)}},BO=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"]),Ei=class n{constructor(e,t){this.opts=e;this.session=t,this.collectionId=t.hello.collection,this.lastStatus=t.hello.status,this.currentHello=fy(t.hello,t.hello.status.grant),this.fenceReads=sy(e.connector),this.readFloor=t.hello.status.confirmedThrough,this.files=new _s(this),this.presence=new ks(this),this.writeLedger=new wd(e.ledger??vd(),{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;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=sy(e.connector);t&&(e={...e});let i=e.reconnect&&e.reconnect.minDelayMs||1e3,o=e.signal,s,r,a,p=()=>e.signal?.aborted||!a?A("cancelled","connect aborted"):a;try{for(;;)try{let l=o,c=await new Promise((d,u)=>{let f=()=>u(p());if(l?.aborted){f();return}l?.addEventListener("abort",f,{once:!0}),go.open(e.connector,n.helloParams(e),l).then(h=>{if(l?.removeEventListener("abort",f),l?.aborted){try{h.close()}catch{}u(p())}else d(h)},h=>{l?.removeEventListener("abort",f),u(h)})});if(o?.aborted)throw c.close(),p();return new n(e,c)}catch(l){if(o?.aborted)throw p();let c=t&&oe(l,"unavailable")&&(l.reason==="grant_lease_expired"||l.reason==="authorization_unavailable");if(!(c||e.waitForDevice&&oe(l,"unavailable")&&l.reason==="no_device_online"))throw l;c&&!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(p())},m=setTimeout(()=>{f(),d()},c?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:sd,clientName:e.app.name,clientVersion:e.app.version,features:[...new Set([...e.features??[],"declared-collection-setup-v1","file-stream-failure-v1"])],...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(e);for(;;){let i=t?this.currentSession():await this.ready(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){for(;;){if(this.linkState==="closed")throw this.linkError??A("unavailable","client closed");if(this.session&&!this.session.closed)return this.session;if(e?.aborted)throw A("cancelled","aborted while reconnecting");await new Promise(t=>{this.reconnectWaiters.push(t),e?.addEventListener("abort",()=>t(),{once:!0})})}}async call(e,t,i={}){let o=i.codec,s=this.fenceReads&&BO.has(e);for(;;){let r=s?await this.readyForRead(i.signal,!i.retry):i.retry?await this.ready(i.signal):this.currentSession();try{let a=await r.request(e,t,{...i.signal?{signal:i.signal}:{},...o?{codec:o}:{}});if(s&&(r!==this.session||r.closed||this.closing)){if(i.retry&&!this.closing)continue;throw A("unavailable","the session changed during the read",{reason:"reconnecting"})}return r===this.session&&!r.closed&&!this.closing&&o===kt&&(e==="receipt"||e==="await")&&this.noteReceipt(a),a}catch(a){let p=oe(a,"unavailable")&&r.closed;if(!(i.retry&&p&&this.opts.reconnect!==!1&&!this.closing))throw a}}}onSession(e){this.restorers.push(e)}relayWitnesses(e){let t=e.hello.headWitness;t&&J_(this.collectionId,t,e.device);let i=X_(this.collectionId,t);i.length&&e.request("report_witnesses",Be([[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=jp.dec(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=kt.dec(t);this.session===e&&this.noteReceipt(i);let o=this.writes.get(i.mutation);if(o)o.update(i),hy(o.receipt)||this.writes.delete(i.mutation);else{let s=this.unclaimed.get(i.mutation);this.unclaimed.set(i.mutation,s?Pd(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(er.dec(t))}catch{}}),e.onPush("holds",t=>{try{this.emitHolds(F(vl).dec(t))}catch{}}),e.onPush("conflicts",t=>{try{this.emitConflicts(F(Al).dec(t))}catch{}}),e.onPush("closed",t=>{let i;try{i=new se(An.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 Rm.enc(await this.fenceHandler(Im.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 go.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=fy(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(oe(s)&&["unauthenticated","forbidden","upgrade_required"].includes(s.code)){this.setLink("closed",s);return}oe(s)&&this.setLink("reconnecting",s);let r=oe(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),hy(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:er,retry:!0});return this.setStatus(e),e}for(;;){let e=await this.ready(),t;try{t=await e.request("get_status",null,{codec:er})}catch(i){if(oe(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=pm.enc({seq:e}),o=await this.call("applied_prefix",i,{codec:dm,retry:!1,...t?{signal:t}:{}});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=fy(this.currentHello,e.grant);for(let t of[...this.statusListeners])t(e)}async describe(e={}){let t=e instanceof AbortSignal?{signal:e}:e,i=await this.call("describe",t.definitions?Be([[0,!0]]):null,{codec:Mm,retry:!0,...t.signal?{signal:t.signal}:{}});if(t.definitions&&(i.types.some(o=>o.definition===void 0)||i.contracts.some(o=>o.schemas===void 0)))throw A("upgrade_required","this replica does not describe definitions","describe_definitions_unsupported");return i}async createType(e,t={}){let{name:i,path:o}=await this.call("new_type_file",Be([[0,e]]),{codec:Tm,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,Sl)||!o(t,Pl)?Promise.reject(A("invalid_request","describe_typing: at most 64 types and 256 non-empty paths","typing_bounds")):this.call("describe_typing",Be([[0,[...e]],[1,[...t]]]),{codec:jm,retry:!0,...i?{signal:i}:{}}).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,i){return this.call("get",Be([[0,_d(e)],[1,Sd(t)]]),{codec:Mn,retry:!0,...i?{signal:i}:{}})}async getContract(e,t,i){let o=await this.contractCall("get_contract_v1",Be([[0,1],[1,_d(e)],[2,t.id],[3,t.version],[4,t.type]]),B_,i);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",Be([[0,1],[1,e.id],[2,e.version],[3,e.type],[4,t===void 0?void 0:_d(t)],[5,i],[6,o?.length?o:void 0],[7,r?!0:void 0]]),F_,s);if(a.version!==1)throw A("upgrade_required","unsupported contract write plan","contract_records_unsupported");return a}contractCall(e,t,i,o){return this.call(e,t,{codec:i,retry:!0,...o?{signal:o}:{}}).catch(s=>{throw oe(s,"invalid_request")&&s.reason==="unknown_method"?A("upgrade_required","this replica does not serve contract-scoped records","contract_records_unsupported"):s})}readMany(e,t,i,o={}){return ld(this,e,t,i,o)}async find(e,t,i){try{return await this.get(e,t,i)}catch(o){if(oe(o,"not_found"))return null;throw o}}query(e,t,i,o={}){return this.call("query",Be([[0,ut(e)],[1,Sd(t)],[2,o.contract]]),{codec:_l,retry:!0,...i?{signal:i}:{}})}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=Math.min(i,128),s=await this.call("query_contract_v1",Be([[0,1],[1,e.id],[2,e.version],[3,o],[4,t.cursor],[5,t.where]]),{codec:K_,retry:!0,...t.signal?{signal:t.signal}:{}});if(s.version!==1)throw A("upgrade_required","unsupported contract query result","contract_query_version");if(s.records.length!==s.page.records.length||s.records.some((r,a)=>r.id!==s.page.records[a]?.id))throw A("unavailable","invalid contract query record binding","contract_query_response");return s}backlinks(e,t={}){return this.call("backlinks",Be([[0,_d(e)],[1,Sd(t.include)],[2,t.limit],[3,t.cursor]]),{codec:qm,retry:!0,...t.signal?{signal:t.signal}:{}})}resources={get:(e,t)=>this.call("get_resource",Be([[0,e]]),{codec:Fp,retry:!0,...t?{signal:t}:{}}),list:(e={})=>this.call("list_resources",Be([[0,e.folder],[1,e.text],[2,e.cursor],[3,e.limit]]),{codec:Em,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.one({kind:"resource_put",path:e,doc:t,...i.baseRevision?{baseRevision:i.baseRevision}:{},...i.mustNotExist?{mustNotExist:!0}:{}},i),delete:(e,t={})=>this.one({kind:"resource_delete",path:e,...t.baseRevision?{baseRevision:t.baseRevision}:{}},t)};typePacks=Object.freeze({plan:(e,t)=>iA(this,e,t),apply:(e,t)=>rA(this,e,t)});recordSessions=new dd(this);records=Object.freeze({open:(e,t)=>this.recordSessions.open(e,t)});views={createSource:(e,t)=>hd(this,e,t),updateSource:(e,t,i)=>md(this,e,t,i),getSourceRecord:(e,t={})=>fd(this,e,t),list:(e,t)=>j_(this,e,t),execute:(e,t,i={})=>N_(this,e,t,i),readSource:(e,t)=>U_(this,e,t)};async pendingWrites(e){let t=[],i;for(;;){let o=await this.call("list_pending",Be([[0,i?T.enc(i):void 0]]),{codec:Lm,retry:!0,...e?{signal:e}:{}});if(t.push(...o.pending),!o.next)return t;i=o.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:Ad(e)})}async preflight(e){let[t]=await this.submit([e],{dryRun:!0}),i=t.receipt;if(i.state==="rejected")throw new se(i.problem);return i.preflight??{rewrites:[],broken:[]}}async*pages(e,t,i,o={}){let s=kd(e),r=t?{...t}:void 0,a=s.cursor,p=!1,l=0;for(delete s.cursor;;){i?.throwIfAborted();let c;try{c=await this.query(a!==void 0?{...s,cursor:a}:{...s},r,i)}catch(d){if(!o.onReset||p||!oe(d,"invalid_request")||d.recovery!=="fix_request"||d.reason!=="cursor_expired"&&d.reason!=="cursor_stale")throw d;i?.throwIfAborted(),await o.onReset({reason:d.reason,error:d,pagesYielded:l,...i?{signal:i}:{}}),i?.throwIfAborted(),p=!0,a=void 0,l=0;continue}if(i?.throwIfAborted(),yield c,l++,!c.cursor)return;a=c.cursor}}queryPages(e,t,i,o={}){return cd(this,e,t,i,o)}live(e,t){let i=new Ss(this,e,t);return this.lives.add(i),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",Be([[0,o]])).catch(()=>{}));try{let s=await this.readyForRead();if(this.fenceReads&&(e.closed||i&&i!==s))return;this.subscribing++;let r;try{let p=await s.request("subscribe",e._params());r=B.dec(p.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",Be([[0,r]])).catch(()=>{});return}e._setSub(r),this.livesBySub.set(r,e);for(let p of a)e._apply(p)}catch(s){let r=Nn(s,"subscribe");oe(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",Be([[0,t]])).catch(()=>{}))}changes(e,t,i){return this.call("changes",Be([[0,e??null],[1,t]]),{codec:us,retry:!0,...i?{signal:i}:{}})}watchChanges(e,t){let i=e,o=!1,s=0,r="starting",a=null,p=null,l=null,c=null,d=null,u=()=>{},f,h,m=new Promise((C,E)=>{f=C,h=E});m.catch(()=>{});let b=new Set,w=C=>{try{C(r,a)}catch{}},g=(C,E=null)=>{r=C,a=E;for(let O of[...b])w(O)},y=()=>{c?.(),c=null,d?.(),d=null;let C=l;l=null,u(),u=()=>{},C?.abort(),p=null},v=()=>{this.restorers=this.restorers.filter(C=>C!==S),x()},_=C=>{o||(o=!0,s++,y(),v(),h(C),g("failed",C),b.clear())},k=()=>{r!=="closed"&&(o=!0,s++,y(),v(),h(A("cancelled","change watch closed")),g("closed"),b.clear())},S=async C=>{if(o||C.closed||C!==this.session||p===C)return;s++,y(),p=C;let E=s,O=()=>!o&&E===s&&!C.closed&&C===this.session;l=new AbortController;let L=l.signal;try{await this.readFence(L)}catch(G){O()&&_(Nn(G,"changes watch"));return}if(!O())return;let z=!0,Q=[],V=0;u=()=>{Q.length=0,V=0};let te=G=>{if(O()){i=G.cursor;try{t(G)}catch{}}};if(d=C.onClose(G=>{if(o||E!==s)return;s++,y();let K=G??A("unavailable","change watch session closed");h(K),g("stale",K)}),c=C.onPush("changes",G=>{if(O())try{let K=us.dec(G);if(!z){te(K);return}let X=64+K.cursor.length*2+K.changes.reduce((Y,ee)=>Y+384+ee.path.length*2,0);if(Q.length>=16||V+X>1024*1024){_(A("unavailable","change watch startup buffer exceeded"));return}V+=X,Q.push(K)}catch(K){_(Nn(K,"changes push"))}}),g("starting"),!!O())try{let G=await C.request("changes",Be([[0,i??null],[2,!0]]),{codec:us,signal:L});if(!O())return;for(i=G.cursor,(G.changes.length||G.reset)&&te(G);Q.length&&O();)te(Q.shift());if(u(),z=!1,!O())return;g("active"),O()&&f()}catch(G){O()&&_(Nn(G,"changes watch"))}},x=this.onLink((C,E)=>{C==="closed"&&(E?_(E):k())});this.onSession(S),this.ready().then(S).catch(C=>_(Nn(C,"changes watch")));let P=Object.assign(k,{ready:m,subscribe:C=>(r!=="closed"&&r!=="failed"&&b.add(C),w(C),()=>{b.delete(C)})});return Object.defineProperties(P,{state:{get:()=>r},error:{get:()=>a}}),Object.freeze(P)}async validate(e,t){t?.throwIfAborted();let{targets:i,expected:o}=f_(e),s=await this.call("validate",Be([[0,i]]),{codec:u_,retry:!0,...t?{signal:t}:{}});return t?.throwIfAborted(),h_(s,o)}async executeAppBases(e,t){let i=e.window===void 0?null:{...e.window},o=Xp({...e,...i===null?{}:{window:i}}),s=await this.readyForRead(t),r=await s.readAppBases(o,t);if(s!==this.session||s.closed||this.readFencedAt!==null)throw A("unavailable","original Bases session is no longer current");try{return Zp(r,i)}catch(a){throw Nn(a,"app Bases result")}}executeAppBasesPages(e,t={}){return l_((i,o)=>this.executeAppBases(i,o),e,t)}async listAppBasesViews(e,t){let i=e.limit,o=Qp(e),s=await this.readyForRead(t),r=await s.readAppBasesDiscovery("list-views",o,t);try{if(s!==this.session||s.closed||this.readFencedAt!==null)throw A("unavailable","original Bases session is no longer current");return td(r,i)}catch(a){throw Nn(a,"app Bases discovery")}finally{r.fill(0)}}async readAppBasesViewSource(e,t){let i={...e},o=ed(i),s=await this.readyForRead(t),r=await s.readAppBasesDiscovery("read-view-source",o,t);try{if(s!==this.session||s.closed||this.readFencedAt!==null)throw A("unavailable","original Bases session is no longer current");return nd(r,i)}catch(a){throw Nn(a,"app Bases exact source")}finally{r.fill(0)}}async submit(e,t={}){if(this.hello.version.minor>=3&&this.hello.grant.role==="viewer")throw 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 yA(this.collectionId,t.intent))[0]});let i={ops:e,mutationId:t.mutationId??Ln()};t.allowPartial&&(i.allowPartial=!0,i.mutationIds=e.map((s,r)=>r===0?i.mutationId:Ln())),t.conflictMode&&(i.conflictMode=t.conflictMode),t.timezone&&(i.timezone=t.timezone),t.dryRun&&(i.dryRun=!0),t.include&&(i.include=t.include),t.wait&&(i.wait=t.wait),t.dryRun||(this.startLedger(),await this.writeLedger.begin(i.mutationIds??[i.mutationId],e));let o;try{o=await this.call("submit",_m.enc(i),{codec:km,retry:!0,...t.signal?{signal:t.signal}:{}})}catch(s){throw t.dryRun?s:(this.writeLedger.settleAll(i.mutationIds??[i.mutationId]),vs(s,"submit",i.mutationIds?{mutationIds:i.mutationIds}:{mutationId:i.mutationId}))}return o.map(s=>t.dryRun?new _o(s):this._track(s))}async one(e,t){let[i]=await this.submit([e],t);return i}create(e,t={}){if(t.intent!==void 0&&t.mutationId===void 0)return yA(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??Ln()};return e.path!==void 0&&(i.path=e.path),e.type!==void 0&&(i.type=e.type),e.frontmatter!==void 0&&(i.frontmatter=xl(e.frontmatter)),e.body!==void 0&&(i.body=e.body),e.document!==void 0&&(i.document=e.document),this.one(i,t).then(o=>Object.assign(o,{recordId:i.id}))}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,xl(e.frontmatter??{}),void 0,i.signal),r={kind:"create",id:e.id??Ln(),type:s.type,frontmatter:s.patch};return e.path!==void 0&&(r.path=e.path),e.body!==void 0&&(r.body=e.body),Object.assign(await this.one(r,i),{recordId:r.id})}update(e,t,i={}){return t.contract?this.updateThroughContract(e,t,t.contract,i):this.one(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?xl(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}),p={kind:"update",id:s.id};return a.body!==void 0&&(p.body=a.body),a.bodyEdits&&(p.bodyEdits=a.bodyEdits),a.bodyBase!==void 0&&(p.bodyBase=a.bodyBase),s.patch.size&&(p.patch=s.patch),s.unset.length&&(p.unset=s.unset),s.base.length&&(p.base=s.base),t.updateRefs!==void 0&&(p.updateRefs=t.updateRefs),t.ifRevision&&(p.ifRevision=t.ifRevision),this.one(p,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:Ad(e)},o=typeof e=="object"&&"frontmatter"in e?e:null;if(t.updateRefs!==void 0&&(i.updateRefs=t.updateRefs),t.patch&&(i.patch=xl(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(ut)]))),t.remove&&(i.remove=new Map(Object.entries(t.remove).map(([s,r])=>[s,r.map(ut)]))),t.ifRevision&&(i.ifRevision=t.ifRevision),t.bodyEdits?.length){i.bodyEdits=t.bodyEdits;let s=t.bodyBase??(o?.body!==void 0?si(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=Jp(o.body,t.body);s.length&&(i.bodyEdits=s,i.bodyBase=si(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 p=o.frontmatter.get(a);s.push(p===void 0?{key:a}:{key:a,observed:p})}s.length&&(i.base=s)}if(o&&i.patch){for(let[s,r]of[...i.patch]){let a=o.frontmatter.get(s);a!==void 0&&Ir(a,r)&&(i.patch.delete(s),i.base=i.base?.filter(p=>p.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:Ad(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.one(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.one(a,s)})}let i={kind:"delete",id:Ad(e)};return typeof e=="object"&&"revision"in e&&(i.baseRevision=e.revision),t.ifRevision&&(i.ifRevision=t.ifRevision),this.one(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.one(o,i)}_track(e){this.noteReceipt(e);let t=e,i=this.unclaimed.get(e.mutation);i&&(this.unclaimed.delete(e.mutation),t=Pd(e,i),(e.state==="pending"||e.state==="confirmed"&&(i.state==="rejected"||i.state==="unknown"))&&(t=Pd({...e,...i},t)));let o=this.writes.get(e.mutation);return o?o.update(t):o=new _o(t),hy(o.receipt)?this.writes.set(e.mutation,o):this.writes.delete(e.mutation),o}async save(e,t={}){let i=await e,o=i.receipt;if(o.state==="pending")try{o=await this.awaitReceipt(i.mutationId,t.timeoutMs??3e3,t.signal),i.update(o)}catch(p){if(oe(p,"cancelled"))throw p;o=i.receipt}let s=o.state==="confirmed"?"confirmed":o.state==="pending"?"saved_on_device":"rejected",r=i.records,a=r[0];return t.readBack&&s!=="rejected"&&a&&(a=await this.find(a.id,void 0,t.signal).catch(()=>null)??a),Object.freeze({outcome:s,mutationId:i.mutationId,records:r,...a?{record:a}:{},...s==="rejected"&&o.problem?{problem:o.problem}:{}})}receipt(e,t){return this.call("receipt",Be([[0,T.enc(e)]]),{codec:kt,retry:!0,...t?{signal:t}:{}}).catch(i=>{throw vs(i,"receipt",{mutationId:e})})}awaitReceipt(e,t,i){return this.call("await",Be([[0,T.enc(e)],[1,t]]),{codec:kt,retry:!0,...i?{signal:i}:{}}).catch(o=>{throw vs(o,"await",{mutationId:e})})}listHolds(e){return this.call("list_holds",null,{codec:F(vl),retry:!0,...e?{signal:e}:{}})}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",Be([[0,T.enc(e)],[1,mm.enc(t)],[2,i]]),{codec:kt});return this._track(o)}listConflicts(e,t){return this.call("list_conflicts",e?Be([[0,T.enc(e)]]):null,{codec:F(Al),retry:!0,...t?{signal:t}:{}})}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.one({kind:"conflict_dismiss",mutation:e.mutation,record:e.conflict.id},t)}async resolveConflict(e,t,i,o={}){let[s]=await this.submit([{kind:"update",id:e.conflict.id,patch:new Map([[t,ut(i)]])},{kind:"conflict_dismiss",mutation:e.mutation,record:e.conflict.id}],o);return s}pendingDevices(e){return this.call("pending_devices",null,{codec:F(cA),retry:!0,...e?{signal:e}:{}})}approveDevice(e,t){return/^\d{6}$/.test(t)?this.call("approve_device",Be([[0,T.enc(e)],[1,t]])).then(()=>{}):Promise.reject(A("invalid_request","the code is six digits","invalid_sas"))}rejectDevice(e){return this.call("reject_device",Be([[0,T.enc(e)]])).then(()=>{})}accountKey={setup:async e=>{mA(e);let t=await this.call("account_key_setup",Be([[0,e]]),{codec:kt});return this._track(t)},unlock:async e=>{mA(e),await this.call("account_key_unlock",Be([[0,e]]))},status:e=>this.call("account_key_status",null,{codec:hA,retry:!0,...e?{signal:e}:{}})};recoveryKey={status:()=>this.call("recovery_key_status",null,{codec:dA,retry:!0}),create:()=>this.call("recovery_key_create",null,{codec:uA}),import:e=>this.call("recovery_key_import",Be([[0,e.trim()]])).then(()=>{})};offerFence(e){this.fenceHandler=e}reportFence(e){return this.call("fence_report",Om.enc({open:e}),{retry:!0}).then(()=>{})}}});function yy(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}function Id(n,e=""){if(typeof n!="boolean")throw new TypeError(Cd(e)+"expected boolean, got type="+typeof n);return n}function Ao(n,e=""){if(typeof n!="number")throw new TypeError(Cd(e)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(Cd(e)+"expected integer >= 0, got "+n);return n}function ft(n,e,t=""){if(yy(n)&&(e===void 0||n.length===e))return n;e!==void 0&&Ao(e,"length");let i=yy(n),o=e!==void 0?` of length ${e}`:"",s=i?`length=${n.length}`:`type=${typeof n}`,r=Cd(t)+"expected Uint8Array"+o+", got "+s;throw i?new RangeError(r):new TypeError(r)}function gy(n,e=!0){if(n.destroyed)throw new Error("hash was destroyed");if(e&&n.finished)throw new Error("digest() was already called")}function bA(n,e){ft(n,void 0,"output");let t=e.outputLen;if(!(n.length>=t))throw new RangeError('"output" expected length >= '+t)}function qi(n){return new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4))}function ci(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function FO(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function VO(n){return n<<24&4278190080|n<<8&16711680|n>>>8&65280|n>>>24&255}function KO(n){for(let e=0;e<n.length;e++)n[e]=VO(n[e]);return n}function WO(n,e){return!n.byteLength||!e.byteLength?!1:n.buffer===e.buffer&&n.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<n.byteOffset+n.byteLength}function wA(n,e){if(WO(n,e)&&n.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function vA(n,e){return gA(n,"defaults"),gA(e,"opts"),Object.assign(n,e)}function _A(n,e){if(n=ft(n),e=ft(e),n.length!==e.length)return!1;let t=0;for(let i=0;i<n.length;i++)t|=n[i]^e[i];return t===0}function AA(n,e,t){let i=e,o=t||(()=>[]),s=(a,p)=>i(p,...o(a)).update(a).digest(),r=i(new Uint8Array(n),...o(new Uint8Array(0)));return s.outputLen=r.outputLen,s.blockLen=r.blockLen,s.create=(a,...p)=>i(a,...p),s}function $l(n,e,t=!0){if(e===void 0)return new Uint8Array(n);if(ft(e,n,"output"),t&&!zl(e))throw new Error("invalid output, must be aligned");return e}function SA(n,e,t){Ao(n),Ao(e),Id(t);let i=new Uint8Array(16),o=FO(i);return o.setBigUint64(0,BigInt(e),t),o.setBigUint64(8,BigInt(n),t),i}function zl(n){return n.byteOffset%4===0}function xs(n){return Uint8Array.from(ft(n))}var Cd,gA,Er,rr,kA,Od=I(()=>{/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */Cd=n=>n?`"${n}" `:"";gA=(n,e)=>{if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof n}`)};Er=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;rr=Er?n=>n:KO;kA=(n,e)=>{function t(i,...o){if(ft(i,void 0,"key"),n.nonceLength!==void 0){let d=o[0];ft(d,n.varSizeNonce?void 0:n.nonceLength,"nonce")}let s=n.tagLength,r=n.nonceLength!==void 0?1:0;if(!n.withAAD){for(let d=r;d<o.length;d++)if(yy(o[d]))throw new Error("AAD not supported")}n.withAAD&&o[r]!==void 0&&ft(o[r],void 0,"AAD");let a=e(i,...o),p=(d,u)=>{if(u!==void 0){if(d!==2)throw new Error("cipher output not supported");ft(u,void 0,"output")}},l=!1;return{encrypt(d,u){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,ft(d,void 0,"data"),p(a.encrypt.length,u),a.encrypt(d,u)},decrypt(d,u){if(ft(d,void 0,"data"),s&&d.length<s)throw new Error('"ciphertext" expected length >= tagLength='+s);return p(a.decrypt.length,u),a.decrypt(d,u)}}}return Object.assign(t,n),t}});function Le(n,e){return n<<e|n>>>32-e}function JO(n,e,t,i,o,s,r,a){let p=o.length,l=new Uint8Array(Bl),c=qi(l),d=Er&&zl(o)&&zl(s),u=d?qi(o):PA,f=d?qi(s):PA;if(!Er){for(let h=0;h<p;r++){if(n(e,t,i,c,r,a),rr(c),r>=by)throw new Error("arx: counter overflow");let m=Math.min(Bl,p-h);for(let b=0,w;b<m;b++)w=h+b,s[w]=o[w]^l[b];h+=m}return}for(let h=0;h<p;r++){if(n(e,t,i,c,r,a),r>=by)throw new Error("arx: counter overflow");let m=Math.min(Bl,p-h);if(d&&m===Bl){let b=h/4;if(h%4!==0)throw new Error("arx: invalid block position");for(let w=0,g;w<YO;w++)g=b+w,f[g]=u[g]^c[w];h+=Bl;continue}for(let b=0,w;b<m;b++)w=h+b,s[w]=o[w]^l[b];h+=m}}function CA(n,e){let{allowShortKeys:t,extendNonceFn:i,counterLength:o,counterRight:s,rounds:r}=vA({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof n!="function")throw new Error("core must be a function");return Ao(o),Ao(r),Id(s),Id(t),(a,p,l,c,d=0)=>{ft(a,void 0,"key"),ft(p,void 0,"nonce"),ft(l,void 0,"data");let u=l.length,f=c!==void 0;if(c=$l(u,c,!1),f&&wA(l,c),Ao(d),d<0||d>=by)throw new Error("arx: counter overflow");let h=[],m=a.length,b,w;if(m===32)h.push(b=xs(a)),w=GO;else if(m===16&&t)b=new Uint8Array(32),b.set(a),b.set(a,16),w=HO,h.push(b);else throw ft(a,32,"arx key"),new Error("invalid key size");(!Er||!zl(p))&&h.push(p=xs(p));let g=qi(b);if(i){if(p.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let _=p.subarray(0,16);if(Er)i(w,g,qi(_),g);else{let k=rr(Uint32Array.from(w));i(k,g,qi(_),g),ci(k),rr(g)}p=p.subarray(16)}else Er||rr(g);let y=16-o;if(y!==p.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){let _=new Uint8Array(12);_.set(p,s?0:12-p.length),p=_,h.push(p)}let v=rr(qi(p));try{return JO(n,w,g,v,l,c,d,r),c}finally{ci(...h)}}}var xA,HO,GO,Bl,YO,by,PA,IA=I(()=>{Od();xA=n=>Uint8Array.from(n.split(""),e=>e.charCodeAt(0)),HO=rr(qi(xA("expand 16-byte k"))),GO=rr(qi(xA("expand 32-byte k")));Bl=64,YO=16,by=2**32-1,PA=Uint32Array.of()});function Mt(n,e){return n[e++]&255|(n[e++]&255)<<8}var wy,OA,RA=I(()=>{Od();wy=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=xs(ft(e,32,"key"));let t=Mt(e,0),i=Mt(e,2),o=Mt(e,4),s=Mt(e,6),r=Mt(e,8),a=Mt(e,10),p=Mt(e,12),l=Mt(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|i<<3)&8191,this.r[2]=(i>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|r<<12)&255,this.r[5]=r>>>1&8190,this.r[6]=(r>>>14|a<<2)&8191,this.r[7]=(a>>>11|p<<5)&8065,this.r[8]=(p>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let c=0;c<8;c++)this.pad[c]=Mt(e,16+2*c)}process(e,t,i=!1){let o=i?0:2048,{h:s,r}=this,a=r[0],p=r[1],l=r[2],c=r[3],d=r[4],u=r[5],f=r[6],h=r[7],m=r[8],b=r[9],w=Mt(e,t+0),g=Mt(e,t+2),y=Mt(e,t+4),v=Mt(e,t+6),_=Mt(e,t+8),k=Mt(e,t+10),S=Mt(e,t+12),x=Mt(e,t+14),P=s[0]+(w&8191),C=s[1]+((w>>>13|g<<3)&8191),E=s[2]+((g>>>10|y<<6)&8191),O=s[3]+((y>>>7|v<<9)&8191),L=s[4]+((v>>>4|_<<12)&8191),z=s[5]+(_>>>1&8191),Q=s[6]+((_>>>14|k<<2)&8191),V=s[7]+((k>>>11|S<<5)&8191),te=s[8]+((S>>>8|x<<8)&8191),G=s[9]+(x>>>5|o),K=0,X=K+P*a+C*(5*b)+E*(5*m)+O*(5*h)+L*(5*f);K=X>>>13,X&=8191,X+=z*(5*u)+Q*(5*d)+V*(5*c)+te*(5*l)+G*(5*p),K+=X>>>13,X&=8191;let Y=K+P*p+C*a+E*(5*b)+O*(5*m)+L*(5*h);K=Y>>>13,Y&=8191,Y+=z*(5*f)+Q*(5*u)+V*(5*d)+te*(5*c)+G*(5*l),K+=Y>>>13,Y&=8191;let ee=K+P*l+C*p+E*a+O*(5*b)+L*(5*m);K=ee>>>13,ee&=8191,ee+=z*(5*h)+Q*(5*f)+V*(5*u)+te*(5*d)+G*(5*c),K+=ee>>>13,ee&=8191;let $e=K+P*c+C*l+E*p+O*a+L*(5*b);K=$e>>>13,$e&=8191,$e+=z*(5*m)+Q*(5*h)+V*(5*f)+te*(5*u)+G*(5*d),K+=$e>>>13,$e&=8191;let mt=K+P*d+C*c+E*l+O*p+L*a;K=mt>>>13,mt&=8191,mt+=z*(5*b)+Q*(5*m)+V*(5*h)+te*(5*f)+G*(5*u),K+=mt>>>13,mt&=8191;let j=K+P*u+C*d+E*c+O*l+L*p;K=j>>>13,j&=8191,j+=z*a+Q*(5*b)+V*(5*m)+te*(5*h)+G*(5*f),K+=j>>>13,j&=8191;let W=K+P*f+C*u+E*d+O*c+L*l;K=W>>>13,W&=8191,W+=z*p+Q*a+V*(5*b)+te*(5*m)+G*(5*h),K+=W>>>13,W&=8191;let $=K+P*h+C*f+E*u+O*d+L*c;K=$>>>13,$&=8191,$+=z*l+Q*p+V*a+te*(5*b)+G*(5*m),K+=$>>>13,$&=8191;let J=K+P*m+C*h+E*f+O*u+L*d;K=J>>>13,J&=8191,J+=z*c+Q*l+V*p+te*a+G*(5*b),K+=J>>>13,J&=8191;let be=K+P*b+C*m+E*h+O*f+L*u;K=be>>>13,be&=8191,be+=z*d+Q*c+V*l+te*p+G*a,K+=be>>>13,be&=8191,K=(K<<2)+K|0,K=K+X|0,X=K&8191,K=K>>>13,Y+=K,s[0]=X,s[1]=Y,s[2]=ee,s[3]=$e,s[4]=mt,s[5]=j,s[6]=W,s[7]=$,s[8]=J,s[9]=be}finalize(){let{h:e,pad:t}=this,i=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,i[0]=e[0]+5,o=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+o,o=i[a]>>>13,i[a]&=8191;i[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)i[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|i[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let r=e[0]+t[0];e[0]=r&65535;for(let a=1;a<8;a++)r=(e[a]+t[a]|0)+(r>>>16)|0,e[a]=r&65535;ci(i)}update(e){gy(this),ft(e),e=xs(e);let{buffer:t,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let r=Math.min(i-this.pos,o-s);if(r===i){for(;i<=o-s;s+=i)this.process(e,s);continue}t.set(e.subarray(s,s+r),this.pos),this.pos+=r,s+=r,this.pos===i&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,ci(this.h,this.r,this.buffer,this.pad)}digestInto(e){gy(this),bA(e,this),this.finished=!0;let{buffer:t,h:i}=this,{pos:o}=this;if(o){for(t[o++]=1;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let r=0;r<8;r++)e[s++]=i[r]>>>0,e[s++]=i[r]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let i=e.slice(0,t);return this.destroy(),i}},OA=AA(32,n=>new wy(n))});function XO(n,e,t,i,o,s=20){let r=n[0],a=n[1],p=n[2],l=n[3],c=e[0],d=e[1],u=e[2],f=e[3],h=e[4],m=e[5],b=e[6],w=e[7],g=o,y=t[0],v=t[1],_=t[2],k=r,S=a,x=p,P=l,C=c,E=d,O=u,L=f,z=h,Q=m,V=b,te=w,G=g,K=y,X=v,Y=_;for(let $e=0;$e<s;$e+=2)k=k+C|0,G=Le(G^k,16),z=z+G|0,C=Le(C^z,12),k=k+C|0,G=Le(G^k,8),z=z+G|0,C=Le(C^z,7),S=S+E|0,K=Le(K^S,16),Q=Q+K|0,E=Le(E^Q,12),S=S+E|0,K=Le(K^S,8),Q=Q+K|0,E=Le(E^Q,7),x=x+O|0,X=Le(X^x,16),V=V+X|0,O=Le(O^V,12),x=x+O|0,X=Le(X^x,8),V=V+X|0,O=Le(O^V,7),P=P+L|0,Y=Le(Y^P,16),te=te+Y|0,L=Le(L^te,12),P=P+L|0,Y=Le(Y^P,8),te=te+Y|0,L=Le(L^te,7),k=k+E|0,Y=Le(Y^k,16),V=V+Y|0,E=Le(E^V,12),k=k+E|0,Y=Le(Y^k,8),V=V+Y|0,E=Le(E^V,7),S=S+O|0,G=Le(G^S,16),te=te+G|0,O=Le(O^te,12),S=S+O|0,G=Le(G^S,8),te=te+G|0,O=Le(O^te,7),x=x+L|0,K=Le(K^x,16),z=z+K|0,L=Le(L^z,12),x=x+L|0,K=Le(K^x,8),z=z+K|0,L=Le(L^z,7),P=P+C|0,X=Le(X^P,16),Q=Q+X|0,C=Le(C^Q,12),P=P+C|0,X=Le(X^P,8),Q=Q+X|0,C=Le(C^Q,7);let ee=0;i[ee++]=r+k|0,i[ee++]=a+S|0,i[ee++]=p+x|0,i[ee++]=l+P|0,i[ee++]=c+C|0,i[ee++]=d+E|0,i[ee++]=u+O|0,i[ee++]=f+L|0,i[ee++]=h+z|0,i[ee++]=m+Q|0,i[ee++]=b+V|0,i[ee++]=w+te|0,i[ee++]=g+G|0,i[ee++]=y+K|0,i[ee++]=v+X|0,i[ee++]=_+Y|0}function qA(n,e,t,i,o){o!==void 0&&ft(o,void 0,"AAD");let s=n(e,t,e1),r=SA(i.length,o?o.length:0,!0),a=OA.create(s);o&&EA(a,o),EA(a,i),a.update(r);let p=a.digest();return ci(s,r),p}var ZO,QO,EA,e1,t1,vy,TA=I(()=>{IA();RA();Od();ZO=CA(XO,{counterRight:!1,counterLength:4,allowShortKeys:!1}),QO=new Uint8Array(16),EA=(n,e)=>{n.update(e);let t=e.length%16;t&&n.update(QO.subarray(t))},e1=new Uint8Array(32);t1=n=>(e,t,i)=>({encrypt(s,r){let a=s.length;r=$l(a+16,r,!1),r.set(s);let p=r.subarray(0,-16);n(e,t,p,p,1);let l=qA(n,e,t,p,i);return r.set(l,a),ci(l),r},decrypt(s,r){r=$l(s.length-16,r,!1);let a=s.subarray(0,-16),p=s.subarray(-16),l=qA(n,e,t,a,i);if(!_A(p,l))throw ci(l),new Error("invalid tag");return r.set(s.subarray(0,-16)),n(e,t,r,r,1),ci(l),r}}),vy=kA({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},t1(ZO))});function Ed(n,e,t=()=>{}){if(!Array.isArray(n))throw new TypeError(`"${e}" expected array, got type=${typeof n}`);for(let i=0;i<n.length;i++)t(n[i],`${e}[${i}]`);return n}function qr(n,e="object"){if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof n}`);return n}function ko(n,e){if(typeof n!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof n}`);return n}function So(n,e=""){if(typeof n!="boolean")throw new TypeError(n1(e)+"expected boolean, got type="+typeof n);return n}function i1(n){if(typeof n=="bigint"){if(!Tr(n))throw new RangeError("positive bigint expected, got "+n)}else _y(n);return n}function Fl(n,e=""){if(typeof n!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof n)}if(!Number.isSafeInteger(n)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+n)}}function NA(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);return n===""?Rd:BigInt("0x"+n)}function Md(n){return NA(ys(n))}function Po(n){return NA(ys(xo(tr(n)).reverse()))}function Ay(n,e){if(ho(e),e===0)throw new Error("zero output length is invalid");n=i1(n);let t=e*2,i=n.toString(16);if(i.length>t)throw new RangeError("number is too large");return Dm(i.padStart(t,"0"))}function Ld(n,e){return Ay(n,e).reverse()}function xo(n){return Uint8Array.from(or(n))}function Tr(n){return typeof n=="bigint"&&Rd<=n}function ky(n,e,t){return Tr(n)&&Tr(e)&&Tr(t)&&e<=n&&n<t}function Co(n,e,t,i){if(!ky(e,t,i))throw new RangeError("expected valid "+n+": "+t+" <= n < "+i+", got "+e)}function Sy(n){if(n<Rd)throw new Error("expected non-negative bigint, got "+n);return n===Rd?0:n.toString(2).length}function Io(n,e={},t={},i="object"){qr(n,i),qr(e,"fields"),qr(t,"optFields");function o(r,a,p){let l=i==="object"?`param "${String(r)}"`:`"${i}.${String(r)}"`,c=n[r];if(!Object.hasOwn(n,r)&&(p?c!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(p&&c===void 0)return;let d=typeof c;if(d!==a||c===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${d}`)}let s=(r,a)=>Object.entries(r).forEach(([p,l])=>o(p,l,a));s(e,!1),s(t,!0)}var or,_y,LA,jA,qd,Td,Rd,MA,n1,UA,Vl=I(()=>{gs();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */or=(n,e,t)=>tr(n,e,t),_y=ho;LA=ys,jA=n=>Dm(n),qd=Kp,Td=n=>Gv(n),Rd=BigInt(0),MA=BigInt(1),n1=n=>n?`"${n}" `:"";UA=n=>(Fl(n,"n"),(MA<<BigInt(n))-MA)});function Ge(n,e){if(e<=It)throw new Error("mod: expected positive modulus, got "+e);let t=n%e;return t>=It?t:e+t}function l1(n,e,t){if(t<=Qe)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<It)throw new Error("invalid exponent, negatives unsupported");if(e===It)return Qe;if(e===Qe)return n;let i=n%t;if(i<It&&(i+=t),e<a1){let a=Qe;for(;e>It;)e&Qe&&(a=a*i%t),i=i*i%t,e>>=Qe;return a}let o=[];for(;e>It;)o.push(Number(e&s1)),e>>=Py;let s=new Array(16);s[0]=Qe,s[1]=i;for(let a=2;a<16;a++)s[a]=s[a-1]*i%t;let r=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){r=r*r%t,r=r*r%t,r=r*r%t,r=r*r%t;let p=o[a];p!==0&&(r=r*s[p]%t)}return r}function Un(n,e,t){if(t<=Qe)throw new Error("pow2: expected modulus > 1, got "+t);if(e<It)throw new Error("pow2: expected non-negative exponent, got "+e);let i=n;for(;e-- >It;)i*=i,i%=t;return i}function DA(n,e){if(n===It)throw new Error("invert: expected non-zero number");if(e<=Qe)throw new Error("invert: expected modulus > 1, got "+e);let t=Ge(n,e),i=e,o=It,s=Qe;for(;t!==It;){let a=i/t,p=i-t*a,l=o-s*a;i=t,t=p,o=s,s=l}if(i!==Qe)throw new Error("invert: does not exist");return Ge(o,e)}function xy(n,e,t){let i=n;if(!i.eql(i.sqr(e),t))throw new Error("Cannot find square root")}function Cy(n,e){if((n&Qe)===It)throw new Error(e+": expected odd modulus, got "+n)}function KA(n,e){let t=n,i=(t.ORDER+Qe)/Py,o=t.pow(e,i);return xy(t,o,e),o}function c1(n,e){let t=n,i=(t.ORDER-BA)/FA,o=t.mul(e,Oo),s=t.pow(o,i),r=t.mul(e,s),a=t.mul(t.mul(r,Oo),s),p=t.mul(r,t.sub(a,t.ONE));return xy(t,p,e),p}function p1(n){let e=Ud(n),t=WA(n),i=t(e,e.neg(e.ONE)),o=t(e,i),s=t(e,e.neg(i)),r=(n+r1)/VA;return((a,p)=>{let l=a,c=l.pow(p,r),d=l.mul(c,i),u=l.mul(c,o),f=l.mul(c,s),h=l.eql(l.sqr(d),p),m=l.eql(l.sqr(u),p);c=l.cmov(c,d,h),d=l.cmov(f,u,m);let b=l.eql(l.sqr(d),p),w=l.cmov(c,d,b);return xy(l,w,p),w})}function WA(n){if(n<zA)throw new Error("sqrt is not defined for small field");Cy(n,"tonelliShanks");let e=n-Qe,t=0;for(;e%Oo===It;)e/=Oo,t++;let i=Oo,o=Ud(n);for(;Kl(o,i)===1;)if(i++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return KA;let s=o.pow(i,e),r=(e+Qe)/Oo;return function(p,l){let c=p;if(c.is0(l))return l;if(Kl(c,l)!==1)throw new Error("Cannot find square root");let d=t,u=c.mul(c.ONE,s),f=c.pow(l,e),h=c.pow(l,r);for(;!c.eql(f,c.ONE);){if(c.is0(f))throw new Error("Cannot find square root: probably non-prime P");let m=1,b=c.sqr(f);for(;!c.eql(b,c.ONE);)if(m++,b=c.sqr(b),m===d)throw new Error("Cannot find square root");let w=Qe<<BigInt(d-m-1),g=c.pow(u,w);d=m,u=c.sqr(g),f=c.mul(f,u),h=c.mul(h,g)}return h}}function d1(n){return Cy(n,"Fp.sqrt"),n%Py===zA?KA:n%FA===BA?c1:n%VA===o1?p1(n):WA(n)}function Cs(n){if(qr(n,"field"),typeof n.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof n.ORDER);Fl(n.BYTES,"BYTES"),Fl(n.BITS,"BITS");for(let e of u1)ko(n[e],"field."+e);if(n.BYTES<1||n.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(n.ORDER<=Qe)throw new Error("invalid field: expected ORDER > 1, got "+n.ORDER);return n}function Nd(n,e,t=!1){Cs(n),Ed(e,"nums"),So(t,"passZero");let i=n,o=new Array(e.length).fill(t?i.ZERO:void 0),s=e.reduce((a,p,l)=>i.is0(p)?a:(o[l]=a,i.mul(a,p)),i.ONE),r=i.inv(s);return e.reduceRight((a,p,l)=>i.is0(p)?a:(o[l]=i.mul(a,o[l]),i.mul(a,p)),r),o}function Kl(n,e){Cs(n);let t=n;Cy(t.ORDER,"FpLegendre");let i=(t.ORDER-Qe)/Oo,o=t.pow(e,i),s=t.eql(o,t.ONE),r=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!r&&!a)throw new Error("invalid Legendre symbol result");return s?1:r?0:-1}function f1(n,e){if(e!==void 0&&_y(e),n<=It)throw new Error("invalid n length: expected positive n, got "+n);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Sy(n);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let i=e!==void 0?e:t,o=Math.ceil(i/8);return{nBitLength:i,nByteLength:o}}function Ud(n,e={}){return Object.freeze(jd.prototype),new jd(n,e)}var It,Qe,Oo,zA,Py,BA,r1,FA,o1,s1,VA,a1,HA,u1,$A,jd,Wl=I(()=>{Vl();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */It=BigInt(0),Qe=BigInt(1),Oo=BigInt(2),zA=BigInt(3),Py=BigInt(4),BA=BigInt(5),r1=BigInt(7),FA=BigInt(8),o1=BigInt(9),s1=BigInt(15),VA=BigInt(16),a1=BigInt("0x10000000000000000");HA=(n,e)=>(Ge(n,e)&Qe)===Qe,u1=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];$A=new WeakMap,jd=class{ORDER;BITS;BYTES;isLE;ZERO=It;ONE=Qe;_lengths;_mod;constructor(e,t={}){if(e<=Qe)throw new Error("invalid field: expected ORDER > 1, got "+e);let i;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(i=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=f1(e,i);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return Ge(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return It<=e&&e<this.ORDER}is0(e){return e===It}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Qe)===Qe}neg(e){return Ge(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Ge(e*e,this.ORDER)}add(e,t){return Ge(e+t,this.ORDER)}sub(e,t){return Ge(e-t,this.ORDER)}mul(e,t){return Ge(e*t,this.ORDER)}pow(e,t){return l1(e,t,this.ORDER)}div(e,t){return Ge(e*DA(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return DA(e,this.ORDER)}sqrt(e){let t=$A.get(this);return t||$A.set(this,t=d1(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Ld(e,this.BYTES):Ay(e,this.BYTES)}fromBytes(e,t=!1){or(e);let{_lengths:i,BYTES:o,isLE:s,ORDER:r,_mod:a}=this;if(i){if(e.length<1||!i.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let p=s?Po(e):Md(e);if(a&&(p=Ge(p,r)),!t&&!this.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p}invertBatch(e){return Nd(this,e,!0)}cmov(e,t,i){return So(i,"condition"),i?t:e}}});function $d(n){let e=n;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof n);ko(e.fromAffine,"Point.fromAffine"),ko(e.fromBytes,"Point.fromBytes"),ko(e.fromHex,"Point.fromHex"),qr(e.BASE,"Point.BASE"),qr(e.ZERO,"Point.ZERO"),Cs(e.Fp),Cs(e.Fn)}function XA(n,e){$d(n),ZA(e,n);let t=Nd(n.Fp,e.map(i=>i.Z));return e.map((i,o)=>n.fromAffine(i.toAffine(t[o])))}function y1(n,e,t=1){if(!Number.isSafeInteger(n)||n<t||n>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+n)}function g1(n,e){let t=n*(4*e+128);if(t>YA)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+YA/2**20+" MiB")}function b1(n,e){if(n!==void 0){ko(n,"randomBytes");try{let t=n(e);if(!qd(t)||t.length!==e)return}catch{return}return n}}function ZA(n,e){Ed(n,"points"),n.forEach((t,i)=>{if(!(t instanceof e))throw new Error("invalid point at index "+i)})}function w1(n,e,t){if(!Array.isArray(n))throw new Error("array of scalars expected");n.forEach((i,o)=>{if(!(t===void 0?e.isValid(i):Tr(i)&&i<t))throw new Error("invalid scalar at index "+o)})}function Oy(n){return QA.get(n)||1}function v1(n,e){let t=n.double(),i=[n];for(let o=1;o<e;o++)i.push(i[o-1].add(t));return i}function _1(n,e){let t=2**e,i=t/2,o=BigInt(t-1),s=[];for(;n>Ry;){let r=0;n&Hl&&(r=Number(n&o),r>=i&&(r-=t),n-=BigInt(r)),s.push(r),n>>=Hl}return s}function A1(n,e,t){let i=2**e,o=i/2,s=BigInt(i-1),r=BigInt(e),a=[];for(let p=0;p<t;p++){let l=Number(n&s);n>>=r,l>o&&(l-=i,n+=Hl),a.push(l)}if(n!==Ry)throw new Error("invalid wnaf");return a}function k1(n,e,t){let i=0;for(let s of t)i=Math.max(i,s.length);let o=n;for(let s=i-1;s>=0;s--){s!==i-1&&(o=o.double());for(let r=0;r<t.length;r++){let a=t[r][s];if(a){let p=e[r][Math.abs(a)-1>>1];o=o.add(a<0?p.negate():p)}}}return o}function S1(n,e,t,i=!1){if($d(n),ZA(e,n),So(i,"allowOversized"),w1(t,n.Fn,i?n.Fn.ORDER**h1:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let o=e.map(r=>v1(r,4)),s=t.map(r=>_1(r,4));return k1(n.ZERO,o,s)}function JA(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Cs(e),e}else return Ud(n,{isLE:t})}function e0(n,e,t={},i){if(n!=="weierstrass"&&n!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(i===void 0&&(i=n==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);Io(t);for(let p of["p","n","h"]){let l=e[p];if(!(Tr(l)&&l!==Ry))throw new Error(`CURVE.${p} must be positive bigint`)}let o=JA(e.p,t.Fp,i),s=JA(e.n,t.Fn,i),a=["Gx","Gy","a",n==="weierstrass"?"b":"d"];for(let p of a)if(!o.isValid(e[p]))throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function Ey(n,e){return function(i){let o=n(i);return{secretKey:o,publicKey:e(o)}}}var Ry,Hl,h1,Iy,GA,m1,YA,QA,Dd,qy=I(()=>{Vl();Wl();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Ry=BigInt(0),Hl=BigInt(1),h1=BigInt(4),Iy=16,GA=128,m1=5,YA=2**31;QA=new WeakMap;Dd=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){$d(e),this.randomBytes=b1(t,Iy),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,i){let o=Math.ceil(i/t)+1,s=2**(t-1),r=[],a=e;for(let p=0;p<o;p++){let l=a;for(let c=0;c<s;c++)r.push(l),l=l.add(a);a=r[r.length-1].double()}return{W:t,bits:i,windows:o,comp:r}}wnafCachedCT(e,t){let{W:i,windows:o,comp:s}=e,r=2**(i-1),a=A1(t,i,o),p=this.ZERO,l=this.BASE;for(let c=0;c<o;c++){let d=a[c],u=c*r,f=Math.abs(d)-1,h=s[u];for(let b=1;b<r;b++)h=b===f?s[u+b]:h;let m=h.negate();d===0?l=l.add(s[u]):p=p.add(d<0?m:h)}return{p,f:l}}getWnafPrecomputes(e,t,i,o){let s=this.wnafPrecomputes.get(t),r=s?.find(a=>a.W===e&&a.bits===i);return r||(r=this.buildWnafTable(t,e,i),typeof o=="function"&&(r={...r,comp:o(r.comp)}),s||(s=[],this.wnafPrecomputes.set(t,s)),s.push(r)),r}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!ky(t,Hl,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,i,o){let s=Oy(e);return s===1?this.fixedWindowCT(e,t,i):this.wnafCachedCT(this.getWnafPrecomputes(s,e,i,o),t)}mulCT(e,t,i){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,i)}mulCTBlinded(e,t,i){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+GA,s=this.randomBytes(Iy);if(!qd(s)||s.length!==Iy)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let r=t+Md(s)*this.Point.Fn.ORDER;return this.runCT(e,r,o,i)}fixedWindowCT(e,t,i){let o=m1,s=1<<o,r=UA(o),a=new Array(s);a[0]=this.ZERO;for(let c=1;c<s;c++)a[c]=a[c-1].add(e);let p=Math.ceil(i/o),l=this.ZERO;for(let c=p-1;c>=0;c--){if(c!==p-1)for(let f=0;f<o;f++)l=l.double();let d=Number(t>>BigInt(c*o)&r),u=a[0];for(let f=1;f<s;f++)u=f===d?a[f]:u;l=l.add(u)}return{p:l,f:l}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===Hl?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,i,o){return this.shouldBlind(e,i)?this.mulCTBlinded(e,t,o):this.mulCT(e,t,o)}mulUnsafe(e,t,i){if(this.assertPoint(e),!Tr(t))throw new Error("invalid scalar");let o=Oy(e);if(o===1||t>=this.Point.Fn.ORDER)return S1(this.Point,[e],[t],!0);let s=this.getWnafPrecomputes(o,e,this.bits,i);return this.wnafCachedCT(s,t).p}setWindowSize(e,t){this.assertPoint(e),y1(t,this.bits);let i=Math.ceil((this.bits+GA)/t)+1;g1(i*2**(t-1),this.Point.Fp.BYTES),QA.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Oy(e)!==1}}});function x1(n,e,t,i){let o=n.sqr(t),s=n.sqr(i),r=n.add(n.mul(e.a,o),s),a=n.add(n.ONE,n.mul(e.d,n.mul(o,s)));return n.eql(r,a)}function n0(n,e={}){Io(e,{},{},"extraOpts");let t=e,i=e0("edwards",n,t,t.FpFnLE),{Fp:o,Fn:s}=i,r=i.CURVE,{h:a}=r;if(Kl(o,r.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Kl(o,r.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Io(t,{},{uvRatio:"function",randomBytes:"function"});let p=t.randomBytes===void 0?Td:t.randomBytes,l=Fd<<BigInt(o.BYTES*8)-Bd;function c(g){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(g)}let d=t.uvRatio===void 0?(g,y)=>{try{return{isValid:!0,value:o.sqrt(o.div(g,y))}}catch{return{isValid:!1,value:zd}}}:t.uvRatio;if(!x1(o,r,r.Gx,r.Gy))throw new Error("bad curve params: generator point");let u=o.eql(r.a,o.neg(o.ONE))?g=>o.neg(g):o.eql(r.a,o.ONE)?g=>g:g=>o.mul(r.a,g);function f(g,y,v=!1){let _=v?Bd:zd;return Co("coordinate "+g,y,_,l),y}function h(g){if(!(g instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(r.Gx,r.Gy,o.ONE,o.mul(r.Gx,r.Gy));static ZERO=new m(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(y,v,_,k){this.X=f("x",y),this.Y=f("y",v),this.Z=f("z",_,!0),this.T=f("t",k),Object.freeze(this)}static CURVE(){return r}static fromAffine(y){if(y instanceof m)throw new Error("extended point not allowed");let{x:v,y:_}=y||{};return f("x",v),f("y",_),new m(v,_,o.ONE,o.mul(v,_))}static fromBytes(y,v=!1){let _=o.BYTES,{a:k,d:S}=r;y=xo(or(y,_,"point")),So(v,"zip215");let x=xo(y),P=y[_-1];x[_-1]=P&-129;let C=Po(x),E=v?l:o.ORDER;Co("point.y",C,zd,E);let O=o.sqr(C),L=o.sub(O,o.ONE),z=o.sub(o.mulN(S,O),k),{isValid:Q,value:V}=d(L,z);if(!Q)throw new Error("bad point: invalid y coordinate");let te=c(V),G=(P&128)!==0;if(!v&&o.is0(V)&&G)throw new Error("bad point: x=0 and x_0=1");return G!==te&&(V=o.neg(V)),m.fromAffine({x:V,y:C})}static fromHex(y,v=!1){return m.fromBytes(jA(y),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=6,v=!0){return w.setWindowSize(this,y),v||this.multiply(Fd),this}assertValidity(){let y=this,{a:v,d:_}=r;if(y.is0())throw new Error("bad point: ZERO");let{X:k,Y:S,Z:x,T:P}=y,C=o.sqr(k),E=o.sqr(S),O=o.sqr(x),L=o.sqr(O),z=o.mul(C,v),Q=o.mul(o.add(z,E),O),V=o.add(L,o.mul(_,o.mul(C,E)));if(!o.eql(Q,V))throw new Error("bad point: equation left != right (1)");let te=o.mul(k,S),G=o.mul(x,P);if(!o.eql(te,G))throw new Error("bad point: equation left != right (2)")}equals(y){h(y);let{X:v,Y:_,Z:k}=this,{X:S,Y:x,Z:P}=y,C=o.mul(v,P),E=o.mul(S,k),O=o.mul(_,P),L=o.mul(x,k);return o.eql(C,E)&&o.eql(O,L)}is0(){return this.equals(m.ZERO)}negate(){return new m(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:y,Y:v,Z:_}=this,k=o.sqr(y),S=o.sqr(v),x=o.mul(o.sqr(_),Fd),P=u(k),C=o.addN(y,v),E=o.sub(o.subN(o.sqr(C),k),S),O=o.addN(P,S),L=o.subN(O,x),z=o.subN(P,S),Q=o.mul(E,L),V=o.mul(O,z),te=o.mul(E,z),G=o.mul(L,O);return new m(Q,V,G,te)}add(y){h(y);let{d:v}=r,{X:_,Y:k,Z:S,T:x}=this,{X:P,Y:C,Z:E,T:O}=y,L=o.mul(_,P),z=o.mul(k,C),Q=o.mul(o.mulN(x,v),O),V=o.mul(S,E),te=o.sub(o.subN(o.mulN(o.addN(_,k),o.addN(P,C)),L),z),G=o.subN(V,Q),K=o.addN(V,Q),X=o.sub(z,u(L)),Y=o.mul(te,G),ee=o.mul(K,X),$e=o.mul(te,X),mt=o.mul(G,K);return new m(Y,ee,mt,$e)}subtract(y){return h(y),this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:_}=w.mulSecret(this,y,a,b);return b([v,_])[0]}multiplyUnsafe(y){if(!s.isValid(y))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return y===zd?m.ZERO:this.is0()||y===Bd?this:w.mulUnsafe(this,y,b)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.mulUnsafe(this,r.n).is0()}toAffine(y){let v=this,_=y;if(_!=null&&typeof _!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof _);let{X:k,Y:S,Z:x}=v,P=v.is0();_==null&&(_=P?o.create(t0):o.inv(x));let C=o.mul(k,_),E=o.mul(S,_),O=o.mul(x,_);if(P)return{x:o.ZERO,y:o.ONE};if(!o.eql(O,o.ONE))throw new Error("invZ was invalid");return{x:C,y:E}}clearCofactor(){return a===Bd?this:a===Fd?this.double():a===P1?this.double().double():a===t0?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:y,y:v}=this.toAffine(),_=o.toBytes(v);return _[_.length-1]|=c(y)?128:0,_}toHex(){return LA(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let b=g=>XA(m,g),w=new Dd(m,p);return w.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}var zd,Bd,Fd,P1,t0,i0=I(()=>{Vl();qy();Wl();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */zd=BigInt(0),Bd=BigInt(1),Fd=BigInt(2),P1=BigInt(4),t0=BigInt(8)});function r0(n,e){return n+e-(e>>Dn<<Dn)}function C1(n){let e=BigInt(6)*n;return(t,i,o)=>{let s=i+o,a=((e+o-i)*t+i)%n;return{x_2:a,x_3:s-a}}}function I1(n){return Io(n,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...n})}function o0(n){let e=I1(n),{P:t,type:i,adjustScalarBytes:o,powPminus2:s,randomBytes:r}=e,a=e.scalarMultBase,p=i==="x25519";if(!p&&i!=="x448")throw new Error("invalid type");let l=r===void 0?Td:r,c=p?255:448,d=C1(t),u=p?32:56,f=BigInt(p?9:5),h=BigInt(p?121665:39081),m=p?Vd**BigInt(254):Vd**BigInt(447),b=p?BigInt(8)*(Vd**BigInt(251)-Dn):BigInt(4)*(Vd**BigInt(445)-Dn),w=m+b+Dn,g=V=>Ge(V,t),y=v(f);function v(V){return Ld(g(V),u)}function _(V){let te=xo(or(V,u,"uCoordinate"));return p&&(te[31]&=127),g(Po(te))}function k(V){return Po(o(xo(or(V,u,"scalar"))))}let S=new Set(p?[Ro,Dn,t-Dn,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[Ro,Dn,t-Dn]);function x(V,te){let G=_(te);if(S.has(G))throw new Error("invalid private or public key received");let K=O(G,k(V));if(K===Ro)throw new Error("invalid private or public key received");return v(K)}function P(V){if(a===void 0)return x(V,y);let te=k(V);Co("scalar",te,m,w);let G=g(a(te));if(G===Ro)throw new Error("invalid private or public key received");return v(G)}let C=P,E=x;function O(V,te){Co("u",V,Ro,t),Co("scalar",te,m,w);let G=te,K=V,X=Dn,Y=Ro,ee=V,$e=Dn,mt=G^G>>Dn;for(let $=BigInt(c-1);$>=Ro;$--){let J=r0(t,mt>>$);({x_2:X,x_3:ee}=d(J,X,ee)),{x_2:Y,x_3:$e}=d(J,Y,$e);let be=X+Y,ye=g(be*be),we=X-Y,et=g(we*we),qe=ye-et,Dt=ee+$e,tt=ee-$e,Ve=g(tt*be),On=g(Dt*we),Ar=Ve+On,Pi=Ve-On;ee=g(Ar*Ar),$e=g(K*g(Pi*Pi)),X=g(ye*et),Y=g(qe*(ye+g(h*qe)))}let j=r0(t,G);({x_2:X,x_3:ee}=d(j,X,ee)),{x_2:Y,x_3:$e}=d(j,Y,$e);let W=s(Y);return g(X*W)}let L={secretKey:u,publicKey:u,seed:u},z=V=>(V=V===void 0?l(u):V,or(V,L.seed,"seed"),V),Q={randomSecretKey:z};return Object.freeze(L),Object.freeze(Q),Object.freeze({keygen:Ey(z,C),getSharedSecret:E,getPublicKey:C,scalarMult:x,scalarMultBase:P,utils:Q,GuBytes:y.slice(),lengths:L})}var Ro,Dn,Vd,s0=I(()=>{Vl();qy();Wl();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Ro=BigInt(0),Dn=BigInt(1),Vd=BigInt(2)});function d0(n){let e=BigInt(10),t=BigInt(20),i=BigInt(40),o=BigInt(80),s=Kd,a=n*n%s*n%s,p=Un(a,l0,s)*a%s,l=Un(p,O1,s)*n%s,c=Un(l,E1,s)*l%s,d=Un(c,e,s)*c%s,u=Un(d,t,s)*d%s,f=Un(u,i,s)*u%s,h=Un(f,o,s)*f%s,m=Un(h,o,s)*f%s,b=Un(m,e,s)*c%s;return{pow_p_5_8:Un(b,l0,s)*n%s,b2:a}}function M1(n){return n[0]&=248,n[31]&=127,n[31]|=64,n}function L1(n,e){let t=Kd,i=Ge(e*e*e,t),o=Ge(i*i*e,t),s=d0(n*o).pow_p_5_8,r=Ge(n*i*s,t),a=Ge(e*r*r,t),p=r,l=Ge(r*c0,t),c=a===n,d=a===Ge(-n,t),u=a===Ge(-n*c0,t);return c&&(r=p),(d||u)&&(r=l),HA(r,t)&&(r=Ge(-r,t)),{isValid:c||d,value:r}}var a0,O1,l0,R1,E1,q1,Kd,T1,c0,p0,sr,Ty=I(()=>{i0();Wl();s0();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */a0=BigInt(0),O1=BigInt(1),l0=BigInt(2),R1=BigInt(3),E1=BigInt(5),q1=BigInt(8),Kd=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),T1={p:Kd,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:q1,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};c0=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");p0=n0(T1,{uvRatio:L1}),sr=(()=>{let n=Kd,e=t=>{let{pow_p_5_8:i,b2:o}=d0(t);return Ge(Un(i,R1,n)*o,n)};return o0({P:n,type:"x25519",powPminus2:e,adjustScalarBytes:M1,scalarMultBase:t=>{let i=Ge(t,p0.Fn.ORDER);if(i===a0)return a0;let o=p0.BASE.multiply(i);return Ge((o.Z+o.Y)*e(Ge(o.Z-o.Y,n)),n)}})})()});var Wd,Hd,u0=I(()=>{gs();Wd=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Vv(e),tr(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(t.length>i?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),ms(o)}update(e){return hs(this),this.iHash.update(e),this}digestInto(e){hs(this),Wp(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:i,finished:o,destroyed:s,blockLen:r,outputLen:a,canXOF:p}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=r,e.outputLen=a,e.canXOF=p,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Hd=(()=>{let n=((e,t,i)=>new Wd(e,t).update(i).digest());return n.create=(e,t)=>new Wd(e,t),n})()});function Yd(n){return"dh"in n?n:{publicKey:n.publicKey,dh:e=>Eo(n.secretKey,e)}}async function h0(n,e){let t;try{t=await n.dh(e)}catch(i){throw i instanceof rt?i:new rt("invalid public key")}return v0(t)}function Es(){let n=sr.utils.randomSecretKey();return{secretKey:n,publicKey:sr.getPublicKey(n)}}function w0(n){return{secretKey:n,publicKey:sr.getPublicKey(n)}}function Gl(...n){let e=0;for(let o of n)e+=o.length;let t=new Uint8Array(e),i=0;for(let o of n)t.set(o,i),i+=o.length;return t}function v0(n){let e=0;for(let t of n)e|=t;if(e===0)throw new rt("invalid public key (all-zero shared secret)");return n}function Eo(n,e){let t;try{t=sr.getSharedSecret(n,e)}catch{throw new rt("invalid public key")}return v0(t)}function m0(n,e){let t=Hd(it,n,e),i=Hd(it,t,Uint8Array.of(1)),o=Hd(it,t,Gl(i,Uint8Array.of(2)));return[i,o]}function y0(n){let e=new Uint8Array(12),t=new DataView(e.buffer);return t.setUint32(4,n>>>0,!0),t.setUint32(8,Math.floor(n/2**32),!0),e}function Ti(n,e,t){for(let[i,o]of[["collection",n],["target device",t]])if(o.length!==16)throw new rt(`${i} ID must be 16 bytes`);if(e&&e.length!==16)throw new rt("grant ID must be 16 bytes");return Gl(j1,n,e??N1,t)}var g0,$n,f0,b0,Is,My,Gd,rt,Os,Jd,Rs,Xd,j1,N1,qo=I(()=>{"use strict";TA();Ty();u0();Cr();g0="Noise_IK_25519_ChaChaPoly_SHA256",$n=32,f0=32,b0=65535,Is=16,My=b0-Is,Gd=2**30;rt=class extends Error{constructor(e){super(e),this.name="NoiseError"}},Os=class{constructor(e=null){this.k=e}k;n=0;hasKey(){return this.k!==null}get count(){return this.n}encrypt(e,t){if(!this.k)return t;if(this.n>=Gd)throw new rt("session message limit reached");let i=vy(this.k,y0(this.n),e).encrypt(t);return this.n++,i}decrypt(e,t){if(!this.k)return t;if(this.n>=Gd)throw new rt("session message limit reached");let i;try{i=vy(this.k,y0(this.n),e).decrypt(t)}catch{throw new rt("decryption failed")}return this.n++,i}},Jd=class{ck;h;cs=new Os;constructor(e){let t=new TextEncoder().encode(e);t.length<=f0?(this.h=new Uint8Array(f0),this.h.set(t)):this.h=it(t),this.ck=this.h}mixKey(e){let[t,i]=m0(this.ck,e);this.ck=t,this.cs=new Os(i)}mixHash(e){this.h=it(Gl(this.h,e))}encryptAndHash(e){let t=this.cs.encrypt(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decrypt(this.h,e);return this.mixHash(e),t}split(){let[e,t]=m0(this.ck,new Uint8Array(0));return[new Os(e),new Os(t)]}},Rs=class{constructor(e){this.opts=e;if(e.remoteStatic.length!==$n)throw new rt("remote static key must be 32 bytes");this.e=e.ephemeral??Es(),this.ss.mixHash(e.prologue),this.ss.mixHash(e.remoteStatic)}opts;ss=new Jd(g0);e;state="start";async writeMessage1(e){if(this.state!=="start")throw new rt("handshake out of order");this.state="sent";let t=Yd(this.opts.staticKey),i=this.ss;i.mixHash(this.e.publicKey),i.mixKey(Eo(this.e.secretKey,this.opts.remoteStatic));let o=i.encryptAndHash(t.publicKey);i.mixKey(await h0(t,this.opts.remoteStatic));let s=i.encryptAndHash(e),r=Gl(this.e.publicKey,o,s);if(r.length>b0)throw new rt("handshake message too large");return r}async readMessage2(e){if(this.state!=="sent")throw new rt("handshake out of order");if(e.length<$n+Is)throw new rt("handshake message too short");this.state="done";let t=this.ss,i=e.subarray(0,$n);t.mixHash(i),t.mixKey(Eo(this.e.secretKey,i)),t.mixKey(await h0(Yd(this.opts.staticKey),i));let o=t.decryptAndHash(e.subarray($n)),[s,r]=t.split();return{payload:o,transport:{send:s,recv:r,handshakeHash:t.h,remoteStatic:this.opts.remoteStatic}}}},Xd=class{constructor(e){this.opts=e;this.e=e.ephemeral??Es(),this.ss.mixHash(e.prologue),this.ss.mixHash(e.staticKey.publicKey)}opts;ss=new Jd(g0);e;rs=null;re=null;state="start";readMessage1(e){if(this.state!=="start")throw new rt("handshake out of order");if(this.state="done",e.length<$n+$n+Is+Is)throw new rt("handshake message too short");let t=this.ss,i=e.subarray(0,$n).slice();t.mixHash(i),t.mixKey(Eo(this.opts.staticKey.secretKey,i));let o=t.decryptAndHash(e.subarray($n,$n+$n+Is));t.mixKey(Eo(this.opts.staticKey.secretKey,o));let s=t.decryptAndHash(e.subarray($n+$n+Is));return this.re=i,this.rs=o,this.state="read",{remoteStatic:o,payload:s}}writeMessage2(e){if(this.state!=="read"||!this.re||!this.rs)throw new rt("handshake out of order");this.state="done";let t=this.ss;t.mixHash(this.e.publicKey),t.mixKey(Eo(this.e.secretKey,this.re)),t.mixKey(Eo(this.e.secretKey,this.rs));let i=t.encryptAndHash(e),[o,s]=t.split();return{message:Gl(this.e.publicKey,i),transport:{send:s,recv:o,handshakeHash:t.h,remoteStatic:this.rs}}}},j1=new TextEncoder().encode("mdbase/v1/client"),N1=new Uint8Array(16)});function U1(n,e,t){return new Promise((i,o)=>{let s=()=>o(A("cancelled","connect aborted"));t?.addEventListener("abort",s,{once:!0}),n.onmessage=r=>{t?.removeEventListener("abort",s),n.onmessage=a=>{e.push(a)},i(r)},n.onclose=r=>{t?.removeEventListener("abort",s),o(r??A("unavailable","connection closed during the handshake"))}})}function jy(n,e,t=Ly,i=[]){let o=new Uint8Array(0),s=!1,r=setTimeout(()=>l(),t);r.unref?.();let a={ondata:null,onclose:null,write(c){if(s)throw A("unavailable","connection closed");for(let d=0;d<c.length;d+=My){if(e.send.count>=Gd-1)throw l(),A("unavailable","session message limit reached; reconnecting");n.send(e.send.encrypt(o,c.subarray(d,d+My)))}},close(){s||(s=!0,clearTimeout(r),n.close())}},p=c=>{if(s)return;let d;try{d=e.recv.decrypt(o,c)}catch{l(A("unavailable","transport message failed authentication","noise"));return}a.ondata?.(d)};if(n.onmessage=p,n.onclose=c=>l(c),i.length){let c=i.splice(0);queueMicrotask(()=>c.forEach(p))}function l(c){s||(s=!0,clearTimeout(r),n.close(),a.onclose?.(c))}return a}function Mi(n){return{description:n.description,async open(e,t){let i=()=>A("cancelled","connect aborted");if(t?.aborted)throw i();let o=await n.target(t);if(t?.aborted)throw i();let s=await o.openCarrier(t);if(t?.aborted)throw s.close(),i();try{let r=new Rs({prologue:o.prologue,staticKey:n.staticKey,remoteStatic:o.remoteStatic}),a=[],p=U1(s,a,t);p.catch(()=>{}),o.preamble&&s.send(o.preamble);let l=await r.writeMessage1(n.firstPayload?n.firstPayload(e):pe(e));if(t?.aborted)throw i();s.send(l);let{payload:c,transport:d}=await r.readMessage2(await p),u=ue(c);return{port:id(jy(s,d,n.lifetimeMs,a)),helloResponse:u,...o.device?{device:o.device}:{}}}catch(r){throw s.close(),oe(r)?r:r instanceof rt?A("unauthenticated",`handshake failed: ${r.message}`,"noise"):A("unavailable",`handshake failed: ${String(r)}`)}}}}function qs(n,e=D1,t){return new Promise((i,o)=>{let s;try{s=e(n)}catch(l){o(oe(l)?l:A("unavailable",`cannot open ${n}: ${String(l)}`));return}s.binaryType="arraybuffer";let r=!1,a={onmessage:null,onclose:null,send(l){s.send(l)},close(){try{s.close(1e3)}catch{}}},p=()=>{s.close(),o(A("cancelled","connect aborted"))};t?.addEventListener("abort",p,{once:!0}),s.onopen=()=>{r=!0,t?.removeEventListener("abort",p),i(a)},s.onmessage=l=>{let c=l.data;c instanceof ArrayBuffer?a.onmessage?.(new Uint8Array(c)):ArrayBuffer.isView(c)&&a.onmessage?.(new Uint8Array(c.buffer,c.byteOffset,c.byteLength))},s.onerror=()=>{},s.onclose=l=>{let c=$1(l.code,l.reason);r?a.onclose?.(c):(t?.removeEventListener("abort",p),o(c??A("unavailable",`cannot connect to ${n}`)))}})}function $1(n,e){switch(n){case 4404:return A("unavailable",e||"no device of this collection is online","no_device_online");case 4401:return A("unauthenticated",e||"relay refused the session");case 4403:return A("forbidden",e||"relay refused the session");case 4429:return A("rate_limited",e||"rate limited");default:return}}function _0(n){let e=new Uint8Array(0),t={onmessage:null,onclose:null,send(i){if(i.length>65535)throw A("too_large","Noise message over 65535 bytes");let o=new Uint8Array(2+i.length);o[0]=i.length>>8,o[1]=i.length&255,o.set(i,2),n.write(o)},close(){n.close()}};return n.ondata=i=>{let o=new Uint8Array(e.length+i.length);o.set(e),o.set(i,e.length);let s=0;for(;o.length-s>=2;){let r=o[s]<<8|o[s+1];if(o.length-s-2<r)break;t.onmessage?.(o.slice(s+2,s+2+r)),s+=2+r}e=o.slice(s)},n.onclose=i=>t.onclose?.(i?A("unavailable",i.message):void 0),t}var Ly,D1,Ts=I(()=>{"use strict";Je();ie();qo();Ol();Ly=1440*60*1e3;D1=n=>{let e=globalThis.WebSocket;if(!e)throw A("unavailable","no WebSocket implementation; pass webSocket");return new e(n)}});function Mr(n){return!1}function ot(n){try{let e=new URL(n);return e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname)}catch{return!1}}function Ny(n){return!1}var Zd=I(()=>{"use strict"});function Uy(n){let e=typeof n=="number"&&Number.isInteger(n)&&n>=1e3&&n<=4999?n:null;return Object.freeze({closeCode:e,closeClass:e===null?"unknown":z1[e]??"other"})}function A0(n){try{if(n instanceof Map&&n.has("relayCloseCode"))return Uy(n.get("relayCloseCode"))}catch{}}var z1,Dy=I(()=>{"use strict";z1={1e3:"normal",1001:"going_away",1002:"protocol_error",1003:"unsupported_data",1005:"no_status",1006:"abnormal",1007:"invalid_payload",1008:"policy_violation",1009:"message_too_big",1010:"extension_required",1011:"internal_error",1012:"service_restart",1013:"try_again_later",1014:"bad_gateway",1015:"tls_failure",4e3:"pipe_closed",4401:"unauthenticated",4403:"grant_inactive",4404:"connector_offline",4429:"connector_busy"}});function To(n,e){let t=typeof e=="string"&&F1.has(e)?e:void 0,i=Uy(n),o=new Map([["relayCloseCode",i.closeCode],["relayCloseClass",i.closeClass]]),s=(r,a,p,l)=>A(r,a,{reason:p,details:o,...l===void 0?{}:{retryAfterMs:l}});switch(i.closeCode){case 4401:return s("unauthenticated",t??"relay: unauthenticated","relay_unauthenticated");case 4403:return s("forbidden",t??"relay: grant inactive",t??"grant_inactive");case 4404:return t&&o.set("relay",t),s("unavailable","no device of this collection is online","no_device_online");case 4429:return s("rate_limited",t??"relay: busy",t??"connector_busy",5e3);case 4e3:return t==="grant_lease_expired"?s("unavailable","grant lease expired",t,1e3):t==="device_key_mismatch"?s("unauthenticated","relay: the routed key is not the device's",t):s("unavailable",`relay closed the pipe: ${t??"unknown"}`,t??"pipe_closed");default:return s("unavailable",`relay connection closed${i.closeCode===null?"":` (${i.closeCode})`}`,"relay_closed")}}function V1(n){let e=globalThis.WebSocket;if(!e)throw A("unavailable","no WebSocket implementation; pass webSocket");return new e(n)}function Ms(n,e,t=V1,i){let o="";try{o=new URL(n).protocol}catch{return Promise.reject(A("invalid_request",`invalid relay URL ${n}`,"relay_url"))}return o!=="wss:"&&!!1?Promise.reject(A("invalid_request","relay pipes require wss:","relay_insecure")):e.grant?new Promise((s,r)=>{let a;try{a=t(n)}catch(h){r(A("unavailable",`cannot open ${n}: ${String(h)}`));return}a.binaryType="arraybuffer";let p=!1,l=!1,c=new Uint8Array(0),d={onmessage:null,onclose:null,send(h){if(h.length>65535)throw A("too_large","Noise message over 65535 bytes");let m=new Uint8Array(4+h.length);new DataView(m.buffer).setUint32(0,h.length),m.set(h,4),a.send(m)},close(){try{a.close(1e3)}catch{}}},u=h=>{l?d.onclose?.(h):(l=!0,i?.removeEventListener("abort",f),r(h))},f=()=>{a.close(),u(A("cancelled","connect aborted"))};i?.addEventListener("abort",f,{once:!0}),a.onopen=()=>{a.send(JSON.stringify({type:"pipe_auth",access_token:e.accessToken,collection:e.collection,grant:e.grant,device:e.device,device_noise_pk:ri(e.devicePublicKey)}))},a.onmessage=h=>{let m=h.data;if(typeof m=="string"){let y;try{y=JSON.parse(m)}catch{return}y.type==="pipe_opened"&&!p?(p=!0,l=!0,i?.removeEventListener("abort",f),s(d)):y.type==="pipe_close"&&(a.close(),u(To(4e3,y.reason)));return}if(!p)return;let b=m instanceof ArrayBuffer?new Uint8Array(m):ArrayBuffer.isView(m)?new Uint8Array(m.buffer,m.byteOffset,m.byteLength):null;if(!b)return;if(b.length>B1){a.close(),u(A("too_large","relay frame over the limit"));return}let w=new Uint8Array(c.length+b.length);w.set(c),w.set(b,c.length);let g=0;for(;w.length-g>=4;){let y=new DataView(w.buffer,w.byteOffset+g,4).getUint32(0);if(y>65535){a.close(),u(A("internal","relay sent an oversized Noise message"));return}if(w.length-g-4<y)break;d.onmessage?.(w.slice(g+4,g+4+y)),g+=4+y}c=w.slice(g)},a.onerror=()=>{},a.onclose=h=>u(To(h.code,h.reason))}):Promise.reject(A("invalid_request","relay pipes require a grant","grant_required"))}var B1,F1,Yl=I(()=>{"use strict";Zd();ie();Dy();Je();B1=65539,F1=new Set("unauthenticated grant_inactive connector_offline connector_busy device_mismatch device_key_mismatch closed client_closed handshake_timeout idle lifetime frame_too_large invalid_frame not_served relay_closing authorization_unavailable grant_revoked grant_lease_expired grant_pending_approval grant_revoked_on_device unknown_grant".split(" "))});function Ls(n){return typeof n=="string"&&K1.has(n)}function zn(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"&&Ls(e.reason)?Object.freeze({state:"unavailable",reason:e.reason}):Object.freeze({state:"unavailable",reason:"device_offline"})}function un(n){let e=new Map([["availability",n]]);return n==="collection_deleted"?new se({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 $y,K1,Lr=I(()=>{"use strict";ie();$y=["device_offline","desktop_update_required","old_connector_running","approval_required","sync_required","no_device_registered","access_removed","collection_migrating","collection_not_yet_migrated","collection_deleted"],K1=new Set($y)});function By(n){let e=new Uint8Array(0),t=!1,i,o=null,s=null,r=[],a=0,p={get onmessage(){return o},set onmessage(d){for(o=d;d&&!t&&r.length&&o===d;){let u=r.shift();a-=u.length,d(u)}},get onclose(){return s},set onclose(d){s=d,d&&t&&i&&d(i)},send(d){if(t)throw A("unavailable","relay pipe closed");if(d.length>zy)throw A("too_large","Noise message over 65535 bytes");let u=new Uint8Array(4+d.length);new DataView(u.buffer).setUint32(0,d.length),u.set(d,4),n.send(u)},close(){t||(t=!0,r.length=0,a=0,n.close())}},l=(d,u)=>{t||(t=!0,e=new Uint8Array(0),r.length=0,a=0,i=To(d,u),n.close(),s?.(i))},c=d=>{if(!t){if(o)return o(d);if(r.length>=W1||a+d.length>H1)return l(4e3,"invalid_frame");r.push(d),a+=d.length}};return n.onmessage=d=>{if(t)return;if(d.length>S0)return l(4e3,"invalid_frame");let u=new Uint8Array(e.length+d.length);u.set(e),u.set(d,e.length);let f=0;for(;u.length-f>=4;){let h=new DataView(u.buffer,u.byteOffset+f,4).getUint32(0);if(h>zy)return l(4e3,"invalid_frame");if(u.length-f-4<h)break;let m=u.slice(f+4,f+4+h);if(f+=4+h,c(m),t)return}e=u.slice(f),e.length>S0&&l(4e3,"invalid_frame")},n.onclose=d=>l(d?.code,d?.reason),p}async function P0(n){try{return await n()}catch(e){if(oe(e))throw e;if(e?.code==="not_authorized")throw A("unauthenticated","Connect authorization is missing","not_authorized");let i=e?.cause;throw typeof i?.code=="number"?To(i.code,typeof i.reason=="string"?i.reason:void 0):A("unavailable","the relay pipe could not be opened","relay_unavailable")}}function js(n,e){let t=n.targets.filter(o=>Qd.test(o.device)&&/^[0-9a-f]{64}$/.test(o.noise_pk)&&!!o.relay_collection&&Qd.test(o.relay_collection)),i=t.filter(o=>o.device===e);return i.length?i:[...t.filter(o=>o.online===!0),...t.filter(o=>o.online!==!0)]}function x0(n){let e=n.collection,t=n.next,i=n.staticKey;if(!Qd.test(e))throw A("invalid_request","collection must be a UUID");let o=t.route.bind(t),s=t.openPipe.bind(t),r=null,a=Mi({description:`next-relay:${e}`,staticKey:i,target:async p=>{let l=await P0(()=>o(e,p?{signal:p}:{}));if(l.collection.toLowerCase()!==e.toLowerCase()||!Qd.test(l.grant))throw A("unauthenticated","the route does not match this collection's grant","route_mismatch");let c=zn(l.availability);if(c?.state==="unavailable")throw un(c.reason);let d=js(l,r)[0];if(!d)throw A("unavailable",l.reason==="no_device_registered"?"this collection has no device set up to serve it":"no device of this collection is online",l.reason??"no_device_online");let u=Object.freeze({...d}),f=u.noise_pk,h=new Uint8Array(32);for(let m=0;m<32;m++)h[m]=parseInt(f.slice(2*m,2*m+2),16);return{prologue:Ti(U(u.relay_collection),U(l.grant),U(u.device)),remoteStatic:h,device:u.device,openCarrier:async m=>{let b=await P0(()=>s(e,u,m?{signal:m}:{}));return By(b)}}}});return gd({description:a.description,open:async(p,l)=>{let c=await a.open(p,l);return r=c.device??null,c},get target(){return r}})}var zy,S0,W1,H1,Qd,Fy=I(()=>{"use strict";ge();Lr();ie();qo();Ts();Yl();bd();zy=65535,S0=4+zy,W1=16,H1=1<<20,Qd=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i});function tu(n){if(!n||typeof n!="object"||Array.isArray(n))throw Bn();return n}function N0(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 j0(n){let e=tu(n);if(!N0(e.issuer)||typeof e.subject!="string"||!e.subject.trim()||typeof e.name!="string"||!e.name.trim())throw Bn();let t=e.account_id;if(t!==void 0){if(typeof t!="string")throw Bn();try{if(U(t).every(i=>i===0))throw Bn()}catch{throw Bn()}}return{issuer:e.issuer,subject:e.subject,name:e.name,...t===void 0?{}:{accountId:t}}}function nu(n,e){return n.issuer===e.issuer&&n.subject===e.subject}function Z1(n){return Array.isArray(n)?n.flatMap(e=>{if(!(e instanceof Map))return[];let t=e.get("issuer"),i=e.get("subject");return typeof t!="string"||typeof i!="string"?[]:[{issuer:t,subject:i}]}):[]}function Q1(n){let e=n.fields;if(!(e instanceof Map))throw Bn();let t=e.get("name"),i=e.get("identities"),o=Z1(i),s=n.issues.find(r=>r.severity==="error");return s?{reason:s.message,claims:o}:typeof t!="string"||!t.trim()?{reason:"It needs a non-blank name.",claims:o}:i!==void 0&&(!Array.isArray(i)||o.length!==i.length||o.some(r=>!r.subject.trim()))?{reason:"Each account identity needs an exact issuer and subject.",claims:o}:{name:t,identities:o,claims:o}}var Gy,Bn,jr,iu=I(()=>{"use strict";ge();ie();Gy=Object.freeze({id:"mdbase.person",version:"2.0.0"}),Bn=()=>A("unavailable","invalid people response","people_response");jr=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=U(this.authority.collection),i=U(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=j0(t),o=tu(t).person_settings_url;if(o===void 0)return i;if(!N0(o))throw Bn();return{...i,personSettingsUrl:o}}async members(e={}){this.check(e.signal);let t=tu(await this.authority.request("members",e));if(this.check(e.signal),!Array.isArray(t.members)||t.members.length>1e3)throw Bn();return t.members.map(i=>{let o=j0(i),s=tu(i).role;if(s!=="owner"&&s!=="editor"&&s!=="viewer")throw Bn();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"&&oe(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 p=a.invalid.filter(u=>u.claims.some(f=>nu(f,s))),l=a.people.filter(u=>u.identities.some(f=>nu(f,s))),c=l[0],d=p.length?{status:"invalid",paths:p.map(u=>u.path)}:l.length>1?{status:"ambiguous",paths:l.map(u=>u.path)}:c?{status:"linked",person:c}:{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,p=[],l=[];for(;;){this.check(e.signal);let d=await this.client.queryContract(Gy,{pageSize:128,...i?{cursor:i}:{},...e.signal?{signal:e.signal}:{}}).catch(f=>{if(!i&&!r.size&&oe(f,"not_found")&&f.reason==="data_contract_not_found")return null;throw f});if(this.check(e.signal),this.checkReadSession(t),!d)return{people:p,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 Bn();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 Bn();if(r.add(h.id),r.size>1e4)throw A("too_large","person directory exceeds its record budget","people_budget");let b=h.implementations.map(Q1),w=b[0],g=b.find(v=>"reason"in v),y=b.flatMap(v=>v.claims);g&&"reason"in g?l.push({id:h.id,path:m.path,reason:g.reason,claims:y}):b.some(v=>JSON.stringify(v)!==JSON.stringify(w))?l.push({id:h.id,path:m.path,reason:"Its Person implementations project different values.",claims:y}):"name"in w&&p.push({id:h.id,path:m.path,name:w.name,identities:w.identities,typeNames:[...new Set(h.implementations.map(v=>v.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 Bn();a.add(u.cursor),i=u.cursor}let c=(d,u)=>d.path<u.path?-1:d.path>u.path?1:0;return{people:p.sort(c),invalid:l.sort(c),session:t}}}});function Jl(n){return typeof n=="string"&&nR.test(n)&&Number.isFinite(Date.parse(n))}function Xl(n){if(typeof n!="string"||!eR.test(n))throw pi()}function $0(n){if(typeof n!="string"||!ru.test(n))throw pi()}function Yy(n){if(typeof n!="string"||!n.length||n.length>100)throw pi()}function Jy(n){if(!n||Object.keys(n).some(e=>e!=="id"&&e!=="fireAt")||($0(n.id),!Jl(n.fireAt)))throw pi();return{id:n.id,fire_at:new Date(n.fireAt).toISOString()}}function ar(n){if(!n||typeof n!="object"||Array.isArray(n))throw Xt();return n}function z0(n){let e=ar(n);if(typeof e.id!="string"||!ru.test(e.id)||typeof e.criterion_id!="string"||!e.criterion_id.length||e.criterion_id.length>100||!Jl(e.fire_at)||!Number.isSafeInteger(e.generation)||e.generation<1||!["scheduled","firing","fired","cancelled"].includes(e.status)||!Jl(e.created_at)||!Jl(e.updated_at)||e.fired_at!==null&&!Jl(e.fired_at))throw Xt();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 Xy(n,e){let t=ar(n);if(t.namespace!==e||!Array.isArray(t.timers)||t.timers.length>Zl)throw Xt();let i=t.timers.map(z0);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 Xt();return{namespace:e,timers:i,...t.intent_revision===void 0?{}:{intentRevision:t.intent_revision}}}function U0(n){let{namespace:e,operationId:t,expectedRevision:i}=n;if(Xl(e),typeof t!="string"||!tR.test(t)||!Number.isSafeInteger(i)||i<0||i===Number.MAX_SAFE_INTEGER)throw pi();return{namespace:e,operationId:t,expectedRevision:i}}function iR(n,e){let t=ar(n),i=Xy(t,e);if(!Array.isArray(t.cancelled_ids)||t.cancelled_ids.length>Zl||t.cancelled_ids.some(o=>typeof o!="string"||!ru.test(o))||new Set(t.cancelled_ids).size!==t.cancelled_ids.length)throw Xt();return{...i,cancelledIds:[...t.cancelled_ids]}}function D0(n,e){let t=ar(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 Xt();let i=ar(t.result);if(Object.keys(i).some(r=>!["namespace","timers","cancelled_ids"].includes(r)))throw Xt();let o=iR(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(ar(r)).some(a=>!s.includes(a)))throw Xt();if(o.cancelledIds.some(r=>o.timers.some(a=>a.id===r)))throw Xt();return{protocolVersion:1,...e,committedRevision:t.committed_revision,result:o}}async function rR(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 eR,ru,tR,nR,Zl,pi,Xt,Ns,Zy=I(()=>{"use strict";ie();eR=/^[A-Za-z0-9._-]{1,64}$/,ru=/^[A-Za-z0-9._:-]{1,128}$/,tR=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,nR=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/i,Zl=1e4,pi=()=>A("invalid_request","Invalid opaque timer request."),Xt=()=>A("internal","Invalid control-plane timer response.","invalid_timer_response");Ns=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&&oe(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 Xl(e),this.run(t,!1,async i=>Xy(await this.port.list(e,i),e))}put(e,t={}){Xl(e.namespace),Yy(e.criterionId);let i=Jy(e.timer),o=e.namespace,s=e.criterionId;return this.run(t,!0,async r=>{let a=z0(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 Xt();return a})}cancel(e,t={}){if(Xl(e.namespace),$0(e.id),e.generation!==void 0&&(!Number.isSafeInteger(e.generation)||e.generation<1))throw pi();let{namespace:i,id:o,generation:s}=e;return this.run(t,!0,async r=>{let a=ar(await this.port.cancel(i,o,s,r));if(a.namespace!==i||a.id!==o||typeof a.cancelled!="boolean")throw Xt();return{namespace:i,id:o,cancelled:a.cancelled}})}reconcile(e,t={}){if(Xl(e.namespace),Yy(e.criterionId),!Array.isArray(e.timers)||e.timers.length>Zl)throw pi();let i=e.timers.map(Jy),o=new Map(i.map(a=>[a.id,a.fire_at]));if(o.size!==i.length)throw pi();let s=e.namespace,r=e.criterionId;return this.run(t,!0,async a=>{let p=ar(await this.port.reconcile(s,{criterion_id:r,timers:i},a)),l=Xy(p,s);if(l.timers.length!==i.length||l.timers.some(c=>!o.has(c.id)||c.criterionId!==r||Date.parse(c.fireAt)!==Date.parse(o.get(c.id)))||!Array.isArray(p.cancelled_ids)||p.cancelled_ids.length>Zl||p.cancelled_ids.some(c=>typeof c!="string"||!ru.test(c)||o.has(c))||new Set(p.cancelled_ids).size!==p.cancelled_ids.length)throw Xt();return{...l,cancelledIds:p.cancelled_ids}})}reconcileWithReceipt(e,t={}){let i=U0(e),o=e.criterionId;if(Yy(o),!Array.isArray(e.timers)||e.timers.length>Zl)throw pi();let s=e.timers.map(Jy),r=new Map(s.map(l=>[l.id,l.fire_at]));if(r.size!==s.length)throw pi();let a=this.port.reconcileWithReceipt;if(!a)throw A("upgrade_required","Timer port does not support original-operation recovery.","timer_operation_recovery_unavailable");let p={protocol_version:1,operation_id:i.operationId,expected_revision:i.expectedRevision};return this.run(t,!0,async l=>{let c=D0(await a.call(this.port,i.namespace,{criterion_id:o,timers:s,recovery:p},l),i);if(c.result.timers.length!==s.length||c.result.timers.some(d=>d.criterionId!==o||!r.has(d.id)||Date.parse(d.fireAt)!==Date.parse(r.get(d.id))))throw Xt();return c})}lookupOperation(e,t={}){let i=U0(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=ar(await o.call(this.port,i.namespace,i.operationId,s));if(r.outcome==="committed"&&Object.keys(r).length===2)return{outcome:"committed",receipt:D0(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 Xt()}).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 rR(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 Ds(n,e={}){return{description:"in-process",open(t,i){return new Promise((o,s)=>{let r;try{r=n.connect(e)}catch(p){s(A("unavailable",`runtime refused to connect: ${String(p)}`));return}let a=()=>{r.close(),s(A("cancelled","connect aborted"))};i?.addEventListener("abort",a,{once:!0}),r.onframe=p=>{i?.removeEventListener("abort",a),r.onframe=null,r.onclose=null,o({port:r,helloResponse:p})},r.onclose=p=>{i?.removeEventListener("abort",a),s(p??A("unavailable","runtime closed the session"))},r.send(t)})}}}var su=I(()=>{"use strict";ie()});function Mo(n){try{n instanceof Map&&(n={code:n.get("code"),paths:n.get("paths")});let e=lu(n),t=lu(e?.error)??e,i=t?.code;if(typeof i!="string"||!uR.test(i))return null;let o=lu(t.details)?.issues,s=Array.isArray(t.paths)?t.paths:Array.isArray(o)?o.slice(0,64).map(a=>lu(a)?.path):[],r=[];for(let a of s.slice(0,64))if(typeof a=="string"&&fR.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 Q0(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 uR,fR,lu,cu=I(()=>{"use strict";uR=/^[a-z][a-z0-9_]{0,63}$/,fR=/^(?:\/[A-Za-z0-9_-]{1,64}){1,6}$/,lu=n=>n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null});var ek,tk=I(()=>{"use strict";ek="Your account has reached its synced collection limit. Open an existing collection, delete one you own if Delete is available, or contact mdbase support to raise your limit."});function kn(n){return typeof n=="object"&&n!==null&&og.has(n)}function gR(n,e){let t=n?.retry_after_ms,i=n?.retry_after_seconds;if(typeof t=="number"&&Number.isFinite(t)&&t>=0)return pu(t);if(typeof i=="number"&&Number.isFinite(i)&&i>=0)return pu(i*1e3);let o=e?.get("retry-after")?.trim();return o&&/^[0-9]{1,6}$/.test(o)?pu(Number(o)*1e3):null}function du(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 Ur(n,e=null){try{if(kn(n))return n;if(typeof n!="object"||n===null||Array.isArray(n)||Object.getPrototypeOf(n)!==Object.prototype||Object.keys(n).sort().join(",")!==bR)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&&zs(t.code)===null||t.reason!==null&&zs(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:zs(t.code),reason:zs(t.reason),retryAfterMs:o===null?null:pu(o),updateUrl:du(t.updateUrl,e)});return og.add(s),s}catch{return null}}function Li(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:zs(s?.code),reason:zs(r?.reason),retryAfterMs:gR(r,t),updateUrl:du(r?.update_url,i)});return og.add(a),a}function St(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":e.some(t=>t==="moved_to_next_runtime"||t==="collection_moved"||t==="client_update_required")||n.status===426?"update_required":null}function Vs(n){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{return}}var hR,og,Bs,Fs,mR,yR,nk,zs,pu,bR,Fn=I(()=>{"use strict";hR=/^[a-z][a-z0-9_]{0,63}$/,og=new WeakSet;Bs=5e3,Fs=6e5,mR=Bs,yR=Fs,nk="https://mdbase.dev/downloads/",zs=n=>typeof n=="string"&&hR.test(n)?n:null,pu=n=>Math.min(yR,Math.max(mR,Math.round(n)));bR="code,reason,retryAfterMs,status,updateUrl"});function sg(n){if(typeof n!="string")return null;if(ok(n))return n;if(Object.hasOwn(uu,n))return uu[n];for(let e of["readiness_","application_"]){if(!n.startsWith(e))continue;let t=n.slice(e.length);if(e==="readiness_"&&Object.hasOwn(rk,t))return rk[t];if(ok(t))return t;if(Object.hasOwn(uu,t))return uu[t]}return null}function OR(n){let e=n.details;if(e instanceof Map&&Ls(e.get("availability")))return e.get("availability");let t=Vn(n.availability)??(n.state==="unavailable"?n:null);return t&&t.state==="unavailable"&&Ls(t.reason)?t.reason:null}function ag(n,e){let t=lr(n);if(t)return{codes:[t],retryAfterMs:null,updateUrl:null};let i=Vn(n);if(!i)return null;try{if(typeof i.kind=="string"&&"problem"in i&&Vn(i.problem)&&typeof Vn(i.problem).code=="string")return ag(Vn(i.problem).code,e);let o=Vn(i.problemDetail),s=Ur(i.server??o?.server,e),r=[s?.reason??null,s?.code??null].filter(c=>c!==null),a={retryAfterMs:s?.retryAfterMs??IR(i.retryAfterMs),updateUrl:du(s?.updateUrl,e),hasServer:i.server!=null||o?.server!=null};if("problem"in i||"readiness"in i||"assessment"in i){let c=lr(i.problem)??lr(Vn(i.problem)?.code);if(c)return{codes:[...r,c],...a,refusal:Mo(o?.registration)};let d=Vn(i.readiness)??i,u=Vn(d.assessment),f=lr(Vn(d.problem)?.code)??lr(Vn(u?.problem)?.code);if(f)return{codes:[f],...a};let h=lr(u?.status)??lr(i.status);return h==="incompatible"||h==="setup_required"?{codes:[h],...a}:null}let p=OR(i);if(p)return{codes:[p==="approval_required"?"device_approval_required":p],...a};if("state"in i&&(i.state==="available"||i.state==="opening"))return null;let l=[...r,lr(i.reason),lr(i.code)].filter(c=>c!==null);return l.length?{codes:l,...a,refusal:Mo(i.details??o?.registration)}:null}catch{return null}}function pk(n){let e=n.codes[n.codes.length-1];try{for(let t of n.codes){if(ck.has(t))return{key:null,original:e};let i=sg(t);if(i)return{key:i,original:e}}}catch{}return{key:"unknown",original:e}}function Lo(n,e={}){let t=typeof e.cpOrigin=="string"?e.cpOrigin:null,i=ag(n,t);if(!i)return null;let{key:o,original:s}=pk(i);if(o===null)return null;let[r,a,p,l,c=!1,d]=o==="unknown"?ak:o==="refused"&&!i.hasServer?PR:lk[o],u;try{let w=e.messages;u=w&&Object.hasOwn(w,o)?Vn(w[o]):void 0}catch{u=void 0}let f=(w,g)=>typeof w=="string"&&w.trim()?w:g,h=typeof e.recoveryAccountLabel=="string"&&e.recoveryAccountLabel.trim().length>0&&e.recoveryAccountLabel.length<=320&&!Array.from(e.recoveryAccountLabel).some(w=>w.charCodeAt(0)<32||w.charCodeAt(0)===127)?e.recoveryAccountLabel:null,m=o==="recovery_account_mismatch"&&h?`This collection belongs to ${h}. Sign in as ${h} to continue.`:a,b=o==="recovery_account_mismatch"&&h?`Sign in as ${h}`:d??wR[p];return Object.freeze({key:o,title:f(u?.title,r),message:f(u?.message,m),action:p,actionLabel:b===null?null:f(u?.actionLabel,b),severity:l,transient:c,code:s,developerMessage:dk(o,s,i.refusal??null),retryAfterMs:i.retryAfterMs,updateUrl:p==="update_app"?i.updateUrl??nk:null})}function dk(n,e,t){return n==="application_registration_refused"?Q0(t):Object.hasOwn(fu,n)?fu[n]:n==="unknown"?`Problem code ${e} has no user-facing copy; it is shown as a generic error.`:null}function hu(n,e={}){let t=ag(n,typeof e.cpOrigin=="string"?e.cpOrigin:null);if(!t)return null;for(let s of t.codes)if(Object.hasOwn(fu,s)&&ck.has(s))return fu[s];let{key:i,original:o}=pk(t);return i===null?null:dk(i,o,t.refusal??null)}var wR,sk,ak,vR,_R,AR,kR,ik,SR,PR,lk,uu,rk,xR,ck,fu,CR,lr,Vn,IR,ok,nc=I(()=>{"use strict";cu();tk();Lr();Fn();wR={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},sk=["device_offline","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","open_failed","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","configuration_conflict","configuration_unavailable","configuration_unsupported","configuration_busy_timeout","readiness_busy_timeout","setup_forbidden","setup_conflict","setup_unresolved","collection_setup_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"],ak=["Something went wrong","An unexpected problem occurred. Reload the app, and contact support if it keeps happening.","reload","error"],vR=["Another step hasn't finished","The app couldn't finish this step yet. Try again, or reload if it keeps happening.","retry","warning",!0],_R=["Can't connect right now","mdbase couldn't be reached. Check your connection and try again.","check_connection","warning"],AR=["Update required","Update mdbase on this computer, then reload the app to try again.","update_app","warning",!1,"Update mdbase"],kR=["Choose a collection","Pick the collection you want this app to use.","choose_collection","info"],ik=["Approval needed","This app needs your approval for extra access to your collection.","approve","info"],SR=["Set up this collection","This collection needs a one-time setup before the app can use it.","set_up","info"],PR=["Sign-in wasn't finished","Access wasn't approved. Sign in again when you're ready.","sign_in","info"],lk={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],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. Your other collections keep their access.","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:AR,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:_R,rate_limited:["Too many requests","Wait a moment, then try again.","retry","warning",!0],quota_exceeded:["Out of storage","You've reached your storage limit. Free up space to keep saving.","free_space","error"],account_collection_quota_exceeded:["Synced collection limit reached",ek,"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:ak,refused:["Sign-in didn't go through","mdbase didn't accept this sign-in. Try signing in again.","sign_in","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"],busy:vR,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:kR,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:SR,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:ik,capability_missing:ik,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"],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 something this app needs, and setup can't add it. A note type this app set up may have been changed or removed. Restore it, then try again.","retry","warning"],collection_setup_conflict:["Collection setup conflicts","This collection's definitions conflict with what this app requires. Ask its owner to review them, or choose a different collection. Setup cannot continue while these conflicts remain.","choose_collection","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"]},uu=Object.assign(Object.create(null),{no_device_online:"device_offline",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",change_entity_unsupported:"update_required",timer_operation_recovery_unavailable:"update_required",contract_query_version:"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",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"}),rk=Object.assign(Object.create(null),{budget:"readiness_budget",unsupported:"readiness_unsupported"}),xR=["application_registration_id_superseded","application_closing","cancelled","aborted"],ck=new Set(xR),fu=Object.assign(Object.create(null),{device_offline:"Collection availability device_offline: no device serving this Private collection is connected to the relay.",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.",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 (snapshot.saveWarning); only a log-confirmed receipt counts as saved.",sign_out_pending_writes:"sign_out_pending_writes: unconfirmed writes are still queued on this device; signOut({discard: true}) discards them."}),CR=/^[a-z][a-z0-9_-]{0,127}$/,lr=n=>typeof n=="string"&&CR.test(n)?n:null,Vn=n=>n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null,IR=n=>typeof n=="number"&&Number.isFinite(n)&&n>=0?Math.min(Fs,Math.max(Bs,Math.round(n))):null,ok=n=>Object.hasOwn(lk,n)});function Ks(n){if(typeof n!="string"||n.length>256)return null;let e=RR.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 lg(n,e){let t=typeof n=="string"?Ks(n):n,i=typeof e=="string"?Ks(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 jo(n,e){let t=Ks(n),i=Ks(e),o=t&&i?lg(t,i):null;return o===null?"unknown":o===0?"same":o<0?"installed_older":t.major===i.major?"installed_newer":"installed_newer_major"}var mu,uk,RR,yu=I(()=>{"use strict";mu="0|[1-9]\\d*",uk=`(?:${mu}|\\d*[a-zA-Z-][0-9a-zA-Z-]*)`,RR=new RegExp(`^v?(${mu})\\.(${mu})\\.(${mu})(?:-(${uk}(?:\\.${uk})*))?(?:\\+[0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*)?$`)});function wu(n){return n.storage.applicationNamespace===n.id?null:n.storage.applicationNamespace}function cg(n){return Array.from(it(new TextEncoder().encode(n)),e=>e.toString(16).padStart(2,"0")).join("")}function mk(n,e){return e===null?`bundle:${n}`:`bundle-storage:${cg(JSON.stringify([n,e]))}`}var vu=I(()=>{"use strict";Cr()});function Ne(n){if(n&&typeof n=="object")switch(n[Zt]){case di:case cr:return!0}return!1}function Re(n){if(n&&typeof n=="object")switch(n[Zt]){case _u:case di:case Sn:case cr:return!0}return!1}var _u,Au,di,pg,Sn,cr,Zt,ui,ji,Pn,xe,ve,fi,ku,Te=I(()=>{_u=Symbol.for("yaml.alias"),Au=Symbol.for("yaml.document"),di=Symbol.for("yaml.map"),pg=Symbol.for("yaml.pair"),Sn=Symbol.for("yaml.scalar"),cr=Symbol.for("yaml.seq"),Zt=Symbol.for("yaml.node.type"),ui=n=>!!n&&typeof n=="object"&&n[Zt]===_u,ji=n=>!!n&&typeof n=="object"&&n[Zt]===Au,Pn=n=>!!n&&typeof n=="object"&&n[Zt]===di,xe=n=>!!n&&typeof n=="object"&&n[Zt]===pg,ve=n=>!!n&&typeof n=="object"&&n[Zt]===Sn,fi=n=>!!n&&typeof n=="object"&&n[Zt]===cr;ku=n=>(ve(n)||Ne(n))&&!!n.anchor});function Ui(n,e){let t=gk(e);ji(n)?Hs(null,n.contents,t,Object.freeze([n]))===Ni&&(n.contents=null):Hs(null,n,t,Object.freeze([]))}function Hs(n,e,t,i){let o=bk(n,e,t,i);if(Re(o)||xe(o))return wk(n,i,o),Hs(n,o,t,i);if(typeof o!="symbol"){if(Ne(e)){i=Object.freeze(i.concat(e));for(let s=0;s<e.items.length;++s){let r=Hs(s,e.items[s],t,i);if(typeof r=="number")s=r-1;else{if(r===fn)return fn;r===Ni&&(e.items.splice(s,1),s-=1)}}}else if(xe(e)){i=Object.freeze(i.concat(e));let s=Hs("key",e.key,t,i);if(s===fn)return fn;s===Ni&&(e.key=null);let r=Hs("value",e.value,t,i);if(r===fn)return fn;r===Ni&&(e.value=null)}}return o}async function Su(n,e){let t=gk(e);ji(n)?await Gs(null,n.contents,t,Object.freeze([n]))===Ni&&(n.contents=null):await Gs(null,n,t,Object.freeze([]))}async function Gs(n,e,t,i){let o=await bk(n,e,t,i);if(Re(o)||xe(o))return wk(n,i,o),Gs(n,o,t,i);if(typeof o!="symbol"){if(Ne(e)){i=Object.freeze(i.concat(e));for(let s=0;s<e.items.length;++s){let r=await Gs(s,e.items[s],t,i);if(typeof r=="number")s=r-1;else{if(r===fn)return fn;r===Ni&&(e.items.splice(s,1),s-=1)}}}else if(xe(e)){i=Object.freeze(i.concat(e));let s=await Gs("key",e.key,t,i);if(s===fn)return fn;s===Ni&&(e.key=null);let r=await Gs("value",e.value,t,i);if(r===fn)return fn;r===Ni&&(e.value=null)}}return o}function gk(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 bk(n,e,t,i){if(typeof t=="function")return t(n,e,i);if(Pn(e))return t.Map?.(n,e,i);if(fi(e))return t.Seq?.(n,e,i);if(xe(e))return t.Pair?.(n,e,i);if(ve(e))return t.Scalar?.(n,e,i);if(ui(e))return t.Alias?.(n,e,i)}function wk(n,e,t){let i=e[e.length-1];if(Ne(i))i.items[n]=t;else if(xe(i))n==="key"?i.key=t:i.value=t;else if(ji(i))i.contents=t;else{let o=ui(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var fn,yk,Ni,rc=I(()=>{Te();fn=Symbol("break visit"),yk=Symbol("skip children"),Ni=Symbol("remove node");Ui.BREAK=fn;Ui.SKIP=yk;Ui.REMOVE=Ni;Su.BREAK=fn;Su.SKIP=yk;Su.REMOVE=Ni});var TR,MR,Di,dg=I(()=>{Te();rc();TR={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},MR=n=>n.replace(/[!,[\]{}]/g,e=>TR[e]),Di=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+MR(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&&Re(e.contents)){let s={};Ui(e.contents,(r,a)=>{Re(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 Qh=Object.defineProperty;var MI=Object.getOwnPropertyDescriptor;var LI=Object.getOwnPropertyNames;var jI=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 ls=(n,e)=>{for(var t in e)Qh(n,t,{get:e[t],enumerable:!0})},NI=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of LI(e))!jI.call(n,o)&&o!==t&&Qh(n,o,{get:()=>e[o],enumerable:!(i=MI(e,o))||i.enumerable});return n};var UI=n=>NI(Qh({},"__esModule",{value:!0}),n);function FI(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 nv(n,e){let t=typeof e=="bigint"?e:BigInt(e);if(t>=0n){if(t>DI)throw new Ie("unencodable","integer above 2^64-1");n.head(0,typeof e=="number"?e:t)}else{if(t<$I)throw new Ie("unencodable","integer below -2^63");let i=-1n-t;n.head(1,i<=BigInt(Number.MAX_SAFE_INTEGER)?Number(i):i)}}function VI(n,e,t){let i=[...e.entries()];rv(i.map(([o])=>o)),n.head(5,i.length);for(let[o,s]of i)typeof o=="number"?n.head(0,o):iv(n,o),vp(n,s,t+1)}function iv(n,e){if(!FI(e))throw new Ie("utf8","text is not well-formed UTF-16");let t=zI.encode(e);try{n.head(3,t.length),n.bytes(t)}finally{n.wipeTemporary(t)}}function rv(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 Ie("mixed_map_keys");if(t.has(i))throw new Ie("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 Ie("mixed_map_keys");if(typeof t=="number"&&!(Number.isSafeInteger(t)&&t>=0))throw new Ie("mixed_map_keys","struct map keys must be unsigned integers");let i=BigInt(t);if(i<0n)throw new Ie("mixed_map_keys");if(e!==void 0&&e>=i)throw new Ie("unsorted_keys");e=i}}function vp(n,e,t){if(t>tm)throw new Ie("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)?nv(n,e):n.float(e);case"bigint":return nv(n,e);case"string":return iv(n,e)}if(e instanceof yt)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)vp(n,i,t+1);return}if(e instanceof Map)return VI(n,e,t);throw new Ie("unencodable",`cannot encode ${Object.prototype.toString.call(e)}`)}function pe(n){let e=new wp;return vp(e,n,0),e.result()}function qn(n){let e=new wp(!0);try{return vp(e,n,0),e.result()}finally{e.buf.fill(0)}}function ue(n){let e=new em(n),t=e.item(0);if(e.remaining!==0)throw new Ie("trailing_bytes");return t}function KI(n){try{return ue(n),!0}catch{return!1}}function WI(n){let e=new Map;for(let[t,i]of n)i!==void 0&&e.set(t,i);return e}function ri(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return e}function cs(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 HI(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 yt,tm,Ie,DI,$I,zI,BI,wp,em,Je=I(()=>{"use strict";yt=class{constructor(e){this.value=e}value;valueOf(){return this.value}toJSON(){return this.value}},tm=128,Ie=class extends Error{constructor(t,i){super(i??t);this.kind=t;this.name="CborError"}kind},DI=(1n<<64n)-1n,$I=-(1n<<63n),zI=new TextEncoder,BI=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),wp=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}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 Ie("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)}};em=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 Ie("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 Ie("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 Ie("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 Ie("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 Ie("non_canonical_head");return t<=BigInt(Number.MAX_SAFE_INTEGER)?Number(t):t}case 31:throw new Ie("indefinite");default:throw new Ie("non_canonical_head","reserved additional info")}}len(e){let t=this.arg(e);if(typeof t=="bigint")throw new Ie("too_long");if(t>this.remaining)throw new Ie("unexpected_end");return t}item(e){if(e>tm)throw new Ie("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 BI.decode(s)}catch{throw new Ie("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 c=this.item(e+1);if(typeof c!="string"&&typeof c!="number"&&typeof c!="bigint")throw new Ie("mixed_map_keys");if((typeof c=="number"||typeof c=="bigint")&&c<0)throw new Ie("mixed_map_keys");r.push(c),a.push(this.item(e+1))}rv(r);let p=new Map;for(let l=0;l<s;l++){let c=r[l];if(typeof c=="bigint")throw new Ie("too_long","struct key beyond 2^53");p.set(c,a[l])}return p}case 6:throw new Ie("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 Ie("float");return Number.isInteger(s)?new yt(s):s}case 25:case 26:throw new Ie("float","float must be binary64");case 31:throw new Ie("indefinite");default:throw new Ie("simple")}}}}});function GI(n){return n===null?"null":n instanceof Uint8Array?"bytes":n instanceof yt?"float":Array.isArray(n)?"array":n instanceof Map?"map":typeof n=="number"?Number.isInteger(n)?"int":"float":typeof n}function ln(n,e,t){return new ne(n,`expected ${e}, found ${GI(t)}`)}function sv(n,e){return{name:e,enc:t=>{if(!(t instanceof Uint8Array)||t.length!==n)throw new ne(e,`must be ${n} bytes`);return t},dec:t=>{if(!(t instanceof Uint8Array))throw ln(e,"bytes",t);if(t.length!==n)throw new ne(e,`must be ${n} bytes`);return t}}}function U(n){if(!YI.test(n))throw new ne("uuid",`not a UUID: ${n}`);return cs(n.replace(/-/g,""))}function yl(n){let e=ri(n);return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20,32)}`}function Ap(n){let e=/^sha256:([0-9a-f]{64})$/.exec(n);if(!e)throw new ne("hash",`not a sha256: revision token: ${n}`);return cs(e[1])}function nm(n){return`sha256:${ri(n)}`}function _p(n,e=0){if(e>128)throw new ne("value","nesting too deep");if(n instanceof Uint8Array)throw new ne("value","byte strings are not values");if(typeof n=="bigint"){if(n>0x7fffffffffffffffn||n<-0x8000000000000000n)throw new ne("value","integer outside int64");return}if(Array.isArray(n))for(let t of n)_p(t,e+1);else if(n instanceof Map)for(let[t,i]of n){if(typeof t!="string")throw new ne("value","map keys must be text");_p(i,e+1)}}function F(n,e={}){let t=`[${n.name}]`;return{name:t,enc:i=>{if(e.nonEmpty&&i.length===0)throw new ne(t,"list must not be empty");return i.map(o=>n.enc(o))},dec:i=>{if(!Array.isArray(i))throw ln(t,"array",i);if(e.nonEmpty&&i.length===0)throw new ne(t,"list must not be empty");return i.map(o=>n.dec(o))}}}function gl(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 ln(e,"map",t);let i=new Map;for(let[o,s]of t){if(typeof o!="string")throw new ne(e,"data map keys must be text");i.set(o,n.dec(s))}return i}}}function Sp(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 Pe(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 ne(n,`unknown value ${JSON.stringify(o)}`);return s},dec:o=>{if(typeof o=="bigint")throw new ne(n,`unknown variant ${o}`,!0);if(typeof o!="number"||!Number.isInteger(o)||o<0)throw ln(n,"uint enum",o);let s=o>=t?e[o-t]:void 0;if(s===void 0)throw new ne(n,`unknown variant ${o}`,!0);return s}}}function N(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,p="req"]of e){let l=o[r];if(l===void 0){if(p==="req"||p==="req1")throw new ne(n,`missing required field ${r}`);continue}if((p==="req1"||p==="opt1")&&Array.isArray(l)&&l.length===0)throw new ne(n,`${r} must not be empty`);i.set(s,a.enc(l))}return i},dec:t=>{if(!(t instanceof Map))throw ln(n,"struct map",t);let i=t;for(let s of i.keys())if(typeof s!="number")throw ln(n,"struct map",t);let o={};for(let[s,r,a,p="req"]of e){let l=i.get(s);if(l===void 0){if(p==="req"||p==="req1")throw new ne(n,`missing required key ${s} (${r})`);continue}let c=a.dec(l);if((p==="req1"||p==="opt1")&&Array.isArray(c)&&c.length===0)throw new ne(n,`${r} must not be empty`);o[r]=c}return o}}}function bl(n,e){let t=new Map,i=new Map;for(let[o,s,r]of e){let a=N(`${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 ne(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 ln(n,"struct map",o);let s=o.get(0);if(s===void 0)throw new ne(n,"missing discriminator");if(typeof s=="bigint")throw new ne(n,`unknown variant ${s}`,!0);if(typeof s!="number")throw ln(n,"uint discriminator",s);let r=t.get(s);if(!r)throw new ne(n,`unknown variant ${s}`,!0);return{kind:r[0],...r[1].dec(o)}}}}function av(n,e,t,i){return{name:n,enc:o=>e.enc(i(o)),dec:o=>t(e.dec(o))}}function im(n,e){return{name:n,enc:t=>e.map((i,o)=>i.enc(t[o])),dec:t=>{if(!Array.isArray(t))throw ln(n,"array",t);if(t.length!==e.length)throw new ne(n,"wrong number of elements");return e.map((i,o)=>i.dec(t[o]))}}}var ne,B,Tn,R,Oe,ov,uo,Ii,YI,T,H,kp,at,ge=I(()=>{"use strict";Je();ne=class extends Error{constructor(t,i,o=!1){super(`${t}: ${i}`);this.ty=t;this.unknown=o;this.name="SchemaError"}ty;unknown};B={name:"uint",enc:n=>{if(!Number.isSafeInteger(n)||n<0)throw new ne("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 ne("uint","value beyond 2^53 is not supported here"):ln("uint","uint",n)}},Tn={name:"int",enc:n=>{if(!Number.isSafeInteger(n))throw new ne("int",`not an integer: ${n}`);return n},dec:n=>{if(typeof n=="number"&&Number.isInteger(n))return n;throw ln("int","int",n)}},R={name:"tstr",enc:n=>{if(typeof n!="string")throw new ne("tstr","not a string");return n},dec:n=>{if(typeof n=="string")return n;throw ln("tstr","text",n)}},Oe={name:"bool",enc:n=>n,dec:n=>{if(typeof n=="boolean")return n;throw ln("bool","bool",n)}},ov={name:"bstr",enc:n=>n,dec:n=>{if(n instanceof Uint8Array)return n;throw ln("bstr","bytes",n)}};uo=sv(16,"b16"),Ii=sv(32,"b32"),YI=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;T={name:"uuid",enc:n=>U(n),dec:n=>yl(uo.dec(n))};H={name:"hash",enc:n=>Ap(n),dec:n=>nm(Ii.dec(n))},kp={name:"any",enc:n=>n,dec:n=>n},at={name:"value",enc:n=>(_p(n),n),dec:n=>(_p(n),n)}});function Sr(n){return Object.prototype.hasOwnProperty.call(Pp,n)}function JI(n){return Sr(n)?Pp[n]:"contact_support"}function A(n,e,t={}){let i=typeof t=="string"?{reason:t}:t;return new se({code:n,recovery:Pp[n],message:e,...i})}function oe(n,e){return n instanceof se&&(e===void 0||n.code===e)}var Pp,se,ie=I(()=>{"use strict";Pp={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"};se=class extends Error{code;recovery;reason;details;retryAfterMs;issues;traceId;mutationId;mutationIds;constructor(e,t={}){super(e.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="MdbaseError",this.code=Sr(e.code)?e.code:"internal",this.recovery=Sr(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);let i=t.mutationIds?Object.freeze([...t.mutationIds]):void 0,o=t.mutationId??i?.[0];o!==void 0&&(this.mutationId=o),i!==void 0&&(this.mutationIds=i)}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 pv(n,e,t){if(!Array.isArray(n)||n.length!==e)throw new ne(t,`must have exactly ${e} elements`);if(B.dec(n[0])!==1)throw new ne(t,"unknown version",!0);return n}var xp,lv,cv,Pr,rm=I(()=>{"use strict";ge();xp={name:"attachment-uint64",enc:n=>{if(typeof n=="number")return B.enc(n);if(typeof n!="bigint"||n<0n||n>0xffffffffffffffffn)throw new ne("attachment-uint64","outside uint64");return n},dec:n=>{if(typeof n=="number")return B.dec(n);if(typeof n!="bigint"||n<0n||n>0xffffffffffffffffn)throw new ne("attachment-uint64","outside uint64");return n<=BigInt(Number.MAX_SAFE_INTEGER)?Number(n):n}},lv=8388608;cv={name:"attachment-ref-v1",enc:n=>[1,T.enc(n.collection),xp.enc(n.keyEpoch),Ii.enc(n.attachmentId),lv,H.enc(n.manifestCipherHash)],dec:n=>{let e=pv(n,6,"attachment-ref-v1");if(B.dec(e[4])!==lv)throw new ne("attachment-ref-v1","unknown chunk profile",!0);return{collection:T.dec(e[1]),keyEpoch:xp.dec(e[2]),attachmentId:Ii.dec(e[3]),manifestCipherHash:H.dec(e[5])}}},Pr={name:"attachment-content-v1",enc:n=>[1,cv.enc(n.reference),H.enc(n.wholePlainHash),xp.enc(n.totalPlainBytes)],dec:n=>{let e=pv(n,4,"attachment-content-v1");return{reference:cv.dec(e[1]),wholePlainHash:H.dec(e[2]),totalPlainBytes:xp.dec(e[3])}}}});function dv(n){return n.content.form==="blob"?n.content.blob.size:n.content.content.totalPlainBytes}function XI(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 hv(n,e){return{name:n,enc:t=>e().enc(t),dec:t=>e().dec(t)}}var Ip,Cp,uv,fv,Op,vM,mv=I(()=>{"use strict";ge();At();rm();Ip={name:"file-content",enc:n=>n.form==="blob"?Xi.enc(n.blob):Pr.enc(n.content),dec:n=>Array.isArray(n)?{form:"attachment",content:Pr.dec(n)}:{form:"blob",blob:Xi.dec(n)}};Cp={name:"unindexed-markdown-payload-v1",enc:n=>{if(dv(n)<=1048576)throw new ne("unindexed-markdown-payload-v1","declared size must exceed record cap");return[2,1,1,Ip.enc(n.content)]},dec:n=>{let e="unindexed-markdown-payload-v1";if(!Array.isArray(n)||n.length!==4)throw new ne(e,"must have exactly four elements");if(B.dec(n[0])!==2||B.dec(n[1])!==1||B.dec(n[2])!==1)throw new ne(e,"unknown discriminator/profile/kind",!0);let t={content:Ip.dec(n[3])};if(dv(t)<=1048576)throw new ne(e,"declared size must exceed record cap");return t}},uv=Sp("text",R,n=>typeof n=="string",n=>typeof n=="string",B),fv=bl("extended-runtime-op",[[13,"file_attach",[[1,"id",T],[2,"path",R],[3,"content",Pr],[4,"ifRevision",H,"opt"],[5,"base",H,"opt"]]],[14,"unindexed_markdown_put",[[1,"id",T],[2,"path",R],[3,"payload",Cp],[4,"expected",Cp,"opt"]]],[15,"record_to_unindexed_markdown",[[1,"id",T],[2,"path",R],[3,"payload",Cp],[4,"priorRevision",H]]],[16,"unindexed_markdown_to_record",[[1,"id",T],[2,"path",R],[3,"doc",uv],[4,"prior",Cp]]],[18,"ordinary_attachment_continuation",[[1,"id",T],[2,"path",R],[3,"content",Pr],[4,"prior",Ip]]],[17,"ordinary_file_to_record",[[1,"id",T],[2,"path",R],[3,"doc",uv],[4,"prior",Ip]]]]);Op={name:"runtime-v1-op",enc:n=>XI(n)?fv.enc(n):ps.enc(n),dec:n=>{let e=n instanceof Map?B.dec(n.get(0)):void 0;return e!==void 0&&e>=13&&e<=18?fv.dec(n):ps.dec(n)}};vM=N("runtime-v1-mutation",[[0,"id",T],[1,"origin",T],[2,"baseSeq",B],[3,"clock",hv("op-clock",()=>fo)],[4,"seed",Ii],[5,"source",Pe("source",["api","external"])],[6,"ops",F(Op,{nonEmpty:!0}),"req1"],[7,"onBehalf",T,"opt"],[8,"conflictMode",hv("conflict-mode",()=>wl),"opt"],[9,"validatedAt",Pe("level",["off","warn","error"]),"opt"],[10,"room",N("room-checkpoint",[[0,"stream",uo],[1,"state",H]]),"opt"]])});var Nm={};ls(Nm,{DESCRIBE_TYPING_MAX_PATHS:()=>Pl,DESCRIBE_TYPING_MAX_TYPES:()=>Sl,HOLD_REASONS:()=>Pv,HOLD_RESOLUTIONS:()=>xv,INCIDENT_KINDS:()=>_v,MEDIA_CLASSES:()=>Ev,PUSH_CODECS:()=>QI,RECOVERY:()=>gv,ROLES:()=>wv,TEMPORAL_HINTS:()=>Vp,TRANSFER_PHASES:()=>jv,appliedPrefix:()=>dm,appliedPrefixParams:()=>pm,authorRef:()=>Tp,b16:()=>uo,b32:()=>Ii,backlinksResult:()=>qm,baseField:()=>Np,blobRef:()=>Xi,bodyEdit:()=>wm,change:()=>Rv,changesResult:()=>us,clientFrame:()=>Qi,confirmedHead:()=>Lp,conflict:()=>Am,conflictEntry:()=>Al,conflictMode:()=>wl,conflictValue:()=>Ep,describeResult:()=>Mm,describeTypingResult:()=>jm,docVersion:()=>sm,executeViewParams:()=>sO,fenceApply:()=>Im,fenceReport:()=>Om,fenceResult:()=>Rm,fileChunk:()=>Up,fileInclusion:()=>vm,fileStreamFailure:()=>Dp,fileView:()=>kl,fmMap:()=>_n,grantInfo:()=>cm,helloParams:()=>lm,helloResult:()=>um,hold:()=>vl,holdReason:()=>fm,holdRef:()=>hm,holdResolution:()=>mm,incident:()=>Av,include:()=>ds,issue:()=>Zi,linkResolution:()=>Iv,linkView:()=>ym,listFilesResult:()=>Sm,listPendingResult:()=>Lm,listResourcesResult:()=>Em,listViewsResult:()=>nO,materialization:()=>zp,mediaClass:()=>fs,mutation:()=>eO,newTypeFile:()=>Tm,op:()=>ps,opClock:()=>fo,openUploadParams:()=>Pm,openUploadResult:()=>xm,peer:()=>Nv,preflight:()=>Tv,presencePush:()=>Bp,problem:()=>An,progress:()=>kv,publishState:()=>qv,queryGroup:()=>bm,queryMetadata:()=>Ov,queryParams:()=>oO,queryResult:()=>_l,queryUpdate:()=>jp,receipt:()=>kt,recordState:()=>Cv,recordView:()=>Mn,recovery:()=>bv,resourceView:()=>Fp,resyncing:()=>Sv,role:()=>vv,severity:()=>Mp,submitParams:()=>_m,submitResult:()=>km,syncStatus:()=>er,target:()=>am,temporalHint:()=>Uv,textOrBlob:()=>Rp,transferProgress:()=>$p,typingEntry:()=>Dv,uploadChunkParams:()=>Cm,version:()=>qp,viewRef:()=>gm,viewSourceDocument:()=>iO});function Lv(n){throw new ne(n,"wrong type")}var qp,gv,bv,Mp,Zi,An,Qi,lm,wv,vv,cm,_v,Av,kv,Sv,Lp,pm,dm,er,um,Xi,Rp,Pv,fm,hm,vl,xv,mm,Cv,Iv,ym,Tp,_n,Mn,ds,gm,bm,Ov,_l,jp,Rv,us,Ev,fs,wl,Np,wm,sm,vm,yv,ps,_m,ZI,Ep,Am,qv,Tv,kt,km,Al,Mv,om,kl,Sm,Pm,xm,Cm,Up,Dp,jv,$p,zp,Nv,Bp,Im,Om,Rm,QI,fo,eO,tO,Fp,Em,qm,nO,iO,Tm,Mm,rO,Lm,am,oO,sO,Vp,Uv,Dv,jm,Sl,Pl,At=I(()=>{"use strict";mv();rm();ge();qp=av("version",im("version",[B,B]),([n,e])=>({major:n,minor:e}),n=>[n.major,n.minor]),gv=["fix_request","refresh","resolve_conflict","reauthorize","repair_collection","retry","free_space","upgrade","resolve_outcome","none","contact_support"],bv=Pe("recovery",gv),Mp=Pe("severity",["warning","error"]),Zi=N("issue",[[0,"code",R],[1,"severity",Mp],[2,"message",R],[3,"details",at,"opt"]]),An=N("problem",[[0,"code",R],[1,"recovery",bv],[2,"message",R],[3,"reason",R,"opt"],[4,"details",at,"opt"],[5,"retryAfterMs",B,"opt"],[6,"issues",F(Zi),"opt"],[7,"traceId",R,"opt"]]),Qi=bl("client-frame",[[0,"request",[[1,"id",B],[2,"method",R],[3,"params",kp]]],[1,"response",[[1,"id",B],[2,"result",kp,"opt"],[3,"problem",An,"opt"]]],[2,"push",[[1,"type",R],[2,"payload",kp]]]]),lm=N("hello-params",[[0,"versions",F(qp,{nonEmpty:!0}),"req1"],[1,"clientName",R],[2,"clientVersion",R],[3,"features",F(R),"opt"],[4,"timezone",R,"opt"]]),wv=["viewer","editor","owner"],vv=Pe("role",wv),cm=N("grant-info",[[0,"grant",T,"opt"],[1,"capabilities",F(R,{nonEmpty:!0}),"req1"],[2,"role",vv],[3,"account",T,"opt"],[4,"fileFolders",F(R),"opt"]]),_v=["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"],Av=N("incident",[[0,"kind",Pe("incident-kind",_v)],[1,"details",at,"opt"]]),kv=N("progress",[[0,"done",B],[1,"total",B]]),Sv=N("resyncing",[[0,"phase",Pe("resync-phase",["probing","repairing","rolling_back","awaiting_control"])],[1,"positions",B]]),Lp=N("confirmed-head",[[0,"seq",B],[1,"chain",H],[2,"policyGeneration",H],[3,"catalogGeneration",H]]),pm=N("applied-prefix-params",[[0,"seq",B]]),dm=N("applied-prefix",[[0,"appliedThrough",B],[1,"seq",B],[2,"chain",H,"opt"]]),er=N("sync-status",[[0,"mode",Pe("sync-mode",["local_only","synced"])],[1,"confirmedThrough",B],[2,"headKnown",B],[3,"pending",B],[4,"oldestPending",Tn,"opt"],[5,"holds",B],[6,"unresolved",B],[7,"connection",Pe("connection",["online","connecting","offline"])],[8,"installing",kv,"opt"],[9,"incidents",F(Av)],[10,"resyncing",Sv,"opt"],[11,"confirmedHead",Lp,"opt"],[12,"grant",cm,"opt"]]),um=N("hello-result",[[0,"version",qp],[1,"runtimeVersion",R],[2,"sem",qp],[3,"collection",T],[4,"grant",cm],[5,"status",er],[6,"features",F(R)],[7,"headWitness",ov,"opt"]]),Xi=N("blob-ref",[[0,"plainHash",H],[1,"size",B],[2,"blobId",Ii],[3,"idEpoch",B],[4,"partSize",B]]),Rp={name:"text-or-blob",enc:n=>{if(typeof n=="string")return R.enc(n);if("form"in n){if(n.form!=="attachment")throw new ne("text-or-blob","unknown arm",!0);return[1,Pr.enc(n.content)]}return Xi.enc(n)},dec:n=>{if(typeof n=="string")return R.dec(n);if(Array.isArray(n)){if(n.length!==2)throw new ne("text-or-blob","attachment arm must have exactly two elements");if(B.dec(n[0])!==1)throw new ne("text-or-blob","unknown attachment arm",!0);return{form:"attachment",content:Pr.dec(n[1])}}return Xi.dec(n)}},Pv=["conflict","unknown_provenance","deleted_elsewhere","read_only","editor_busy","suspect_write"],fm=Pe("hold-reason",Pv),hm=N("hold-ref",[[0,"id",T],[1,"reason",fm]]),vl=N("hold",[[0,"id",T],[1,"path",R],[2,"reason",fm],[3,"since",Tn],[4,"base",Rp,"opt"],[5,"mine",Rp],[6,"theirs",Rp,"opt"],[7,"saves",B]]),xv=["keep_mine","take_theirs","use","delete","keep_both"],mm=Pe("hold-resolution",xv),Cv=N("record-state",[[0,"state",Pe("confirmation",["confirmed","pending"])],[1,"confirmedSeq",B],[2,"hold",hm,"opt"],[3,"unresolved",B,"opt"]]),Iv=N("link-resolution",[[0,"kind",Pe("link-kind",["record","file","ambiguous","not_found","invalid"])],[1,"target",T,"opt"],[2,"path",R,"opt"]]),ym=N("link-view",[[0,"raw",R],[1,"embed",Oe],[2,"resolution",Iv],[3,"field",R,"opt"]]),Tp=N("author-ref",[[0,"account",T],[1,"device",T],[2,"grant",T,"opt"],[3,"grantAccount",T,"opt"]]),_n=gl(at),Mn=N("record-view",[[0,"id",T],[1,"path",R],[2,"revision",H],[3,"frontmatter",_n],[4,"effective",_n,"opt"],[5,"body",R,"opt"],[6,"document",R,"opt"],[7,"types",F(R)],[8,"state",Cv],[9,"diagnostics",F(Zi),"opt"],[10,"values",_n,"opt"],[11,"mtime",Tn,"opt"],[12,"links",F(ym),"opt"],[13,"createdBy",Tp,"opt"],[14,"modifiedBy",Tp,"opt"]]),ds=N("include",[[0,"effective",Oe,"opt"],[1,"body",Oe,"opt"],[2,"document",Oe,"opt"],[3,"diagnostics",Oe,"opt"],[4,"links",Oe,"opt"]]),gm=N("view-ref",[[0,"path",R],[1,"view",R]]),bm=N("query-group",[[0,"values",_n],[1,"count",B],[2,"summaries",_n,"opt"]]),Ov=N("query-metadata",[[0,"columns",F(R),"opt"],[1,"totalCount",B,"opt"],[2,"diagnostics",F(Zi),"opt"],[3,"view",gm,"opt"],[4,"groups",F(bm),"opt"],[5,"hasMore",Oe,"opt"]]),_l=N("query-result",[[0,"records",F(Mn)],[1,"cursor",R,"opt"],[2,"complete",Oe],[3,"asOf",B],[4,"columns",F(R),"opt"],[5,"totalCount",B,"opt"],[6,"diagnostics",F(Zi),"opt"],[7,"view",gm,"opt"],[8,"groups",F(bm),"opt"],[9,"hasMore",Oe,"opt"]]),jp=N("query-update",[[0,"sub",B],[1,"kind",Pe("update-kind",["snapshot","diff","reset"])],[2,"added",F(Mn),"opt"],[3,"changed",F(Mn),"opt"],[4,"removed",F(T),"opt"],[5,"order",F(T),"opt"],[6,"complete",Oe],[7,"asOf",B],[8,"metadata",Ov,"opt"]]),Rv=N("change",[[0,"id",T],[1,"path",R],[2,"kind",Pe("change-kind",["put","remove"])],[3,"version",B],[4,"author",Tp,"opt"],[5,"entity",Pe("change-entity",["record","file"]),"opt"],[6,"types",F(R),"opt"]]),us=N("changes-result",[[0,"changes",F(Rv)],[1,"cursor",R],[2,"reset",Oe]]),Ev=["image","audio","video","pdf","other"],fs=Pe("media-class",Ev),wl=Pe("conflict-mode",["record","reject"]),Np={name:"base-field",enc:n=>n.observed===void 0?[n.key]:[n.key,at.enc(n.observed)],dec:n=>{if(!Array.isArray(n)||n.length<1||n.length>2)throw new ne("base-field","must have 1 or 2 elements");return n.length===1?{key:R.dec(n[0])}:{key:R.dec(n[0]),observed:at.dec(n[1])}}},wm=im("body-edit",[B,B,R]),sm=N("doc-version",[[0,"path",R],[1,"doc",R]]),vm=N("file-inclusion",[[0,"include",F(fs)],[1,"exclude",F(R),"opt"],[2,"maxSize",B,"opt"]]),yv=gl(F(at)),ps=bl("op",[[1,"create",[[1,"id",T],[2,"path",R,"opt"],[3,"type",R,"opt"],[4,"frontmatter",_n,"opt"],[5,"body",R,"opt"],[6,"document",R,"opt"]]],[2,"update",[[1,"id",T],[2,"patch",_n,"opt"],[3,"unset",F(R),"opt1"],[4,"add",yv,"opt"],[5,"remove",yv,"opt"],[6,"body",R,"opt"],[7,"bodyEdits",F(wm),"opt1"],[8,"bodyBase",H,"opt"],[9,"bodyBaseText",R,"opt"],[10,"base",F(Np),"opt1"],[11,"ifRevision",H,"opt"],[12,"updateRefs",Oe,"opt"]]],[3,"document",[[1,"id",T],[2,"base",sm,"opt"],[3,"new",sm,"opt"],[4,"ifRevision",H,"opt"]]],[4,"delete",[[1,"id",T],[2,"baseRevision",H,"opt"],[3,"ifRevision",H,"opt"]]],[5,"rename",[[1,"id",T],[2,"from",R],[3,"to",R],[4,"updateRefs",Oe],[5,"ifRevision",H,"opt"]]],[6,"resource_put",[[1,"path",R],[2,"doc",R],[3,"baseRevision",H,"opt"],[4,"mustNotExist",Oe,"opt"]]],[7,"resource_delete",[[1,"path",R],[2,"baseRevision",H,"opt"]]],[8,"file_put",[[1,"id",T],[2,"path",R],[3,"blob",Xi],[4,"ifRevision",H,"opt"],[5,"base",H,"opt"]]],[9,"file_delete",[[1,"id",T],[2,"ifRevision",H,"opt"],[3,"base",H,"opt"]]],[10,"file_move",[[1,"id",T],[2,"from",R],[3,"to",R],[4,"updateRefs",Oe],[5,"ifRevision",H,"opt"]]],[11,"conflict_dismiss",[[1,"mutation",T],[2,"record",T]]],[12,"sync_settings",[[1,"inclusion",vm]]]]),_m=N("submit-params",[[0,"ops",F(ps,{nonEmpty:!0}),"req1"],[1,"mutationId",T,"opt"],[2,"conflictMode",wl,"opt"],[3,"timezone",R,"opt"],[4,"allowPartial",Oe,"opt"],[5,"mutationIds",F(T),"opt1"],[6,"dryRun",Oe,"opt"],[7,"include",ds,"opt"],[8,"wait",Pe("wait-for",["pending","confirmed","published"]),"opt"]]),ZI=["missing","value","text","blob","deleted"],Ep={name:"conflict-value",enc:n=>{switch(n.form){case"missing":return[0];case"value":return[1,at.enc(n.value)];case"text":return[2,n.text];case"blob":return[3,Xi.enc(n.blob)];case"deleted":return[4]}},dec:n=>{if(!Array.isArray(n)||n.length===0)throw new ne("conflict-value","malformed conflict value");let e=n[0];if(typeof e!="number")throw new ne("conflict-value","malformed conflict value");if(e>4)throw new ne("conflict-value",`unknown variant ${e}`,!0);let t=ZI[e];if(t==="missing"||t==="deleted"){if(n.length!==1)throw new ne("conflict-value","malformed conflict value");return{form:t}}if(n.length!==2)throw new ne("conflict-value","malformed conflict value");return t==="value"?{form:t,value:at.dec(n[1])}:t==="text"?{form:t,text:R.dec(n[1])}:{form:t,blob:Xi.dec(n[1])}}},Am=N("conflict",[[0,"kind",Pe("conflict-kind",["field","frontmatter","body","path","delete","file"],1)],[1,"id",T],[2,"field",R,"opt"],[3,"base",Ep,"opt"],[4,"kept",Ep],[5,"lost",Ep]]),qv=Pe("publish-state",["publishing","published","not_published"]),Tv=N("preflight",[[0,"rewrites",F(N("link-rewrite",[[0,"record",T],[1,"path",R],[2,"from",R],[3,"to",R],[4,"field",R,"opt"]]))],[1,"broken",F(N("broken-link",[[0,"record",T],[1,"path",R],[2,"raw",R],[3,"target",T],[4,"field",R,"opt"]]))]]),kt=N("receipt",[[0,"mutation",T],[1,"state",Pe("receipt-state",["pending","confirmed","rejected","unknown"])],[2,"seq",B,"opt"],[3,"status",Pe("status",["applied","merged","conflicted"]),"opt"],[4,"conflicts",F(Am),"opt1"],[5,"records",F(Mn),"opt"],[6,"problem",An,"opt"],[7,"published",qv,"opt"],[8,"preflight",Tv,"opt"],[9,"relocatedFrom",B,"opt"]]),km=F(kt,{nonEmpty:!0}),Al=N("conflict-entry",[[0,"mutation",T],[1,"seq",B],[2,"conflict",Am]]),Mv=Pe("file-content-profile",["ordinary_blob","ordinary_attachment_v1","unindexed_markdown_blob","unindexed_markdown_attachment_v1"]),om=N("file-view",[[0,"id",T],[1,"path",R],[2,"size",B],[3,"digest",H],[4,"media",fs],[5,"state",Pe("file-state",["materialized","remote","fetching","pending_upload"])],[6,"confirmedSeq",B],[7,"hold",hm,"opt"],[8,"mtime",Tn,"opt"],[9,"mediaType",R,"opt"],[10,"contentProfile",Mv,"opt"]]),kl={...om,dec(n){let e=n instanceof Map?n:void 0;if(e?.has(10))try{Mv.dec(e.get(10))}catch(t){if(!(t instanceof ne)||!t.unknown)throw t;let i=new Map(e);return i.delete(10),om.dec(i)}return om.dec(n)}},Sm=N("list-files-result",[[0,"files",F(kl)],[1,"cursor",R,"opt"],[2,"complete",Oe]]),Pm=N("open-upload-params",[[0,"transfer",T],[1,"path",R],[2,"size",B],[3,"digest",H,"opt"],[4,"fileId",T,"opt"],[5,"ifRevision",H,"opt"],[6,"mutationId",T,"opt"]]),xm=N("open-upload-result",[[0,"transfer",T],[1,"chunkSize",B],[2,"received",F(B)],[3,"expiresAt",Tn],[4,"fileId",T,"opt"]]),Cm=N("upload-chunk-params",[[0,"transfer",T],[1,"index",B],[2,"bytes",{name:"bstr",enc:n=>n,dec:n=>n instanceof Uint8Array?n:Lv("bstr")}]]);Up=N("file-chunk",[[0,"stream",B],[1,"offset",B],[2,"bytes",{name:"bstr",enc:n=>n,dec:n=>n instanceof Uint8Array?n:Lv("bstr")}],[3,"last",Oe]]),Dp=N("file-stream-failure",[[0,"stream",B],[1,"problem",An]]),jv=["receiving","sealing","uploading","appending","confirmed","fetching","streaming","done"],$p=N("transfer-progress",[[0,"id",Sp("transfer-id",T,n=>typeof n=="string",n=>n instanceof Uint8Array,B)],[1,"phase",Pe("phase",jv)],[2,"done",B],[3,"total",B]]),zp=N("materialization",[[0,"mode",Pe("materialize-mode",["all","on_demand"])],[1,"pinned",F(R),"opt"],[2,"media",F(fs),"opt"],[3,"maxSize",B,"opt"]]),Nv=N("peer",[[0,"session",uo],[1,"account",T,"opt"],[2,"app",R,"opt"],[3,"state",at],[4,"lastSeen",Tn]]),Bp=N("presence",[[0,"record",T],[1,"peers",F(Nv)]]),Im=N("fence-apply",[[0,"path",R],[1,"base",H],[2,"edits",F(wm,{nonEmpty:!0}),"req1"],[3,"expected",H]]),Om=N("fence-report",[[0,"open",F(N("fence-open",[[0,"path",R],[1,"dirty",Oe],[2,"buffer",H]]))]]),Rm=N("fence-result",[[0,"outcome",Pe("fence-outcome",["applied","not_open","buffer_changed"])],[1,"buffer",R,"opt"]]),QI={query_update:jp,receipt:kt,status:er,holds:F(vl),conflicts:F(Al),presence:Bp,file_chunk:Up,file_stream_failed:Dp,transfer_progress:$p,changes:us},fo=N("op-clock",[[0,"instant",Tn],[1,"tz",R],[2,"localDate",R]]),eO=N("mutation",[[0,"id",T],[1,"origin",T],[2,"baseSeq",B],[3,"clock",fo],[4,"seed",Ii],[5,"source",Pe("source",["api","external"])],[6,"ops",F(ps,{nonEmpty:!0}),"req1"],[7,"onBehalf",T,"opt"],[8,"conflictMode",wl,"opt"],[9,"validatedAt",Pe("level",["off","warn","error"]),"opt"],[10,"room",N("room-checkpoint",[[0,"stream",uo],[1,"state",H]]),"opt"]]),tO=Pe("confirmation",["confirmed","pending"]),Fp=N("resource-view",[[0,"path",R],[1,"revision",H],[2,"size",B],[3,"state",tO],[4,"text",R,"opt"]]),Em=N("list-resources-result",[[0,"resources",F(Fp)],[1,"complete",Oe],[2,"cursor",R,"opt"]]),qm=N("backlinks-result",[[0,"backlinks",F(N("backlink",[[0,"record",Mn],[1,"links",F(ym,{nonEmpty:!0}),"req1"]]))],[1,"cursor",R,"opt"],[2,"complete",Oe],[3,"asOf",B]]),nO=N("list-views-result",[[0,"sources",F(N("view-source",[[0,"record",T],[1,"id",R],[2,"name",R],[3,"source",N("view-source-ref",[[0,"path",R],[1,"format",R],[2,"revision",H],[3,"writable",Oe]])],[4,"views",F(N("view-descriptor",[[0,"id",R],[1,"name",R],[2,"properties",F(N("view-property",[[0,"key",R],[1,"label",R,"opt"],[2,"description",R,"opt"],[3,"format",R,"opt"],[4,"hidden",Oe,"opt"]]))],[3,"presentation",at,"opt"]]))]]))],[1,"diagnostics",F(Zi)],[2,"complete",Oe]]),iO=N("view-source-document",[[0,"path",R],[1,"format",R],[2,"revision",H],[3,"document",R],[4,"record",T]]),Tm=N("new-type-file",[[0,"name",R],[1,"path",R]]),Mm=N("describe-result",[[0,"specVersion",R],[1,"types",F(N("type-summary",[[0,"name",R],[1,"path",R],[2,"implements",F(N("implementation",[[0,"contract",R],[1,"version",R],[2,"fields",gl(R)],[3,"binding",at,"opt"],[4,"digest",H,"opt"]]))],[3,"version",Tn,"opt"],[4,"revision",H,"opt"],[5,"definition",at,"opt"],[6,"schema",at,"opt"]]))],[2,"settings",at],[3,"inclusion",vm],[4,"issues",F(Zi)],[5,"contracts",F(N("contract-summary",[[0,"id",R],[1,"version",R],[2,"path",R],[3,"digest",H],[4,"contractType",R],[5,"implementedBy",F(R)],[6,"schemas",gl(at),"opt"]]))]]),rO={name:"pending-runtime-op",enc:n=>Op.enc(n),dec:n=>Op.dec(n)},Lm=N("list-pending-result",[[0,"pending",F(N("pending-mutation",[[0,"receipt",kt],[1,"captured",Tn],[2,"ops",F(rO,{nonEmpty:!0}),"req1"]]))],[1,"next",T,"opt"]]),am={name:"target",enc:n=>typeof n=="string"?T.enc(n):n.path,dec:n=>typeof n=="string"?{path:n}:T.dec(n)},oO=N("query-params",[[0,"query",at],[1,"include",ds,"opt"],[2,"contract",R,"opt"]]),sO=N("execute-view-params",[[0,"source",am],[1,"view",R],[2,"context",am,"opt"],[3,"limit",B,"opt"],[4,"offset",B,"opt"],[5,"timezone",R,"opt"],[6,"include",ds,"opt"]]),Vp=["none","date","date_time"],Uv=Pe("temporal-hint",Vp),Dv=N("typing-entry",[[0,"path",R],[1,"hint",Uv]]),jm=N("describe-typing-result",[[0,"catalogGeneration",B],[1,"fields",F(Dv)]]),Sl=64,Pl=256});function $v(n,e,t,i){let o=aO(t),s=lO(t);n.setUint32(e,i?s:o,i),n.setUint32(e+4,i?o:s,i)}var aO,lO,zv=I(()=>{aO=n=>n/2**32|0,lO=n=>n>>>0});function Kp(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}function ho(n,e=""){if(typeof n!="number")throw new TypeError(Um(e)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(Um(e)+"expected integer >= 0, got "+n);return n}function tr(n,e,t=""){if(Kp(n)&&(e===void 0||n.length===e))return n;e!==void 0&&ho(e,"length");let i=Kp(n),o=e!==void 0?` of length ${e}`:"",s=i?`length=${n.length}`:`type=${typeof n}`,r=Um(t)+"expected Uint8Array"+o+", got "+s;throw i?new RangeError(r):new TypeError(r)}function Vv(n){if(typeof n!="function"||typeof n.create!="function")throw new TypeError("expected hash wrapped by utils.createHasher");if(ho(n.outputLen),ho(n.blockLen),n.outputLen<1||n.blockLen<1)throw new Error("hash blockLen / outputLen must be >= 1")}function hs(n,e=!0){if(n.destroyed)throw new Error("hash was destroyed");if(e&&n.finished)throw new Error("digest() was already called")}function Wp(n,e){tr(n,void 0,"output");let t=e.outputLen;if(!(n.length>=t))throw new RangeError('"output" expected length >= '+t)}function ms(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function Hp(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function oi(n,e){return n<<32-e|n>>>e}function ys(n){if(tr(n),Kv)return n.toHex();let e="";for(let t=0;t<n.length;t++)e+=pO[n[t]];return e}function Fv(n){return n>=48&&n<=57?n-48:n>=65&&n<=70?n-55:n>=97&&n<=102?n-87:void 0}function Dm(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);if(Kv)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=Fv(n.charCodeAt(s)),a=Fv(n.charCodeAt(s+1));if(r===void 0||a===void 0){let p=n[s]+n[s+1];throw new RangeError('hex string expected, got non-hex character "'+p+'" at index '+s)}i[o]=r*16+a}return i}function Wv(n){if(typeof n!="string")throw new TypeError("string expected");let e=new TextEncoder().encode(n);try{return new Uint8Array(e)}finally{ms(e)}}function dO(n,e,t="opts"){return Bv(n,"defaults"),e!==void 0&&Bv(e,t),Object.assign(Object.create(null),n,e)}function Hv(n,e={}){if(typeof n!="function")throw new TypeError('"hashCons" expected function, got type='+typeof n);e=dO({},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 Gv(n=32){ho(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 Um,cO,Bv,Kv,pO,Yv,gs=I(()=>{Um=n=>n?`"${n}" `:"";cO=(n,e)=>{if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError((e==="object"?"":`"${e}" `)+"expected object, got type="+typeof n)},Bv=(n,e)=>{cO(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`)};Kv=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",pO=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));Yv=n=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,n])})});function Jv(n,e,t){return n&e^~n&t}function Xv(n,e,t){return n&e^n&t^e&t}var Gp,Zv,Qv=I(()=>{zv();gs();Gp=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=Hp(this.buffer)}update(e){hs(this),tr(e);let{view:t,buffer:i,blockLen:o}=this,s=e.length,r=!1;for(let a=0;a<s;){let p=Math.min(o-this.pos,s-a);if(p===o){let l=Hp(e);for(;o<=s-a;a+=o)this.process(l,a);r=!0;continue}i.set(a===0&&p===s?e:e.subarray(a,a+p),this.pos),this.pos+=p,a+=p,this.pos===o&&(this.process(t,0),this.pos=0,r=!0)}return this.length+=e.length,r&&this.roundClean(),this}digestInto(e){hs(this),Wp(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)),$v(i,o-8,this.length*8,s),this.process(i,0),this.roundClean();let a=e===t?i:Hp(e),p=this.outputLen,l=p/4,c=this.get();if(p%4||l>c.length)throw new Error("invalid outputLen");for(let d=0;d<l;d++)a.setUint32(4*d,c[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()}},Zv=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225])});var uO,xr,$m,zm,it,Cr=I(()=>{Qv();gs();uO=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]),xr=new Uint32Array(64),$m=class extends Gp{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:p}=this;return[e,t,i,o,s,r,a,p]}set(e,t,i,o,s,r,a,p){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=p|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)xr[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let u=xr[d-15],f=xr[d-2],h=oi(u,7)^oi(u,18)^u>>>3,m=oi(f,17)^oi(f,19)^f>>>10;xr[d]=m+xr[d-7]+h+xr[d-16]|0}let{A:i,B:o,C:s,D:r,E:a,F:p,G:l,H:c}=this;for(let d=0;d<64;d++){let u=oi(a,6)^oi(a,11)^oi(a,25),f=c+u+Jv(a,p,l)+uO[d]+xr[d]|0,m=(oi(i,2)^oi(i,13)^oi(i,22))+Xv(i,o,s)|0;c=l,l=p,p=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,p=p+this.F|0,l=l+this.G|0,c=c+this.H|0,this.set(i,o,s,r,a,p,l,c)}roundClean(){ms(xr)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ms(this.buffer)}},zm=class extends $m{constructor(){super(32,Zv)}},it=Hv(()=>new zm,Yv(1))});function ut(n){if(n==null)return null;if(typeof n!="object"||n instanceof yt)return n;if(Array.isArray(n))return n.map(ut);if(n instanceof Map){let t=new Map;for(let[i,o]of n)t.set(i,ut(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,ut(i));return e}function xl(n){return ut(n)}function bs(n){if(n===null||typeof n=="boolean"||typeof n=="number"||typeof n=="string")return n;if(typeof n=="bigint")return n.toString();if(n instanceof yt)return n.value;if(n instanceof Uint8Array)return ri(n);if(Array.isArray(n))return n.map(bs);let e={};for(let[t,i]of n)e[String(t)]=bs(i);return e}function Ir(n,e){if(n===e)return!0;if(n instanceof yt&&e instanceof yt)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)=>Ir(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&&Ir(s,i[r][1]))}return!1}function si(n){let e=typeof n=="string"?new TextEncoder().encode(n):n;return`sha256:${ri(it(e))}`}function fO(n){let e=new Uint8Array(n);return globalThis.crypto.getRandomValues(e),e}function Ln(n=Date.now()){let e=fO(16);n<=Yp?(n=Yp,mo=mo+1&4095,mo===0&&(n=++Yp)):(mo=(e[6]&15)<<8|e[7],mo&=2047),Yp=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|mo>>8&15,e[7]=mo&255,e[8]=128|e[8]&63,yl(e)}function Jp(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 Yp,mo,Oi=I(()=>{"use strict";Cr();Je();ge();Yp=0,mo=0});function je(n,e=yO){if(typeof n!="string"||Ri.encode(n).length>e)throw fe("bounded text required");return n}function Yt(n,e){let t=B.dec(n);if(t>e)throw fe("integer exceeds bound");return t}function $t(n,e){if(!Array.isArray(n)||n.length>e)throw fe("bounded array required");return n}function Cl(n,e){let t=$t(n,e);if(t.length!==e)throw fe("wrong tuple length");return t}function ai(n,e){if(!(n instanceof Map))throw fe("exact struct required");let t=n;if(t.size!==e.length||e.some(i=>!t.has(i)))throw fe("exact struct required");return n}function e_(n){let e=n instanceof yt?n.value:n;if(typeof e!="number"||!Number.isFinite(e)||!(n instanceof yt)&&Number.isInteger(e))throw fe("finite binary64 required");return e}function t_(n){return n.kind==="list"?n.values.every(t_):n.kind!=="map"&&n.kind!=="duration"&&n.kind!=="error"&&n.kind!=="unavailable"}function yo(n,e=1){if(!Number.isInteger(e)||e<1||e>32)throw fe("cell depth exceeds bound");let t=$t(n,5),i=B.dec(t[0]),o=s=>{if(t.length!==s)throw fe("wrong tagged cell length")};switch(i){case 0:return o(1),{kind:"null"};case 1:return o(2),{kind:"boolean",value:Oe.dec(t[1])};case 2:return o(2),{kind:"number",value:e_(t[1])};case 3:return o(2),{kind:"text",value:je(t[1])};case 4:{o(5);let s=Tn.dec(t[1]);if(!Number.isSafeInteger(s))throw fe("date millis exceeds JS-safe range");return{kind:"date",millis:s,display:je(t[2]),authoritativeZone:je(t[3]),dateOnly:Oe.dec(t[4])}}case 5:return o(3),{kind:"duration",components:Cl(t[1],8).map(e_),display:je(t[2])};case 6:return o(2),{kind:"list",values:$t(t[1],ws).map(s=>yo(s,e+1))};case 7:{if(o(2),!(t[1]instanceof Map)||t[1].size>ws)throw fe("bounded cell data map required");let s=new Map,r=null;for(let[a,p]of t[1]){let l=je(a),c=Ri.encode(l);if(r&&gO(r,c)>=0)throw fe("cell data map keys must ascend");r=c,s.set(l,yo(p,e+1))}return{kind:"map",values:s}}case 8:return o(2),{kind:"error",message:je(t[1])};case 9:return o(3),{kind:"unavailable",code:je(t[1]),detail:je(t[2])};default:throw fe("unknown tagged cell",!0)}}function gO(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 bO(n){let e=new Map,t=0,i=0,o=r=>{if(++t>4096||(i+=r)>1024*1024)throw fe("summary metadata exceeds bound")},s=(r,a)=>{if(a>32)throw fe("summary value depth exceeds bound");o(128);let p=$t(r,5),l=B.dec(p[0]);if(l===3||l===8)o(Ri.encode(je(p[1])).length);else if(l===4)o(Ri.encode(je(p[2])).length+Ri.encode(je(p[3])).length);else if(l===5)o(Ri.encode(je(p[2])).length);else if(l===6)for(let c of $t(p[1],ws))s(c,a+1);else if(l===7){if(!(p[1]instanceof Map)||p[1].size>ws)throw fe("bounded summary data map required");for(let[c,d]of p[1])o(Ri.encode(je(c)).length+64),s(d,a+1)}else if(l!==0&&l!==1&&l!==2)throw fe("summary must be a tagged value",!0)};for(let r of $t(n,64)){let a=Cl(r,2),p=je(a[0],1024);if(p.length===0||/[\u0000-\u001f\u007f-\u009f]/u.test(p)||e.has(p))throw fe("unique nonempty summary name required");o(Ri.encode(p).length+64),s(a[1],1),e.set(p,yo(a[1]))}return e}function Bm(n){let e=Yt(n.offset,4294967295),t=Yt(n.limit,jn);if(t===0)throw fe("window limit must be positive");return{offset:e,limit:t}}function Xp(n){if(!(n.hints instanceof Map)||n.hints.size>ws)throw fe("bounded hints map required");let e=new Map,t=0;for(let[s,r]of n.hints){if(je(s),je(r),t+=Ri.encode(s).length+Ri.encode(r).length,t>65536)throw fe("hint bytes exceed bound");e.set(s,r)}let i=new Map([[0,T.enc(n.record)],[1,H.enc(n.sourceRevision)],[2,Yt(n.ordinal,4294967295)],[3,e],[4,je(n.captureTimezone,128)],[5,Fm]]);if(n.window!==void 0){let s=Bm(n.window);i.set(6,new Map([[0,s.offset],[1,s.limit]]))}let o=pe(i);if(o.length>mO)throw fe("request bytes exceed bound");return o}function n_(n){let e=ai(n,[0,1,2,3,4,5,6]);return{record:T.dec(e.get(0)),path:je(e.get(1)),sourceRevision:H.dec(e.get(2)),ordinal:Yt(e.get(3),4294967295),name:e.get(4)===null?null:je(e.get(4)),viewType:je(e.get(5)),implementations:$t(e.get(6),ws).map(t=>{let i=ai(t,[0,1,2,3]);return{typeName:je(i.get(0)),version:je(i.get(1)),contractDigest:H.dec(i.get(2)),implementationDigest:H.dec(i.get(3))}})}}function Zp(n,e){if(!(n instanceof Uint8Array)||!n.length||n.length>hO)throw fe("response bytes exceed bound");let t=ue(n);if(!(t instanceof Map))throw fe("result struct required");let i=t;if(i.get(0)!==1)throw fe("unknown result version",!0);if(i.has(7)){let b=ai(i,[0,7]);return{kind:"refusal",problem:An.dec(b.get(7))}}let o=i.has(8),s=i.has(9),r=ai(i,[0,1,2,3,4,5,6,...o?[8]:[],...s?[9]:[]]);if(e!==void 0&&o!==(e!==null))throw fe("window response differs from request");let a=n_(r.get(1)),p=ai(r.get(2),[0,1]),l=$t(p.get(0),64).map(b=>je(b)),c=$t(p.get(1),64).map(b=>{let w=ai(b,[0,1,2]),g=Yt(w.get(0),63);if(g>=l.length)throw fe("unavailable column index out of bounds");return{index:g,code:je(w.get(1)),detail:je(w.get(2))}}),d=$t(r.get(3),jn).map(b=>{let w=Cl(b,4),g=$t(w[3],64);if(g.length!==l.length)throw fe("row cell count differs from columns");return{record:T.dec(w[0]),path:je(w[1]),sourceRevision:H.dec(w[2]),cells:g.map(y=>yo(y))}}),u=$t(r.get(4),jn).map(b=>{let w=Cl(b,2),g=yo(w[0]);if(!t_(g))throw fe("group key must be a qualified scalar or list");let y=$t(w[1],jn).map(v=>{let _=Yt(v,jn-1);if(_>=d.length)throw fe("group row index out of bounds");return _});return{key:g,rowIndices:y}}),f;if(o){let b=ai(r.get(8),[0,1,2,3]),w=Bm({offset:Yt(b.get(0),4294967295),limit:Yt(b.get(1),jn)}),g=Yt(b.get(2),jn);if(d.length!==Math.min(w.limit,Math.max(g-w.offset,0)))throw fe("window row count differs from total/request");if(e!=null){let k=Bm(e);if(w.offset!==k.offset||w.limit!==k.limit)throw fe("window echo differs from request")}let y=-1,v=$t(b.get(3),jn);if(v.length!==u.length||u.some(k=>k.rowIndices.length===0))throw fe("group placements must align represented groups");let _=v.map((k,S)=>{let x=Cl(k,3),P=Yt(x[0],jn-1),C=Yt(x[1],jn);if(P<=y||P>=g||C===0||C>g)throw fe("group placement bounds/order invalid");y=P;let E=-1,O=$t(x[2],jn).map(L=>{let z=Yt(L,jn-1);if(z<=E||z>=C)throw fe("group row ordinal bounds/order invalid");return E=z,z});if(O.length!==u[S].rowIndices.length)throw fe("group ordinal count differs from represented rows");return{globalGroupOrdinal:P,totalGroupRows:C,rowOrdinals:O}});f={...w,totalMatchedRows:g,groupPlacements:_}}let h=fo.dec(r.get(5));if(!Number.isSafeInteger(h.instant))throw fe("clock instant exceeds JS-safe range");let m=s?bO(r.get(9)):void 0;return{kind:"success",view:a,columns:l,unavailableColumns:c,rows:d,groups:u,clock:h,collectionRevision:H.dec(r.get(6)),...f===void 0?{}:{window:f},...m===void 0?{}:{summaries:m}}}function i_(n){if(n==null)return null;if(!(n instanceof Uint8Array)||n.length!==32)throw fe("native discovery handle must be 32 bytes");return new Uint8Array(n)}function Qp(n){let e=Yt(n.limit,128);if(!e)throw fe("discovery limit must be positive");return pe(new Map([[0,1],[1,je(n.captureTimezone,128)],[2,e],[3,i_(n.continuation)]]))}function ed(n){return pe(new Map([[0,1],[1,T.enc(n.record)],[2,H.enc(n.sourceRevision)],[3,Yt(n.ordinal,4294967295)],[4,je(n.captureTimezone,128)]]))}function r_(n){if(!(n instanceof Uint8Array)||!n.length||n.length>1024*1024)throw fe("discovery response bytes exceed bound");let e=ue(n);if(!(e instanceof Map))throw fe("discovery result struct required");let t=e;if(t.get(0)!==1)throw fe("unknown discovery result version");return t}function o_(n){let e=n_(n);if(!e.implementations.length||e.implementations.length>16)throw fe("bounded native implementation provenance required");return e}function s_(n){let e=fo.dec(n);if(!Number.isSafeInteger(e.instant))throw fe("clock instant exceeds JS-safe range");return je(e.tz,128),je(e.localDate,128),e}function td(n,e=128){let t=Yt(e,128);if(!t)throw fe("discovery limit must be positive");let i=r_(n);if(i.has(7)){let a=ai(i,[0,7]);return{kind:"refusal",problem:An.dec(a.get(7))}}let o=ai(i,[0,1,2,3,4]),s=$t(o.get(1),t).map(o_);for(let a=1;a<s.length;a++){let p=s[a-1],l=s[a];if(p.record>l.record||p.record===l.record&&p.ordinal>=l.ordinal)throw fe("discovery source/ordinal frontier must ascend");if(p.record===l.record&&(p.path!==l.path||p.sourceRevision!==l.sourceRevision))throw fe("one source identity cannot have two revisions/paths within a page")}let r=o.get(4);if(r!==null&&!(r instanceof Uint8Array))throw fe("native discovery handle required");return{kind:"success",views:s,clock:s_(o.get(2)),collectionRevision:H.dec(o.get(3)),continuation:i_(r)}}function nd(n,e){let t=r_(n);if(t.has(7)){let r=ai(t,[0,7]);return{kind:"refusal",problem:An.dec(r.get(7))}}let i=ai(t,[0,1,2,3,4]),o=o_(i.get(1)),s=je(i.get(2),512*1024);if(si(s)!==o.sourceRevision)throw fe("exact native source SHA differs from bytes");if(e&&(o.record!==T.dec(T.enc(e.record))||o.sourceRevision!==H.dec(H.enc(e.sourceRevision))||o.ordinal!==e.ordinal))throw fe("exact source identity/revision/ordinal differs from request");return{kind:"success",view:o,source:s,clock:s_(i.get(3)),collectionRevision:H.dec(i.get(4))}}var Fm,hO,mO,yO,ws,jn,Ri,fe,Vm=I(()=>{"use strict";Je();ge();Oi();At();Fm="whole-view-synthetic-policy-reference-v1",hO=16*1024*1024,mO=128*1024,yO=4096,ws=4096,jn=65536,Ri=new TextEncoder,fe=(n,e=!1)=>new ne("app-bases-v1",n,e)});async function*l_(n,e,t={}){let i=a_(t.firstPageSize,200),o=a_(t.pageSize,1e3),s=e.window?.offset??0,r=0,a=0,p;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 c=l.window?.totalMatchedRows;if(c===void 0)throw A("internal","native Bases page omitted its window");p??={revision:l.collectionRevision,total:c},r+=l.rows.length;let d=l.rows.length===0||s+l.rows.length>=c;if(yield{...l,page:a,offset:s,loaded:r,complete:d,changedSinceFirst:p.revision!==l.collectionRevision||p.total!==c},d)return;s+=l.rows.length,a+=1}}var a_,c_=I(()=>{"use strict";ie();a_=(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 p_(n){if(n==="request"||n==="single_record"||n==="cross_record")return n;throw new ne("validation-tier","unknown diagnostic tier",!0)}function f_(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=T.dec(T.enc(i));e.push(T.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=T.dec(T.enc(i.id)),r=H.dec(H.enc(i.revision));e.push(T.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 h_(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 wO,vO,_O,d_,Or,u_,m_=I(()=>{"use strict";ge();Je();At();ie();wO={name:"validation-tier",enc:p_,dec:p_},vO=N("validation-issue",[[0,"code",R],[1,"severity",Mp],[2,"message",R],[3,"details",at,"opt"],[4,"location",R,"opt"],[5,"typeName",R,"opt"],[6,"tier",wO]]),_O=N("record-validation",[[0,"id",T],[1,"issues",F(vO)],[2,"path",R],[3,"revision",H]]),d_=F(_O),Or=n=>new ne("record-validations",n),u_={name:"record-validations",enc:n=>d_.enc(n),dec:n=>{if(!Array.isArray(n)||n.length>1e3)throw Or("invalid inventory");let e=0,t=0,i=[[n,0]];for(;i.length;){let[s,r]=i.pop();if(++t>65536||r>32)throw Or("result exceeds tree bounds");if(Array.isArray(s)){if(s.length>65536)throw Or("oversized array");for(let a of s)i.push([a,r+1])}else if(s instanceof Map){if(s.size>32768)throw Or("oversized map");for(let[a,p]of s)i.push([a,r+1],[p,r+1])}}for(let s of n){let r=s instanceof Map?s.get(1):void 0;if(!Array.isArray(r))throw Or("missing diagnostics");if(e+=r.length,e>4096)throw Or("too many diagnostics")}if(pe(n).byteLength>1024*1024)throw Or("result exceeds byte bounds");let o=d_.dec(n);for(let s of o)if(!s.path||new TextEncoder().encode(s.path).byteLength>4096)throw Or("invalid current path");return o}}});function AO(n){if(n.length>Rr)throw A("too_large",`frame of ${n.length} bytes exceeds ${Rr}`);let e=new Uint8Array(4+n.length);return new DataView(e.buffer).setUint32(0,n.length),e.set(n,4),e}function Km(n){return y_.has(n)}function id(n){let e=new Il,t=!1,i=null,o=[],s={get onframe(){return i},set onframe(a){if(i=a,a&&o.length)for(let p of o.splice(0))a(p)},onclose:null,send(a){if(t)throw A("unavailable","connection closed");n.write(AO(pe(a)))},close(){t||(t=!0,n.close(),s.onclose?.())}};y_.add(s),n.ondata=a=>{try{for(let p of e.push(a)){let l=ue(p);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(p){r(p instanceof se?p:A("internal",`invalid frame from replica: ${String(p)}`))}},n.onclose=a=>r(a);function r(a){t||(t=!0,n.close(),s.onclose?.(a))}return s}function g_(){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 Rr,Il,y_,Ol=I(()=>{"use strict";Je();ie();Rr=16*1024*1024,Il=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>Rr)throw A("too_large",`frame of ${i} bytes exceeds ${Rr}`);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}}};y_=new WeakSet});var rd,b_=I(()=>{"use strict";ie();rd=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,p=!1,l=new Promise((u,f)=>{r=u,a=f}),c=()=>{p||(p=!0,s.fill(0),a(A("cancelled","Bases READ cancelled")))};o?.addEventListener("abort",c,{once:!0});let d=async()=>{try{if(p)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(p||o?.aborted){u.fill(0),c();return}p=!0,r(u)}catch(u){p||(p=!0,a(u))}finally{s.fill(0),o?.removeEventListener("abort",c),this.occupied--}};return this.tail=this.tail.then(d,d),l}}});function w_(n,e){od.set(n,e)}function v_(n,e){let t=od.get(n);t&&od.set(e,t)}function __(n){return od.get(n)}var od,Wm=I(()=>{"use strict";od=new WeakMap});function Nn(n,e){return oe(n)?n:n instanceof ne&&n.unknown?A("upgrade_required",`${e}: ${n.message}`,{reason:"unknown_variant"}):A("internal",`${e}: ${n instanceof Error?n.message:String(n)}`)}function vs(n,e,t){return new se(Nn(n,e).toProblem(),{...t,cause:n})}var sd,A_,Hm,go,Rl=I(()=>{"use strict";ge();ie();Ol();b_();Wm();At();sd=[{major:1,minor:3},{major:1,minor:2},{major:1,minor:1},{major:1,minor:0}];A_=new WeakSet,Hm=n=>n instanceof se&&A_.has(n),go=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 rd((e,t)=>this.request(e,new Map([[0,t]])));device;static async open(e,t,i){let o=Qi.enc({kind:"request",id:0,method:"hello",params:lm.enc(t)}),s;try{s=await e.open(o,i)}catch(p){throw oe(p)?p:A("unavailable",`cannot reach the replica (${e.description}): ${String(p)}`)}let r;try{let p=Qi.dec(s.helloResponse);if(p.kind!=="response"||p.id!==0)throw A("internal","replica answered hello with another frame");if(p.problem)throw new se(p.problem);r=um.dec(p.result??null)}catch(p){throw s.port.close(),Nn(p,"hello")}let a=new n(s.port,r);return v_(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"&&!Km(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"&&!Km(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{}p.reject(A("cancelled",`${e} cancelled`))},p={resolve:l=>{p.cleanup();try{s(i.codec?i.codec.dec(l):l)}catch(c){r(Nn(c,`${e} result`))}},reject:l=>{p.cleanup(),r(l)},cleanup:()=>{this.pending.delete(o),i.signal?.removeEventListener("abort",a)}};this.pending.set(o,p),i.signal?.addEventListener("abort",a,{once:!0});try{this.sendFrame({kind:"request",id:o,method:e,params:t})}catch(l){p.reject(oe(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(Qi.enc(e))}onFrame(e){let t;try{t=Qi.dec(e)}catch(i){if(i instanceof ne&&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 se(t.problem);A_.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=(oe(a)?a:A("internal",String(a))).toProblem()}if(!this.closedFlag)try{this.port.send(Qi.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 S_(n,e){return oe(n,"unavailable")&&n.reason==="hosted_chunk_busy"&&Date.now()<e}function P_(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",p),o()},i),p=()=>{clearTimeout(a),s(A("cancelled",`${e} aborted`))};t?.addEventListener("abort",p,{once:!0})})}function Ym(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=SO.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 I_(n,e){El.set(n,e)}function x_(n){return typeof n=="string"?T.enc(n):"id"in n?T.enc(n.id):n.path}function Gm(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 nr(n){let e=new Map;for(let[t,i]of n)i!==void 0&&e.set(t,i);return e}async function C_(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 PO(n){return n instanceof Uint8Array||n instanceof ArrayBuffer?n.byteLength:n.size}var k_,ad,kO,SO,El,_s,ql=I(()=>{"use strict";Cr();ge();ie();Rl();Oi();At();k_=9e4;ad=64*1024*1024,kO=8*1024*1024,SO=[["list","collection.read"],["read","collection.read"],["add","records.create"],["replace","records.edit"],["move","records.edit"],["delete","records.delete"]];El=new WeakMap;_s=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=Ym(this.client.hello),t=El.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(t.cursor,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})})}wire(e){this.wired.has(e)||(this.wired.add(e),e.onPush("transfer_progress",t=>{try{let i=$p.dec(t);this.progress.get(i.id)?.(i)}catch{}}),e.onPush("file_chunk",t=>{try{let i=Up.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,p)=>a+p.bytes.length,0)+i.bytes.length<=kO&&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}=Dp.dec(t),s=this.streams.get(i);s?(this.streams.delete(i),s.onEnd(new se(o))):this.opening>0&&this.earlyFailures.size<16&&this.earlyFailures.set(i,new se(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(e));return this.wire(i),i}listPage(e={}){return this.client.call("list_files",nr([[0,e.folder],[1,e.media?.map(t=>fs.enc(t))],[2,e.cursor],[3,e.limit]]),{codec:Sm,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",nr([[0,x_(e)]]),{codec:kl,retry:!0,...t?{signal:t}:{}})}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(El.get(this)?.check(i.fileId?"replace":"add"),i.signal?.aborted)throw A("cancelled","upload aborted");let o=PO(t),s=it.create(),r=4*1024*1024;for(let d=0;d<o;d+=r)s.update(await C_(t,d,Math.min(o,d+r)));let a=nm(s.digest()),p=i.transferId??Ln(),l={transfer:p,path:e,size:o,digest:a,mutationId:i.mutationId??Ln()};i.fileId&&(l.fileId=i.fileId),i.ifRevision&&(l.ifRevision=i.ifRevision),i.onProgress&&this.progress.set(p,i.onProgress);let c=Date.now()+k_;for(;;)try{return await this.uploadOnce(t,o,l,i)}catch(d){if(oe(d,"unavailable")&&this.client.link==="reconnecting")continue;if(S_(d,c)){await P_(d,"upload",i.signal);continue}throw this.progress.delete(p),await this.abortUpload(p).catch(()=>{}),vs(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",Pm.enc(i),{codec:xm,...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 p=new Set(a.received),l=Math.ceil(t/a.chunkSize),c=p.size*a.chunkSize,d=new Set;for(let h=0;h<l;h++){if(p.has(h))continue;let m=h*a.chunkSize,b=await C_(e,m,Math.min(t,m+a.chunkSize)),w=s.request("upload_chunk",Cm.enc({transfer:i.transfer,index:h,bytes:b}),r).then(()=>{c+=b.length,o.onProgress?.({id:i.transfer,phase:"receiving",done:Math.min(c,t),total:t})});d.add(w),w.finally(()=>d.delete(w)).catch(()=>{}),d.size>=4&&await Promise.race(d)}await Promise.all(d);let u=await s.request("commit_upload",nr([[0,T.enc(i.transfer)]]),{codec:kt,...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",nr([[0,T.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 p=this,l=new AbortController,c=A("cancelled","file download cancelled"),d=!1,u=!1,f=!1,h=()=>{},m=()=>{i!==null&&(p.streams.delete(i),p.early.delete(i),f||(f=!0,o?.request("cancel_stream",nr([[0,i]])).catch(()=>{})))},b=()=>{u||(d=!0,h(),r(c),l.abort(),m())},w=new ReadableStream({async start(g){let y=()=>{u||d||(b(),g.error(c))};if(h=()=>t.signal?.removeEventListener("abort",y),t.signal?.addEventListener("abort",y,{once:!0}),t.signal?.aborted){y();return}try{if(o=await p.session(l.signal,!0),d)return;let v=nr([[0,x_(e)]]);t.range&&v.set(1,[t.range[0],t.range[1]]),t.revision&&v.set(2,H.enc(t.revision));let _=0,k=0;p.opening++;let S;try{let O=Date.now()+k_;for(;;)try{S=await o.request("read_file",v,{signal:l.signal});break}catch(L){if(!S_(L,O))throw L;await P_(L,"download",l.signal)}}finally{p.opening--}i=B.dec(S.get(0)??null);let x=p.early.get(i)??[],P=p.earlyFailures.get(i);if(p.early.delete(i),p.earlyFailures.delete(i),p.opening===0&&(p.early.clear(),p.earlyFailures.clear()),d){m(),u=!0;return}let C=kl.dec(S.get(1)??null);s(C),_=t.range?t.range[1]:C.size;let E=O=>{d||u||(g.enqueue(O.bytes),k+=O.bytes.length,t.onProgress?.({id:i,phase:"streaming",done:k,total:_}),!(d||u)&&(o.request("ack_chunks",nr([[0,i],[1,O.offset+O.bytes.length]])).catch(()=>{}),O.last&&!d&&!u&&(u=!0,h(),p.streams.delete(i),g.close())))};p.streams.set(i,{onChunk:E,onEnd:O=>{u=!0,h(),g.error(O??A("unavailable","stream ended"))}});for(let O of x)E(O);P&&!u&&(p.streams.delete(i),u=!0,h(),g.error(P))}catch(v){u=!0,h(),p.opening===0&&(p.early.clear(),p.earlyFailures.clear()),m(),r(v),g.error(v)}},cancel:b});return Object.assign(w,{file:a})}async download(e,t={}){let i=typeof e=="object"&&"size"in e?e:await this.get(e,t.signal);if(i.size>ad)throw A("too_large",`file is ${i.size} bytes; use downloadStream`,{details:new Map([["limit",ad]])});let o=new Uint8Array(i.size),s=0,r=this.downloadStream(i,t).getReader();for(;;){let{done:a,value:p}=await r.read();if(a)break;o.set(p,s),s+=p.length}return o.subarray(0,s)}fetch(e,t){return this.client.call("fetch_file",nr([[0,T.enc(Gm(e))]]),{retry:!0,...t?{signal:t}:{}}).then(()=>{})}evict(e){return this.client.call("evict_file",nr([[0,T.enc(Gm(e))]])).then(()=>{})}getMaterialization(){return this.client.call("get_materialization",null,{codec:zp,retry:!0})}setMaterialization(e){return this.client.call("set_materialization",zp.enc(e)).then(()=>{})}async move(e,t,i={}){El.get(this)?.check("move");let o={kind:"file_move",id:e.id,from:e.path,to:t,updateRefs:i.updateRefs??!0},[s]=await this.client.submit([i.ifRevision?{...o,ifRevision:i.ifRevision}:o],i);return s}async delete(e,t={}){El.get(this)?.check("delete");let i={kind:"file_delete",id:Gm(e)};typeof e=="object"&&"digest"in e&&(i.base=e.digest),t.ifRevision&&(i.ifRevision=t.ifRevision);let[o]=await this.client.submit([i],t);return o}}});async function ld(n,e,t,i,o={}){i?.throwIfAborted();let s=o.concurrency??8;if(!Number.isSafeInteger(s)||s<1||s>Xm)throw A("invalid_request","readMany concurrency must be 1..16","read_many_bounds");if(!Array.isArray(e)||e.length>Jm)throw A("invalid_request","readMany accepts at most 1000 record selections","read_many_bounds");let r=Array.from(e,xO),a=t?Object.freeze({...t}):void 0,p=new Array(r.length),l=0,c=!1,d;async function u(){for(;!c&&l<r.length;)try{i?.throwIfAborted();let f=l++,h=r[f],m=await n.get(h,a,i);if(i?.throwIfAborted(),c)return;if(typeof h=="string"&&m.id!==h)throw A("invalid_request","readMany readback belongs to another UUID","read_many_identity_mismatch");p[f]=m}catch(f){c||(c=!0,d=f);return}}if(await Promise.all(Array.from({length:Math.min(s,r.length)},()=>u())),c)throw d;return i?.throwIfAborted(),p}function xO(n){if(typeof n=="string")return T.dec(T.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 T.dec(T.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 cd(n,e,t,i,o={}){return n.pages(e,t,i,o)}async function O_(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,p=e?.field,l=k=>typeof k=="string"&&k.length>0&&k.length<=4096&&new TextEncoder().encode(k).byteLength<=4096;if(!l(a)||!l(p))throw A("invalid_request","record link path/field must be nonempty and bounded","record_links_bounds");let c=JSON.stringify(p),d=`(${c} in raw ? raw[${c}] : 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}]},void 0,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 b=h.records[0].values;if(b===void 0)throw A("upgrade_required","native record link projection unsupported","record_links_unsupported");if(!(b instanceof Map)||b.size!==2||!b.has("raw")||!b.has("paths"))throw m();let w=b.get("raw"),g=b.get("paths"),y=w===null?[]:typeof w=="string"?[w]:w;if(!Array.isArray(y)||!Array.isArray(g)||y.length!==g.length||y.length>1e3)throw m();let v=0,_=[];for(let k=0;k<y.length;k++){let S=y[k],x=g[k];if(typeof S!="string"||S.length>(1<<20)-v||x!==null&&!l(x)||(v+=new TextEncoder().encode(S).byteLength+(x===null?0:new TextEncoder().encode(x).byteLength),v>1<<20))throw m();_.push(Object.freeze({raw:S,path:x}))}return r(),Object.freeze(_)}var Jm,Xm,Zm=I(()=>{"use strict";ge();ie();Jm=1e3,Xm=16});function As(n,e){if((n.document?.length??0)>Tl||(n.body?.length??0)>Tl)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"||si(n.document)!==n.revision)throw A("invalid_request","record session needs actual complete, revision-consistent source and identity","record_witness_required")}function bo(n){return n.state.hold!==void 0||n.state.unresolved!==void 0&&n.state.unresolved!==0}function wo(n){return n.state.state==="confirmed"&&!bo(n)}function Tt(n){return Mn.dec(ue(pe(Mn.enc(n))))}function Ll(n){return n instanceof se?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 cn(n,e,t){return new se({code:n,message:e,reason:t,recovery:n==="conflict"?"resolve_conflict":n==="outcome_unknown"?"resolve_outcome":"retry"})}function Qm(n){return pe(Mn.enc(n)).byteLength*2}function ey(n){if(n.length>Tl)throw A("invalid_request","record session draft exceeds retained budget","record_session_budget");return new TextEncoder().encode(n).byteLength*2}function jl(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 Ml,Tl,ty=I(()=>{"use strict";Je();ie();Oi();At();Ml={body:!0,document:!0,effective:!0},Tl=8*1024*1024});function Nl(n){return wo(n)?"saved":"saved_on_device"}function R_(n,e){let t=pe(n),i=pe(e);return t.length===i.length&&t.every((o,s)=>o===i[s])}function CO(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 IO(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 pd,E_=I(()=>{"use strict";Je();ie();Oi();At();ty();pd=class{constructor(e,t,i){this.client=e;this.reserve=i;As(t),this.base=Tt(t),this.body=t.body,this.state=bo(t)?"conflict":Nl(t),this.publish()}client;reserve;base;body;patch=new Map;remote=null;captured=null;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;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}}}e?.throwIfAborted(),this.captured&&(this.state="recovery",this.why=cn("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 retained(){return this.dirty||this.captured!==null||!wo(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.defaultTimeout=jl(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:ue(pe(ut(o))),r=this.base.frontmatter.get(i);!this.captured?.patch.has(i)&&(s===void 0&&r===void 0||s!==void 0&&r!==void 0&&R_(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":Nl(this.base),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){let a=Qm(i)+ey(e)+pe(new Map([...t].map(([p,l])=>[p,l??null]))).byteLength*2;o&&(a+=Qm(o)),r&&(a+=ey(r.body)+pe(new Map([...r.patch].map(([p,l])=>[p,l??null]))).byteLength*2),s&&(a+=pe(kt.enc(s)).byteLength*2),this.reserve(a)}publish(){this.charge();let e=new Map(this.base.frontmatter);for(let[t,i]of this.patch)i===void 0?e.delete(t):e.set(t,i);this.snapshot=Object.freeze({state:this.state,body:this.body,frontmatter:ue(pe(e)),record:Tt(this.base),remote:this.remote?Tt(this.remote):null,dirty:this.dirty,problem:this.why,lastReceipt:this.lastReceipt?kt.dec(ue(pe(kt.enc(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,Ml,e);return e.throwIfAborted(),As(t,this.id),t}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;try{let t=await this.read(e);if(this.captured||this.running){this.captured&&!this.running&&this.start(!1,{}).catch(()=>{});continue}this.charge(this.body,this.patch,this.base,t),this.dirty?(t.revision!==this.base.revision||bo(t))&&(this.remote=Tt(t),this.state="conflict",this.why=cn("conflict","record changed while this draft was open","record_session_conflict").toProblem()):(this.base=Tt(t),this.body=t.body,this.remote=null,this.state=bo(t)?"conflict":Nl(t),this.why=null),this.publish()}catch(t){if(e.aborted)return;this.why=Ll(t),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=jl(t.timeoutMs??this.defaultTimeout),o=CO(i),s=AbortSignal.any([...t.signal?[t.signal]:[],o.signal]),r=this.running;if(r&&(this.writing||!e))return IO(r,s).finally(o.clear);let a=AbortSignal.any([this.life.signal,s]),p={until:Date.now()+i,margin:Math.min(2e3,Math.floor(i/4))},l=()=>this.drive(a,p,e),c=(r?r.then(l,l):l()).finally(()=>{o.clear(),this.running===c&&(this.running=null,this.writing=!1,this.schedule())});return this.running=c,this.writing=e,c}async drive(e,t,i){try{for(;;){if(e.throwIfAborted(),this.captured){await this.settle(e,t);continue}if(!i)return wo(this.base)?{ok:!0,record:Tt(this.base)}:{ok:!0,record:Tt(this.base),saved:"on_device"};let o=await this.read(e);if(bo(o))throw this.charge(this.body,this.patch,this.base,o),this.remote=Tt(o),cn("conflict","native hold/unresolved edits require native resolution before saving","native_protection_resolution_required");if(this.state==="deleted")throw cn("conflict","the original record was deleted","record_deleted");if(!this.dirty)return this.charge(o.body,this.patch,o,null),this.base=Tt(o),this.body=o.body,this.remote=null,this.state=Nl(o),this.why=null,this.publish(),wo(o)?{ok:!0,record:Tt(o)}:{ok:!0,record:Tt(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=Tt(o),cn("conflict","explicitly resolve the current native revision before saving","record_session_conflict");As(this.base,this.id),this.base=Tt(o);let s=this.body,r=new Map(this.patch),a=Ln(),p={bound:!0,body:s,patch:r,recovery:{mutationId:a,recordId:this.id,baseRevision:this.base.revision,receipt:null,write:null}};this.charge(this.body,this.patch,this.base,this.remote,this.lastReceipt,p),this.captured=p,this.state="saving",this.why=null,this.publish();let l={ifRevision:this.base.revision};s!==this.base.body&&(l.body=s);let c=new Map,d=[];for(let[f,h]of r)h===void 0?d.push(f):c.set(f,h);c.size&&(l.patch=c),d.length&&(l.unset=d);let u=await this.client.update(Tt(this.base),l,{mutationId:a,include:Ml,conflictMode:"reject",signal:e});if(e.throwIfAborted(),u.mutationId!==a)throw cn("outcome_unknown","native write changed its original mutation identity","mutation_identity_mismatch");this.captured.recovery={...this.captured.recovery,write:u,receipt:u.receipt},this.publish()}}catch(o){return this.why=Ll(o),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,Math.max(1,t.until-Date.now()-t.margin),e);if(e.throwIfAborted(),s.mutation!==o.mutationId)throw cn("outcome_unknown","native receipt belongs to another mutation","mutation_identity_mismatch");let r=s.records?.some(c=>c.id===o.recordId)??!1;if(s.records?.length&&!r||!i.bound&&s.state==="confirmed"&&!r)throw cn("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 cn("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 se(s.problem):cn("conflict","original mutation conflicted","record_session_conflict");let a=await this.read(e);if(s.state==="pending"?bo(a):!wo(a))throw cn("outcome_unknown","confirmed receipt has pending/protected current readback","unqualified_readback");this.charge(this.body,this.patch,a,null);let l=this.body===i.body;for(let[c,d]of i.patch){let u=this.patch.get(c);this.patch.has(c)&&(d===void 0?u===void 0:u!==void 0&&R_(d,u))&&this.patch.delete(c)}this.base=Tt(a),l&&(this.body=a.body),this.captured=null,this.remote=null,this.state=this.dirty?"unsaved":Nl(a),this.why=null,this.publish()}resolve=e=>{if(this.ensure(),this.captured||this.running)throw cn("outcome_unknown","recover the original mutation before resolving or preparing another","record_recovery_required");let t=this.remote;if(!t||!wo(t))throw cn("conflict","a confirmed unprotected native record is required for resolution","native_protection_resolution_required");let i="body"in e?e.body:e.keep==="theirs"?t.body:this.body,o="keep"in e&&e.keep==="theirs"?new Map:this.patch;this.charge(i,o,t,null),this.base=Tt(t),this.body=i,this.patch=o,this.remote=null,this.state=this.dirty?"unsaved":"saved",this.why=null,this.publish(),this.schedule()}}});var dd,q_=I(()=>{"use strict";ie();ge();E_();ty();dd=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:T.dec(T.enc(i.recovery.mutationId)),recordId:T.dec(T.enc(i.recovery.recordId))},i.recovery.baseRevision!==null&&H.enc(i.recovery.baseRevision)),jl(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,Ml,t.signal);if(t.signal?.throwIfAborted(),this.closed)throw A("unavailable","record sessions client closed");As(i);let o=typeof e=="string"?e:"id"in e?e.id:void 0,s=o===void 0?void 0:T.dec(T.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]),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 autosave 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 pd(this.client,i,m=>{let b=this.bytes-h.bytes+m;if(b>Tl)throw A("invalid_request","record session retained data exceeds 8MiB","record_session_budget");this.bytes=b,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 p=a,l=!1,c=new Set,d=()=>{if(l)throw A("cancelled","record lease released")},u=Object.freeze({getSnapshot:p.session.getSnapshot,subscribe:h=>{d();let m=p.session.subscribe(h);return c.add(m),()=>{c.delete(m),m()}},setBody:h=>{d(),p.session.setBody(h)},patchFrontmatter:h=>{d(),p.session.patchFrontmatter(h)},resolve:h=>{d(),p.session.resolve(h)},flush:h=>(d(),p.session.flush(h))}),f=()=>{if(!l){l=!0,t.signal?.removeEventListener("abort",f);for(let h of c)h();c.clear(),--p.leases===0&&(p.session.suspend(),p.session.retained||(this.bytes-=p.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()),p.session.refresh(),Object.freeze({session:u,release:f})}startWatch(){if(this.watch)return;let e=this.client.watchChanges(void 0,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(Ll(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 OO(n,e){let t=li(n.get("properties")),i=[],o=Array.isArray(e.get("select"))?e.get("select"):[];for(let s of o){let r=li(s),a=Jt(s),p=r?Jt(r.get("name")):a?.slice(a.lastIndexOf(".")+1);if(!p)continue;let l=li(t?.get(r||!a?p:a))??li(t?.get(p)),c={key:p},d=Jt(r?.get("label"))??Jt(l?.get("label")),u=Jt(r?.get("description"))??Jt(l?.get("description")),f=Jt(l?.get("format")),h=l?.get("hidden");d!==void 0&&(c.label=d),u!==void 0&&(c.description=u),f!==void 0&&(c.format=f),typeof h=="boolean"&&(c.hidden=h),i.push(c)}return i}async function j_(n,e,t){let i=[],o=[],s=e?e.replace(/\/?$/,"/"):"",r,a=!0;do{let p;try{p=await n.queryContract(Ul,{...r?{cursor:r}:{},...t?{signal:t}:{}})}catch(l){if(oe(l,"not_found")&&l.reason==="data_contract_not_found")return{sources:i,diagnostics:o,complete:!0};throw l}a&&=p.page.complete,p.records.forEach((l,c)=>{let d=p.page.records[c];if(!d.path.startsWith(s))return;let u=l.implementations[0],f=u?.issues.find(w=>w.severity==="error");if(!u||f){o.push(T_("invalid_view",f?.message??"View record does not implement mdbase.view.",d.path));return}let h=u.fields,m=[],b=new Set;for(let w of Array.isArray(h.get("views"))?h.get("views"):[]){let g=li(w),y=Jt(g?.get("id")),v=Jt(g?.get("name"));if(!g||!y||!v)continue;if(b.has(y)){o.push(T_("invalid_view","View record contains duplicate named-view IDs.",d.path));return}b.add(y);let _={id:y,name:v,properties:OO(h,g)};g.has("presentation")&&(_.presentation=g.get("presentation")),m.push(_)}i.push({record:d.id,id:Jt(h.get("id"))??d.path,name:Jt(h.get("name"))??d.path,source:{path:d.path,format:Ul.id,revision:d.revision,writable:!0},views:m})}),r=p.page.cursor}while(r);return i.sort((p,l)=>p.source.path<l.source.path?-1:p.source.path>l.source.path?1:0),{sources:i,diagnostics:o,complete:a}}async function N_(n,e,t,i={}){let o=i.signal,s=await n.getContract(e,Ul,o).catch(v=>M_(v,L_(e))),r=s.fields,a=s.path,p=Array.isArray(r.get("views"))?r.get("views").map(li):[],l=p.map(v=>Jt(v?.get("id")));if(new Set(l).size!==l.length)throw A("invalid_request","View record contains duplicate named-view IDs.","invalid_view");let c=p[l.indexOf(t)];if(!c)throw A("not_found",`named view '${t}' was not found`,"view_not_found");let d=li(r.get("query"))??new Map,u=new Map,f=c.get("types")??d.get("types");f!==void 0&&u.set("types",f);let h=[Jt(d.get("where")),Jt(c.get("where"))].filter(v=>!!v);h.length&&u.set("where",h.length===2?`(${h[0]}) && (${h[1]})`:h[0]);let m=new Map(li(d.get("projections")));for(let[v,_]of li(c.get("projections"))??[]){let k=m.get(v);if(k!==void 0&&ud(k)!==ud(_))throw A("invalid_request",`Projection '${v}' has conflicting definitions.`,"invalid_view");m.set(v,_)}m.size&&u.set("projections",m);for(let v of["select","order_by","group_by","summaries","limit","offset","include_body","frontmatter_mode"])c.has(v)&&u.set(v,c.get(v));r.has("summary_functions")&&u.set("summary_functions",r.get("summary_functions")),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=li(li(c.get("context")??d.get("context"))?.get("this")),w=Jt(b?.get("on_missing"))??"view",g=i.context;if(g===void 0&&w==="error")throw A("invalid_request","This named view requires an invocation context.","context_required");if(g===void 0&&w==="view"&&(g={path:a}),g!==void 0){let v=Array.isArray(b?.get("types"))?b.get("types").filter(k=>typeof k=="string"):[],_=typeof g=="string"?void 0:g.path;if(v.length||_===void 0){let k=await n.get(g,void 0,o);if(_=k.path,v.length&&!k.types.some(S=>v.some(x=>x.toLowerCase()===S.toLowerCase())))throw A("invalid_request","The invocation context does not match an allowed context type.","context_type_mismatch")}u.set("context",new Map([["this",new Map([["path",_]])]]))}return{...await n.query(u,i.include,o),view:{path:a,view:t}}}async function U_(n,e,t){let i=await n.getContract(e,Ul,t).catch(s=>M_(s,L_(e))),o=await n.get(i.id,{document:!0},t);if(o.revision!==i.revision||typeof o.document!="string")throw A("unavailable","saved view source changed while it was read","view_source_changed");return{path:o.path,format:Ul.id,revision:o.revision,document:o.document,record:o.id}}function ud(n){return n instanceof Map?`{${[...n].map(([e,t])=>[JSON.stringify(String(e)),ud(t)]).sort((e,t)=>e[0]<t[0]?-1:1).map(([e,t])=>`${e}:${t}`).join(",")}}`:Array.isArray(n)?`[${n.map(ud).join(",")}]`:typeof n=="bigint"?`${n}n`:JSON.stringify(n instanceof Uint8Array?[...n]:n)}var Ul,li,Jt,T_,M_,L_,D_=I(()=>{"use strict";ie();Ul=Object.freeze({id:"mdbase.view",version:"1.0.0"}),li=n=>n instanceof Map?n:void 0,Jt=n=>typeof n=="string"?n:void 0,T_=(n,e,t)=>({code:n,severity:"warning",message:e,details:new Map([["path",t]])}),M_=(n,e)=>{throw oe(n,"not_found")?A("not_found",`saved view source '${e}' was not found`,"view_not_found"):n},L_=n=>typeof n=="string"?n:n.path});function ir(n){return A("invalid_request",n,"view_source_witness_required")}function ny(n){try{T.enc(n)}catch{throw ir("view source writes need their original record and mutation UUIDs")}}function $_(n){if(!n||typeof n.path!="string"||n.path.length===0||typeof n.document!="string")throw ir("view source update needs the complete RecordView read with document included");ny(n.id);try{H.enc(n.revision)}catch{throw ir("view source needs its original source revision")}if(si(n.document)!==n.revision)throw ir("view source document differs from its captured revision")}function z_(n){return ny(n?.mutationId),{...n,include:{...n.include,document:!0}}}async function fd(n,e,t={}){let i=typeof e=="string"?e:"id"in e?e.id:void 0,o=i===void 0?void 0:T.dec(T.enc(i)),s=await n.get(e,{...t.include,document:!0},t.signal);if($_(s),o!==void 0&&s.id!==o)throw ir("view source readback belongs to another record");return s}function hd(n,e,t){if(ny(e?.id),typeof e.path!="string"||e.path.length===0||typeof e.document!="string")throw ir("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,z_(t))}function md(n,e,t,i){$_(e);let o=e.state;if(!o||o.state!=="pending"&&o.state!=="confirmed"||!Number.isSafeInteger(o.confirmedSeq)||o.confirmedSeq<0)throw ir("view source update needs actual native record state, not inferred confirmation");if(o.hold!==void 0||o.unresolved!==void 0&&o.unresolved!==0)throw ir("resolve the original view source hold or unresolved mutation before replacing its document");if(typeof t!="string")throw ir("view source update needs complete source text");return n.replaceDocument(e,t,{...z_(i),ifRevision:e.revision})}var iy=I(()=>{"use strict";ge();ie();Oi()});var B_,F_,V_=I(()=>{"use strict";ge();At();B_=N("contract-record-v1",[[0,"version",B],[1,"id",T],[2,"path",R],[3,"revision",H],[4,"type",R],[5,"fields",_n],[6,"contractDigest",H],[7,"implementationDigest",H]]),F_=N("contract-write-plan-v1",[[0,"version",B],[1,"type",R],[2,"patch",_n],[3,"unset",F(R)],[4,"base",F(Np)],[5,"contractDigest",H],[6,"implementationDigest",H],[7,"id",T,"opt"],[8,"path",R,"opt"],[9,"revision",H,"opt"]])});var K_,W_=I(()=>{"use strict";ge();At();K_=N("contract-query-v1",[[0,"version",B],[1,"page",_l],[2,"records",F(N("contract-query-record",[[0,"id",T],[1,"implementations",F(N("contract-projection",[[0,"typeName",R],[1,"fields",_n],[2,"issues",F(Zi)]]))]]))],[3,"contractDigest",H]])});var yd,H_=I(()=>{"use strict";yd=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}}});var G_,RO,ks,ry=I(()=>{"use strict";ge();ie();Oi();At();G_=4096,RO=100,ks=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,T.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=Bp.dec(t);for(let o of this.watchers.get(i.record)??[])o(i.peers)}catch{}}))}params(e,t){return new Map([[0,T.enc(e)],[1,t]])}check(e){if(JSON.stringify(e,(i,o)=>typeof o=="bigint"?o.toString():o instanceof Map?[...o]:o).length>G_)throw A("too_large","presence state over 4 KiB",{details:new Map([["limit",G_]])})}async join(e,t){let i=ut(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=ut(t),this.check(i.state),i.timer)return;let o=Math.max(0,i.last+RO-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,T.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,T.enc(e)]])))).catch(()=>{}),()=>{i.delete(t),i.size===0&&this.watchers.delete(e)}}}});function Y_(n){try{let e=ue(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:ri(t),seq:i}}catch{return null}}function qO(n){return n.replace(/-/g,"").toLowerCase()}function J_(n,e,t){if(!t)return;let i=Y_(e);if(!i||qO(t)!==i.device)return;let o=oy.get(n);o||oy.set(n,o=new Map);let s=o.get(i.device);if(!s){if(o.size>=EO)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 X_(n,e){let t=e?Y_(e)?.device:void 0,i=[];for(let[o,s]of oy.get(n)??[])if(o!==t)for(let[,r]of s.values())i.push(r);return i}var EO,oy,Z_=I(()=>{"use strict";Je();EO=64,oy=new Map});function gd(n){return Q_.add(n),n}function sy(n){return Q_.has(n)}var Q_,bd=I(()=>{"use strict";Q_=new WeakSet});function pn(n,e){return e===void 0?{}:{[n]:e}}function ay(n){let e=vo(n);return{id:Ke(e.id),version:Ke(e.version),digest:Ke(e.digest),installedBy:Ke(e.installed_by),resources:(Array.isArray(e.resources)?e.resources:[]).map(t=>{let i=vo(t);return{source:Ke(i.source),target:Ke(i.target),kind:Ke(i.kind),mode:Ke(i.mode),digest:Ke(i.digest),...pn("originDigest",Ke(i.origin_digest))}})}}function jO(n){let e=vo(n),t=e.upgrade_baseline===void 0?void 0:vo(e.upgrade_baseline),i=t&&(typeof t.version=="number"?t.version:typeof t.version=="string"?Number(t.version):void 0);return{source:Ke(e.source)??"",target:Ke(e.target),kind:Ke(e.kind),mode:Ke(e.mode),action:Ke(e.action),...pn("digest",Ke(e.digest)),...pn("currentDigest",Ke(e.current_digest)),...pn("installedDigest",Ke(e.installed_digest)),...pn("adoptedFromDigest",Ke(e.adopted_from_digest)),...pn("upgradeBaseline",t&&{digest:Ke(t.digest),...pn("version",i)}),...pn("reason",Ke(e.reason))}}function NO(n,e){return e?`${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 tA(n,e,t){let i=vo(bs(n)),o=(Array.isArray(i.resources)?i.resources:[]).map(jO),s=Object.fromEntries(LO.map(f=>[f,o.filter(h=>h.action===f).map(h=>h.target)])),r={},a=o.filter(f=>f.action==="conflict").map(f=>{let h=f.mode==="managed"&&f.currentDigest!==void 0&&f.installedDigest===void 0;return h&&(r[f.target]=f.currentDigest),{target:f.target,kind:f.kind,...pn("reason",f.reason),message:NO(f,h),...pn("adoptable",h?{digest:f.currentDigest}:void 0)}}),p=Ke(i.status),l=Array.isArray(i.issues)?i.issues.map(vo):[],c=ay(i.desired),d;if(i.definitions_manage!==!0)d={code:"forbidden",message:"This app doesn't have permission to change the collection's types."};else if(p==="downgrade"){let f=i.current===void 0?"a newer version":`version ${ay(i.current).version}`;d={code:"type_pack_downgrade",message:`${c.id} ${f} is installed; ${c.version} is older.`}}else if(a.length){let f=a.length;d={code:"type_pack_conflict",message:Object.keys(r).length===f?`${f===1?"A type already exists":`${f} types already exist`} with different content. Review and adopt ${f===1?"it":"them"} to continue.`:a.map(h=>h.message).join(" ")}}else(l.length||i.applicable!==!0)&&(d={code:"invalid_type_pack",message:`This pack would leave the collection invalid: ${Ke(l[0]?.message)??"the staged types do not validate"}.`});let u=vo(i.lock);return Object.freeze({status:p,canApply:i.applicable===!0&&d===void 0,digest:Ke(i.assessment_digest),summary:s,conflicts:a,adoptable:r,resources:o,...pn("current",i.current===void 0?void 0:ay(i.current)),desired:c,lock:{target:Ke(u.target),action:Ke(u.action),digest:Ke(u.digest)},...pn("refusal",d),pack:e,options:t})}function eA(n){return n&&Object.keys(n).length?ut(n):void 0}function UO(n){return n==null?!1:Array.isArray(n)?n.length>0:typeof n=="object"&&Object.keys(n).length>0}async function nA(n,e,t,i){if(UO(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",ut(e.manifest)],["resources",e.resources.map(p=>new Map([["source",p.source],["document",p.document]]))]]);e.provides!==void 0&&o.set("provides",ut(e.provides));let s=new Map([[0,1],[1,o],[2,t.installedBy]]),r=eA(t.adopt);r!==void 0&&s.set(3,r),t.preserveSeedTargets?.length&&s.set(4,[...t.preserveSeedTargets]);let a=eA(t.targetOverrides);a!==void 0&&s.set(5,a),t.allowDowngrade&&s.set(6,!0),i!==void 0&&s.set(7,H.enc(i));try{let p=await n.call("plan_type_pack_v1",s,{codec:MO,retry:!0,...t.signal?{signal:t.signal}:{}});if(p.version!==1)throw A("upgrade_required","unsupported type pack plan","type_packs_unsupported");return p}catch(p){throw oe(p,"invalid_request")&&p.reason==="unknown_method"?A("upgrade_required","This collection's replica can't install type packs yet.","type_packs_unsupported"):p}}async function iA(n,e,t){return tA((await nA(n,e,t)).assessment,e,t)}async function rA(n,e,t={}){if(e.refusal)throw A(DO[e.refusal.code],e.refusal.message,e.refusal.code);let i=t.signal?{...e.options,signal:t.signal}:e.options,o=await nA(n,e.pack,i,e.digest),s=tA(o.assessment,e.pack,e.options),r=o.writes??[];if(!r.length)return{outcome:"already_current",receipt:s.desired};let a=r.map(c=>c.doc===void 0?{kind:"resource_delete",path:c.path,...pn("baseRevision",c.baseRevision)}:{kind:"resource_put",path:c.path,doc:c.doc,...pn("baseRevision",c.baseRevision),...c.mustNotExist?{mustNotExist:!0}:{}}),p=(await n.submit(a,{...t,allowPartial:!1}))[0],l=p.receipt;if(l.state==="rejected"||l.state==="unknown")throw new se(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:p};if(l.status==="conflicted"||(l.conflicts?.length??0)>0)throw new se({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:p}}var TO,MO,LO,vo,Ke,DO,oA=I(()=>{"use strict";ge();ie();Oi();TO=N("type-pack-write-v1",[[0,"path",R],[1,"doc",R,"opt"],[2,"baseRevision",H,"opt"],[3,"mustNotExist",Oe]]),MO=N("type-pack-plan-v1",[[0,"version",B],[1,"assessment",at],[2,"writes",F(TO),"opt"]]),LO=["create","update","delete","adopt","unchanged","preserve","conflict"],vo=n=>n&&typeof n=="object"&&!Array.isArray(n)?n:{},Ke=n=>typeof n=="string"?n:void 0;DO={forbidden:"forbidden",type_pack_conflict:"conflict",type_pack_downgrade:"conflict",invalid_type_pack:"invalid_request",type_pack_contract_setups_unsupported:"invalid_request"}});function fA(n){return/^\d{6}$/.test(n)?`${n.slice(0,3)} ${n.slice(3)}`:n}var ly,sA,$O,aA,cA,lA,pA,dA,uA,cy,zO,hA,py=I(()=>{"use strict";ge();At();ly=["desktop","mobile","app_runtime","cli","hosted","escrow","recovery"],sA=Pe("device-kind",ly),$O={name:"device-kind",enc:n=>sA.enc(n),dec:n=>{try{return sA.dec(n)}catch{return"unknown"}}},aA=N("pending-device",[[0,"device",T],[1,"account",T],[2,"kind",$O],[3,"sas",R,"opt"],[4,"exchangeReady",Oe]]),cA={...aA,enc:n=>aA.enc({...n,sas:void 0})},lA=N("approval-readiness",[[0,"device",T],[1,"sas",R,"opt"],[2,"exchangeReady",Oe]]),pA={...lA,enc:n=>lA.enc({...n,sas:void 0})},dA=N("recovery-key-status",[[0,"configured",Oe],[1,"device",T,"opt"]]),uA=N("recovery-key-created",[[0,"phrase",R],[1,"device",T]]);cy=["idle","reading_ahead","pending_grant","keyed","refused"],zO=Pe("account-key-state",cy),hA=N("account-key-status",[[0,"state",zO],[1,"problem",An,"opt"]])});function vd(){let n=new Map;return{list:async()=>[...n.values()],put:async e=>{n.set(e.mutationId,e)},remove:async e=>{n.delete(e)}}}var dy,Dl,wd,uy=I(()=>{"use strict";ie();dy=n=>[...new Set(n.flatMap(e=>{let t=e,i=t.id??t.record;return typeof i=="string"?[i]:[]}))],Dl=(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},wd=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 Promise.all(e.map((i,o)=>this.set(Dl(i,dy(e.length===1?t:[t[o]]),"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(Dl(e.mutation,i,"pending")):t?.state!=="rejected"&&this.set(Dl(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,Dl(o.receipt.mutation,dy(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,Dl(i.receipt.mutation,dy(i.ops),"pending")),t=!0);t&&this.changed()}settleAll(e){return Promise.all(e.map(t=>this.settle(t)))}async settle(e){try{this.observe(await this.native.receipt(e))}catch(t){oe(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 xd={};ls(xd,{LiveQuery:()=>Ss,MdbaseClient:()=>Ei,Write:()=>_o,connect:()=>my});function kd(n){return n instanceof yt?new yt(n.value):n instanceof Date?new Date(n):Array.isArray(n)?n.map(e=>kd(e)):n instanceof Map?new Map([...n].map(([e,t])=>[e,kd(t)])):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,kd(t)])):n}function _d(n){return typeof n=="string"?T.enc(n):"id"in n&&typeof n.id=="string"?T.enc(n.id):n.path}function Ad(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 Sd(n){return n?ds.enc(n):void 0}function mA(n){if(!(n instanceof Uint8Array)||n.length!==32)throw A("invalid_request","the account secret is 32 bytes","account_secret_length")}function Be(n){let e=new Map;for(let[t,i]of n)i!==void 0&&e.set(t,i);return e}function fy(n,e){let t=n.grant;return!e||t.grant===e.grant&&t.role===e.role&&Ir(t.capabilities,e.capabilities)&&Ir(t.fileFolders??null,e.fileFolders??null)?n:{...n,grant:e}}async function yA(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,yl(s)};return[i(0),i(16)]}function hy(n){return n.state==="pending"||n.state==="confirmed"&&n.published==="publishing"}function Pd(n,e){let t=e.published;return t==="published"||t==="not_published"||n.published===void 0&&t!==void 0?{...n,published:t}:n}function my(n){return Ei.connect(n)}var _o,Ss,BO,Ei,Ps=I(()=>{"use strict";Je();Vm();c_();ge();m_();ie();ql();Zm();q_();D_();iy();V_();W_();H_();ry();Z_();Rl();bd();oA();Oi();py();At();uy();At();_o=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;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=Pd(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 se(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)}}},Ss=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 yd;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=this.include){this.query=e,this.include=t,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 Be([[0,ut(this.query)],[1,Sd(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)}},BO=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"]),Ei=class n{constructor(e,t){this.opts=e;this.session=t,this.collectionId=t.hello.collection,this.lastStatus=t.hello.status,this.currentHello=fy(t.hello,t.hello.status.grant),this.fenceReads=sy(e.connector),this.readFloor=t.hello.status.confirmedThrough,this.files=new _s(this),this.presence=new ks(this),this.writeLedger=new wd(e.ledger??vd(),{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;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=sy(e.connector);t&&(e={...e});let i=e.reconnect&&e.reconnect.minDelayMs||1e3,o=e.signal,s,r,a,p=()=>e.signal?.aborted||!a?A("cancelled","connect aborted"):a;try{for(;;)try{let l=o,c=await new Promise((d,u)=>{let f=()=>u(p());if(l?.aborted){f();return}l?.addEventListener("abort",f,{once:!0}),go.open(e.connector,n.helloParams(e),l).then(h=>{if(l?.removeEventListener("abort",f),l?.aborted){try{h.close()}catch{}u(p())}else d(h)},h=>{l?.removeEventListener("abort",f),u(h)})});if(o?.aborted)throw c.close(),p();return new n(e,c)}catch(l){if(o?.aborted)throw p();let c=t&&oe(l,"unavailable")&&(l.reason==="grant_lease_expired"||l.reason==="authorization_unavailable");if(!(c||e.waitForDevice&&oe(l,"unavailable")&&l.reason==="no_device_online"))throw l;c&&!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(p())},m=setTimeout(()=>{f(),d()},c?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:sd,clientName:e.app.name,clientVersion:e.app.version,features:[...new Set([...e.features??[],"declared-collection-setup-v1","file-stream-failure-v1"])],...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(e);for(;;){let i=t?this.currentSession():await this.ready(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){for(;;){if(this.linkState==="closed")throw this.linkError??A("unavailable","client closed");if(this.session&&!this.session.closed)return this.session;if(e?.aborted)throw A("cancelled","aborted while reconnecting");await new Promise(t=>{this.reconnectWaiters.push(t),e?.addEventListener("abort",()=>t(),{once:!0})})}}async call(e,t,i={}){let o=i.codec,s=this.fenceReads&&BO.has(e);for(;;){let r=s?await this.readyForRead(i.signal,!i.retry):i.retry?await this.ready(i.signal):this.currentSession();try{let a=await r.request(e,t,{...i.signal?{signal:i.signal}:{},...o?{codec:o}:{}});if(s&&(r!==this.session||r.closed||this.closing)){if(i.retry&&!this.closing)continue;throw A("unavailable","the session changed during the read",{reason:"reconnecting"})}return r===this.session&&!r.closed&&!this.closing&&o===kt&&(e==="receipt"||e==="await")&&this.noteReceipt(a),a}catch(a){let p=oe(a,"unavailable")&&r.closed;if(!(i.retry&&p&&this.opts.reconnect!==!1&&!this.closing))throw a}}}onSession(e){this.restorers.push(e)}relayWitnesses(e){let t=e.hello.headWitness;t&&J_(this.collectionId,t,e.device);let i=X_(this.collectionId,t);i.length&&e.request("report_witnesses",Be([[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=jp.dec(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=kt.dec(t);this.session===e&&this.noteReceipt(i);let o=this.writes.get(i.mutation);if(o)o.update(i),hy(o.receipt)||this.writes.delete(i.mutation);else{let s=this.unclaimed.get(i.mutation);this.unclaimed.set(i.mutation,s?Pd(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(er.dec(t))}catch{}}),e.onPush("holds",t=>{try{this.emitHolds(F(vl).dec(t))}catch{}}),e.onPush("conflicts",t=>{try{this.emitConflicts(F(Al).dec(t))}catch{}}),e.onPush("closed",t=>{let i;try{i=new se(An.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 Rm.enc(await this.fenceHandler(Im.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 go.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=fy(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(oe(s)&&["unauthenticated","forbidden","upgrade_required"].includes(s.code)){this.setLink("closed",s);return}oe(s)&&this.setLink("reconnecting",s);let r=oe(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),hy(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:er,retry:!0});return this.setStatus(e),e}for(;;){let e=await this.ready(),t;try{t=await e.request("get_status",null,{codec:er})}catch(i){if(oe(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=pm.enc({seq:e}),o=await this.call("applied_prefix",i,{codec:dm,retry:!1,...t?{signal:t}:{}});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=fy(this.currentHello,e.grant);for(let t of[...this.statusListeners])t(e)}async describe(e={}){let t=e instanceof AbortSignal?{signal:e}:e,i=await this.call("describe",t.definitions?Be([[0,!0]]):null,{codec:Mm,retry:!0,...t.signal?{signal:t.signal}:{}});if(t.definitions&&(i.types.some(o=>o.definition===void 0)||i.contracts.some(o=>o.schemas===void 0)))throw A("upgrade_required","this replica does not describe definitions","describe_definitions_unsupported");return i}async createType(e,t={}){let{name:i,path:o}=await this.call("new_type_file",Be([[0,e]]),{codec:Tm,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,Sl)||!o(t,Pl)?Promise.reject(A("invalid_request","describe_typing: at most 64 types and 256 non-empty paths","typing_bounds")):this.call("describe_typing",Be([[0,[...e]],[1,[...t]]]),{codec:jm,retry:!0,...i?{signal:i}:{}}).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,i){return this.call("get",Be([[0,_d(e)],[1,Sd(t)]]),{codec:Mn,retry:!0,...i?{signal:i}:{}})}async getContract(e,t,i){let o=await this.contractCall("get_contract_v1",Be([[0,1],[1,_d(e)],[2,t.id],[3,t.version],[4,t.type]]),B_,i);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",Be([[0,1],[1,e.id],[2,e.version],[3,e.type],[4,t===void 0?void 0:_d(t)],[5,i],[6,o?.length?o:void 0],[7,r?!0:void 0]]),F_,s);if(a.version!==1)throw A("upgrade_required","unsupported contract write plan","contract_records_unsupported");return a}contractCall(e,t,i,o){return this.call(e,t,{codec:i,retry:!0,...o?{signal:o}:{}}).catch(s=>{throw oe(s,"invalid_request")&&s.reason==="unknown_method"?A("upgrade_required","this replica does not serve contract-scoped records","contract_records_unsupported"):s})}readMany(e,t,i,o={}){return ld(this,e,t,i,o)}async find(e,t,i){try{return await this.get(e,t,i)}catch(o){if(oe(o,"not_found"))return null;throw o}}query(e,t,i,o={}){return this.call("query",Be([[0,ut(e)],[1,Sd(t)],[2,o.contract]]),{codec:_l,retry:!0,...i?{signal:i}:{}})}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=Math.min(i,128),s=await this.call("query_contract_v1",Be([[0,1],[1,e.id],[2,e.version],[3,o],[4,t.cursor],[5,t.where]]),{codec:K_,retry:!0,...t.signal?{signal:t.signal}:{}});if(s.version!==1)throw A("upgrade_required","unsupported contract query result","contract_query_version");if(s.records.length!==s.page.records.length||s.records.some((r,a)=>r.id!==s.page.records[a]?.id))throw A("unavailable","invalid contract query record binding","contract_query_response");return s}backlinks(e,t={}){return this.call("backlinks",Be([[0,_d(e)],[1,Sd(t.include)],[2,t.limit],[3,t.cursor]]),{codec:qm,retry:!0,...t.signal?{signal:t.signal}:{}})}resources={get:(e,t)=>this.call("get_resource",Be([[0,e]]),{codec:Fp,retry:!0,...t?{signal:t}:{}}),list:(e={})=>this.call("list_resources",Be([[0,e.folder],[1,e.text],[2,e.cursor],[3,e.limit]]),{codec:Em,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.one({kind:"resource_put",path:e,doc:t,...i.baseRevision?{baseRevision:i.baseRevision}:{},...i.mustNotExist?{mustNotExist:!0}:{}},i),delete:(e,t={})=>this.one({kind:"resource_delete",path:e,...t.baseRevision?{baseRevision:t.baseRevision}:{}},t)};typePacks=Object.freeze({plan:(e,t)=>iA(this,e,t),apply:(e,t)=>rA(this,e,t)});recordSessions=new dd(this);records=Object.freeze({open:(e,t)=>this.recordSessions.open(e,t)});views={createSource:(e,t)=>hd(this,e,t),updateSource:(e,t,i)=>md(this,e,t,i),getSourceRecord:(e,t={})=>fd(this,e,t),list:(e,t)=>j_(this,e,t),execute:(e,t,i={})=>N_(this,e,t,i),readSource:(e,t)=>U_(this,e,t)};async pendingWrites(e){let t=[],i;for(;;){let o=await this.call("list_pending",Be([[0,i?T.enc(i):void 0]]),{codec:Lm,retry:!0,...e?{signal:e}:{}});if(t.push(...o.pending),!o.next)return t;i=o.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:Ad(e)})}async preflight(e){let[t]=await this.submit([e],{dryRun:!0}),i=t.receipt;if(i.state==="rejected")throw new se(i.problem);return i.preflight??{rewrites:[],broken:[]}}async*pages(e,t,i,o={}){let s=kd(e),r=t?{...t}:void 0,a=s.cursor,p=!1,l=0;for(delete s.cursor;;){i?.throwIfAborted();let c;try{c=await this.query(a!==void 0?{...s,cursor:a}:{...s},r,i)}catch(d){if(!o.onReset||p||!oe(d,"invalid_request")||d.recovery!=="fix_request"||d.reason!=="cursor_expired"&&d.reason!=="cursor_stale")throw d;i?.throwIfAborted(),await o.onReset({reason:d.reason,error:d,pagesYielded:l,...i?{signal:i}:{}}),i?.throwIfAborted(),p=!0,a=void 0,l=0;continue}if(i?.throwIfAborted(),c.hasMore&&!c.cursor)throw A("invalid_request","Query requires offset paging","query_cursor_required");if(yield c,l++,!c.cursor)return;a=c.cursor}}queryPages(e,t,i,o={}){return cd(this,e,t,i,o)}live(e,t){let i=new Ss(this,e,t);return this.lives.add(i),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",Be([[0,o]])).catch(()=>{}));try{let s=await this.readyForRead();if(this.fenceReads&&(e.closed||i&&i!==s))return;this.subscribing++;let r;try{let p=await s.request("subscribe",e._params());r=B.dec(p.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",Be([[0,r]])).catch(()=>{});return}e._setSub(r),this.livesBySub.set(r,e);for(let p of a)e._apply(p)}catch(s){let r=Nn(s,"subscribe");oe(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",Be([[0,t]])).catch(()=>{}))}changes(e,t,i){return this.call("changes",Be([[0,e??null],[1,t]]),{codec:us,retry:!0,...i?{signal:i}:{}})}watchChanges(e,t){let i=e,o=!1,s=0,r="starting",a=null,p=null,l=null,c=null,d=null,u=()=>{},f,h,m=new Promise((C,E)=>{f=C,h=E});m.catch(()=>{});let b=new Set,w=C=>{try{C(r,a)}catch{}},g=(C,E=null)=>{r=C,a=E;for(let O of[...b])w(O)},y=()=>{c?.(),c=null,d?.(),d=null;let C=l;l=null,u(),u=()=>{},C?.abort(),p=null},v=()=>{this.restorers=this.restorers.filter(C=>C!==S),x()},_=C=>{o||(o=!0,s++,y(),v(),h(C),g("failed",C),b.clear())},k=()=>{r!=="closed"&&(o=!0,s++,y(),v(),h(A("cancelled","change watch closed")),g("closed"),b.clear())},S=async C=>{if(o||C.closed||C!==this.session||p===C)return;s++,y(),p=C;let E=s,O=()=>!o&&E===s&&!C.closed&&C===this.session;l=new AbortController;let L=l.signal;try{await this.readFence(L)}catch(G){O()&&_(Nn(G,"changes watch"));return}if(!O())return;let z=!0,Q=[],V=0;u=()=>{Q.length=0,V=0};let te=G=>{if(O()){i=G.cursor;try{t(G)}catch{}}};if(d=C.onClose(G=>{if(o||E!==s)return;s++,y();let K=G??A("unavailable","change watch session closed");h(K),g("stale",K)}),c=C.onPush("changes",G=>{if(O())try{let K=us.dec(G);if(!z){te(K);return}let X=64+K.cursor.length*2+K.changes.reduce((Y,ee)=>Y+384+ee.path.length*2,0);if(Q.length>=16||V+X>1024*1024){_(A("unavailable","change watch startup buffer exceeded"));return}V+=X,Q.push(K)}catch(K){_(Nn(K,"changes push"))}}),g("starting"),!!O())try{let G=await C.request("changes",Be([[0,i??null],[2,!0]]),{codec:us,signal:L});if(!O())return;for(i=G.cursor,(G.changes.length||G.reset)&&te(G);Q.length&&O();)te(Q.shift());if(u(),z=!1,!O())return;g("active"),O()&&f()}catch(G){O()&&_(Nn(G,"changes watch"))}},x=this.onLink((C,E)=>{C==="closed"&&(E?_(E):k())});this.onSession(S),this.ready().then(S).catch(C=>_(Nn(C,"changes watch")));let P=Object.assign(k,{ready:m,subscribe:C=>(r!=="closed"&&r!=="failed"&&b.add(C),w(C),()=>{b.delete(C)})});return Object.defineProperties(P,{state:{get:()=>r},error:{get:()=>a}}),Object.freeze(P)}async validate(e,t){t?.throwIfAborted();let{targets:i,expected:o}=f_(e),s=await this.call("validate",Be([[0,i]]),{codec:u_,retry:!0,...t?{signal:t}:{}});return t?.throwIfAborted(),h_(s,o)}async executeAppBases(e,t){let i=e.window===void 0?null:{...e.window},o=Xp({...e,...i===null?{}:{window:i}}),s=await this.readyForRead(t),r=await s.readAppBases(o,t);if(s!==this.session||s.closed||this.readFencedAt!==null)throw A("unavailable","original Bases session is no longer current");try{return Zp(r,i)}catch(a){throw Nn(a,"app Bases result")}}executeAppBasesPages(e,t={}){return l_((i,o)=>this.executeAppBases(i,o),e,t)}async listAppBasesViews(e,t){let i=e.limit,o=Qp(e),s=await this.readyForRead(t),r=await s.readAppBasesDiscovery("list-views",o,t);try{if(s!==this.session||s.closed||this.readFencedAt!==null)throw A("unavailable","original Bases session is no longer current");return td(r,i)}catch(a){throw Nn(a,"app Bases discovery")}finally{r.fill(0)}}async readAppBasesViewSource(e,t){let i={...e},o=ed(i),s=await this.readyForRead(t),r=await s.readAppBasesDiscovery("read-view-source",o,t);try{if(s!==this.session||s.closed||this.readFencedAt!==null)throw A("unavailable","original Bases session is no longer current");return nd(r,i)}catch(a){throw Nn(a,"app Bases exact source")}finally{r.fill(0)}}async submit(e,t={}){if(this.hello.version.minor>=3&&this.hello.grant.role==="viewer")throw 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 yA(this.collectionId,t.intent))[0]});let i={ops:e,mutationId:t.mutationId??Ln()};t.allowPartial&&(i.allowPartial=!0,i.mutationIds=e.map((s,r)=>r===0?i.mutationId:Ln())),t.conflictMode&&(i.conflictMode=t.conflictMode),t.timezone&&(i.timezone=t.timezone),t.dryRun&&(i.dryRun=!0),t.include&&(i.include=t.include),t.wait&&(i.wait=t.wait),t.dryRun||(this.startLedger(),await this.writeLedger.begin(i.mutationIds??[i.mutationId],e));let o;try{o=await this.call("submit",_m.enc(i),{codec:km,retry:!0,...t.signal?{signal:t.signal}:{}})}catch(s){throw t.dryRun?s:(this.writeLedger.settleAll(i.mutationIds??[i.mutationId]),vs(s,"submit",i.mutationIds?{mutationIds:i.mutationIds}:{mutationId:i.mutationId}))}return o.map(s=>t.dryRun?new _o(s):this._track(s))}async one(e,t){let[i]=await this.submit([e],t);return i}create(e,t={}){if(t.intent!==void 0&&t.mutationId===void 0)return yA(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??Ln()};return e.path!==void 0&&(i.path=e.path),e.type!==void 0&&(i.type=e.type),e.frontmatter!==void 0&&(i.frontmatter=xl(e.frontmatter)),e.body!==void 0&&(i.body=e.body),e.document!==void 0&&(i.document=e.document),this.one(i,t).then(o=>Object.assign(o,{recordId:i.id}))}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,xl(e.frontmatter??{}),void 0,i.signal),r={kind:"create",id:e.id??Ln(),type:s.type,frontmatter:s.patch};return e.path!==void 0&&(r.path=e.path),e.body!==void 0&&(r.body=e.body),Object.assign(await this.one(r,i),{recordId:r.id})}update(e,t,i={}){return t.contract?this.updateThroughContract(e,t,t.contract,i):this.one(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?xl(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}),p={kind:"update",id:s.id};return a.body!==void 0&&(p.body=a.body),a.bodyEdits&&(p.bodyEdits=a.bodyEdits),a.bodyBase!==void 0&&(p.bodyBase=a.bodyBase),s.patch.size&&(p.patch=s.patch),s.unset.length&&(p.unset=s.unset),s.base.length&&(p.base=s.base),t.updateRefs!==void 0&&(p.updateRefs=t.updateRefs),t.ifRevision&&(p.ifRevision=t.ifRevision),this.one(p,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:Ad(e)},o=typeof e=="object"&&"frontmatter"in e?e:null;if(t.updateRefs!==void 0&&(i.updateRefs=t.updateRefs),t.patch&&(i.patch=xl(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(ut)]))),t.remove&&(i.remove=new Map(Object.entries(t.remove).map(([s,r])=>[s,r.map(ut)]))),t.ifRevision&&(i.ifRevision=t.ifRevision),t.bodyEdits?.length){i.bodyEdits=t.bodyEdits;let s=t.bodyBase??(o?.body!==void 0?si(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=Jp(o.body,t.body);s.length&&(i.bodyEdits=s,i.bodyBase=si(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 p=o.frontmatter.get(a);s.push(p===void 0?{key:a}:{key:a,observed:p})}s.length&&(i.base=s)}if(o&&i.patch){for(let[s,r]of[...i.patch]){let a=o.frontmatter.get(s);a!==void 0&&Ir(a,r)&&(i.patch.delete(s),i.base=i.base?.filter(p=>p.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:Ad(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.one(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.one(a,s)})}let i={kind:"delete",id:Ad(e)};return typeof e=="object"&&"revision"in e&&(i.baseRevision=e.revision),t.ifRevision&&(i.ifRevision=t.ifRevision),this.one(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.one(o,i)}_track(e){this.noteReceipt(e);let t=e,i=this.unclaimed.get(e.mutation);i&&(this.unclaimed.delete(e.mutation),t=Pd(e,i),(e.state==="pending"||e.state==="confirmed"&&(i.state==="rejected"||i.state==="unknown"))&&(t=Pd({...e,...i},t)));let o=this.writes.get(e.mutation);return o?o.update(t):o=new _o(t),hy(o.receipt)?this.writes.set(e.mutation,o):this.writes.delete(e.mutation),o}async save(e,t={}){let i=await e,o=i.receipt;if(o.state==="pending")try{o=await this.awaitReceipt(i.mutationId,t.timeoutMs??3e3,t.signal),i.update(o)}catch(p){if(oe(p,"cancelled"))throw p;o=i.receipt}let s=o.state==="confirmed"?"confirmed":o.state==="pending"?"saved_on_device":"rejected",r=i.records,a=r[0];return t.readBack&&s!=="rejected"&&a&&(a=await this.find(a.id,void 0,t.signal).catch(()=>null)??a),Object.freeze({outcome:s,mutationId:i.mutationId,records:r,...a?{record:a}:{},...s==="rejected"&&o.problem?{problem:o.problem}:{}})}receipt(e,t){return this.call("receipt",Be([[0,T.enc(e)]]),{codec:kt,retry:!0,...t?{signal:t}:{}}).catch(i=>{throw vs(i,"receipt",{mutationId:e})})}awaitReceipt(e,t,i){return this.call("await",Be([[0,T.enc(e)],[1,t]]),{codec:kt,retry:!0,...i?{signal:i}:{}}).catch(o=>{throw vs(o,"await",{mutationId:e})})}listHolds(e){return this.call("list_holds",null,{codec:F(vl),retry:!0,...e?{signal:e}:{}})}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",Be([[0,T.enc(e)],[1,mm.enc(t)],[2,i]]),{codec:kt});return this._track(o)}listConflicts(e,t){return this.call("list_conflicts",e?Be([[0,T.enc(e)]]):null,{codec:F(Al),retry:!0,...t?{signal:t}:{}})}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.one({kind:"conflict_dismiss",mutation:e.mutation,record:e.conflict.id},t)}async resolveConflict(e,t,i,o={}){let[s]=await this.submit([{kind:"update",id:e.conflict.id,patch:new Map([[t,ut(i)]])},{kind:"conflict_dismiss",mutation:e.mutation,record:e.conflict.id}],o);return s}pendingDevices(e){return this.call("pending_devices",null,{codec:F(cA),retry:!0,...e?{signal:e}:{}})}approveDevice(e,t){return/^\d{6}$/.test(t)?this.call("approve_device",Be([[0,T.enc(e)],[1,t]])).then(()=>{}):Promise.reject(A("invalid_request","the code is six digits","invalid_sas"))}rejectDevice(e){return this.call("reject_device",Be([[0,T.enc(e)]])).then(()=>{})}accountKey={setup:async e=>{mA(e);let t=await this.call("account_key_setup",Be([[0,e]]),{codec:kt});return this._track(t)},unlock:async e=>{mA(e),await this.call("account_key_unlock",Be([[0,e]]))},status:e=>this.call("account_key_status",null,{codec:hA,retry:!0,...e?{signal:e}:{}})};recoveryKey={status:()=>this.call("recovery_key_status",null,{codec:dA,retry:!0}),create:()=>this.call("recovery_key_create",null,{codec:uA}),import:e=>this.call("recovery_key_import",Be([[0,e.trim()]])).then(()=>{})};offerFence(e){this.fenceHandler=e}reportFence(e){return this.call("fence_report",Om.enc({open:e}),{retry:!0}).then(()=>{})}}});function yy(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}function Id(n,e=""){if(typeof n!="boolean")throw new TypeError(Cd(e)+"expected boolean, got type="+typeof n);return n}function Ao(n,e=""){if(typeof n!="number")throw new TypeError(Cd(e)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(Cd(e)+"expected integer >= 0, got "+n);return n}function ft(n,e,t=""){if(yy(n)&&(e===void 0||n.length===e))return n;e!==void 0&&Ao(e,"length");let i=yy(n),o=e!==void 0?` of length ${e}`:"",s=i?`length=${n.length}`:`type=${typeof n}`,r=Cd(t)+"expected Uint8Array"+o+", got "+s;throw i?new RangeError(r):new TypeError(r)}function gy(n,e=!0){if(n.destroyed)throw new Error("hash was destroyed");if(e&&n.finished)throw new Error("digest() was already called")}function bA(n,e){ft(n,void 0,"output");let t=e.outputLen;if(!(n.length>=t))throw new RangeError('"output" expected length >= '+t)}function qi(n){return new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4))}function ci(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function FO(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function VO(n){return n<<24&4278190080|n<<8&16711680|n>>>8&65280|n>>>24&255}function KO(n){for(let e=0;e<n.length;e++)n[e]=VO(n[e]);return n}function WO(n,e){return!n.byteLength||!e.byteLength?!1:n.buffer===e.buffer&&n.byteOffset<e.byteOffset+e.byteLength&&e.byteOffset<n.byteOffset+n.byteLength}function wA(n,e){if(WO(n,e)&&n.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function vA(n,e){return gA(n,"defaults"),gA(e,"opts"),Object.assign(n,e)}function _A(n,e){if(n=ft(n),e=ft(e),n.length!==e.length)return!1;let t=0;for(let i=0;i<n.length;i++)t|=n[i]^e[i];return t===0}function AA(n,e,t){let i=e,o=t||(()=>[]),s=(a,p)=>i(p,...o(a)).update(a).digest(),r=i(new Uint8Array(n),...o(new Uint8Array(0)));return s.outputLen=r.outputLen,s.blockLen=r.blockLen,s.create=(a,...p)=>i(a,...p),s}function $l(n,e,t=!0){if(e===void 0)return new Uint8Array(n);if(ft(e,n,"output"),t&&!zl(e))throw new Error("invalid output, must be aligned");return e}function SA(n,e,t){Ao(n),Ao(e),Id(t);let i=new Uint8Array(16),o=FO(i);return o.setBigUint64(0,BigInt(e),t),o.setBigUint64(8,BigInt(n),t),i}function zl(n){return n.byteOffset%4===0}function xs(n){return Uint8Array.from(ft(n))}var Cd,gA,Er,rr,kA,Od=I(()=>{/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */Cd=n=>n?`"${n}" `:"";gA=(n,e)=>{if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof n}`)};Er=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;rr=Er?n=>n:KO;kA=(n,e)=>{function t(i,...o){if(ft(i,void 0,"key"),n.nonceLength!==void 0){let d=o[0];ft(d,n.varSizeNonce?void 0:n.nonceLength,"nonce")}let s=n.tagLength,r=n.nonceLength!==void 0?1:0;if(!n.withAAD){for(let d=r;d<o.length;d++)if(yy(o[d]))throw new Error("AAD not supported")}n.withAAD&&o[r]!==void 0&&ft(o[r],void 0,"AAD");let a=e(i,...o),p=(d,u)=>{if(u!==void 0){if(d!==2)throw new Error("cipher output not supported");ft(u,void 0,"output")}},l=!1;return{encrypt(d,u){if(l)throw new Error("cannot encrypt() twice with same key + nonce");return l=!0,ft(d,void 0,"data"),p(a.encrypt.length,u),a.encrypt(d,u)},decrypt(d,u){if(ft(d,void 0,"data"),s&&d.length<s)throw new Error('"ciphertext" expected length >= tagLength='+s);return p(a.decrypt.length,u),a.decrypt(d,u)}}}return Object.assign(t,n),t}});function Le(n,e){return n<<e|n>>>32-e}function JO(n,e,t,i,o,s,r,a){let p=o.length,l=new Uint8Array(Bl),c=qi(l),d=Er&&zl(o)&&zl(s),u=d?qi(o):PA,f=d?qi(s):PA;if(!Er){for(let h=0;h<p;r++){if(n(e,t,i,c,r,a),rr(c),r>=by)throw new Error("arx: counter overflow");let m=Math.min(Bl,p-h);for(let b=0,w;b<m;b++)w=h+b,s[w]=o[w]^l[b];h+=m}return}for(let h=0;h<p;r++){if(n(e,t,i,c,r,a),r>=by)throw new Error("arx: counter overflow");let m=Math.min(Bl,p-h);if(d&&m===Bl){let b=h/4;if(h%4!==0)throw new Error("arx: invalid block position");for(let w=0,g;w<YO;w++)g=b+w,f[g]=u[g]^c[w];h+=Bl;continue}for(let b=0,w;b<m;b++)w=h+b,s[w]=o[w]^l[b];h+=m}}function CA(n,e){let{allowShortKeys:t,extendNonceFn:i,counterLength:o,counterRight:s,rounds:r}=vA({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof n!="function")throw new Error("core must be a function");return Ao(o),Ao(r),Id(s),Id(t),(a,p,l,c,d=0)=>{ft(a,void 0,"key"),ft(p,void 0,"nonce"),ft(l,void 0,"data");let u=l.length,f=c!==void 0;if(c=$l(u,c,!1),f&&wA(l,c),Ao(d),d<0||d>=by)throw new Error("arx: counter overflow");let h=[],m=a.length,b,w;if(m===32)h.push(b=xs(a)),w=GO;else if(m===16&&t)b=new Uint8Array(32),b.set(a),b.set(a,16),w=HO,h.push(b);else throw ft(a,32,"arx key"),new Error("invalid key size");(!Er||!zl(p))&&h.push(p=xs(p));let g=qi(b);if(i){if(p.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let _=p.subarray(0,16);if(Er)i(w,g,qi(_),g);else{let k=rr(Uint32Array.from(w));i(k,g,qi(_),g),ci(k),rr(g)}p=p.subarray(16)}else Er||rr(g);let y=16-o;if(y!==p.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){let _=new Uint8Array(12);_.set(p,s?0:12-p.length),p=_,h.push(p)}let v=rr(qi(p));try{return JO(n,w,g,v,l,c,d,r),c}finally{ci(...h)}}}var xA,HO,GO,Bl,YO,by,PA,IA=I(()=>{Od();xA=n=>Uint8Array.from(n.split(""),e=>e.charCodeAt(0)),HO=rr(qi(xA("expand 16-byte k"))),GO=rr(qi(xA("expand 32-byte k")));Bl=64,YO=16,by=2**32-1,PA=Uint32Array.of()});function Mt(n,e){return n[e++]&255|(n[e++]&255)<<8}var wy,OA,RA=I(()=>{Od();wy=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=xs(ft(e,32,"key"));let t=Mt(e,0),i=Mt(e,2),o=Mt(e,4),s=Mt(e,6),r=Mt(e,8),a=Mt(e,10),p=Mt(e,12),l=Mt(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|i<<3)&8191,this.r[2]=(i>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|r<<12)&255,this.r[5]=r>>>1&8190,this.r[6]=(r>>>14|a<<2)&8191,this.r[7]=(a>>>11|p<<5)&8065,this.r[8]=(p>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let c=0;c<8;c++)this.pad[c]=Mt(e,16+2*c)}process(e,t,i=!1){let o=i?0:2048,{h:s,r}=this,a=r[0],p=r[1],l=r[2],c=r[3],d=r[4],u=r[5],f=r[6],h=r[7],m=r[8],b=r[9],w=Mt(e,t+0),g=Mt(e,t+2),y=Mt(e,t+4),v=Mt(e,t+6),_=Mt(e,t+8),k=Mt(e,t+10),S=Mt(e,t+12),x=Mt(e,t+14),P=s[0]+(w&8191),C=s[1]+((w>>>13|g<<3)&8191),E=s[2]+((g>>>10|y<<6)&8191),O=s[3]+((y>>>7|v<<9)&8191),L=s[4]+((v>>>4|_<<12)&8191),z=s[5]+(_>>>1&8191),Q=s[6]+((_>>>14|k<<2)&8191),V=s[7]+((k>>>11|S<<5)&8191),te=s[8]+((S>>>8|x<<8)&8191),G=s[9]+(x>>>5|o),K=0,X=K+P*a+C*(5*b)+E*(5*m)+O*(5*h)+L*(5*f);K=X>>>13,X&=8191,X+=z*(5*u)+Q*(5*d)+V*(5*c)+te*(5*l)+G*(5*p),K+=X>>>13,X&=8191;let Y=K+P*p+C*a+E*(5*b)+O*(5*m)+L*(5*h);K=Y>>>13,Y&=8191,Y+=z*(5*f)+Q*(5*u)+V*(5*d)+te*(5*c)+G*(5*l),K+=Y>>>13,Y&=8191;let ee=K+P*l+C*p+E*a+O*(5*b)+L*(5*m);K=ee>>>13,ee&=8191,ee+=z*(5*h)+Q*(5*f)+V*(5*u)+te*(5*d)+G*(5*c),K+=ee>>>13,ee&=8191;let $e=K+P*c+C*l+E*p+O*a+L*(5*b);K=$e>>>13,$e&=8191,$e+=z*(5*m)+Q*(5*h)+V*(5*f)+te*(5*u)+G*(5*d),K+=$e>>>13,$e&=8191;let mt=K+P*d+C*c+E*l+O*p+L*a;K=mt>>>13,mt&=8191,mt+=z*(5*b)+Q*(5*m)+V*(5*h)+te*(5*f)+G*(5*u),K+=mt>>>13,mt&=8191;let j=K+P*u+C*d+E*c+O*l+L*p;K=j>>>13,j&=8191,j+=z*a+Q*(5*b)+V*(5*m)+te*(5*h)+G*(5*f),K+=j>>>13,j&=8191;let W=K+P*f+C*u+E*d+O*c+L*l;K=W>>>13,W&=8191,W+=z*p+Q*a+V*(5*b)+te*(5*m)+G*(5*h),K+=W>>>13,W&=8191;let $=K+P*h+C*f+E*u+O*d+L*c;K=$>>>13,$&=8191,$+=z*l+Q*p+V*a+te*(5*b)+G*(5*m),K+=$>>>13,$&=8191;let J=K+P*m+C*h+E*f+O*u+L*d;K=J>>>13,J&=8191,J+=z*c+Q*l+V*p+te*a+G*(5*b),K+=J>>>13,J&=8191;let be=K+P*b+C*m+E*h+O*f+L*u;K=be>>>13,be&=8191,be+=z*d+Q*c+V*l+te*p+G*a,K+=be>>>13,be&=8191,K=(K<<2)+K|0,K=K+X|0,X=K&8191,K=K>>>13,Y+=K,s[0]=X,s[1]=Y,s[2]=ee,s[3]=$e,s[4]=mt,s[5]=j,s[6]=W,s[7]=$,s[8]=J,s[9]=be}finalize(){let{h:e,pad:t}=this,i=new Uint16Array(10),o=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=o,o=e[a]>>>13,e[a]&=8191;e[0]+=o*5,o=e[0]>>>13,e[0]&=8191,e[1]+=o,o=e[1]>>>13,e[1]&=8191,e[2]+=o,i[0]=e[0]+5,o=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+o,o=i[a]>>>13,i[a]&=8191;i[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)i[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|i[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let r=e[0]+t[0];e[0]=r&65535;for(let a=1;a<8;a++)r=(e[a]+t[a]|0)+(r>>>16)|0,e[a]=r&65535;ci(i)}update(e){gy(this),ft(e),e=xs(e);let{buffer:t,blockLen:i}=this,o=e.length;for(let s=0;s<o;){let r=Math.min(i-this.pos,o-s);if(r===i){for(;i<=o-s;s+=i)this.process(e,s);continue}t.set(e.subarray(s,s+r),this.pos),this.pos+=r,s+=r,this.pos===i&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,ci(this.h,this.r,this.buffer,this.pad)}digestInto(e){gy(this),bA(e,this),this.finished=!0;let{buffer:t,h:i}=this,{pos:o}=this;if(o){for(t[o++]=1;o<16;o++)t[o]=0;this.process(t,0,!0)}this.finalize();let s=0;for(let r=0;r<8;r++)e[s++]=i[r]>>>0,e[s++]=i[r]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let i=e.slice(0,t);return this.destroy(),i}},OA=AA(32,n=>new wy(n))});function XO(n,e,t,i,o,s=20){let r=n[0],a=n[1],p=n[2],l=n[3],c=e[0],d=e[1],u=e[2],f=e[3],h=e[4],m=e[5],b=e[6],w=e[7],g=o,y=t[0],v=t[1],_=t[2],k=r,S=a,x=p,P=l,C=c,E=d,O=u,L=f,z=h,Q=m,V=b,te=w,G=g,K=y,X=v,Y=_;for(let $e=0;$e<s;$e+=2)k=k+C|0,G=Le(G^k,16),z=z+G|0,C=Le(C^z,12),k=k+C|0,G=Le(G^k,8),z=z+G|0,C=Le(C^z,7),S=S+E|0,K=Le(K^S,16),Q=Q+K|0,E=Le(E^Q,12),S=S+E|0,K=Le(K^S,8),Q=Q+K|0,E=Le(E^Q,7),x=x+O|0,X=Le(X^x,16),V=V+X|0,O=Le(O^V,12),x=x+O|0,X=Le(X^x,8),V=V+X|0,O=Le(O^V,7),P=P+L|0,Y=Le(Y^P,16),te=te+Y|0,L=Le(L^te,12),P=P+L|0,Y=Le(Y^P,8),te=te+Y|0,L=Le(L^te,7),k=k+E|0,Y=Le(Y^k,16),V=V+Y|0,E=Le(E^V,12),k=k+E|0,Y=Le(Y^k,8),V=V+Y|0,E=Le(E^V,7),S=S+O|0,G=Le(G^S,16),te=te+G|0,O=Le(O^te,12),S=S+O|0,G=Le(G^S,8),te=te+G|0,O=Le(O^te,7),x=x+L|0,K=Le(K^x,16),z=z+K|0,L=Le(L^z,12),x=x+L|0,K=Le(K^x,8),z=z+K|0,L=Le(L^z,7),P=P+C|0,X=Le(X^P,16),Q=Q+X|0,C=Le(C^Q,12),P=P+C|0,X=Le(X^P,8),Q=Q+X|0,C=Le(C^Q,7);let ee=0;i[ee++]=r+k|0,i[ee++]=a+S|0,i[ee++]=p+x|0,i[ee++]=l+P|0,i[ee++]=c+C|0,i[ee++]=d+E|0,i[ee++]=u+O|0,i[ee++]=f+L|0,i[ee++]=h+z|0,i[ee++]=m+Q|0,i[ee++]=b+V|0,i[ee++]=w+te|0,i[ee++]=g+G|0,i[ee++]=y+K|0,i[ee++]=v+X|0,i[ee++]=_+Y|0}function qA(n,e,t,i,o){o!==void 0&&ft(o,void 0,"AAD");let s=n(e,t,e1),r=SA(i.length,o?o.length:0,!0),a=OA.create(s);o&&EA(a,o),EA(a,i),a.update(r);let p=a.digest();return ci(s,r),p}var ZO,QO,EA,e1,t1,vy,TA=I(()=>{IA();RA();Od();ZO=CA(XO,{counterRight:!1,counterLength:4,allowShortKeys:!1}),QO=new Uint8Array(16),EA=(n,e)=>{n.update(e);let t=e.length%16;t&&n.update(QO.subarray(t))},e1=new Uint8Array(32);t1=n=>(e,t,i)=>({encrypt(s,r){let a=s.length;r=$l(a+16,r,!1),r.set(s);let p=r.subarray(0,-16);n(e,t,p,p,1);let l=qA(n,e,t,p,i);return r.set(l,a),ci(l),r},decrypt(s,r){r=$l(s.length-16,r,!1);let a=s.subarray(0,-16),p=s.subarray(-16),l=qA(n,e,t,a,i);if(!_A(p,l))throw ci(l),new Error("invalid tag");return r.set(s.subarray(0,-16)),n(e,t,r,r,1),ci(l),r}}),vy=kA({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},t1(ZO))});function Ed(n,e,t=()=>{}){if(!Array.isArray(n))throw new TypeError(`"${e}" expected array, got type=${typeof n}`);for(let i=0;i<n.length;i++)t(n[i],`${e}[${i}]`);return n}function qr(n,e="object"){if(n===null||typeof n!="object"||Array.isArray(n))throw new TypeError(e==="object"?"expected valid options object":`"${e}" expected object, got type=${typeof n}`);return n}function ko(n,e){if(typeof n!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof n}`);return n}function So(n,e=""){if(typeof n!="boolean")throw new TypeError(n1(e)+"expected boolean, got type="+typeof n);return n}function i1(n){if(typeof n=="bigint"){if(!Tr(n))throw new RangeError("positive bigint expected, got "+n)}else _y(n);return n}function Fl(n,e=""){if(typeof n!="number"){let t=e&&`"${e}" `;throw new TypeError(t+"expected number, got type="+typeof n)}if(!Number.isSafeInteger(n)){let t=e&&`"${e}" `;throw new RangeError(t+"expected safe integer, got "+n)}}function NA(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);return n===""?Rd:BigInt("0x"+n)}function Md(n){return NA(ys(n))}function Po(n){return NA(ys(xo(tr(n)).reverse()))}function Ay(n,e){if(ho(e),e===0)throw new Error("zero output length is invalid");n=i1(n);let t=e*2,i=n.toString(16);if(i.length>t)throw new RangeError("number is too large");return Dm(i.padStart(t,"0"))}function Ld(n,e){return Ay(n,e).reverse()}function xo(n){return Uint8Array.from(or(n))}function Tr(n){return typeof n=="bigint"&&Rd<=n}function ky(n,e,t){return Tr(n)&&Tr(e)&&Tr(t)&&e<=n&&n<t}function Co(n,e,t,i){if(!ky(e,t,i))throw new RangeError("expected valid "+n+": "+t+" <= n < "+i+", got "+e)}function Sy(n){if(n<Rd)throw new Error("expected non-negative bigint, got "+n);return n===Rd?0:n.toString(2).length}function Io(n,e={},t={},i="object"){qr(n,i),qr(e,"fields"),qr(t,"optFields");function o(r,a,p){let l=i==="object"?`param "${String(r)}"`:`"${i}.${String(r)}"`,c=n[r];if(!Object.hasOwn(n,r)&&(p?c!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(p&&c===void 0)return;let d=typeof c;if(d!==a||c===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${d}`)}let s=(r,a)=>Object.entries(r).forEach(([p,l])=>o(p,l,a));s(e,!1),s(t,!0)}var or,_y,LA,jA,qd,Td,Rd,MA,n1,UA,Vl=I(()=>{gs();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */or=(n,e,t)=>tr(n,e,t),_y=ho;LA=ys,jA=n=>Dm(n),qd=Kp,Td=n=>Gv(n),Rd=BigInt(0),MA=BigInt(1),n1=n=>n?`"${n}" `:"";UA=n=>(Fl(n,"n"),(MA<<BigInt(n))-MA)});function Ge(n,e){if(e<=It)throw new Error("mod: expected positive modulus, got "+e);let t=n%e;return t>=It?t:e+t}function l1(n,e,t){if(t<=Qe)throw new Error("pow: expected modulus > 1, got "+t);if(typeof e!="bigint")throw new TypeError("invalid exponent: expected bigint, got "+typeof e);if(e<It)throw new Error("invalid exponent, negatives unsupported");if(e===It)return Qe;if(e===Qe)return n;let i=n%t;if(i<It&&(i+=t),e<a1){let a=Qe;for(;e>It;)e&Qe&&(a=a*i%t),i=i*i%t,e>>=Qe;return a}let o=[];for(;e>It;)o.push(Number(e&s1)),e>>=Py;let s=new Array(16);s[0]=Qe,s[1]=i;for(let a=2;a<16;a++)s[a]=s[a-1]*i%t;let r=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){r=r*r%t,r=r*r%t,r=r*r%t,r=r*r%t;let p=o[a];p!==0&&(r=r*s[p]%t)}return r}function Un(n,e,t){if(t<=Qe)throw new Error("pow2: expected modulus > 1, got "+t);if(e<It)throw new Error("pow2: expected non-negative exponent, got "+e);let i=n;for(;e-- >It;)i*=i,i%=t;return i}function DA(n,e){if(n===It)throw new Error("invert: expected non-zero number");if(e<=Qe)throw new Error("invert: expected modulus > 1, got "+e);let t=Ge(n,e),i=e,o=It,s=Qe;for(;t!==It;){let a=i/t,p=i-t*a,l=o-s*a;i=t,t=p,o=s,s=l}if(i!==Qe)throw new Error("invert: does not exist");return Ge(o,e)}function xy(n,e,t){let i=n;if(!i.eql(i.sqr(e),t))throw new Error("Cannot find square root")}function Cy(n,e){if((n&Qe)===It)throw new Error(e+": expected odd modulus, got "+n)}function KA(n,e){let t=n,i=(t.ORDER+Qe)/Py,o=t.pow(e,i);return xy(t,o,e),o}function c1(n,e){let t=n,i=(t.ORDER-BA)/FA,o=t.mul(e,Oo),s=t.pow(o,i),r=t.mul(e,s),a=t.mul(t.mul(r,Oo),s),p=t.mul(r,t.sub(a,t.ONE));return xy(t,p,e),p}function p1(n){let e=Ud(n),t=WA(n),i=t(e,e.neg(e.ONE)),o=t(e,i),s=t(e,e.neg(i)),r=(n+r1)/VA;return((a,p)=>{let l=a,c=l.pow(p,r),d=l.mul(c,i),u=l.mul(c,o),f=l.mul(c,s),h=l.eql(l.sqr(d),p),m=l.eql(l.sqr(u),p);c=l.cmov(c,d,h),d=l.cmov(f,u,m);let b=l.eql(l.sqr(d),p),w=l.cmov(c,d,b);return xy(l,w,p),w})}function WA(n){if(n<zA)throw new Error("sqrt is not defined for small field");Cy(n,"tonelliShanks");let e=n-Qe,t=0;for(;e%Oo===It;)e/=Oo,t++;let i=Oo,o=Ud(n);for(;Kl(o,i)===1;)if(i++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return KA;let s=o.pow(i,e),r=(e+Qe)/Oo;return function(p,l){let c=p;if(c.is0(l))return l;if(Kl(c,l)!==1)throw new Error("Cannot find square root");let d=t,u=c.mul(c.ONE,s),f=c.pow(l,e),h=c.pow(l,r);for(;!c.eql(f,c.ONE);){if(c.is0(f))throw new Error("Cannot find square root: probably non-prime P");let m=1,b=c.sqr(f);for(;!c.eql(b,c.ONE);)if(m++,b=c.sqr(b),m===d)throw new Error("Cannot find square root");let w=Qe<<BigInt(d-m-1),g=c.pow(u,w);d=m,u=c.sqr(g),f=c.mul(f,u),h=c.mul(h,g)}return h}}function d1(n){return Cy(n,"Fp.sqrt"),n%Py===zA?KA:n%FA===BA?c1:n%VA===o1?p1(n):WA(n)}function Cs(n){if(qr(n,"field"),typeof n.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof n.ORDER);Fl(n.BYTES,"BYTES"),Fl(n.BITS,"BITS");for(let e of u1)ko(n[e],"field."+e);if(n.BYTES<1||n.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(n.ORDER<=Qe)throw new Error("invalid field: expected ORDER > 1, got "+n.ORDER);return n}function Nd(n,e,t=!1){Cs(n),Ed(e,"nums"),So(t,"passZero");let i=n,o=new Array(e.length).fill(t?i.ZERO:void 0),s=e.reduce((a,p,l)=>i.is0(p)?a:(o[l]=a,i.mul(a,p)),i.ONE),r=i.inv(s);return e.reduceRight((a,p,l)=>i.is0(p)?a:(o[l]=i.mul(a,o[l]),i.mul(a,p)),r),o}function Kl(n,e){Cs(n);let t=n;Cy(t.ORDER,"FpLegendre");let i=(t.ORDER-Qe)/Oo,o=t.pow(e,i),s=t.eql(o,t.ONE),r=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!r&&!a)throw new Error("invalid Legendre symbol result");return s?1:r?0:-1}function f1(n,e){if(e!==void 0&&_y(e),n<=It)throw new Error("invalid n length: expected positive n, got "+n);if(e!==void 0&&e<1)throw new Error("invalid n length: expected positive bit length, got "+e);let t=Sy(n);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let i=e!==void 0?e:t,o=Math.ceil(i/8);return{nBitLength:i,nByteLength:o}}function Ud(n,e={}){return Object.freeze(jd.prototype),new jd(n,e)}var It,Qe,Oo,zA,Py,BA,r1,FA,o1,s1,VA,a1,HA,u1,$A,jd,Wl=I(()=>{Vl();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */It=BigInt(0),Qe=BigInt(1),Oo=BigInt(2),zA=BigInt(3),Py=BigInt(4),BA=BigInt(5),r1=BigInt(7),FA=BigInt(8),o1=BigInt(9),s1=BigInt(15),VA=BigInt(16),a1=BigInt("0x10000000000000000");HA=(n,e)=>(Ge(n,e)&Qe)===Qe,u1=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];$A=new WeakMap,jd=class{ORDER;BITS;BYTES;isLE;ZERO=It;ONE=Qe;_lengths;_mod;constructor(e,t={}){if(e<=Qe)throw new Error("invalid field: expected ORDER > 1, got "+e);let i;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(i=t.BITS),typeof t.sqrt=="function"&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));let{nBitLength:o,nByteLength:s}=f1(e,i);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=s,Object.freeze(this)}create(e){return Ge(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return It<=e&&e<this.ORDER}is0(e){return e===It}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Qe)===Qe}neg(e){return Ge(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Ge(e*e,this.ORDER)}add(e,t){return Ge(e+t,this.ORDER)}sub(e,t){return Ge(e-t,this.ORDER)}mul(e,t){return Ge(e*t,this.ORDER)}pow(e,t){return l1(e,t,this.ORDER)}div(e,t){return Ge(e*DA(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return DA(e,this.ORDER)}sqrt(e){let t=$A.get(this);return t||$A.set(this,t=d1(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?Ld(e,this.BYTES):Ay(e,this.BYTES)}fromBytes(e,t=!1){or(e);let{_lengths:i,BYTES:o,isLE:s,ORDER:r,_mod:a}=this;if(i){if(e.length<1||!i.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+e.length);let l=new Uint8Array(o);l.set(e,s?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let p=s?Po(e):Md(e);if(a&&(p=Ge(p,r)),!t&&!this.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p}invertBatch(e){return Nd(this,e,!0)}cmov(e,t,i){return So(i,"condition"),i?t:e}}});function $d(n){let e=n;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof n);ko(e.fromAffine,"Point.fromAffine"),ko(e.fromBytes,"Point.fromBytes"),ko(e.fromHex,"Point.fromHex"),qr(e.BASE,"Point.BASE"),qr(e.ZERO,"Point.ZERO"),Cs(e.Fp),Cs(e.Fn)}function XA(n,e){$d(n),ZA(e,n);let t=Nd(n.Fp,e.map(i=>i.Z));return e.map((i,o)=>n.fromAffine(i.toAffine(t[o])))}function y1(n,e,t=1){if(!Number.isSafeInteger(n)||n<t||n>e)throw new Error("invalid window size, expected ["+t+".."+e+"], got W="+n)}function g1(n,e){let t=n*(4*e+128);if(t>YA)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+YA/2**20+" MiB")}function b1(n,e){if(n!==void 0){ko(n,"randomBytes");try{let t=n(e);if(!qd(t)||t.length!==e)return}catch{return}return n}}function ZA(n,e){Ed(n,"points"),n.forEach((t,i)=>{if(!(t instanceof e))throw new Error("invalid point at index "+i)})}function w1(n,e,t){if(!Array.isArray(n))throw new Error("array of scalars expected");n.forEach((i,o)=>{if(!(t===void 0?e.isValid(i):Tr(i)&&i<t))throw new Error("invalid scalar at index "+o)})}function Oy(n){return QA.get(n)||1}function v1(n,e){let t=n.double(),i=[n];for(let o=1;o<e;o++)i.push(i[o-1].add(t));return i}function _1(n,e){let t=2**e,i=t/2,o=BigInt(t-1),s=[];for(;n>Ry;){let r=0;n&Hl&&(r=Number(n&o),r>=i&&(r-=t),n-=BigInt(r)),s.push(r),n>>=Hl}return s}function A1(n,e,t){let i=2**e,o=i/2,s=BigInt(i-1),r=BigInt(e),a=[];for(let p=0;p<t;p++){let l=Number(n&s);n>>=r,l>o&&(l-=i,n+=Hl),a.push(l)}if(n!==Ry)throw new Error("invalid wnaf");return a}function k1(n,e,t){let i=0;for(let s of t)i=Math.max(i,s.length);let o=n;for(let s=i-1;s>=0;s--){s!==i-1&&(o=o.double());for(let r=0;r<t.length;r++){let a=t[r][s];if(a){let p=e[r][Math.abs(a)-1>>1];o=o.add(a<0?p.negate():p)}}}return o}function S1(n,e,t,i=!1){if($d(n),ZA(e,n),So(i,"allowOversized"),w1(t,n.Fn,i?n.Fn.ORDER**h1:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let o=e.map(r=>v1(r,4)),s=t.map(r=>_1(r,4));return k1(n.ZERO,o,s)}function JA(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Cs(e),e}else return Ud(n,{isLE:t})}function e0(n,e,t={},i){if(n!=="weierstrass"&&n!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(i===void 0&&(i=n==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);Io(t);for(let p of["p","n","h"]){let l=e[p];if(!(Tr(l)&&l!==Ry))throw new Error(`CURVE.${p} must be positive bigint`)}let o=JA(e.p,t.Fp,i),s=JA(e.n,t.Fn,i),a=["Gx","Gy","a",n==="weierstrass"?"b":"d"];for(let p of a)if(!o.isValid(e[p]))throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function Ey(n,e){return function(i){let o=n(i);return{secretKey:o,publicKey:e(o)}}}var Ry,Hl,h1,Iy,GA,m1,YA,QA,Dd,qy=I(()=>{Vl();Wl();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Ry=BigInt(0),Hl=BigInt(1),h1=BigInt(4),Iy=16,GA=128,m1=5,YA=2**31;QA=new WeakMap;Dd=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){$d(e),this.randomBytes=b1(t,Iy),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,i){let o=Math.ceil(i/t)+1,s=2**(t-1),r=[],a=e;for(let p=0;p<o;p++){let l=a;for(let c=0;c<s;c++)r.push(l),l=l.add(a);a=r[r.length-1].double()}return{W:t,bits:i,windows:o,comp:r}}wnafCachedCT(e,t){let{W:i,windows:o,comp:s}=e,r=2**(i-1),a=A1(t,i,o),p=this.ZERO,l=this.BASE;for(let c=0;c<o;c++){let d=a[c],u=c*r,f=Math.abs(d)-1,h=s[u];for(let b=1;b<r;b++)h=b===f?s[u+b]:h;let m=h.negate();d===0?l=l.add(s[u]):p=p.add(d<0?m:h)}return{p,f:l}}getWnafPrecomputes(e,t,i,o){let s=this.wnafPrecomputes.get(t),r=s?.find(a=>a.W===e&&a.bits===i);return r||(r=this.buildWnafTable(t,e,i),typeof o=="function"&&(r={...r,comp:o(r.comp)}),s||(s=[],this.wnafPrecomputes.set(t,s)),s.push(r)),r}assertPoint(e){if(!(e instanceof this.Point))throw new TypeError('"point" expected Point instance, got type='+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!ky(t,Hl,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,i,o){let s=Oy(e);return s===1?this.fixedWindowCT(e,t,i):this.wnafCachedCT(this.getWnafPrecomputes(s,e,i,o),t)}mulCT(e,t,i){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,i)}mulCTBlinded(e,t,i){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+GA,s=this.randomBytes(Iy);if(!qd(s)||s.length!==Iy)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let r=t+Md(s)*this.Point.Fn.ORDER;return this.runCT(e,r,o,i)}fixedWindowCT(e,t,i){let o=m1,s=1<<o,r=UA(o),a=new Array(s);a[0]=this.ZERO;for(let c=1;c<s;c++)a[c]=a[c-1].add(e);let p=Math.ceil(i/o),l=this.ZERO;for(let c=p-1;c>=0;c--){if(c!==p-1)for(let f=0;f<o;f++)l=l.double();let d=Number(t>>BigInt(c*o)&r),u=a[0];for(let f=1;f<s;f++)u=f===d?a[f]:u;l=l.add(u)}return{p:l,f:l}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===Hl?!0:e!==this.BASE?!1:(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,i,o){return this.shouldBlind(e,i)?this.mulCTBlinded(e,t,o):this.mulCT(e,t,o)}mulUnsafe(e,t,i){if(this.assertPoint(e),!Tr(t))throw new Error("invalid scalar");let o=Oy(e);if(o===1||t>=this.Point.Fn.ORDER)return S1(this.Point,[e],[t],!0);let s=this.getWnafPrecomputes(o,e,this.bits,i);return this.wnafCachedCT(s,t).p}setWindowSize(e,t){this.assertPoint(e),y1(t,this.bits);let i=Math.ceil((this.bits+GA)/t)+1;g1(i*2**(t-1),this.Point.Fp.BYTES),QA.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return Oy(e)!==1}}});function x1(n,e,t,i){let o=n.sqr(t),s=n.sqr(i),r=n.add(n.mul(e.a,o),s),a=n.add(n.ONE,n.mul(e.d,n.mul(o,s)));return n.eql(r,a)}function n0(n,e={}){Io(e,{},{},"extraOpts");let t=e,i=e0("edwards",n,t,t.FpFnLE),{Fp:o,Fn:s}=i,r=i.CURVE,{h:a}=r;if(Kl(o,r.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Kl(o,r.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");Io(t,{},{uvRatio:"function",randomBytes:"function"});let p=t.randomBytes===void 0?Td:t.randomBytes,l=Fd<<BigInt(o.BYTES*8)-Bd;function c(g){if(!o.isOdd)throw new Error("Field does not have .isOdd()");return o.isOdd(g)}let d=t.uvRatio===void 0?(g,y)=>{try{return{isValid:!0,value:o.sqrt(o.div(g,y))}}catch{return{isValid:!1,value:zd}}}:t.uvRatio;if(!x1(o,r,r.Gx,r.Gy))throw new Error("bad curve params: generator point");let u=o.eql(r.a,o.neg(o.ONE))?g=>o.neg(g):o.eql(r.a,o.ONE)?g=>g:g=>o.mul(r.a,g);function f(g,y,v=!1){let _=v?Bd:zd;return Co("coordinate "+g,y,_,l),y}function h(g){if(!(g instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(r.Gx,r.Gy,o.ONE,o.mul(r.Gx,r.Gy));static ZERO=new m(o.ZERO,o.ONE,o.ONE,o.ZERO);static Fp=o;static Fn=s;X;Y;Z;T;constructor(y,v,_,k){this.X=f("x",y),this.Y=f("y",v),this.Z=f("z",_,!0),this.T=f("t",k),Object.freeze(this)}static CURVE(){return r}static fromAffine(y){if(y instanceof m)throw new Error("extended point not allowed");let{x:v,y:_}=y||{};return f("x",v),f("y",_),new m(v,_,o.ONE,o.mul(v,_))}static fromBytes(y,v=!1){let _=o.BYTES,{a:k,d:S}=r;y=xo(or(y,_,"point")),So(v,"zip215");let x=xo(y),P=y[_-1];x[_-1]=P&-129;let C=Po(x),E=v?l:o.ORDER;Co("point.y",C,zd,E);let O=o.sqr(C),L=o.sub(O,o.ONE),z=o.sub(o.mulN(S,O),k),{isValid:Q,value:V}=d(L,z);if(!Q)throw new Error("bad point: invalid y coordinate");let te=c(V),G=(P&128)!==0;if(!v&&o.is0(V)&&G)throw new Error("bad point: x=0 and x_0=1");return G!==te&&(V=o.neg(V)),m.fromAffine({x:V,y:C})}static fromHex(y,v=!1){return m.fromBytes(jA(y),v)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=6,v=!0){return w.setWindowSize(this,y),v||this.multiply(Fd),this}assertValidity(){let y=this,{a:v,d:_}=r;if(y.is0())throw new Error("bad point: ZERO");let{X:k,Y:S,Z:x,T:P}=y,C=o.sqr(k),E=o.sqr(S),O=o.sqr(x),L=o.sqr(O),z=o.mul(C,v),Q=o.mul(o.add(z,E),O),V=o.add(L,o.mul(_,o.mul(C,E)));if(!o.eql(Q,V))throw new Error("bad point: equation left != right (1)");let te=o.mul(k,S),G=o.mul(x,P);if(!o.eql(te,G))throw new Error("bad point: equation left != right (2)")}equals(y){h(y);let{X:v,Y:_,Z:k}=this,{X:S,Y:x,Z:P}=y,C=o.mul(v,P),E=o.mul(S,k),O=o.mul(_,P),L=o.mul(x,k);return o.eql(C,E)&&o.eql(O,L)}is0(){return this.equals(m.ZERO)}negate(){return new m(o.neg(this.X),this.Y,this.Z,o.neg(this.T))}double(){let{X:y,Y:v,Z:_}=this,k=o.sqr(y),S=o.sqr(v),x=o.mul(o.sqr(_),Fd),P=u(k),C=o.addN(y,v),E=o.sub(o.subN(o.sqr(C),k),S),O=o.addN(P,S),L=o.subN(O,x),z=o.subN(P,S),Q=o.mul(E,L),V=o.mul(O,z),te=o.mul(E,z),G=o.mul(L,O);return new m(Q,V,G,te)}add(y){h(y);let{d:v}=r,{X:_,Y:k,Z:S,T:x}=this,{X:P,Y:C,Z:E,T:O}=y,L=o.mul(_,P),z=o.mul(k,C),Q=o.mul(o.mulN(x,v),O),V=o.mul(S,E),te=o.sub(o.subN(o.mulN(o.addN(_,k),o.addN(P,C)),L),z),G=o.subN(V,Q),K=o.addN(V,Q),X=o.sub(z,u(L)),Y=o.mul(te,G),ee=o.mul(K,X),$e=o.mul(te,X),mt=o.mul(G,K);return new m(Y,ee,mt,$e)}subtract(y){return h(y),this.add(y.negate())}multiply(y){if(!s.isValidNot0(y))throw new RangeError("invalid scalar: expected 1 <= sc < curve.n");let{p:v,f:_}=w.mulSecret(this,y,a,b);return b([v,_])[0]}multiplyUnsafe(y){if(!s.isValid(y))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return y===zd?m.ZERO:this.is0()||y===Bd?this:w.mulUnsafe(this,y,b)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return w.mulUnsafe(this,r.n).is0()}toAffine(y){let v=this,_=y;if(_!=null&&typeof _!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof _);let{X:k,Y:S,Z:x}=v,P=v.is0();_==null&&(_=P?o.create(t0):o.inv(x));let C=o.mul(k,_),E=o.mul(S,_),O=o.mul(x,_);if(P)return{x:o.ZERO,y:o.ONE};if(!o.eql(O,o.ONE))throw new Error("invZ was invalid");return{x:C,y:E}}clearCofactor(){return a===Bd?this:a===Fd?this.double():a===P1?this.double().double():a===t0?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:y,y:v}=this.toAffine(),_=o.toBytes(v);return _[_.length-1]|=c(y)?128:0,_}toHex(){return LA(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let b=g=>XA(m,g),w=new Dd(m,p);return w.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}var zd,Bd,Fd,P1,t0,i0=I(()=>{Vl();qy();Wl();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */zd=BigInt(0),Bd=BigInt(1),Fd=BigInt(2),P1=BigInt(4),t0=BigInt(8)});function r0(n,e){return n+e-(e>>Dn<<Dn)}function C1(n){let e=BigInt(6)*n;return(t,i,o)=>{let s=i+o,a=((e+o-i)*t+i)%n;return{x_2:a,x_3:s-a}}}function I1(n){return Io(n,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...n})}function o0(n){let e=I1(n),{P:t,type:i,adjustScalarBytes:o,powPminus2:s,randomBytes:r}=e,a=e.scalarMultBase,p=i==="x25519";if(!p&&i!=="x448")throw new Error("invalid type");let l=r===void 0?Td:r,c=p?255:448,d=C1(t),u=p?32:56,f=BigInt(p?9:5),h=BigInt(p?121665:39081),m=p?Vd**BigInt(254):Vd**BigInt(447),b=p?BigInt(8)*(Vd**BigInt(251)-Dn):BigInt(4)*(Vd**BigInt(445)-Dn),w=m+b+Dn,g=V=>Ge(V,t),y=v(f);function v(V){return Ld(g(V),u)}function _(V){let te=xo(or(V,u,"uCoordinate"));return p&&(te[31]&=127),g(Po(te))}function k(V){return Po(o(xo(or(V,u,"scalar"))))}let S=new Set(p?[Ro,Dn,t-Dn,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[Ro,Dn,t-Dn]);function x(V,te){let G=_(te);if(S.has(G))throw new Error("invalid private or public key received");let K=O(G,k(V));if(K===Ro)throw new Error("invalid private or public key received");return v(K)}function P(V){if(a===void 0)return x(V,y);let te=k(V);Co("scalar",te,m,w);let G=g(a(te));if(G===Ro)throw new Error("invalid private or public key received");return v(G)}let C=P,E=x;function O(V,te){Co("u",V,Ro,t),Co("scalar",te,m,w);let G=te,K=V,X=Dn,Y=Ro,ee=V,$e=Dn,mt=G^G>>Dn;for(let $=BigInt(c-1);$>=Ro;$--){let J=r0(t,mt>>$);({x_2:X,x_3:ee}=d(J,X,ee)),{x_2:Y,x_3:$e}=d(J,Y,$e);let be=X+Y,ye=g(be*be),we=X-Y,et=g(we*we),qe=ye-et,Dt=ee+$e,tt=ee-$e,Ve=g(tt*be),On=g(Dt*we),Ar=Ve+On,Pi=Ve-On;ee=g(Ar*Ar),$e=g(K*g(Pi*Pi)),X=g(ye*et),Y=g(qe*(ye+g(h*qe)))}let j=r0(t,G);({x_2:X,x_3:ee}=d(j,X,ee)),{x_2:Y,x_3:$e}=d(j,Y,$e);let W=s(Y);return g(X*W)}let L={secretKey:u,publicKey:u,seed:u},z=V=>(V=V===void 0?l(u):V,or(V,L.seed,"seed"),V),Q={randomSecretKey:z};return Object.freeze(L),Object.freeze(Q),Object.freeze({keygen:Ey(z,C),getSharedSecret:E,getPublicKey:C,scalarMult:x,scalarMultBase:P,utils:Q,GuBytes:y.slice(),lengths:L})}var Ro,Dn,Vd,s0=I(()=>{Vl();qy();Wl();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Ro=BigInt(0),Dn=BigInt(1),Vd=BigInt(2)});function d0(n){let e=BigInt(10),t=BigInt(20),i=BigInt(40),o=BigInt(80),s=Kd,a=n*n%s*n%s,p=Un(a,l0,s)*a%s,l=Un(p,O1,s)*n%s,c=Un(l,E1,s)*l%s,d=Un(c,e,s)*c%s,u=Un(d,t,s)*d%s,f=Un(u,i,s)*u%s,h=Un(f,o,s)*f%s,m=Un(h,o,s)*f%s,b=Un(m,e,s)*c%s;return{pow_p_5_8:Un(b,l0,s)*n%s,b2:a}}function M1(n){return n[0]&=248,n[31]&=127,n[31]|=64,n}function L1(n,e){let t=Kd,i=Ge(e*e*e,t),o=Ge(i*i*e,t),s=d0(n*o).pow_p_5_8,r=Ge(n*i*s,t),a=Ge(e*r*r,t),p=r,l=Ge(r*c0,t),c=a===n,d=a===Ge(-n,t),u=a===Ge(-n*c0,t);return c&&(r=p),(d||u)&&(r=l),HA(r,t)&&(r=Ge(-r,t)),{isValid:c||d,value:r}}var a0,O1,l0,R1,E1,q1,Kd,T1,c0,p0,sr,Ty=I(()=>{i0();Wl();s0();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */a0=BigInt(0),O1=BigInt(1),l0=BigInt(2),R1=BigInt(3),E1=BigInt(5),q1=BigInt(8),Kd=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),T1={p:Kd,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:q1,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};c0=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");p0=n0(T1,{uvRatio:L1}),sr=(()=>{let n=Kd,e=t=>{let{pow_p_5_8:i,b2:o}=d0(t);return Ge(Un(i,R1,n)*o,n)};return o0({P:n,type:"x25519",powPminus2:e,adjustScalarBytes:M1,scalarMultBase:t=>{let i=Ge(t,p0.Fn.ORDER);if(i===a0)return a0;let o=p0.BASE.multiply(i);return Ge((o.Z+o.Y)*e(Ge(o.Z-o.Y,n)),n)}})})()});var Wd,Hd,u0=I(()=>{gs();Wd=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(Vv(e),tr(t,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("expected Hash instance");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let i=this.blockLen,o=new Uint8Array(i);o.set(t.length>i?e.create().update(t).digest():t);for(let s=0;s<o.length;s++)o[s]^=54;this.iHash.update(o),this.oHash=e.create();for(let s=0;s<o.length;s++)o[s]^=106;this.oHash.update(o),ms(o)}update(e){return hs(this),this.iHash.update(e),this}digestInto(e){hs(this),Wp(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:i,finished:o,destroyed:s,blockLen:r,outputLen:a,canXOF:p}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=r,e.outputLen=a,e.canXOF=p,e.oHash=t._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},Hd=(()=>{let n=((e,t,i)=>new Wd(e,t).update(i).digest());return n.create=(e,t)=>new Wd(e,t),n})()});function Yd(n){return"dh"in n?n:{publicKey:n.publicKey,dh:e=>Eo(n.secretKey,e)}}async function h0(n,e){let t;try{t=await n.dh(e)}catch(i){throw i instanceof rt?i:new rt("invalid public key")}return v0(t)}function Es(){let n=sr.utils.randomSecretKey();return{secretKey:n,publicKey:sr.getPublicKey(n)}}function w0(n){return{secretKey:n,publicKey:sr.getPublicKey(n)}}function Gl(...n){let e=0;for(let o of n)e+=o.length;let t=new Uint8Array(e),i=0;for(let o of n)t.set(o,i),i+=o.length;return t}function v0(n){let e=0;for(let t of n)e|=t;if(e===0)throw new rt("invalid public key (all-zero shared secret)");return n}function Eo(n,e){let t;try{t=sr.getSharedSecret(n,e)}catch{throw new rt("invalid public key")}return v0(t)}function m0(n,e){let t=Hd(it,n,e),i=Hd(it,t,Uint8Array.of(1)),o=Hd(it,t,Gl(i,Uint8Array.of(2)));return[i,o]}function y0(n){let e=new Uint8Array(12),t=new DataView(e.buffer);return t.setUint32(4,n>>>0,!0),t.setUint32(8,Math.floor(n/2**32),!0),e}function Ti(n,e,t){for(let[i,o]of[["collection",n],["target device",t]])if(o.length!==16)throw new rt(`${i} ID must be 16 bytes`);if(e&&e.length!==16)throw new rt("grant ID must be 16 bytes");return Gl(j1,n,e??N1,t)}var g0,$n,f0,b0,Is,My,Gd,rt,Os,Jd,Rs,Xd,j1,N1,qo=I(()=>{"use strict";TA();Ty();u0();Cr();g0="Noise_IK_25519_ChaChaPoly_SHA256",$n=32,f0=32,b0=65535,Is=16,My=b0-Is,Gd=2**30;rt=class extends Error{constructor(e){super(e),this.name="NoiseError"}},Os=class{constructor(e=null){this.k=e}k;n=0;hasKey(){return this.k!==null}get count(){return this.n}encrypt(e,t){if(!this.k)return t;if(this.n>=Gd)throw new rt("session message limit reached");let i=vy(this.k,y0(this.n),e).encrypt(t);return this.n++,i}decrypt(e,t){if(!this.k)return t;if(this.n>=Gd)throw new rt("session message limit reached");let i;try{i=vy(this.k,y0(this.n),e).decrypt(t)}catch{throw new rt("decryption failed")}return this.n++,i}},Jd=class{ck;h;cs=new Os;constructor(e){let t=new TextEncoder().encode(e);t.length<=f0?(this.h=new Uint8Array(f0),this.h.set(t)):this.h=it(t),this.ck=this.h}mixKey(e){let[t,i]=m0(this.ck,e);this.ck=t,this.cs=new Os(i)}mixHash(e){this.h=it(Gl(this.h,e))}encryptAndHash(e){let t=this.cs.encrypt(this.h,e);return this.mixHash(t),t}decryptAndHash(e){let t=this.cs.decrypt(this.h,e);return this.mixHash(e),t}split(){let[e,t]=m0(this.ck,new Uint8Array(0));return[new Os(e),new Os(t)]}},Rs=class{constructor(e){this.opts=e;if(e.remoteStatic.length!==$n)throw new rt("remote static key must be 32 bytes");this.e=e.ephemeral??Es(),this.ss.mixHash(e.prologue),this.ss.mixHash(e.remoteStatic)}opts;ss=new Jd(g0);e;state="start";async writeMessage1(e){if(this.state!=="start")throw new rt("handshake out of order");this.state="sent";let t=Yd(this.opts.staticKey),i=this.ss;i.mixHash(this.e.publicKey),i.mixKey(Eo(this.e.secretKey,this.opts.remoteStatic));let o=i.encryptAndHash(t.publicKey);i.mixKey(await h0(t,this.opts.remoteStatic));let s=i.encryptAndHash(e),r=Gl(this.e.publicKey,o,s);if(r.length>b0)throw new rt("handshake message too large");return r}async readMessage2(e){if(this.state!=="sent")throw new rt("handshake out of order");if(e.length<$n+Is)throw new rt("handshake message too short");this.state="done";let t=this.ss,i=e.subarray(0,$n);t.mixHash(i),t.mixKey(Eo(this.e.secretKey,i)),t.mixKey(await h0(Yd(this.opts.staticKey),i));let o=t.decryptAndHash(e.subarray($n)),[s,r]=t.split();return{payload:o,transport:{send:s,recv:r,handshakeHash:t.h,remoteStatic:this.opts.remoteStatic}}}},Xd=class{constructor(e){this.opts=e;this.e=e.ephemeral??Es(),this.ss.mixHash(e.prologue),this.ss.mixHash(e.staticKey.publicKey)}opts;ss=new Jd(g0);e;rs=null;re=null;state="start";readMessage1(e){if(this.state!=="start")throw new rt("handshake out of order");if(this.state="done",e.length<$n+$n+Is+Is)throw new rt("handshake message too short");let t=this.ss,i=e.subarray(0,$n).slice();t.mixHash(i),t.mixKey(Eo(this.opts.staticKey.secretKey,i));let o=t.decryptAndHash(e.subarray($n,$n+$n+Is));t.mixKey(Eo(this.opts.staticKey.secretKey,o));let s=t.decryptAndHash(e.subarray($n+$n+Is));return this.re=i,this.rs=o,this.state="read",{remoteStatic:o,payload:s}}writeMessage2(e){if(this.state!=="read"||!this.re||!this.rs)throw new rt("handshake out of order");this.state="done";let t=this.ss;t.mixHash(this.e.publicKey),t.mixKey(Eo(this.e.secretKey,this.re)),t.mixKey(Eo(this.e.secretKey,this.rs));let i=t.encryptAndHash(e),[o,s]=t.split();return{message:Gl(this.e.publicKey,i),transport:{send:s,recv:o,handshakeHash:t.h,remoteStatic:this.rs}}}},j1=new TextEncoder().encode("mdbase/v1/client"),N1=new Uint8Array(16)});function U1(n,e,t){return new Promise((i,o)=>{let s=()=>o(A("cancelled","connect aborted"));t?.addEventListener("abort",s,{once:!0}),n.onmessage=r=>{t?.removeEventListener("abort",s),n.onmessage=a=>{e.push(a)},i(r)},n.onclose=r=>{t?.removeEventListener("abort",s),o(r??A("unavailable","connection closed during the handshake"))}})}function jy(n,e,t=Ly,i=[]){let o=new Uint8Array(0),s=!1,r=setTimeout(()=>l(),t);r.unref?.();let a={ondata:null,onclose:null,write(c){if(s)throw A("unavailable","connection closed");for(let d=0;d<c.length;d+=My){if(e.send.count>=Gd-1)throw l(),A("unavailable","session message limit reached; reconnecting");n.send(e.send.encrypt(o,c.subarray(d,d+My)))}},close(){s||(s=!0,clearTimeout(r),n.close())}},p=c=>{if(s)return;let d;try{d=e.recv.decrypt(o,c)}catch{l(A("unavailable","transport message failed authentication","noise"));return}a.ondata?.(d)};if(n.onmessage=p,n.onclose=c=>l(c),i.length){let c=i.splice(0);queueMicrotask(()=>c.forEach(p))}function l(c){s||(s=!0,clearTimeout(r),n.close(),a.onclose?.(c))}return a}function Mi(n){return{description:n.description,async open(e,t){let i=()=>A("cancelled","connect aborted");if(t?.aborted)throw i();let o=await n.target(t);if(t?.aborted)throw i();let s=await o.openCarrier(t);if(t?.aborted)throw s.close(),i();try{let r=new Rs({prologue:o.prologue,staticKey:n.staticKey,remoteStatic:o.remoteStatic}),a=[],p=U1(s,a,t);p.catch(()=>{}),o.preamble&&s.send(o.preamble);let l=await r.writeMessage1(n.firstPayload?n.firstPayload(e):pe(e));if(t?.aborted)throw i();s.send(l);let{payload:c,transport:d}=await r.readMessage2(await p),u=ue(c);return{port:id(jy(s,d,n.lifetimeMs,a)),helloResponse:u,...o.device?{device:o.device}:{}}}catch(r){throw s.close(),oe(r)?r:r instanceof rt?A("unauthenticated",`handshake failed: ${r.message}`,"noise"):A("unavailable",`handshake failed: ${String(r)}`)}}}}function qs(n,e=D1,t){return new Promise((i,o)=>{let s;try{s=e(n)}catch(l){o(oe(l)?l:A("unavailable",`cannot open ${n}: ${String(l)}`));return}s.binaryType="arraybuffer";let r=!1,a={onmessage:null,onclose:null,send(l){s.send(l)},close(){try{s.close(1e3)}catch{}}},p=()=>{s.close(),o(A("cancelled","connect aborted"))};t?.addEventListener("abort",p,{once:!0}),s.onopen=()=>{r=!0,t?.removeEventListener("abort",p),i(a)},s.onmessage=l=>{let c=l.data;c instanceof ArrayBuffer?a.onmessage?.(new Uint8Array(c)):ArrayBuffer.isView(c)&&a.onmessage?.(new Uint8Array(c.buffer,c.byteOffset,c.byteLength))},s.onerror=()=>{},s.onclose=l=>{let c=$1(l.code,l.reason);r?a.onclose?.(c):(t?.removeEventListener("abort",p),o(c??A("unavailable",`cannot connect to ${n}`)))}})}function $1(n,e){switch(n){case 4404:return A("unavailable",e||"no device of this collection is online","no_device_online");case 4401:return A("unauthenticated",e||"relay refused the session");case 4403:return A("forbidden",e||"relay refused the session");case 4429:return A("rate_limited",e||"rate limited");default:return}}function _0(n){let e=new Uint8Array(0),t={onmessage:null,onclose:null,send(i){if(i.length>65535)throw A("too_large","Noise message over 65535 bytes");let o=new Uint8Array(2+i.length);o[0]=i.length>>8,o[1]=i.length&255,o.set(i,2),n.write(o)},close(){n.close()}};return n.ondata=i=>{let o=new Uint8Array(e.length+i.length);o.set(e),o.set(i,e.length);let s=0;for(;o.length-s>=2;){let r=o[s]<<8|o[s+1];if(o.length-s-2<r)break;t.onmessage?.(o.slice(s+2,s+2+r)),s+=2+r}e=o.slice(s)},n.onclose=i=>t.onclose?.(i?A("unavailable",i.message):void 0),t}var Ly,D1,Ts=I(()=>{"use strict";Je();ie();qo();Ol();Ly=1440*60*1e3;D1=n=>{let e=globalThis.WebSocket;if(!e)throw A("unavailable","no WebSocket implementation; pass webSocket");return new e(n)}});function Mr(n){return!1}function ot(n){try{let e=new URL(n);return e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname)}catch{return!1}}function Ny(n){return!1}var Zd=I(()=>{"use strict"});function Uy(n){let e=typeof n=="number"&&Number.isInteger(n)&&n>=1e3&&n<=4999?n:null;return Object.freeze({closeCode:e,closeClass:e===null?"unknown":z1[e]??"other"})}function A0(n){try{if(n instanceof Map&&n.has("relayCloseCode"))return Uy(n.get("relayCloseCode"))}catch{}}var z1,Dy=I(()=>{"use strict";z1={1e3:"normal",1001:"going_away",1002:"protocol_error",1003:"unsupported_data",1005:"no_status",1006:"abnormal",1007:"invalid_payload",1008:"policy_violation",1009:"message_too_big",1010:"extension_required",1011:"internal_error",1012:"service_restart",1013:"try_again_later",1014:"bad_gateway",1015:"tls_failure",4e3:"pipe_closed",4401:"unauthenticated",4403:"grant_inactive",4404:"connector_offline",4429:"connector_busy"}});function To(n,e){let t=typeof e=="string"&&F1.has(e)?e:void 0,i=Uy(n),o=new Map([["relayCloseCode",i.closeCode],["relayCloseClass",i.closeClass]]),s=(r,a,p,l)=>A(r,a,{reason:p,details:o,...l===void 0?{}:{retryAfterMs:l}});switch(i.closeCode){case 4401:return s("unauthenticated",t??"relay: unauthenticated","relay_unauthenticated");case 4403:return s("forbidden",t??"relay: grant inactive",t??"grant_inactive");case 4404:return t&&o.set("relay",t),s("unavailable","no device of this collection is online","no_device_online");case 4429:return s("rate_limited",t??"relay: busy",t??"connector_busy",5e3);case 4e3:return t==="grant_lease_expired"?s("unavailable","grant lease expired",t,1e3):t==="device_key_mismatch"?s("unauthenticated","relay: the routed key is not the device's",t):s("unavailable",`relay closed the pipe: ${t??"unknown"}`,t??"pipe_closed");default:return s("unavailable",`relay connection closed${i.closeCode===null?"":` (${i.closeCode})`}`,"relay_closed")}}function V1(n){let e=globalThis.WebSocket;if(!e)throw A("unavailable","no WebSocket implementation; pass webSocket");return new e(n)}function Ms(n,e,t=V1,i){let o="";try{o=new URL(n).protocol}catch{return Promise.reject(A("invalid_request",`invalid relay URL ${n}`,"relay_url"))}return o!=="wss:"&&!!1?Promise.reject(A("invalid_request","relay pipes require wss:","relay_insecure")):e.grant?new Promise((s,r)=>{let a;try{a=t(n)}catch(h){r(A("unavailable",`cannot open ${n}: ${String(h)}`));return}a.binaryType="arraybuffer";let p=!1,l=!1,c=new Uint8Array(0),d={onmessage:null,onclose:null,send(h){if(h.length>65535)throw A("too_large","Noise message over 65535 bytes");let m=new Uint8Array(4+h.length);new DataView(m.buffer).setUint32(0,h.length),m.set(h,4),a.send(m)},close(){try{a.close(1e3)}catch{}}},u=h=>{l?d.onclose?.(h):(l=!0,i?.removeEventListener("abort",f),r(h))},f=()=>{a.close(),u(A("cancelled","connect aborted"))};i?.addEventListener("abort",f,{once:!0}),a.onopen=()=>{a.send(JSON.stringify({type:"pipe_auth",access_token:e.accessToken,collection:e.collection,grant:e.grant,device:e.device,device_noise_pk:ri(e.devicePublicKey)}))},a.onmessage=h=>{let m=h.data;if(typeof m=="string"){let y;try{y=JSON.parse(m)}catch{return}y.type==="pipe_opened"&&!p?(p=!0,l=!0,i?.removeEventListener("abort",f),s(d)):y.type==="pipe_close"&&(a.close(),u(To(4e3,y.reason)));return}if(!p)return;let b=m instanceof ArrayBuffer?new Uint8Array(m):ArrayBuffer.isView(m)?new Uint8Array(m.buffer,m.byteOffset,m.byteLength):null;if(!b)return;if(b.length>B1){a.close(),u(A("too_large","relay frame over the limit"));return}let w=new Uint8Array(c.length+b.length);w.set(c),w.set(b,c.length);let g=0;for(;w.length-g>=4;){let y=new DataView(w.buffer,w.byteOffset+g,4).getUint32(0);if(y>65535){a.close(),u(A("internal","relay sent an oversized Noise message"));return}if(w.length-g-4<y)break;d.onmessage?.(w.slice(g+4,g+4+y)),g+=4+y}c=w.slice(g)},a.onerror=()=>{},a.onclose=h=>u(To(h.code,h.reason))}):Promise.reject(A("invalid_request","relay pipes require a grant","grant_required"))}var B1,F1,Yl=I(()=>{"use strict";Zd();ie();Dy();Je();B1=65539,F1=new Set("unauthenticated grant_inactive connector_offline connector_busy device_mismatch device_key_mismatch closed client_closed handshake_timeout idle lifetime frame_too_large invalid_frame not_served relay_closing authorization_unavailable grant_revoked grant_lease_expired grant_pending_approval grant_revoked_on_device unknown_grant".split(" "))});function Ls(n){return typeof n=="string"&&K1.has(n)}function zn(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"&&Ls(e.reason)?Object.freeze({state:"unavailable",reason:e.reason}):Object.freeze({state:"unavailable",reason:"device_offline"})}function un(n){let e=new Map([["availability",n]]);return n==="collection_deleted"?new se({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 $y,K1,Lr=I(()=>{"use strict";ie();$y=["device_offline","desktop_update_required","old_connector_running","approval_required","sync_required","no_device_registered","access_removed","collection_migrating","collection_not_yet_migrated","collection_deleted"],K1=new Set($y)});function By(n){let e=new Uint8Array(0),t=!1,i,o=null,s=null,r=[],a=0,p={get onmessage(){return o},set onmessage(d){for(o=d;d&&!t&&r.length&&o===d;){let u=r.shift();a-=u.length,d(u)}},get onclose(){return s},set onclose(d){s=d,d&&t&&i&&d(i)},send(d){if(t)throw A("unavailable","relay pipe closed");if(d.length>zy)throw A("too_large","Noise message over 65535 bytes");let u=new Uint8Array(4+d.length);new DataView(u.buffer).setUint32(0,d.length),u.set(d,4),n.send(u)},close(){t||(t=!0,r.length=0,a=0,n.close())}},l=(d,u)=>{t||(t=!0,e=new Uint8Array(0),r.length=0,a=0,i=To(d,u),n.close(),s?.(i))},c=d=>{if(!t){if(o)return o(d);if(r.length>=W1||a+d.length>H1)return l(4e3,"invalid_frame");r.push(d),a+=d.length}};return n.onmessage=d=>{if(t)return;if(d.length>S0)return l(4e3,"invalid_frame");let u=new Uint8Array(e.length+d.length);u.set(e),u.set(d,e.length);let f=0;for(;u.length-f>=4;){let h=new DataView(u.buffer,u.byteOffset+f,4).getUint32(0);if(h>zy)return l(4e3,"invalid_frame");if(u.length-f-4<h)break;let m=u.slice(f+4,f+4+h);if(f+=4+h,c(m),t)return}e=u.slice(f),e.length>S0&&l(4e3,"invalid_frame")},n.onclose=d=>l(d?.code,d?.reason),p}async function P0(n){try{return await n()}catch(e){if(oe(e))throw e;if(e?.code==="not_authorized")throw A("unauthenticated","Connect authorization is missing","not_authorized");let i=e?.cause;throw typeof i?.code=="number"?To(i.code,typeof i.reason=="string"?i.reason:void 0):A("unavailable","the relay pipe could not be opened","relay_unavailable")}}function js(n,e){let t=n.targets.filter(o=>Qd.test(o.device)&&/^[0-9a-f]{64}$/.test(o.noise_pk)&&!!o.relay_collection&&Qd.test(o.relay_collection)),i=t.filter(o=>o.device===e);return i.length?i:[...t.filter(o=>o.online===!0),...t.filter(o=>o.online!==!0)]}function x0(n){let e=n.collection,t=n.next,i=n.staticKey;if(!Qd.test(e))throw A("invalid_request","collection must be a UUID");let o=t.route.bind(t),s=t.openPipe.bind(t),r=null,a=Mi({description:`next-relay:${e}`,staticKey:i,target:async p=>{let l=await P0(()=>o(e,p?{signal:p}:{}));if(l.collection.toLowerCase()!==e.toLowerCase()||!Qd.test(l.grant))throw A("unauthenticated","the route does not match this collection's grant","route_mismatch");let c=zn(l.availability);if(c?.state==="unavailable")throw un(c.reason);let d=js(l,r)[0];if(!d)throw A("unavailable",l.reason==="no_device_registered"?"this collection has no device set up to serve it":"no device of this collection is online",l.reason??"no_device_online");let u=Object.freeze({...d}),f=u.noise_pk,h=new Uint8Array(32);for(let m=0;m<32;m++)h[m]=parseInt(f.slice(2*m,2*m+2),16);return{prologue:Ti(U(u.relay_collection),U(l.grant),U(u.device)),remoteStatic:h,device:u.device,openCarrier:async m=>{let b=await P0(()=>s(e,u,m?{signal:m}:{}));return By(b)}}}});return gd({description:a.description,open:async(p,l)=>{let c=await a.open(p,l);return r=c.device??null,c},get target(){return r}})}var zy,S0,W1,H1,Qd,Fy=I(()=>{"use strict";ge();Lr();ie();qo();Ts();Yl();bd();zy=65535,S0=4+zy,W1=16,H1=1<<20,Qd=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i});function tu(n){if(!n||typeof n!="object"||Array.isArray(n))throw Bn();return n}function N0(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 j0(n){let e=tu(n);if(!N0(e.issuer)||typeof e.subject!="string"||!e.subject.trim()||typeof e.name!="string"||!e.name.trim())throw Bn();let t=e.account_id;if(t!==void 0){if(typeof t!="string")throw Bn();try{if(U(t).every(i=>i===0))throw Bn()}catch{throw Bn()}}return{issuer:e.issuer,subject:e.subject,name:e.name,...t===void 0?{}:{accountId:t}}}function nu(n,e){return n.issuer===e.issuer&&n.subject===e.subject}function Z1(n){return Array.isArray(n)?n.flatMap(e=>{if(!(e instanceof Map))return[];let t=e.get("issuer"),i=e.get("subject");return typeof t!="string"||typeof i!="string"?[]:[{issuer:t,subject:i}]}):[]}function Q1(n){let e=n.fields;if(!(e instanceof Map))throw Bn();let t=e.get("name"),i=e.get("identities"),o=Z1(i),s=n.issues.find(r=>r.severity==="error");return s?{reason:s.message,claims:o}:typeof t!="string"||!t.trim()?{reason:"It needs a non-blank name.",claims:o}:i!==void 0&&(!Array.isArray(i)||o.length!==i.length||o.some(r=>!r.subject.trim()))?{reason:"Each account identity needs an exact issuer and subject.",claims:o}:{name:t,identities:o,claims:o}}var Gy,Bn,jr,iu=I(()=>{"use strict";ge();ie();Gy=Object.freeze({id:"mdbase.person",version:"2.0.0"}),Bn=()=>A("unavailable","invalid people response","people_response");jr=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=U(this.authority.collection),i=U(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=j0(t),o=tu(t).person_settings_url;if(o===void 0)return i;if(!N0(o))throw Bn();return{...i,personSettingsUrl:o}}async members(e={}){this.check(e.signal);let t=tu(await this.authority.request("members",e));if(this.check(e.signal),!Array.isArray(t.members)||t.members.length>1e3)throw Bn();return t.members.map(i=>{let o=j0(i),s=tu(i).role;if(s!=="owner"&&s!=="editor"&&s!=="viewer")throw Bn();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"&&oe(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 p=a.invalid.filter(u=>u.claims.some(f=>nu(f,s))),l=a.people.filter(u=>u.identities.some(f=>nu(f,s))),c=l[0],d=p.length?{status:"invalid",paths:p.map(u=>u.path)}:l.length>1?{status:"ambiguous",paths:l.map(u=>u.path)}:c?{status:"linked",person:c}:{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,p=[],l=[];for(;;){this.check(e.signal);let d=await this.client.queryContract(Gy,{pageSize:128,...i?{cursor:i}:{},...e.signal?{signal:e.signal}:{}}).catch(f=>{if(!i&&!r.size&&oe(f,"not_found")&&f.reason==="data_contract_not_found")return null;throw f});if(this.check(e.signal),this.checkReadSession(t),!d)return{people:p,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 Bn();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 Bn();if(r.add(h.id),r.size>1e4)throw A("too_large","person directory exceeds its record budget","people_budget");let b=h.implementations.map(Q1),w=b[0],g=b.find(v=>"reason"in v),y=b.flatMap(v=>v.claims);g&&"reason"in g?l.push({id:h.id,path:m.path,reason:g.reason,claims:y}):b.some(v=>JSON.stringify(v)!==JSON.stringify(w))?l.push({id:h.id,path:m.path,reason:"Its Person implementations project different values.",claims:y}):"name"in w&&p.push({id:h.id,path:m.path,name:w.name,identities:w.identities,typeNames:[...new Set(h.implementations.map(v=>v.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 Bn();a.add(u.cursor),i=u.cursor}let c=(d,u)=>d.path<u.path?-1:d.path>u.path?1:0;return{people:p.sort(c),invalid:l.sort(c),session:t}}}});function Jl(n){return typeof n=="string"&&nR.test(n)&&Number.isFinite(Date.parse(n))}function Xl(n){if(typeof n!="string"||!eR.test(n))throw pi()}function $0(n){if(typeof n!="string"||!ru.test(n))throw pi()}function Yy(n){if(typeof n!="string"||!n.length||n.length>100)throw pi()}function Jy(n){if(!n||Object.keys(n).some(e=>e!=="id"&&e!=="fireAt")||($0(n.id),!Jl(n.fireAt)))throw pi();return{id:n.id,fire_at:new Date(n.fireAt).toISOString()}}function ar(n){if(!n||typeof n!="object"||Array.isArray(n))throw Xt();return n}function z0(n){let e=ar(n);if(typeof e.id!="string"||!ru.test(e.id)||typeof e.criterion_id!="string"||!e.criterion_id.length||e.criterion_id.length>100||!Jl(e.fire_at)||!Number.isSafeInteger(e.generation)||e.generation<1||!["scheduled","firing","fired","cancelled"].includes(e.status)||!Jl(e.created_at)||!Jl(e.updated_at)||e.fired_at!==null&&!Jl(e.fired_at))throw Xt();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 Xy(n,e){let t=ar(n);if(t.namespace!==e||!Array.isArray(t.timers)||t.timers.length>Zl)throw Xt();let i=t.timers.map(z0);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 Xt();return{namespace:e,timers:i,...t.intent_revision===void 0?{}:{intentRevision:t.intent_revision}}}function U0(n){let{namespace:e,operationId:t,expectedRevision:i}=n;if(Xl(e),typeof t!="string"||!tR.test(t)||!Number.isSafeInteger(i)||i<0||i===Number.MAX_SAFE_INTEGER)throw pi();return{namespace:e,operationId:t,expectedRevision:i}}function iR(n,e){let t=ar(n),i=Xy(t,e);if(!Array.isArray(t.cancelled_ids)||t.cancelled_ids.length>Zl||t.cancelled_ids.some(o=>typeof o!="string"||!ru.test(o))||new Set(t.cancelled_ids).size!==t.cancelled_ids.length)throw Xt();return{...i,cancelledIds:[...t.cancelled_ids]}}function D0(n,e){let t=ar(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 Xt();let i=ar(t.result);if(Object.keys(i).some(r=>!["namespace","timers","cancelled_ids"].includes(r)))throw Xt();let o=iR(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(ar(r)).some(a=>!s.includes(a)))throw Xt();if(o.cancelledIds.some(r=>o.timers.some(a=>a.id===r)))throw Xt();return{protocolVersion:1,...e,committedRevision:t.committed_revision,result:o}}async function rR(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 eR,ru,tR,nR,Zl,pi,Xt,Ns,Zy=I(()=>{"use strict";ie();eR=/^[A-Za-z0-9._-]{1,64}$/,ru=/^[A-Za-z0-9._:-]{1,128}$/,tR=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,nR=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/i,Zl=1e4,pi=()=>A("invalid_request","Invalid opaque timer request."),Xt=()=>A("internal","Invalid control-plane timer response.","invalid_timer_response");Ns=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&&oe(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 Xl(e),this.run(t,!1,async i=>Xy(await this.port.list(e,i),e))}put(e,t={}){Xl(e.namespace),Yy(e.criterionId);let i=Jy(e.timer),o=e.namespace,s=e.criterionId;return this.run(t,!0,async r=>{let a=z0(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 Xt();return a})}cancel(e,t={}){if(Xl(e.namespace),$0(e.id),e.generation!==void 0&&(!Number.isSafeInteger(e.generation)||e.generation<1))throw pi();let{namespace:i,id:o,generation:s}=e;return this.run(t,!0,async r=>{let a=ar(await this.port.cancel(i,o,s,r));if(a.namespace!==i||a.id!==o||typeof a.cancelled!="boolean")throw Xt();return{namespace:i,id:o,cancelled:a.cancelled}})}reconcile(e,t={}){if(Xl(e.namespace),Yy(e.criterionId),!Array.isArray(e.timers)||e.timers.length>Zl)throw pi();let i=e.timers.map(Jy),o=new Map(i.map(a=>[a.id,a.fire_at]));if(o.size!==i.length)throw pi();let s=e.namespace,r=e.criterionId;return this.run(t,!0,async a=>{let p=ar(await this.port.reconcile(s,{criterion_id:r,timers:i},a)),l=Xy(p,s);if(l.timers.length!==i.length||l.timers.some(c=>!o.has(c.id)||c.criterionId!==r||Date.parse(c.fireAt)!==Date.parse(o.get(c.id)))||!Array.isArray(p.cancelled_ids)||p.cancelled_ids.length>Zl||p.cancelled_ids.some(c=>typeof c!="string"||!ru.test(c)||o.has(c))||new Set(p.cancelled_ids).size!==p.cancelled_ids.length)throw Xt();return{...l,cancelledIds:p.cancelled_ids}})}reconcileWithReceipt(e,t={}){let i=U0(e),o=e.criterionId;if(Yy(o),!Array.isArray(e.timers)||e.timers.length>Zl)throw pi();let s=e.timers.map(Jy),r=new Map(s.map(l=>[l.id,l.fire_at]));if(r.size!==s.length)throw pi();let a=this.port.reconcileWithReceipt;if(!a)throw A("upgrade_required","Timer port does not support original-operation recovery.","timer_operation_recovery_unavailable");let p={protocol_version:1,operation_id:i.operationId,expected_revision:i.expectedRevision};return this.run(t,!0,async l=>{let c=D0(await a.call(this.port,i.namespace,{criterion_id:o,timers:s,recovery:p},l),i);if(c.result.timers.length!==s.length||c.result.timers.some(d=>d.criterionId!==o||!r.has(d.id)||Date.parse(d.fireAt)!==Date.parse(r.get(d.id))))throw Xt();return c})}lookupOperation(e,t={}){let i=U0(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=ar(await o.call(this.port,i.namespace,i.operationId,s));if(r.outcome==="committed"&&Object.keys(r).length===2)return{outcome:"committed",receipt:D0(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 Xt()}).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 rR(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 Ds(n,e={}){return{description:"in-process",open(t,i){return new Promise((o,s)=>{let r;try{r=n.connect(e)}catch(p){s(A("unavailable",`runtime refused to connect: ${String(p)}`));return}let a=()=>{r.close(),s(A("cancelled","connect aborted"))};i?.addEventListener("abort",a,{once:!0}),r.onframe=p=>{i?.removeEventListener("abort",a),r.onframe=null,r.onclose=null,o({port:r,helloResponse:p})},r.onclose=p=>{i?.removeEventListener("abort",a),s(p??A("unavailable","runtime closed the session"))},r.send(t)})}}}var su=I(()=>{"use strict";ie()});function Mo(n){try{n instanceof Map&&(n={code:n.get("code"),paths:n.get("paths")});let e=lu(n),t=lu(e?.error)??e,i=t?.code;if(typeof i!="string"||!uR.test(i))return null;let o=lu(t.details)?.issues,s=Array.isArray(t.paths)?t.paths:Array.isArray(o)?o.slice(0,64).map(a=>lu(a)?.path):[],r=[];for(let a of s.slice(0,64))if(typeof a=="string"&&fR.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 Q0(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 uR,fR,lu,cu=I(()=>{"use strict";uR=/^[a-z][a-z0-9_]{0,63}$/,fR=/^(?:\/[A-Za-z0-9_-]{1,64}){1,6}$/,lu=n=>n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null});var ek,tk=I(()=>{"use strict";ek="Your account has reached its synced collection limit. Open an existing collection, delete one you own if Delete is available, or contact mdbase support to raise your limit."});function kn(n){return typeof n=="object"&&n!==null&&og.has(n)}function gR(n,e){let t=n?.retry_after_ms,i=n?.retry_after_seconds;if(typeof t=="number"&&Number.isFinite(t)&&t>=0)return pu(t);if(typeof i=="number"&&Number.isFinite(i)&&i>=0)return pu(i*1e3);let o=e?.get("retry-after")?.trim();return o&&/^[0-9]{1,6}$/.test(o)?pu(Number(o)*1e3):null}function du(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 Ur(n,e=null){try{if(kn(n))return n;if(typeof n!="object"||n===null||Array.isArray(n)||Object.getPrototypeOf(n)!==Object.prototype||Object.keys(n).sort().join(",")!==bR)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&&zs(t.code)===null||t.reason!==null&&zs(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:zs(t.code),reason:zs(t.reason),retryAfterMs:o===null?null:pu(o),updateUrl:du(t.updateUrl,e)});return og.add(s),s}catch{return null}}function Li(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:zs(s?.code),reason:zs(r?.reason),retryAfterMs:gR(r,t),updateUrl:du(r?.update_url,i)});return og.add(a),a}function St(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":e.some(t=>t==="moved_to_next_runtime"||t==="collection_moved"||t==="client_update_required")||n.status===426?"update_required":null}function Vs(n){try{return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n))}catch{return}}var hR,og,Bs,Fs,mR,yR,nk,zs,pu,bR,Fn=I(()=>{"use strict";hR=/^[a-z][a-z0-9_]{0,63}$/,og=new WeakSet;Bs=5e3,Fs=6e5,mR=Bs,yR=Fs,nk="https://mdbase.dev/downloads/",zs=n=>typeof n=="string"&&hR.test(n)?n:null,pu=n=>Math.min(yR,Math.max(mR,Math.round(n)));bR="code,reason,retryAfterMs,status,updateUrl"});function sg(n){if(typeof n!="string")return null;if(ok(n))return n;if(Object.hasOwn(uu,n))return uu[n];for(let e of["readiness_","application_"]){if(!n.startsWith(e))continue;let t=n.slice(e.length);if(e==="readiness_"&&Object.hasOwn(rk,t))return rk[t];if(ok(t))return t;if(Object.hasOwn(uu,t))return uu[t]}return null}function OR(n){let e=n.details;if(e instanceof Map&&Ls(e.get("availability")))return e.get("availability");let t=Vn(n.availability)??(n.state==="unavailable"?n:null);return t&&t.state==="unavailable"&&Ls(t.reason)?t.reason:null}function ag(n,e){let t=lr(n);if(t)return{codes:[t],retryAfterMs:null,updateUrl:null};let i=Vn(n);if(!i)return null;try{if(typeof i.kind=="string"&&"problem"in i&&Vn(i.problem)&&typeof Vn(i.problem).code=="string")return ag(Vn(i.problem).code,e);let o=Vn(i.problemDetail),s=Ur(i.server??o?.server,e),r=[s?.reason??null,s?.code??null].filter(c=>c!==null),a={retryAfterMs:s?.retryAfterMs??IR(i.retryAfterMs),updateUrl:du(s?.updateUrl,e),hasServer:i.server!=null||o?.server!=null};if("problem"in i||"readiness"in i||"assessment"in i){let c=lr(i.problem)??lr(Vn(i.problem)?.code);if(c)return{codes:[...r,c],...a,refusal:Mo(o?.registration)};let d=Vn(i.readiness)??i,u=Vn(d.assessment),f=lr(Vn(d.problem)?.code)??lr(Vn(u?.problem)?.code);if(f)return{codes:[f],...a};let h=lr(u?.status)??lr(i.status);return h==="incompatible"||h==="setup_required"?{codes:[h],...a}:null}let p=OR(i);if(p)return{codes:[p==="approval_required"?"device_approval_required":p],...a};if("state"in i&&(i.state==="available"||i.state==="opening"))return null;let l=[...r,lr(i.reason),lr(i.code)].filter(c=>c!==null);return l.length?{codes:l,...a,refusal:Mo(i.details??o?.registration)}:null}catch{return null}}function pk(n){let e=n.codes[n.codes.length-1];try{for(let t of n.codes){if(ck.has(t))return{key:null,original:e};let i=sg(t);if(i)return{key:i,original:e}}}catch{}return{key:"unknown",original:e}}function Lo(n,e={}){let t=typeof e.cpOrigin=="string"?e.cpOrigin:null,i=ag(n,t);if(!i)return null;let{key:o,original:s}=pk(i);if(o===null)return null;let[r,a,p,l,c=!1,d]=o==="unknown"?ak:o==="refused"&&!i.hasServer?PR:lk[o],u;try{let w=e.messages;u=w&&Object.hasOwn(w,o)?Vn(w[o]):void 0}catch{u=void 0}let f=(w,g)=>typeof w=="string"&&w.trim()?w:g,h=typeof e.recoveryAccountLabel=="string"&&e.recoveryAccountLabel.trim().length>0&&e.recoveryAccountLabel.length<=320&&!Array.from(e.recoveryAccountLabel).some(w=>w.charCodeAt(0)<32||w.charCodeAt(0)===127)?e.recoveryAccountLabel:null,m=o==="recovery_account_mismatch"&&h?`This collection belongs to ${h}. Sign in as ${h} to continue.`:a,b=o==="recovery_account_mismatch"&&h?`Sign in as ${h}`:d??wR[p];return Object.freeze({key:o,title:f(u?.title,r),message:f(u?.message,m),action:p,actionLabel:b===null?null:f(u?.actionLabel,b),severity:l,transient:c,code:s,developerMessage:dk(o,s,i.refusal??null),retryAfterMs:i.retryAfterMs,updateUrl:p==="update_app"?i.updateUrl??nk:null})}function dk(n,e,t){return n==="application_registration_refused"?Q0(t):Object.hasOwn(fu,n)?fu[n]:n==="unknown"?`Problem code ${e} has no user-facing copy; it is shown as a generic error.`:null}function hu(n,e={}){let t=ag(n,typeof e.cpOrigin=="string"?e.cpOrigin:null);if(!t)return null;for(let s of t.codes)if(Object.hasOwn(fu,s)&&ck.has(s))return fu[s];let{key:i,original:o}=pk(t);return i===null?null:dk(i,o,t.refusal??null)}var wR,sk,ak,vR,_R,AR,kR,ik,SR,PR,lk,uu,rk,xR,ck,fu,CR,lr,Vn,IR,ok,nc=I(()=>{"use strict";cu();tk();Lr();Fn();wR={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},sk=["device_offline","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","open_failed","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","configuration_conflict","configuration_unavailable","configuration_unsupported","configuration_busy_timeout","readiness_busy_timeout","setup_forbidden","setup_conflict","setup_unresolved","collection_setup_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"],ak=["Something went wrong","An unexpected problem occurred. Reload the app, and contact support if it keeps happening.","reload","error"],vR=["Another step hasn't finished","The app couldn't finish this step yet. Try again, or reload if it keeps happening.","retry","warning",!0],_R=["Can't complete this request","mdbase couldn't complete this request. Try again.","retry","warning"],AR=["Update required","Update mdbase on this computer, then reload the app to try again.","update_app","warning",!1,"Update mdbase"],kR=["Choose a collection","Pick the collection you want this app to use.","choose_collection","info"],ik=["Approval needed","This app needs your approval for extra access to your collection.","approve","info"],SR=["Set up this collection","This collection needs a one-time setup before the app can use it.","set_up","info"],PR=["Sign-in wasn't finished","Access wasn't approved. Sign in again when you're ready.","sign_in","info"],lk={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],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. Your other collections keep their access.","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:AR,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:_R,rate_limited:["Too many requests","Wait a moment, then try again.","retry","warning",!0],quota_exceeded:["Out of storage","You've reached your storage limit. Free up space to keep saving.","free_space","error"],account_collection_quota_exceeded:["Synced collection limit reached",ek,"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:ak,refused:["Sign-in didn't go through","mdbase didn't accept this sign-in. Try signing in again.","sign_in","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"],busy:vR,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:kR,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:SR,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:ik,capability_missing:ik,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"],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 something this app needs, and setup can't add it. A note type this app set up may have been changed or removed. Restore it, then try again.","retry","warning"],collection_setup_conflict:["Collection setup conflicts","This collection's definitions conflict with what this app requires. Ask its owner to review them, or choose a different collection. Setup cannot continue while these conflicts remain.","choose_collection","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"]},uu=Object.assign(Object.create(null),{no_device_online:"device_offline",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",change_entity_unsupported:"update_required",timer_operation_recovery_unavailable:"update_required",contract_query_version:"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",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"}),rk=Object.assign(Object.create(null),{budget:"readiness_budget",unsupported:"readiness_unsupported"}),xR=["application_registration_id_superseded","application_closing","cancelled","aborted"],ck=new Set(xR),fu=Object.assign(Object.create(null),{device_offline:"Collection availability device_offline: no device serving this Private collection is connected to the relay.",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.",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 (snapshot.saveWarning); only a log-confirmed receipt counts as saved.",sign_out_pending_writes:"sign_out_pending_writes: unconfirmed writes are still queued on this device; signOut({discard: true}) discards them."}),CR=/^[a-z][a-z0-9_-]{0,127}$/,lr=n=>typeof n=="string"&&CR.test(n)?n:null,Vn=n=>n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null,IR=n=>typeof n=="number"&&Number.isFinite(n)&&n>=0?Math.min(Fs,Math.max(Bs,Math.round(n))):null,ok=n=>Object.hasOwn(lk,n)});function Ks(n){if(typeof n!="string"||n.length>256)return null;let e=RR.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 lg(n,e){let t=typeof n=="string"?Ks(n):n,i=typeof e=="string"?Ks(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 jo(n,e){let t=Ks(n),i=Ks(e),o=t&&i?lg(t,i):null;return o===null?"unknown":o===0?"same":o<0?"installed_older":t.major===i.major?"installed_newer":"installed_newer_major"}var mu,uk,RR,yu=I(()=>{"use strict";mu="0|[1-9]\\d*",uk=`(?:${mu}|\\d*[a-zA-Z-][0-9a-zA-Z-]*)`,RR=new RegExp(`^v?(${mu})\\.(${mu})\\.(${mu})(?:-(${uk}(?:\\.${uk})*))?(?:\\+[0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*)?$`)});function wu(n){return n.storage.applicationNamespace===n.id?null:n.storage.applicationNamespace}function cg(n){return Array.from(it(new TextEncoder().encode(n)),e=>e.toString(16).padStart(2,"0")).join("")}function mk(n,e){return e===null?`bundle:${n}`:`bundle-storage:${cg(JSON.stringify([n,e]))}`}var vu=I(()=>{"use strict";Cr()});function Ne(n){if(n&&typeof n=="object")switch(n[Zt]){case di:case cr:return!0}return!1}function Re(n){if(n&&typeof n=="object")switch(n[Zt]){case _u:case di:case Sn:case cr:return!0}return!1}var _u,Au,di,pg,Sn,cr,Zt,ui,ji,Pn,xe,ve,fi,ku,Te=I(()=>{_u=Symbol.for("yaml.alias"),Au=Symbol.for("yaml.document"),di=Symbol.for("yaml.map"),pg=Symbol.for("yaml.pair"),Sn=Symbol.for("yaml.scalar"),cr=Symbol.for("yaml.seq"),Zt=Symbol.for("yaml.node.type"),ui=n=>!!n&&typeof n=="object"&&n[Zt]===_u,ji=n=>!!n&&typeof n=="object"&&n[Zt]===Au,Pn=n=>!!n&&typeof n=="object"&&n[Zt]===di,xe=n=>!!n&&typeof n=="object"&&n[Zt]===pg,ve=n=>!!n&&typeof n=="object"&&n[Zt]===Sn,fi=n=>!!n&&typeof n=="object"&&n[Zt]===cr;ku=n=>(ve(n)||Ne(n))&&!!n.anchor});function Ui(n,e){let t=gk(e);ji(n)?Hs(null,n.contents,t,Object.freeze([n]))===Ni&&(n.contents=null):Hs(null,n,t,Object.freeze([]))}function Hs(n,e,t,i){let o=bk(n,e,t,i);if(Re(o)||xe(o))return wk(n,i,o),Hs(n,o,t,i);if(typeof o!="symbol"){if(Ne(e)){i=Object.freeze(i.concat(e));for(let s=0;s<e.items.length;++s){let r=Hs(s,e.items[s],t,i);if(typeof r=="number")s=r-1;else{if(r===fn)return fn;r===Ni&&(e.items.splice(s,1),s-=1)}}}else if(xe(e)){i=Object.freeze(i.concat(e));let s=Hs("key",e.key,t,i);if(s===fn)return fn;s===Ni&&(e.key=null);let r=Hs("value",e.value,t,i);if(r===fn)return fn;r===Ni&&(e.value=null)}}return o}async function Su(n,e){let t=gk(e);ji(n)?await Gs(null,n.contents,t,Object.freeze([n]))===Ni&&(n.contents=null):await Gs(null,n,t,Object.freeze([]))}async function Gs(n,e,t,i){let o=await bk(n,e,t,i);if(Re(o)||xe(o))return wk(n,i,o),Gs(n,o,t,i);if(typeof o!="symbol"){if(Ne(e)){i=Object.freeze(i.concat(e));for(let s=0;s<e.items.length;++s){let r=await Gs(s,e.items[s],t,i);if(typeof r=="number")s=r-1;else{if(r===fn)return fn;r===Ni&&(e.items.splice(s,1),s-=1)}}}else if(xe(e)){i=Object.freeze(i.concat(e));let s=await Gs("key",e.key,t,i);if(s===fn)return fn;s===Ni&&(e.key=null);let r=await Gs("value",e.value,t,i);if(r===fn)return fn;r===Ni&&(e.value=null)}}return o}function gk(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 bk(n,e,t,i){if(typeof t=="function")return t(n,e,i);if(Pn(e))return t.Map?.(n,e,i);if(fi(e))return t.Seq?.(n,e,i);if(xe(e))return t.Pair?.(n,e,i);if(ve(e))return t.Scalar?.(n,e,i);if(ui(e))return t.Alias?.(n,e,i)}function wk(n,e,t){let i=e[e.length-1];if(Ne(i))i.items[n]=t;else if(xe(i))n==="key"?i.key=t:i.value=t;else if(ji(i))i.contents=t;else{let o=ui(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${o} parent`)}}var fn,yk,Ni,rc=I(()=>{Te();fn=Symbol("break visit"),yk=Symbol("skip children"),Ni=Symbol("remove node");Ui.BREAK=fn;Ui.SKIP=yk;Ui.REMOVE=Ni;Su.BREAK=fn;Su.SKIP=yk;Su.REMOVE=Ni});var TR,MR,Di,dg=I(()=>{Te();rc();TR={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},MR=n=>n.replace(/[!,[\]{}]/g,e=>TR[e]),Di=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+MR(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&&Re(e.contents)){let s={};Ui(e.contents,(r,a)=>{Re(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
|
`)}};Di.defaultYaml={explicit:!1,version:"1.2"};Di.defaultTags={"!!":"tag:yaml.org,2002:"}});function Pu(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 ug(n){let e=new Set;return Ui(n,{Value(t,i){i.anchor&&e.add(i.anchor)}}),e}function fg(n,e){for(let t=1;;++t){let i=`${n}${t}`;if(!e.has(i))return i}}function vk(n,e){let t=[],i=new Map,o=null;return{onAnchor:s=>{t.push(s),o??(o=ug(n));let r=fg(e,o);return o.add(r),r},setAnchors:()=>{for(let s of t){let r=i.get(s);if(typeof r=="object"&&r.anchor&&(ve(r.node)||Ne(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 xu=I(()=>{Te();rc()});function Dr(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=Dr(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=Dr(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=Dr(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=Dr(n,i,o,s);r===void 0?delete i[o]:r!==s&&(i[o]=r)}return n.call(e,t,i)}var hg=I(()=>{});function Pt(n,e,t){if(Array.isArray(n))return n.map((i,o)=>Pt(i,String(o),t));if(n&&typeof n.toJSON=="function"){if(!t||!ku(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 $r=I(()=>{Te()});var zr,Cu=I(()=>{hg();Te();$r();zr=class{constructor(e){Object.defineProperty(this,Zt,{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(!ji(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=Pt(this,"",r);if(typeof o=="function")for(let{count:p,res:l}of r.anchors.values())o(l,p);return typeof s=="function"?Dr(s,{"":a},"",a):a}}});function Iu(n,e,t){if(ui(e)){let i=e.resolve(n),o=t&&i&&t.get(i);return o?o.count*o.aliasCount:0}else if(Ne(e)){let i=0;for(let o of e.items){let s=Iu(n,o,t);s>i&&(i=s)}return i}else if(xe(e)){let i=Iu(n,e.key,t),o=Iu(n,e.value,t);return Math.max(i,o)}return 1}var pr,oc=I(()=>{xu();rc();Te();Cu();$r();pr=class extends zr{constructor(e){super(_u),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=[],Ui(e,{Node:(s,r)=>{(ui(r)||ku(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,p=s.get(o);if(p||(Pt(o,null,t),p=s.get(o)),p?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(a>=0&&(p.count+=1,p.aliasCount===0&&(p.aliasCount=Iu(r,o,s)),p.count*p.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(Pu(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 Ou,re,gt=I(()=>{Te();Cu();$r();Ou=n=>!n||typeof n!="function"&&typeof n!="object",re=class extends zr{constructor(e){super(Sn),this.value=e}toJSON(e,t){return t?.keep?this.value:Pt(this.value,e,t)}toString(){return String(this.value)}};re.BLOCK_FOLDED="BLOCK_FOLDED";re.BLOCK_LITERAL="BLOCK_LITERAL";re.PLAIN="PLAIN";re.QUOTE_DOUBLE="QUOTE_DOUBLE";re.QUOTE_SINGLE="QUOTE_SINGLE"});function jR(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 dr(n,e,t){if(ji(n)&&(n=n.contents),Re(n))return n;if(xe(n)){let d=t.schema[di].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,p;if(i&&n&&typeof n=="object"){if(p=a.get(n),p)return p.anchor??(p.anchor=o(n)),new pr(p.anchor);p={anchor:null,node:null},a.set(n,p)}e?.startsWith("!!")&&(e=LR+e.slice(2));let l=jR(n,e,r.tags);if(!l){if(n&&typeof n.toJSON=="function"&&(n=n.toJSON()),!n||typeof n!="object"){let d=new re(n);return p&&(p.node=d),d}l=n instanceof Map?r[di]:Symbol.iterator in Object(n)?r[cr]:r[di]}s&&(s(l),delete t.onTagObj);let c=l?.createNode?l.createNode(t.schema,n,t):typeof l?.nodeClass?.from=="function"?l.nodeClass.from(t.schema,n,t):new re(n);return e?c.tag=e:l.default||(c.tag=l.tag),p&&(p.node=c),c}var LR,sc=I(()=>{oc();Te();gt();LR="tag:yaml.org,2002:"});function ac(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 dr(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 Js,Ys,Ru=I(()=>{sc();Te();Cu();Js=n=>n==null||typeof n=="object"&&!!n[Symbol.iterator]().next().done,Ys=class extends zr{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=>Re(i)||xe(i)?i.clone(e):i),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Js(e))this.add(t);else{let[i,...o]=e,s=this.get(i,!0);if(Ne(s))s.addIn(o,t);else if(s===void 0&&this.schema)this.set(i,ac(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(Ne(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&&ve(s)?s.value:s:Ne(s)?s.getIn(o,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!xe(t))return!1;let i=t.value;return i==null||e&&ve(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 Ne(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(Ne(s))s.setIn(o,t);else if(s===void 0&&this.schema)this.set(i,ac(this.schema,o,t));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${o}`)}}}});function Kn(n,e){return/^\n+$/.test(n)?n.substring(1):e?n.replace(/^(?! *$)/gm,e):n}var _k,$i,lc=I(()=>{_k=n=>n.replace(/^(?!$)(?: $)?/gm,"#");$i=(n,e,t)=>n.endsWith(`
|
|
3
3
|
`)?Kn(t,e):t.includes(`
|
|
4
4
|
`)?`
|
|
@@ -127,4 +127,4 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
127
127
|
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let i="end"in t.value?t.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){pf(o,t.start),o.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,o=i&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",s=[];if(o&&t.sep&&!t.value){let r=[];for(let a=0;a<t.sep.length;++a){let p=t.sep[a];switch(p.type){case"newline":r.push(a);break;case"space":break;case"comment":p.indent>e.indent&&(r.length=0);break;default:r.length=0}}r.length>=2&&(s=t.sep.splice(r[1]))}switch(this.type){case"anchor":case"tag":o||t.value?(s.push(this.sourceToken),e.items.push({start:s}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):o||t.value?(s.push(this.sourceToken),e.items.push({start:s,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Yr(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]});else if(PS(t.key)&&!Yr(t.sep,"newline")){let r=aa(t.start),a=t.key,p=t.sep;p.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:a,sep:p}]})}else s.length>0?t.sep=t.sep.concat(s,this.sourceToken):t.sep.push(this.sourceToken);else if(Yr(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let r=aa(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||o?e.items.push({start:s,key:null,sep:[this.sourceToken]}):Yr(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);o||t.value?(e.items.push({start:s,key:r,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(r):(Object.assign(t,{key:r,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Yr(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&e.items.push({start:s});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let i="end"in t.value?t.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let o=e.items[e.items.length-2]?.value?.end;if(Array.isArray(o)){pf(o,t.start),o.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||Yr(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:o,sep:[]}):t.sep?this.stack.push(o):Object.assign(t,{key:o,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===e.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let o=cf(i),s=aa(o);SS(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
|
|
128
128
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
129
129
|
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=cf(e),i=aa(t);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=cf(e),i=aa(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}}});function cE(n){let e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new Ec||null,prettyErrors:e}}function ab(n,e={}){let{lineCounter:t,prettyErrors:i}=cE(e),o=new qc(t?.addNewLine),s=new Oc(e),r=null;for(let a of s.compose(o.parse(n),!0,n.length))if(!r)r=a;else if(r.options.logLevel!=="silent"){r.errors.push(new gi(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&t&&(r.errors.forEach($g(n,t)),r.warnings.forEach($g(n,t))),r}var xS=I(()=>{Zg();Ac();Pc();wg();Te();ob();sb()});var lb=I(()=>{Zg();Ac();Dg();Pc();oc();Te();Br();gt();Vr();Kr();af();rb();ob();sb();xS();rc()});var CS=I(()=>{lb();lb()});function Wn(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=Wn.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){for(let l in n)if(!(l==="app-runtime"||l==="mobile")){let c={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[c]:r.push(c),a++}if(n["app-runtime"]!==void 0){let l=n["app-runtime"];if(Array.isArray(l)){if(l.length>16){let f={instancePath:e+"/app-runtime",schemaPath:"#/$defs/installationOrigins/maxItems",keyword:"maxItems",params:{limit:16},message:"must NOT have more than 16 items"};r===null?r=[f]:r.push(f),a++}let c=l.length;for(let f=0;f<c;f++){let h=l[f];if(typeof h=="string"){if(D(h)>255){let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/maxLength",keyword:"maxLength",params:{limit:255},message:"must NOT have more than 255 characters"};r===null?r=[m]:r.push(m),a++}if(D(h)<1){let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[m]:r.push(m),a++}if(!hn(h)){let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[m]:r.push(m),a++}}else{let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[m]:r.push(m),a++}}let d=l.length,u;if(d>1){let f={};for(;d--;){let h=l[d];if(typeof h=="string"){if(typeof f[h]=="number"){u=f[h];let m={instancePath:e+"/app-runtime",schemaPath:"#/$defs/installationOrigins/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[m]:r.push(m),a++;break}f[h]=d}}}}else{let c={instancePath:e+"/app-runtime",schemaPath:"#/$defs/installationOrigins/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[c]:r.push(c),a++}}if(n.mobile!==void 0){let l=n.mobile;if(Array.isArray(l)){if(l.length>16){let f={instancePath:e+"/mobile",schemaPath:"#/$defs/installationOrigins/maxItems",keyword:"maxItems",params:{limit:16},message:"must NOT have more than 16 items"};r===null?r=[f]:r.push(f),a++}let c=l.length;for(let f=0;f<c;f++){let h=l[f];if(typeof h=="string"){if(D(h)>255){let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/maxLength",keyword:"maxLength",params:{limit:255},message:"must NOT have more than 255 characters"};r===null?r=[m]:r.push(m),a++}if(D(h)<1){let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[m]:r.push(m),a++}if(!hn(h)){let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[m]:r.push(m),a++}}else{let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[m]:r.push(m),a++}}let d=l.length,u;if(d>1){let f={};for(;d--;){let h=l[d];if(typeof h=="string"){if(typeof f[h]=="number"){u=f[h];let m={instancePath:e+"/mobile",schemaPath:"#/$defs/installationOrigins/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[m]:r.push(m),a++;break}f[h]=d}}}}else{let c={instancePath:e+"/mobile",schemaPath:"#/$defs/installationOrigins/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[c]:r.push(c),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return Wn.errors=r,a===0}function la(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=la.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.contract_version===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contract_version"},message:"must have required property 'contract_version'"};r===null?r=[l]:r.push(l),a++}if(n.required===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"required"},message:"must have required property 'required'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="contract_version"||l==="required"||l==="optional")){let c={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[c]:r.push(c),a++}if(n.contract_version!==void 0&&n.contract_version!==2){let l={instancePath:e+"/contract_version",schemaPath:"#/properties/contract_version/const",keyword:"const",params:{allowedValue:2},message:"must be equal to constant"};r===null?r=[l]:r.push(l),a++}if(n.required!==void 0){let l=n.required;if(Array.isArray(l)){if(l.length>32){let f={instancePath:e+"/required",schemaPath:"#/properties/required/maxItems",keyword:"maxItems",params:{limit:32},message:"must NOT have more than 32 items"};r===null?r=[f]:r.push(f),a++}let c=l.length;for(let f=0;f<c;f++){let h=l[f];if(!(h==="collection.read"||h==="records.create"||h==="records.edit"||h==="records.delete"||h==="views.manage"||h==="definitions.manage"||h==="background.schedule"||h==="offline.replica")){let m={instancePath:e+"/required/"+f,schemaPath:"#/$defs/applicationCapability/enum",keyword:"enum",params:{allowedValues:RS.enum},message:"must be equal to one of the allowed values"};r===null?r=[m]:r.push(m),a++}}let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(xn(l[d],l[u])){let f={instancePath:e+"/required",schemaPath:"#/properties/required/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[f]:r.push(f),a++;break e}}}else{let c={instancePath:e+"/required",schemaPath:"#/properties/required/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[c]:r.push(c),a++}}if(n.optional!==void 0){let l=n.optional;if(Array.isArray(l)){if(l.length>32){let f={instancePath:e+"/optional",schemaPath:"#/properties/optional/maxItems",keyword:"maxItems",params:{limit:32},message:"must NOT have more than 32 items"};r===null?r=[f]:r.push(f),a++}let c=l.length;for(let f=0;f<c;f++){let h=l[f];if(!(h==="collection.read"||h==="records.create"||h==="records.edit"||h==="records.delete"||h==="views.manage"||h==="definitions.manage"||h==="background.schedule"||h==="offline.replica")){let m={instancePath:e+"/optional/"+f,schemaPath:"#/$defs/applicationCapability/enum",keyword:"enum",params:{allowedValues:RS.enum},message:"must be equal to one of the allowed values"};r===null?r=[m]:r.push(m),a++}}let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(xn(l[d],l[u])){let f={instancePath:e+"/optional",schemaPath:"#/properties/optional/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[f]:r.push(f),a++;break e}}}else{let c={instancePath:e+"/optional",schemaPath:"#/properties/optional/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[c]:r.push(c),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return la.errors=r,a===0}function ca(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=ca.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.required===void 0){let d={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"required"},message:"must have required property 'required'"};r===null?r=[d]:r.push(d),a++}if(n.scope===void 0){let d={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"scope"},message:"must have required property 'scope'"};r===null?r=[d]:r.push(d),a++}for(let d in n)if(!(d==="required"||d==="optional"||d==="scope")){let u={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:d},message:"must NOT have additional properties"};r===null?r=[u]:r.push(u),a++}if(n.required!==void 0){let d=n.required;if(Array.isArray(d)){if(d.length>6){let m={instancePath:e+"/required",schemaPath:"#/$defs/fileActions/maxItems",keyword:"maxItems",params:{limit:6},message:"must NOT have more than 6 items"};r===null?r=[m]:r.push(m),a++}if(d.length<1){let m={instancePath:e+"/required",schemaPath:"#/$defs/fileActions/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[m]:r.push(m),a++}let u=d.length;for(let m=0;m<u;m++){let b=d[m];if(!(b==="list"||b==="read"||b==="add"||b==="replace"||b==="move"||b==="delete")){let w={instancePath:e+"/required/"+m,schemaPath:"#/$defs/fileActions/items/enum",keyword:"enum",params:{allowedValues:ES.items.enum},message:"must be equal to one of the allowed values"};r===null?r=[w]:r.push(w),a++}}let f=d.length,h;if(f>1){e:for(;f--;)for(h=f;h--;)if(xn(d[f],d[h])){let m={instancePath:e+"/required",schemaPath:"#/$defs/fileActions/uniqueItems",keyword:"uniqueItems",params:{i:f,j:h},message:"must NOT have duplicate items (items ## "+h+" and "+f+" are identical)"};r===null?r=[m]:r.push(m),a++;break e}}}else{let u={instancePath:e+"/required",schemaPath:"#/$defs/fileActions/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[u]:r.push(u),a++}}if(n.optional!==void 0){let d=n.optional;if(Array.isArray(d)){if(d.length>6){let m={instancePath:e+"/optional",schemaPath:"#/$defs/fileActions/maxItems",keyword:"maxItems",params:{limit:6},message:"must NOT have more than 6 items"};r===null?r=[m]:r.push(m),a++}if(d.length<1){let m={instancePath:e+"/optional",schemaPath:"#/$defs/fileActions/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[m]:r.push(m),a++}let u=d.length;for(let m=0;m<u;m++){let b=d[m];if(!(b==="list"||b==="read"||b==="add"||b==="replace"||b==="move"||b==="delete")){let w={instancePath:e+"/optional/"+m,schemaPath:"#/$defs/fileActions/items/enum",keyword:"enum",params:{allowedValues:ES.items.enum},message:"must be equal to one of the allowed values"};r===null?r=[w]:r.push(w),a++}}let f=d.length,h;if(f>1){e:for(;f--;)for(h=f;h--;)if(xn(d[f],d[h])){let m={instancePath:e+"/optional",schemaPath:"#/$defs/fileActions/uniqueItems",keyword:"uniqueItems",params:{i:f,j:h},message:"must NOT have duplicate items (items ## "+h+" and "+f+" are identical)"};r===null?r=[m]:r.push(m),a++;break e}}}else{let u={instancePath:e+"/optional",schemaPath:"#/$defs/fileActions/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[u]:r.push(u),a++}}if(n.scope!==void 0){let d=n.scope,u=a,f=!1,h=null,m=a;if(d&&typeof d=="object"&&!Array.isArray(d)){if(d.kind===void 0){let w={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};r===null?r=[w]:r.push(w),a++}if(d.folders===void 0){let w={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/required",keyword:"required",params:{missingProperty:"folders"},message:"must have required property 'folders'"};r===null?r=[w]:r.push(w),a++}for(let w in d)if(!(w==="kind"||w==="folders")){let g={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:w},message:"must NOT have additional properties"};r===null?r=[g]:r.push(g),a++}if(d.kind!==void 0&&d.kind!=="selected_folders"){let w={instancePath:e+"/scope/kind",schemaPath:"#/$defs/fileScope/oneOf/0/properties/kind/const",keyword:"const",params:{allowedValue:"selected_folders"},message:"must be equal to constant"};r===null?r=[w]:r.push(w),a++}if(d.folders!==void 0){let w=d.folders;if(Array.isArray(w)){if(w.length>100){let _={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/maxItems",keyword:"maxItems",params:{limit:100},message:"must NOT have more than 100 items"};r===null?r=[_]:r.push(_),a++}if(w.length<1){let _={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[_]:r.push(_),a++}let g=w.length;for(let _=0;_<g;_++){let k=w[_];if(typeof k=="string"){if(D(k)>1024){let S={instancePath:e+"/scope/folders/"+_,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};r===null?r=[S]:r.push(S),a++}if(D(k)<1){let S={instancePath:e+"/scope/folders/"+_,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[S]:r.push(S),a++}if(!$S.test(k)){let S={instancePath:e+"/scope/folders/"+_,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/pattern",keyword:"pattern",params:{pattern:"^(?!/)(?!\\.)(?!.*//)(?!.*\\\\)(?!.*/\\.)(?!(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*\\/(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*/$).+$"},message:'must match pattern "^(?!/)(?!\\.)(?!.*//)(?!.*\\\\)(?!.*/\\.)(?!(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*\\/(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*/$).+$"'};r===null?r=[S]:r.push(S),a++}}else{let S={instancePath:e+"/scope/folders/"+_,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[S]:r.push(S),a++}}let y=w.length,v;if(y>1){let _={};for(;y--;){let k=w[y];if(typeof k=="string"){if(typeof _[k]=="number"){v=_[k];let S={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/uniqueItems",keyword:"uniqueItems",params:{i:y,j:v},message:"must NOT have duplicate items (items ## "+v+" and "+y+" are identical)"};r===null?r=[S]:r.push(S),a++;break}_[k]=y}}}}else{let g={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[g]:r.push(g),a++}}}else{let w={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[w]:r.push(w),a++}var c=m===a;if(c){f=!0,h=0;var l=!0}let b=a;if(d&&typeof d=="object"&&!Array.isArray(d)){if(d.kind===void 0){let w={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};r===null?r=[w]:r.push(w),a++}for(let w in d)if(w!=="kind"){let g={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:w},message:"must NOT have additional properties"};r===null?r=[g]:r.push(g),a++}if(d.kind!==void 0&&d.kind!=="collection"){let w={instancePath:e+"/scope/kind",schemaPath:"#/$defs/fileScope/oneOf/1/properties/kind/const",keyword:"const",params:{allowedValue:"collection"},message:"must be equal to constant"};r===null?r=[w]:r.push(w),a++}}else{let w={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[w]:r.push(w),a++}var c=b===a;if(c&&f?(f=!1,h=[h,1]):c&&(f=!0,h=1,l!==!0&&(l=!0)),f)a=u,r!==null&&(u?r.length=u:r=null);else{let w={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf",keyword:"oneOf",params:{passingSchemas:h},message:"must match exactly one schema in oneOf"};r===null?r=[w]:r.push(w),a++}}}else{let d={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[d]:r.push(d),a++}return ca.errors=r,a===0}function pa(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=pa.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.id===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[c]:r.push(c),a++}if(n.path===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"path"},message:"must have required property 'path'"};r===null?r=[c]:r.push(c),a++}if(n.predicate===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"predicate"},message:"must have required property 'predicate'"};r===null?r=[c]:r.push(c),a++}if(n.value===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"value"},message:"must have required property 'value'"};r===null?r=[c]:r.push(c),a++}for(let c in n)if(!(c==="id"||c==="path"||c==="predicate"||c==="value")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:c},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(n.id!==void 0){let c=n.id;if(typeof c=="string"){if(D(c)>100){let d={instancePath:e+"/id",schemaPath:"#/properties/id/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[d]:r.push(d),a++}if(D(c)<1){let d={instancePath:e+"/id",schemaPath:"#/properties/id/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}if(!hf.test(c)){let d={instancePath:e+"/id",schemaPath:"#/properties/id/pattern",keyword:"pattern",params:{pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},message:'must match pattern "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"'};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.path!==void 0){let c=n.path;if(typeof c=="string"){if(D(c)>1024){let d={instancePath:e+"/path",schemaPath:"#/properties/path/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};r===null?r=[d]:r.push(d),a++}if(D(c)<1){let d={instancePath:e+"/path",schemaPath:"#/properties/path/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/path",schemaPath:"#/properties/path/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.predicate!==void 0&&n.predicate!=="contains"){let c={instancePath:e+"/predicate",schemaPath:"#/properties/predicate/const",keyword:"const",params:{allowedValue:"contains"},message:"must be equal to constant"};r===null?r=[c]:r.push(c),a++}if(n.value!==void 0){let c=n.value,d=a,u=!1,f=a;if(typeof c!="string"){let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/0/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[w]:r.push(w),a++}var l=f===a;u=u||l;let h=a;if(!(typeof c=="number"&&isFinite(c))){let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/1/type",keyword:"type",params:{type:"number"},message:"must be number"};r===null?r=[w]:r.push(w),a++}var l=h===a;u=u||l;let m=a;if(typeof c!="boolean"){let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/2/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};r===null?r=[w]:r.push(w),a++}var l=m===a;u=u||l;let b=a;if(c!==null){let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/3/type",keyword:"type",params:{type:"null"},message:"must be null"};r===null?r=[w]:r.push(w),a++}var l=b===a;if(u=u||l,u)a=d,r!==null&&(d?r.length=d:r=null);else{let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};r===null?r=[w]:r.push(w),a++}}}else{let c={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[c]:r.push(c),a++}return pa.errors=r,a===0}function Gn(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=Gn.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.id===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[l]:r.push(l),a++}if(n.version===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"version"},message:"must have required property 'version'"};r===null?r=[l]:r.push(l),a++}if(n.digest===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"digest"},message:"must have required property 'digest'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="id"||l==="version"||l==="digest")){let c={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[c]:r.push(c),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(D(l)>100){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[c]:r.push(c),a++}if(D(l)<1){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[c]:r.push(c),a++}if(!xa.test(l)){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/pattern",keyword:"pattern",params:{pattern:"^[a-z0-9]+(?:[._-][a-z0-9]+)*$"},message:'must match pattern "^[a-z0-9]+(?:[._-][a-z0-9]+)*$"'};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.version!==void 0){let l=n.version;if(typeof l=="string"){if(!mf.test(l)){let c={instancePath:e+"/version",schemaPath:"#/properties/version/pattern",keyword:"pattern",params:{pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},message:'must match pattern "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"'};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/version",schemaPath:"#/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.digest!==void 0){let l=n.digest;if(typeof l=="string"){if(!da.test(l)){let c={instancePath:e+"/digest",schemaPath:"#/properties/digest/pattern",keyword:"pattern",params:{pattern:"^sha256:[0-9a-f]{64}$"},message:'must match pattern "^sha256:[0-9a-f]{64}$"'};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/digest",schemaPath:"#/properties/digest/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return Gn.errors=r,a===0}function ua(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=ua.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.access===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"access"},message:"must have required property 'access'"};r===null?r=[c]:r.push(c),a++}if(n.contracts===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contracts"},message:"must have required property 'contracts'"};r===null?r=[c]:r.push(c),a++}for(let c in n)if(!(c==="capabilities"||c==="access"||c==="collection_kind"||c==="people"||c==="files"||c==="configuration"||c==="contracts")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:c},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(n.capabilities!==void 0&&(la(n.capabilities,{instancePath:e+"/capabilities",parentData:n,parentDataProperty:"capabilities",rootData:o,dynamicAnchors:s})||(r=r===null?la.errors:r.concat(la.errors),a=r.length)),n.access!==void 0&&n.access!=="full_collection"){let c={instancePath:e+"/access",schemaPath:"#/properties/access/const",keyword:"const",params:{allowedValue:"full_collection"},message:"must be equal to constant"};r===null?r=[c]:r.push(c),a++}if(n.collection_kind!==void 0&&n.collection_kind!=="hosted"){let c={instancePath:e+"/collection_kind",schemaPath:"#/properties/collection_kind/const",keyword:"const",params:{allowedValue:"hosted"},message:"must be equal to constant"};r===null?r=[c]:r.push(c),a++}if(n.people!==void 0){let c=n.people,d=a,u=!1,f=a;if(c&&typeof c=="object"&&!Array.isArray(c)&&c.required===void 0){let m={instancePath:e+"/people",schemaPath:"#/properties/people/anyOf/0/required",keyword:"required",params:{missingProperty:"required"},message:"must have required property 'required'"};r===null?r=[m]:r.push(m),a++}var l=f===a;u=u||l;let h=a;if(c&&typeof c=="object"&&!Array.isArray(c)&&c.optional===void 0){let m={instancePath:e+"/people",schemaPath:"#/properties/people/anyOf/1/required",keyword:"required",params:{missingProperty:"optional"},message:"must have required property 'optional'"};r===null?r=[m]:r.push(m),a++}var l=h===a;if(u=u||l,u)a=d,r!==null&&(d?r.length=d:r=null);else{let m={instancePath:e+"/people",schemaPath:"#/properties/people/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};r===null?r=[m]:r.push(m),a++}if(c&&typeof c=="object"&&!Array.isArray(c)){if(c.version===void 0){let m={instancePath:e+"/people",schemaPath:"#/properties/people/required",keyword:"required",params:{missingProperty:"version"},message:"must have required property 'version'"};r===null?r=[m]:r.push(m),a++}for(let m in c)if(!(m==="version"||m==="required"||m==="optional")){let b={instancePath:e+"/people",schemaPath:"#/properties/people/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:m},message:"must NOT have additional properties"};r===null?r=[b]:r.push(b),a++}if(c.version!==void 0&&c.version!==1){let m={instancePath:e+"/people/version",schemaPath:"#/properties/people/properties/version/const",keyword:"const",params:{allowedValue:1},message:"must be equal to constant"};r===null?r=[m]:r.push(m),a++}if(c.required!==void 0){let m=c.required;if(Array.isArray(m)){if(m.length<1){let y={instancePath:e+"/people/required",schemaPath:"#/$defs/peoplePermissions/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[y]:r.push(y),a++}let b=m.length;for(let y=0;y<b;y++){let v=m[y];if(!(v==="identity"||v==="members")){let _={instancePath:e+"/people/required/"+y,schemaPath:"#/$defs/peoplePermissions/items/enum",keyword:"enum",params:{allowedValues:OS.items.enum},message:"must be equal to one of the allowed values"};r===null?r=[_]:r.push(_),a++}}let w=m.length,g;if(w>1){e:for(;w--;)for(g=w;g--;)if(xn(m[w],m[g])){let y={instancePath:e+"/people/required",schemaPath:"#/$defs/peoplePermissions/uniqueItems",keyword:"uniqueItems",params:{i:w,j:g},message:"must NOT have duplicate items (items ## "+g+" and "+w+" are identical)"};r===null?r=[y]:r.push(y),a++;break e}}}else{let b={instancePath:e+"/people/required",schemaPath:"#/$defs/peoplePermissions/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[b]:r.push(b),a++}}if(c.optional!==void 0){let m=c.optional;if(Array.isArray(m)){if(m.length<1){let y={instancePath:e+"/people/optional",schemaPath:"#/$defs/peoplePermissions/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[y]:r.push(y),a++}let b=m.length;for(let y=0;y<b;y++){let v=m[y];if(!(v==="identity"||v==="members")){let _={instancePath:e+"/people/optional/"+y,schemaPath:"#/$defs/peoplePermissions/items/enum",keyword:"enum",params:{allowedValues:OS.items.enum},message:"must be equal to one of the allowed values"};r===null?r=[_]:r.push(_),a++}}let w=m.length,g;if(w>1){e:for(;w--;)for(g=w;g--;)if(xn(m[w],m[g])){let y={instancePath:e+"/people/optional",schemaPath:"#/$defs/peoplePermissions/uniqueItems",keyword:"uniqueItems",params:{i:w,j:g},message:"must NOT have duplicate items (items ## "+g+" and "+w+" are identical)"};r===null?r=[y]:r.push(y),a++;break e}}}else{let b={instancePath:e+"/people/optional",schemaPath:"#/$defs/peoplePermissions/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[b]:r.push(b),a++}}}else{let m={instancePath:e+"/people",schemaPath:"#/properties/people/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[m]:r.push(m),a++}}if(n.files!==void 0&&(ca(n.files,{instancePath:e+"/files",parentData:n,parentDataProperty:"files",rootData:o,dynamicAnchors:s})||(r=r===null?ca.errors:r.concat(ca.errors),a=r.length)),n.configuration!==void 0){let c=n.configuration;if(Array.isArray(c)){if(c.length>50){let u={instancePath:e+"/configuration",schemaPath:"#/properties/configuration/maxItems",keyword:"maxItems",params:{limit:50},message:"must NOT have more than 50 items"};r===null?r=[u]:r.push(u),a++}let d=c.length;for(let u=0;u<d;u++)pa(c[u],{instancePath:e+"/configuration/"+u,parentData:c,parentDataProperty:u,rootData:o,dynamicAnchors:s})||(r=r===null?pa.errors:r.concat(pa.errors),a=r.length)}else{let d={instancePath:e+"/configuration",schemaPath:"#/properties/configuration/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[d]:r.push(d),a++}}if(n.contracts!==void 0){let c=n.contracts;if(Array.isArray(c)){if(c.length>20){let h={instancePath:e+"/contracts",schemaPath:"#/properties/contracts/maxItems",keyword:"maxItems",params:{limit:20},message:"must NOT have more than 20 items"};r===null?r=[h]:r.push(h),a++}let d=c.length;for(let h=0;h<d;h++)Gn(c[h],{instancePath:e+"/contracts/"+h,parentData:c,parentDataProperty:h,rootData:o,dynamicAnchors:s})||(r=r===null?Gn.errors:r.concat(Gn.errors),a=r.length);let u=c.length,f;if(u>1){e:for(;u--;)for(f=u;f--;)if(xn(c[u],c[f])){let h={instancePath:e+"/contracts",schemaPath:"#/properties/contracts/uniqueItems",keyword:"uniqueItems",params:{i:u,j:f},message:"must NOT have duplicate items (items ## "+f+" and "+u+" are identical)"};r===null?r=[h]:r.push(h),a++;break e}}}else{let d={instancePath:e+"/contracts",schemaPath:"#/properties/contracts/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[d]:r.push(d),a++}}}else{let c={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[c]:r.push(c),a++}return ua.errors=r,a===0}function fa(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=fa.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.requirement===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"requirement"},message:"must have required property 'requirement'"};r===null?r=[c]:r.push(c),a++}if(n.operation===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"operation"},message:"must have required property 'operation'"};r===null?r=[c]:r.push(c),a++}if(n.path===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"path"},message:"must have required property 'path'"};r===null?r=[c]:r.push(c),a++}if(n.value===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"value"},message:"must have required property 'value'"};r===null?r=[c]:r.push(c),a++}for(let c in n)if(!(c==="requirement"||c==="operation"||c==="path"||c==="value")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:c},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(n.requirement!==void 0){let c=n.requirement;if(typeof c=="string"){if(D(c)>100){let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[d]:r.push(d),a++}if(D(c)<1){let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}if(!hf.test(c)){let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/pattern",keyword:"pattern",params:{pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},message:'must match pattern "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"'};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.operation!==void 0&&n.operation!=="set_add"){let c={instancePath:e+"/operation",schemaPath:"#/properties/operation/const",keyword:"const",params:{allowedValue:"set_add"},message:"must be equal to constant"};r===null?r=[c]:r.push(c),a++}if(n.path!==void 0){let c=n.path;if(typeof c=="string"){if(D(c)>1024){let d={instancePath:e+"/path",schemaPath:"#/properties/path/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};r===null?r=[d]:r.push(d),a++}if(D(c)<1){let d={instancePath:e+"/path",schemaPath:"#/properties/path/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/path",schemaPath:"#/properties/path/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.value!==void 0){let c=n.value,d=a,u=!1,f=a;if(typeof c!="string"){let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/0/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[w]:r.push(w),a++}var l=f===a;u=u||l;let h=a;if(!(typeof c=="number"&&isFinite(c))){let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/1/type",keyword:"type",params:{type:"number"},message:"must be number"};r===null?r=[w]:r.push(w),a++}var l=h===a;u=u||l;let m=a;if(typeof c!="boolean"){let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/2/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};r===null?r=[w]:r.push(w),a++}var l=m===a;u=u||l;let b=a;if(c!==null){let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/3/type",keyword:"type",params:{type:"null"},message:"must be null"};r===null?r=[w]:r.push(w),a++}var l=b===a;if(u=u||l,u)a=d,r!==null&&(d?r.length=d:r=null);else{let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};r===null?r=[w]:r.push(w),a++}}}else{let c={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[c]:r.push(c),a++}return fa.errors=r,a===0}function ha(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=ha.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.kind===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};r===null?r=[c]:r.push(c),a++}if(n.mode===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"mode"},message:"must have required property 'mode'"};r===null?r=[c]:r.push(c),a++}if(n.source===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"source"},message:"must have required property 'source'"};r===null?r=[c]:r.push(c),a++}if(n.target===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"target"},message:"must have required property 'target'"};r===null?r=[c]:r.push(c),a++}if(n.digest===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"digest"},message:"must have required property 'digest'"};r===null?r=[c]:r.push(c),a++}for(let c in n)if(!(c==="kind"||c==="mode"||c==="upgrade_from"||c==="source"||c==="target"||c==="digest")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:c},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(n.kind!==void 0){let c=n.kind;if(!(c==="contract"||c==="type"||c==="schema")){let d={instancePath:e+"/kind",schemaPath:"#/properties/kind/enum",keyword:"enum",params:{allowedValues:qS.properties.kind.enum},message:"must be equal to one of the allowed values"};r===null?r=[d]:r.push(d),a++}}if(n.mode!==void 0){let c=n.mode;if(!(c==="managed"||c==="seed")){let d={instancePath:e+"/mode",schemaPath:"#/properties/mode/enum",keyword:"enum",params:{allowedValues:qS.properties.mode.enum},message:"must be equal to one of the allowed values"};r===null?r=[d]:r.push(d),a++}}if(n.upgrade_from!==void 0){let c=n.upgrade_from,d=a,u=!1,f=null,h=a;if(c&&typeof c=="object"&&!Array.isArray(c)){if(c.digest===void 0){let b={instancePath:e+"/upgrade_from",schemaPath:"#/$defs/typePackUpgradeBaseline/required",keyword:"required",params:{missingProperty:"digest"},message:"must have required property 'digest'"};r===null?r=[b]:r.push(b),a++}if(c.document===void 0){let b={instancePath:e+"/upgrade_from",schemaPath:"#/$defs/typePackUpgradeBaseline/required",keyword:"required",params:{missingProperty:"document"},message:"must have required property 'document'"};r===null?r=[b]:r.push(b),a++}for(let b in c)if(!(b==="digest"||b==="document"||b==="version")){let w={instancePath:e+"/upgrade_from",schemaPath:"#/$defs/typePackUpgradeBaseline/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:b},message:"must NOT have additional properties"};r===null?r=[w]:r.push(w),a++}if(c.digest!==void 0){let b=c.digest;if(typeof b=="string"){if(!da.test(b)){let w={instancePath:e+"/upgrade_from/digest",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/digest/pattern",keyword:"pattern",params:{pattern:"^sha256:[0-9a-f]{64}$"},message:'must match pattern "^sha256:[0-9a-f]{64}$"'};r===null?r=[w]:r.push(w),a++}}else{let w={instancePath:e+"/upgrade_from/digest",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/digest/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[w]:r.push(w),a++}}if(c.document!==void 0){let b=c.document;if(typeof b=="string"){if(D(b)>262144){let w={instancePath:e+"/upgrade_from/document",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/document/maxLength",keyword:"maxLength",params:{limit:262144},message:"must NOT have more than 262144 characters"};r===null?r=[w]:r.push(w),a++}}else{let w={instancePath:e+"/upgrade_from/document",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/document/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[w]:r.push(w),a++}}if(c.version!==void 0){let b=c.version;if(!(typeof b=="number"&&!(b%1)&&!isNaN(b)&&isFinite(b))){let w={instancePath:e+"/upgrade_from/version",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/version/type",keyword:"type",params:{type:"integer"},message:"must be integer"};r===null?r=[w]:r.push(w),a++}if(typeof b=="number"&&isFinite(b)&&(b<1||isNaN(b))){let w={instancePath:e+"/upgrade_from/version",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/version/minimum",keyword:"minimum",params:{comparison:">=",limit:1},message:"must be >= 1"};r===null?r=[w]:r.push(w),a++}}}else{let b={instancePath:e+"/upgrade_from",schemaPath:"#/$defs/typePackUpgradeBaseline/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[b]:r.push(b),a++}var l=h===a;l&&(u=!0,f=0);let m=a;if(Array.isArray(c)){if(c.length<1){let w={instancePath:e+"/upgrade_from",schemaPath:"#/properties/upgrade_from/oneOf/1/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[w]:r.push(w),a++}let b=c.length;for(let w=0;w<b;w++){let g=c[w];if(g&&typeof g=="object"&&!Array.isArray(g)){if(g.digest===void 0){let y={instancePath:e+"/upgrade_from/"+w,schemaPath:"#/$defs/typePackUpgradeBaseline/required",keyword:"required",params:{missingProperty:"digest"},message:"must have required property 'digest'"};r===null?r=[y]:r.push(y),a++}if(g.document===void 0){let y={instancePath:e+"/upgrade_from/"+w,schemaPath:"#/$defs/typePackUpgradeBaseline/required",keyword:"required",params:{missingProperty:"document"},message:"must have required property 'document'"};r===null?r=[y]:r.push(y),a++}for(let y in g)if(!(y==="digest"||y==="document"||y==="version")){let v={instancePath:e+"/upgrade_from/"+w,schemaPath:"#/$defs/typePackUpgradeBaseline/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};r===null?r=[v]:r.push(v),a++}if(g.digest!==void 0){let y=g.digest;if(typeof y=="string"){if(!da.test(y)){let v={instancePath:e+"/upgrade_from/"+w+"/digest",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/digest/pattern",keyword:"pattern",params:{pattern:"^sha256:[0-9a-f]{64}$"},message:'must match pattern "^sha256:[0-9a-f]{64}$"'};r===null?r=[v]:r.push(v),a++}}else{let v={instancePath:e+"/upgrade_from/"+w+"/digest",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/digest/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[v]:r.push(v),a++}}if(g.document!==void 0){let y=g.document;if(typeof y=="string"){if(D(y)>262144){let v={instancePath:e+"/upgrade_from/"+w+"/document",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/document/maxLength",keyword:"maxLength",params:{limit:262144},message:"must NOT have more than 262144 characters"};r===null?r=[v]:r.push(v),a++}}else{let v={instancePath:e+"/upgrade_from/"+w+"/document",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/document/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[v]:r.push(v),a++}}if(g.version!==void 0){let y=g.version;if(!(typeof y=="number"&&!(y%1)&&!isNaN(y)&&isFinite(y))){let v={instancePath:e+"/upgrade_from/"+w+"/version",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/version/type",keyword:"type",params:{type:"integer"},message:"must be integer"};r===null?r=[v]:r.push(v),a++}if(typeof y=="number"&&isFinite(y)&&(y<1||isNaN(y))){let v={instancePath:e+"/upgrade_from/"+w+"/version",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/version/minimum",keyword:"minimum",params:{comparison:">=",limit:1},message:"must be >= 1"};r===null?r=[v]:r.push(v),a++}}}else{let y={instancePath:e+"/upgrade_from/"+w,schemaPath:"#/$defs/typePackUpgradeBaseline/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[y]:r.push(y),a++}}}else{let b={instancePath:e+"/upgrade_from",schemaPath:"#/properties/upgrade_from/oneOf/1/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[b]:r.push(b),a++}var l=m===a;if(l&&u?(u=!1,f=[f,1]):l&&(u=!0,f=1),u)a=d,r!==null&&(d?r.length=d:r=null);else{let b={instancePath:e+"/upgrade_from",schemaPath:"#/properties/upgrade_from/oneOf",keyword:"oneOf",params:{passingSchemas:f},message:"must match exactly one schema in oneOf"};r===null?r=[b]:r.push(b),a++}}if(n.source!==void 0){let c=n.source;if(typeof c=="string"){if(D(c)>240){let d={instancePath:e+"/source",schemaPath:"#/properties/source/maxLength",keyword:"maxLength",params:{limit:240},message:"must NOT have more than 240 characters"};r===null?r=[d]:r.push(d),a++}if(D(c)<1){let d={instancePath:e+"/source",schemaPath:"#/properties/source/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/source",schemaPath:"#/properties/source/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.target!==void 0){let c=n.target;if(typeof c=="string"){if(D(c)>240){let d={instancePath:e+"/target",schemaPath:"#/properties/target/maxLength",keyword:"maxLength",params:{limit:240},message:"must NOT have more than 240 characters"};r===null?r=[d]:r.push(d),a++}if(D(c)<1){let d={instancePath:e+"/target",schemaPath:"#/properties/target/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/target",schemaPath:"#/properties/target/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.digest!==void 0){let c=n.digest;if(typeof c=="string"){if(!da.test(c)){let d={instancePath:e+"/digest",schemaPath:"#/properties/digest/pattern",keyword:"pattern",params:{pattern:"^sha256:[0-9a-f]{64}$"},message:'must match pattern "^sha256:[0-9a-f]{64}$"'};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/digest",schemaPath:"#/properties/digest/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}}else{let c={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[c]:r.push(c),a++}return ha.errors=r,a===0}function ma(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=ma.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.kind===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};r===null?r=[l]:r.push(l),a++}if(n.id===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[l]:r.push(l),a++}if(n.version===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"version"},message:"must have required property 'version'"};r===null?r=[l]:r.push(l),a++}if(n.resources===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"resources"},message:"must have required property 'resources'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="kind"||l==="id"||l==="version"||l==="name"||l==="description"||l==="resources"||zS.test(l))){let c={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[c]:r.push(c),a++}if(n.kind!==void 0&&n.kind!=="mdbase.type-pack"){let l={instancePath:e+"/kind",schemaPath:"#/properties/kind/const",keyword:"const",params:{allowedValue:"mdbase.type-pack"},message:"must be equal to constant"};r===null?r=[l]:r.push(l),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(D(l)>100){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[c]:r.push(c),a++}if(D(l)<1){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[c]:r.push(c),a++}if(!xa.test(l)){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/pattern",keyword:"pattern",params:{pattern:"^[a-z0-9]+(?:[._-][a-z0-9]+)*$"},message:'must match pattern "^[a-z0-9]+(?:[._-][a-z0-9]+)*$"'};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.version!==void 0){let l=n.version;if(typeof l=="string"){if(!mf.test(l)){let c={instancePath:e+"/version",schemaPath:"#/$defs/contract/properties/version/pattern",keyword:"pattern",params:{pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},message:'must match pattern "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"'};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/version",schemaPath:"#/$defs/contract/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.name!==void 0){let l=n.name;if(typeof l=="string"){if(D(l)>100){let c={instancePath:e+"/name",schemaPath:"#/properties/name/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[c]:r.push(c),a++}if(D(l)<1){let c={instancePath:e+"/name",schemaPath:"#/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.description!==void 0){let l=n.description;if(typeof l=="string"){if(D(l)>500){let c={instancePath:e+"/description",schemaPath:"#/properties/description/maxLength",keyword:"maxLength",params:{limit:500},message:"must NOT have more than 500 characters"};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.resources!==void 0){let l=n.resources;if(Array.isArray(l)){if(l.length>100){let d={instancePath:e+"/resources",schemaPath:"#/properties/resources/maxItems",keyword:"maxItems",params:{limit:100},message:"must NOT have more than 100 items"};r===null?r=[d]:r.push(d),a++}if(l.length<1){let d={instancePath:e+"/resources",schemaPath:"#/properties/resources/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[d]:r.push(d),a++}let c=l.length;for(let d=0;d<c;d++)ha(l[d],{instancePath:e+"/resources/"+d,parentData:l,parentDataProperty:d,rootData:o,dynamicAnchors:s})||(r=r===null?ha.errors:r.concat(ha.errors),a=r.length)}else{let c={instancePath:e+"/resources",schemaPath:"#/properties/resources/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[c]:r.push(c),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return ma.errors=r,a===0}function ya(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=ya.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.manifest===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"manifest"},message:"must have required property 'manifest'"};r===null?r=[l]:r.push(l),a++}if(n.resources===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"resources"},message:"must have required property 'resources'"};r===null?r=[l]:r.push(l),a++}if(n.provides===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"provides"},message:"must have required property 'provides'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="manifest"||l==="resources"||l==="provides")){let c={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[c]:r.push(c),a++}if(n.manifest!==void 0&&(ma(n.manifest,{instancePath:e+"/manifest",parentData:n,parentDataProperty:"manifest",rootData:o,dynamicAnchors:s})||(r=r===null?ma.errors:r.concat(ma.errors),a=r.length)),n.resources!==void 0){let l=n.resources;if(Array.isArray(l)){if(l.length>100){let d={instancePath:e+"/resources",schemaPath:"#/properties/resources/maxItems",keyword:"maxItems",params:{limit:100},message:"must NOT have more than 100 items"};r===null?r=[d]:r.push(d),a++}if(l.length<1){let d={instancePath:e+"/resources",schemaPath:"#/properties/resources/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[d]:r.push(d),a++}let c=l.length;for(let d=0;d<c;d++){let u=l[d];if(u&&typeof u=="object"&&!Array.isArray(u)){if(u.source===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/required",keyword:"required",params:{missingProperty:"source"},message:"must have required property 'source'"};r===null?r=[f]:r.push(f),a++}if(u.document===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/required",keyword:"required",params:{missingProperty:"document"},message:"must have required property 'document'"};r===null?r=[f]:r.push(f),a++}for(let f in u)if(!(f==="source"||f==="document")){let h={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:f},message:"must NOT have additional properties"};r===null?r=[h]:r.push(h),a++}if(u.source!==void 0){let f=u.source;if(typeof f=="string"){if(D(f)>240){let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackSourceResource/properties/source/maxLength",keyword:"maxLength",params:{limit:240},message:"must NOT have more than 240 characters"};r===null?r=[h]:r.push(h),a++}if(D(f)<1){let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackSourceResource/properties/source/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[h]:r.push(h),a++}}else{let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackSourceResource/properties/source/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[h]:r.push(h),a++}}if(u.document!==void 0){let f=u.document;if(typeof f=="string"){if(D(f)>262144){let h={instancePath:e+"/resources/"+d+"/document",schemaPath:"#/$defs/typePackSourceResource/properties/document/maxLength",keyword:"maxLength",params:{limit:262144},message:"must NOT have more than 262144 characters"};r===null?r=[h]:r.push(h),a++}}else{let h={instancePath:e+"/resources/"+d+"/document",schemaPath:"#/$defs/typePackSourceResource/properties/document/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[h]:r.push(h),a++}}}else{let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[f]:r.push(f),a++}}}else{let c={instancePath:e+"/resources",schemaPath:"#/properties/resources/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[c]:r.push(c),a++}}if(n.provides!==void 0){let l=n.provides;if(Array.isArray(l)){if(l.length>20){let f={instancePath:e+"/provides",schemaPath:"#/properties/provides/maxItems",keyword:"maxItems",params:{limit:20},message:"must NOT have more than 20 items"};r===null?r=[f]:r.push(f),a++}let c=l.length;for(let f=0;f<c;f++)Gn(l[f],{instancePath:e+"/provides/"+f,parentData:l,parentDataProperty:f,rootData:o,dynamicAnchors:s})||(r=r===null?Gn.errors:r.concat(Gn.errors),a=r.length);let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(xn(l[d],l[u])){let f={instancePath:e+"/provides",schemaPath:"#/properties/provides/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[f]:r.push(f),a++;break e}}}else{let c={instancePath:e+"/provides",schemaPath:"#/properties/provides/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[c]:r.push(c),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return ya.errors=r,a===0}function ga(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=ga.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.id===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[l]:r.push(l),a++}if(n.event===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"event"},message:"must have required property 'event'"};r===null?r=[l]:r.push(l),a++}if(n.presentation===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"presentation"},message:"must have required property 'presentation'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="id"||l==="event"||l==="if"||l==="debounce"||l==="minimum_interval"||l==="presentation")){let c={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[c]:r.push(c),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(D(l)>100){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[c]:r.push(c),a++}if(D(l)<1){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[c]:r.push(c),a++}if(!xa.test(l)){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/pattern",keyword:"pattern",params:{pattern:"^[a-z0-9]+(?:[._-][a-z0-9]+)*$"},message:'must match pattern "^[a-z0-9]+(?:[._-][a-z0-9]+)*$"'};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.event!==void 0&&(Gn(n.event,{instancePath:e+"/event",parentData:n,parentDataProperty:"event",rootData:o,dynamicAnchors:s})||(r=r===null?Gn.errors:r.concat(Gn.errors),a=r.length)),n.if!==void 0){let l=n.if;if(l&&typeof l=="object"&&!Array.isArray(l)){if(l.$expr===void 0){let c={instancePath:e+"/if",schemaPath:"#/properties/if/required",keyword:"required",params:{missingProperty:"$expr"},message:"must have required property '$expr'"};r===null?r=[c]:r.push(c),a++}for(let c in l)if(c!=="$expr"){let d={instancePath:e+"/if",schemaPath:"#/properties/if/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:c},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(l.$expr!==void 0){let c=l.$expr;if(typeof c=="string"){if(D(c)>4096){let d={instancePath:e+"/if/$expr",schemaPath:"#/properties/if/properties/%24expr/maxLength",keyword:"maxLength",params:{limit:4096},message:"must NOT have more than 4096 characters"};r===null?r=[d]:r.push(d),a++}if(D(c)<1){let d={instancePath:e+"/if/$expr",schemaPath:"#/properties/if/properties/%24expr/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/if/$expr",schemaPath:"#/properties/if/properties/%24expr/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}}else{let c={instancePath:e+"/if",schemaPath:"#/properties/if/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[c]:r.push(c),a++}}if(n.debounce!==void 0){let l=n.debounce;if(typeof l=="string"){if(!df.test(l)){let c={instancePath:e+"/debounce",schemaPath:"#/$defs/duration/pattern",keyword:"pattern",params:{pattern:"^[0-9]+(ms|s|m|h|d)$"},message:'must match pattern "^[0-9]+(ms|s|m|h|d)$"'};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/debounce",schemaPath:"#/$defs/duration/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.minimum_interval!==void 0){let l=n.minimum_interval;if(typeof l=="string"){if(!df.test(l)){let c={instancePath:e+"/minimum_interval",schemaPath:"#/$defs/duration/pattern",keyword:"pattern",params:{pattern:"^[0-9]+(ms|s|m|h|d)$"},message:'must match pattern "^[0-9]+(ms|s|m|h|d)$"'};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/minimum_interval",schemaPath:"#/$defs/duration/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.presentation!==void 0){let l=n.presentation;if(l&&typeof l=="object"&&!Array.isArray(l)){if(l.title===void 0){let c={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/required",keyword:"required",params:{missingProperty:"title"},message:"must have required property 'title'"};r===null?r=[c]:r.push(c),a++}for(let c in l)if(!(c==="title"||c==="body"||c==="tag")){let d={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:c},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(l.title!==void 0){let c=l.title;if(typeof c=="string"){if(D(c)>80){let d={instancePath:e+"/presentation/title",schemaPath:"#/properties/presentation/properties/title/maxLength",keyword:"maxLength",params:{limit:80},message:"must NOT have more than 80 characters"};r===null?r=[d]:r.push(d),a++}if(D(c)<1){let d={instancePath:e+"/presentation/title",schemaPath:"#/properties/presentation/properties/title/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/presentation/title",schemaPath:"#/properties/presentation/properties/title/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(l.body!==void 0){let c=l.body;if(typeof c=="string"){if(D(c)>160){let d={instancePath:e+"/presentation/body",schemaPath:"#/properties/presentation/properties/body/maxLength",keyword:"maxLength",params:{limit:160},message:"must NOT have more than 160 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/presentation/body",schemaPath:"#/properties/presentation/properties/body/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(l.tag!==void 0){let c=l.tag;if(typeof c=="string"){if(D(c)>80){let d={instancePath:e+"/presentation/tag",schemaPath:"#/properties/presentation/properties/tag/maxLength",keyword:"maxLength",params:{limit:80},message:"must NOT have more than 80 characters"};r===null?r=[d]:r.push(d),a++}if(D(c)<1){let d={instancePath:e+"/presentation/tag",schemaPath:"#/properties/presentation/properties/tag/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/presentation/tag",schemaPath:"#/properties/presentation/properties/tag/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}}else{let c={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[c]:r.push(c),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return ga.errors=r,a===0}function uf(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=uf.evaluated;p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0);let l=a,c=!1,d=null,u=a;if(n&&typeof n=="object"&&!Array.isArray(n)){if(n.homepage===void 0){let g={instancePath:e,schemaPath:"#/oneOf/0/required",keyword:"required",params:{missingProperty:"homepage"},message:"must have required property 'homepage'"};r===null?r=[g]:r.push(g),a++}if(n.redirect_uris===void 0){let g={instancePath:e,schemaPath:"#/oneOf/0/required",keyword:"required",params:{missingProperty:"redirect_uris"},message:"must have required property 'redirect_uris'"};r===null?r=[g]:r.push(g),a++}if(n.distribution!==void 0&&n.distribution!=="web"){let g={instancePath:e+"/distribution",schemaPath:"#/oneOf/0/properties/distribution/const",keyword:"const",params:{allowedValue:"web"},message:"must be equal to constant"};r===null?r=[g]:r.push(g),a++}if(n.project_url!==void 0){let g={instancePath:e+"/project_url",schemaPath:"#/oneOf/0/properties/project_url/false schema",keyword:"false schema",params:{},message:"boolean schema is false"};r===null?r=[g]:r.push(g),a++}}var m=u===a;if(m){c=!0,d=0;var f={};f.distribution=!0,f.homepage=!0,f.redirect_uris=!0,f.project_url=!0}let h=a;if(n&&typeof n=="object"&&!Array.isArray(n)){if(n.distribution===void 0){let g={instancePath:e,schemaPath:"#/oneOf/1/required",keyword:"required",params:{missingProperty:"distribution"},message:"must have required property 'distribution'"};r===null?r=[g]:r.push(g),a++}if(n.distribution!==void 0&&n.distribution!=="portable"){let g={instancePath:e+"/distribution",schemaPath:"#/oneOf/1/properties/distribution/const",keyword:"const",params:{allowedValue:"portable"},message:"must be equal to constant"};r===null?r=[g]:r.push(g),a++}if(n.platform!==void 0){let g={instancePath:e+"/platform",schemaPath:"#/oneOf/1/properties/platform/false schema",keyword:"false schema",params:{},message:"boolean schema is false"};r===null?r=[g]:r.push(g),a++}if(n.homepage!==void 0){let g={instancePath:e+"/homepage",schemaPath:"#/oneOf/1/properties/homepage/false schema",keyword:"false schema",params:{},message:"boolean schema is false"};r===null?r=[g]:r.push(g),a++}if(n.redirect_uris!==void 0){let g={instancePath:e+"/redirect_uris",schemaPath:"#/oneOf/1/properties/redirect_uris/false schema",keyword:"false schema",params:{},message:"boolean schema is false"};r===null?r=[g]:r.push(g),a++}}var m=h===a;if(m&&c?(c=!1,d=[d,1]):m&&(c=!0,d=1,f!==!0&&(f=f||{},f.distribution=!0,f.platform=!0,f.homepage=!0,f.redirect_uris=!0)),c)a=l,r!==null&&(l?r.length=l:r=null);else{let g={instancePath:e,schemaPath:"#/oneOf",keyword:"oneOf",params:{passingSchemas:d},message:"must match exactly one schema in oneOf"};r===null?r=[g]:r.push(g),a++}if(n&&typeof n=="object"&&!Array.isArray(n)){if(n.manifest_version===void 0){let g={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"manifest_version"},message:"must have required property 'manifest_version'"};r===null?r=[g]:r.push(g),a++}if(n.id===void 0){let g={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[g]:r.push(g),a++}if(n.name===void 0){let g={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"name"},message:"must have required property 'name'"};r===null?r=[g]:r.push(g),a++}for(let g in n)if(!NS.call(IS.properties,g)){let y={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:g},message:"must NOT have additional properties"};r===null?r=[y]:r.push(y),a++}if(n.manifest_version!==void 0&&n.manifest_version!==1){let g={instancePath:e+"/manifest_version",schemaPath:"#/properties/manifest_version/const",keyword:"const",params:{allowedValue:1},message:"must be equal to constant"};r===null?r=[g]:r.push(g),a++}if(n.distribution!==void 0){let g=n.distribution;if(!(g==="web"||g==="portable")){let y={instancePath:e+"/distribution",schemaPath:"#/properties/distribution/enum",keyword:"enum",params:{allowedValues:IS.properties.distribution.enum},message:"must be equal to one of the allowed values"};r===null?r=[y]:r.push(y),a++}}if(n.id!==void 0){let g=n.id;if(typeof g=="string"){if(D(g)>150){let y={instancePath:e+"/id",schemaPath:"#/properties/id/maxLength",keyword:"maxLength",params:{limit:150},message:"must NOT have more than 150 characters"};r===null?r=[y]:r.push(y),a++}if(D(g)<5){let y={instancePath:e+"/id",schemaPath:"#/properties/id/minLength",keyword:"minLength",params:{limit:5},message:"must NOT have fewer than 5 characters"};r===null?r=[y]:r.push(y),a++}if(!US.test(g)){let y={instancePath:e+"/id",schemaPath:"#/properties/id/pattern",keyword:"pattern",params:{pattern:"^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*){2,}$"},message:'must match pattern "^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*){2,}$"'};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.name!==void 0){let g=n.name;if(typeof g=="string"){if(D(g)>100){let y={instancePath:e+"/name",schemaPath:"#/properties/name/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[y]:r.push(y),a++}if(D(g)<1){let y={instancePath:e+"/name",schemaPath:"#/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.platform!==void 0&&n.platform!=="native"){let g={instancePath:e+"/platform",schemaPath:"#/properties/platform/const",keyword:"const",params:{allowedValue:"native"},message:"must be equal to constant"};r===null?r=[g]:r.push(g),a++}if(n.homepage!==void 0){let g=n.homepage;if(typeof g=="string"){if(!Jr.test(g)){let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};r===null?r=[y]:r.push(y),a++}if(!hn(g)){let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.project_url!==void 0){let g=n.project_url;if(typeof g=="string"){if(!Jr.test(g)){let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};r===null?r=[y]:r.push(y),a++}if(!hn(g)){let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.icon!==void 0){let g=n.icon;if(typeof g=="string"){if(!Jr.test(g)){let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};r===null?r=[y]:r.push(y),a++}if(!hn(g)){let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.redirect_uris!==void 0){let g=n.redirect_uris;if(Array.isArray(g)){if(g.length>10){let k={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/maxItems",keyword:"maxItems",params:{limit:10},message:"must NOT have more than 10 items"};r===null?r=[k]:r.push(k),a++}if(g.length<1){let k={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[k]:r.push(k),a++}let y=g.length;for(let k=0;k<y;k++){let S=g[k];if(typeof S=="string"){if(!hn(S)){let x={instancePath:e+"/redirect_uris/"+k,schemaPath:"#/properties/redirect_uris/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[x]:r.push(x),a++}}else{let x={instancePath:e+"/redirect_uris/"+k,schemaPath:"#/properties/redirect_uris/items/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[x]:r.push(x),a++}}let v=g.length,_;if(v>1){let k={};for(;v--;){let S=g[v];if(typeof S=="string"){if(typeof k[S]=="number"){_=k[S];let x={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/uniqueItems",keyword:"uniqueItems",params:{i:v,j:_},message:"must NOT have duplicate items (items ## "+_+" and "+v+" are identical)"};r===null?r=[x]:r.push(x),a++;break}k[S]=v}}}}else{let y={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[y]:r.push(y),a++}}if(n.installation_origins!==void 0){let g=n.installation_origins;if(g&&typeof g=="object"&&!Array.isArray(g)){for(let y in g)if(!(y==="lab"||y==="staging"||y==="production")){let v={instancePath:e+"/installation_origins",schemaPath:"#/properties/installation_origins/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};r===null?r=[v]:r.push(v),a++}g.lab!==void 0&&(Wn(g.lab,{instancePath:e+"/installation_origins/lab",parentData:g,parentDataProperty:"lab",rootData:o,dynamicAnchors:s})||(r=r===null?Wn.errors:r.concat(Wn.errors),a=r.length)),g.staging!==void 0&&(Wn(g.staging,{instancePath:e+"/installation_origins/staging",parentData:g,parentDataProperty:"staging",rootData:o,dynamicAnchors:s})||(r=r===null?Wn.errors:r.concat(Wn.errors),a=r.length)),g.production!==void 0&&(Wn(g.production,{instancePath:e+"/installation_origins/production",parentData:g,parentDataProperty:"production",rootData:o,dynamicAnchors:s})||(r=r===null?Wn.errors:r.concat(Wn.errors),a=r.length))}else{let y={instancePath:e+"/installation_origins",schemaPath:"#/properties/installation_origins/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[y]:r.push(y),a++}}if(n.requirements!==void 0&&(ua(n.requirements,{instancePath:e+"/requirements",parentData:n,parentDataProperty:"requirements",rootData:o,dynamicAnchors:s})||(r=r===null?ua.errors:r.concat(ua.errors),a=r.length)),n.provisions!==void 0){let g=n.provisions;if(g&&typeof g=="object"&&!Array.isArray(g)){if(g.type_packs===void 0){let y={instancePath:e+"/provisions",schemaPath:"#/properties/provisions/required",keyword:"required",params:{missingProperty:"type_packs"},message:"must have required property 'type_packs'"};r===null?r=[y]:r.push(y),a++}for(let y in g)if(!(y==="configuration"||y==="type_packs")){let v={instancePath:e+"/provisions",schemaPath:"#/properties/provisions/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};r===null?r=[v]:r.push(v),a++}if(g.configuration!==void 0){let y=g.configuration;if(Array.isArray(y)){if(y.length>50){let _={instancePath:e+"/provisions/configuration",schemaPath:"#/properties/provisions/properties/configuration/maxItems",keyword:"maxItems",params:{limit:50},message:"must NOT have more than 50 items"};r===null?r=[_]:r.push(_),a++}let v=y.length;for(let _=0;_<v;_++)fa(y[_],{instancePath:e+"/provisions/configuration/"+_,parentData:y,parentDataProperty:_,rootData:o,dynamicAnchors:s})||(r=r===null?fa.errors:r.concat(fa.errors),a=r.length)}else{let v={instancePath:e+"/provisions/configuration",schemaPath:"#/properties/provisions/properties/configuration/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[v]:r.push(v),a++}}if(g.type_packs!==void 0){let y=g.type_packs;if(Array.isArray(y)){if(y.length>20){let _={instancePath:e+"/provisions/type_packs",schemaPath:"#/properties/provisions/properties/type_packs/maxItems",keyword:"maxItems",params:{limit:20},message:"must NOT have more than 20 items"};r===null?r=[_]:r.push(_),a++}let v=y.length;for(let _=0;_<v;_++)ya(y[_],{instancePath:e+"/provisions/type_packs/"+_,parentData:y,parentDataProperty:_,rootData:o,dynamicAnchors:s})||(r=r===null?ya.errors:r.concat(ya.errors),a=r.length)}else{let v={instancePath:e+"/provisions/type_packs",schemaPath:"#/properties/provisions/properties/type_packs/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[v]:r.push(v),a++}}}else{let y={instancePath:e+"/provisions",schemaPath:"#/properties/provisions/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[y]:r.push(y),a++}}if(n.notifications!==void 0){let g=n.notifications;if(g&&typeof g=="object"&&!Array.isArray(g)){if(g.criteria===void 0){let y={instancePath:e+"/notifications",schemaPath:"#/properties/notifications/required",keyword:"required",params:{missingProperty:"criteria"},message:"must have required property 'criteria'"};r===null?r=[y]:r.push(y),a++}for(let y in g)if(!(y==="criteria"||y==="native_delivery")){let v={instancePath:e+"/notifications",schemaPath:"#/properties/notifications/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};r===null?r=[v]:r.push(v),a++}if(g.criteria!==void 0){let y=g.criteria;if(Array.isArray(y)){if(y.length>50){let _={instancePath:e+"/notifications/criteria",schemaPath:"#/properties/notifications/properties/criteria/maxItems",keyword:"maxItems",params:{limit:50},message:"must NOT have more than 50 items"};r===null?r=[_]:r.push(_),a++}let v=y.length;for(let _=0;_<v;_++)ga(y[_],{instancePath:e+"/notifications/criteria/"+_,parentData:y,parentDataProperty:_,rootData:o,dynamicAnchors:s})||(r=r===null?ga.errors:r.concat(ga.errors),a=r.length)}else{let v={instancePath:e+"/notifications/criteria",schemaPath:"#/properties/notifications/properties/criteria/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[v]:r.push(v),a++}}if(g.native_delivery!==void 0){let y=g.native_delivery,v=a,_=!1,k=null,S=a;if(y&&typeof y=="object"&&!Array.isArray(y)){if(y.mode===void 0){let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/required",keyword:"required",params:{missingProperty:"mode"},message:"must have required property 'mode'"};r===null?r=[P]:r.push(P),a++}if(y.firebase_project_id===void 0){let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/required",keyword:"required",params:{missingProperty:"firebase_project_id"},message:"must have required property 'firebase_project_id'"};r===null?r=[P]:r.push(P),a++}for(let P in y)if(!(P==="mode"||P==="firebase_project_id")){let C={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:P},message:"must NOT have additional properties"};r===null?r=[C]:r.push(C),a++}if(y.mode!==void 0&&y.mode!=="managed_fcm"){let P={instancePath:e+"/notifications/native_delivery/mode",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/mode/const",keyword:"const",params:{allowedValue:"managed_fcm"},message:"must be equal to constant"};r===null?r=[P]:r.push(P),a++}if(y.firebase_project_id!==void 0){let P=y.firebase_project_id;if(typeof P=="string"){if(D(P)>63){let C={instancePath:e+"/notifications/native_delivery/firebase_project_id",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/firebase_project_id/maxLength",keyword:"maxLength",params:{limit:63},message:"must NOT have more than 63 characters"};r===null?r=[C]:r.push(C),a++}if(D(P)<6){let C={instancePath:e+"/notifications/native_delivery/firebase_project_id",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/firebase_project_id/minLength",keyword:"minLength",params:{limit:6},message:"must NOT have fewer than 6 characters"};r===null?r=[C]:r.push(C),a++}if(!DS.test(P)){let C={instancePath:e+"/notifications/native_delivery/firebase_project_id",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/firebase_project_id/pattern",keyword:"pattern",params:{pattern:"^[a-z][a-z0-9-]*[a-z0-9]$"},message:'must match pattern "^[a-z][a-z0-9-]*[a-z0-9]$"'};r===null?r=[C]:r.push(C),a++}}else{let C={instancePath:e+"/notifications/native_delivery/firebase_project_id",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/firebase_project_id/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[C]:r.push(C),a++}}}else{let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[P]:r.push(P),a++}var w=S===a;if(w){_=!0,k=0;var b=!0}let x=a;if(y&&typeof y=="object"&&!Array.isArray(y)){if(y.mode===void 0){let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/required",keyword:"required",params:{missingProperty:"mode"},message:"must have required property 'mode'"};r===null?r=[P]:r.push(P),a++}if(y.url===void 0){let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/required",keyword:"required",params:{missingProperty:"url"},message:"must have required property 'url'"};r===null?r=[P]:r.push(P),a++}for(let P in y)if(!(P==="mode"||P==="url")){let C={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:P},message:"must NOT have additional properties"};r===null?r=[C]:r.push(C),a++}if(y.mode!==void 0&&y.mode!=="webhook"){let P={instancePath:e+"/notifications/native_delivery/mode",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/properties/mode/const",keyword:"const",params:{allowedValue:"webhook"},message:"must be equal to constant"};r===null?r=[P]:r.push(P),a++}if(y.url!==void 0){let P=y.url;if(typeof P=="string"){if(!Jr.test(P)){let C={instancePath:e+"/notifications/native_delivery/url",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/properties/url/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};r===null?r=[C]:r.push(C),a++}if(!hn(P)){let C={instancePath:e+"/notifications/native_delivery/url",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/properties/url/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[C]:r.push(C),a++}}else{let C={instancePath:e+"/notifications/native_delivery/url",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/properties/url/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[C]:r.push(C),a++}}}else{let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[P]:r.push(P),a++}var w=x===a;if(w&&_?(_=!1,k=[k,1]):w&&(_=!0,k=1,b!==!0&&(b=!0)),_)a=v,r!==null&&(v?r.length=v:r=null);else{let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf",keyword:"oneOf",params:{passingSchemas:k},message:"must match exactly one schema in oneOf"};r===null?r=[P]:r.push(P),a++}}}else{let y={instancePath:e+"/notifications",schemaPath:"#/properties/notifications/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[y]:r.push(y),a++}}}else{let g={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[g]:r.push(g),a++}return uf.errors=r,a===0}function Hn(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=Hn.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){for(let l in n)if(!(l==="app-runtime"||l==="mobile")){let c={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[c]:r.push(c),a++}if(n["app-runtime"]!==void 0){let l=n["app-runtime"];if(Array.isArray(l)){if(l.length>16){let f={instancePath:e+"/app-runtime",schemaPath:"#/$defs/installationOrigins/maxItems",keyword:"maxItems",params:{limit:16},message:"must NOT have more than 16 items"};r===null?r=[f]:r.push(f),a++}let c=l.length;for(let f=0;f<c;f++){let h=l[f];if(typeof h=="string"){if(D(h)>255){let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/maxLength",keyword:"maxLength",params:{limit:255},message:"must NOT have more than 255 characters"};r===null?r=[m]:r.push(m),a++}if(D(h)<1){let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[m]:r.push(m),a++}if(!hn(h)){let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[m]:r.push(m),a++}}else{let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[m]:r.push(m),a++}}let d=l.length,u;if(d>1){let f={};for(;d--;){let h=l[d];if(typeof h=="string"){if(typeof f[h]=="number"){u=f[h];let m={instancePath:e+"/app-runtime",schemaPath:"#/$defs/installationOrigins/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[m]:r.push(m),a++;break}f[h]=d}}}}else{let c={instancePath:e+"/app-runtime",schemaPath:"#/$defs/installationOrigins/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[c]:r.push(c),a++}}if(n.mobile!==void 0){let l=n.mobile;if(Array.isArray(l)){if(l.length>16){let f={instancePath:e+"/mobile",schemaPath:"#/$defs/installationOrigins/maxItems",keyword:"maxItems",params:{limit:16},message:"must NOT have more than 16 items"};r===null?r=[f]:r.push(f),a++}let c=l.length;for(let f=0;f<c;f++){let h=l[f];if(typeof h=="string"){if(D(h)>255){let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/maxLength",keyword:"maxLength",params:{limit:255},message:"must NOT have more than 255 characters"};r===null?r=[m]:r.push(m),a++}if(D(h)<1){let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[m]:r.push(m),a++}if(!hn(h)){let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[m]:r.push(m),a++}}else{let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[m]:r.push(m),a++}}let d=l.length,u;if(d>1){let f={};for(;d--;){let h=l[d];if(typeof h=="string"){if(typeof f[h]=="number"){u=f[h];let m={instancePath:e+"/mobile",schemaPath:"#/$defs/installationOrigins/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[m]:r.push(m),a++;break}f[h]=d}}}}else{let c={instancePath:e+"/mobile",schemaPath:"#/$defs/installationOrigins/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[c]:r.push(c),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return Hn.errors=r,a===0}function ba(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=ba.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.contract_version===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contract_version"},message:"must have required property 'contract_version'"};r===null?r=[l]:r.push(l),a++}if(n.required===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"required"},message:"must have required property 'required'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="contract_version"||l==="required"||l==="optional")){let c={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[c]:r.push(c),a++}if(n.contract_version!==void 0&&n.contract_version!==1){let l={instancePath:e+"/contract_version",schemaPath:"#/properties/contract_version/const",keyword:"const",params:{allowedValue:1},message:"must be equal to constant"};r===null?r=[l]:r.push(l),a++}if(n.required!==void 0){let l=n.required;if(Array.isArray(l)){if(l.length>32){let f={instancePath:e+"/required",schemaPath:"#/properties/required/maxItems",keyword:"maxItems",params:{limit:32},message:"must NOT have more than 32 items"};r===null?r=[f]:r.push(f),a++}let c=l.length;for(let f=0;f<c;f++){let h=l[f];if(!(h==="collection.inspect"||h==="records.watch"||h==="records.read"||h==="records.query"||h==="records.validate"||h==="records.create"||h==="records.update"||h==="records.delete"||h==="records.rename"||h==="views.list"||h==="views.execute"||h==="views.source.read"||h==="views.source.create"||h==="views.source.update"||h==="views.source.delete"||h==="definitions.contracts.current"||h==="definitions.read"||h==="definitions.create"||h==="definitions.update"||h==="definitions.type-pack.inspect"||h==="definitions.type-pack.apply"||h==="collection.setup.apply"||h==="timers.list"||h==="timers.put"||h==="timers.cancel"||h==="timers.reconcile"||h==="sync.offline-replica"||h==="notifications.background-delivery"||h==="files.list"||h==="files.read"||h==="files.add"||h==="files.replace"||h==="files.move"||h==="files.delete")){let m={instancePath:e+"/required/"+f,schemaPath:"#/$defs/applicationCapability/enum",keyword:"enum",params:{allowedValues:MS.enum},message:"must be equal to one of the allowed values"};r===null?r=[m]:r.push(m),a++}}let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(xn(l[d],l[u])){let f={instancePath:e+"/required",schemaPath:"#/properties/required/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[f]:r.push(f),a++;break e}}}else{let c={instancePath:e+"/required",schemaPath:"#/properties/required/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[c]:r.push(c),a++}}if(n.optional!==void 0){let l=n.optional;if(Array.isArray(l)){if(l.length>32){let f={instancePath:e+"/optional",schemaPath:"#/properties/optional/maxItems",keyword:"maxItems",params:{limit:32},message:"must NOT have more than 32 items"};r===null?r=[f]:r.push(f),a++}let c=l.length;for(let f=0;f<c;f++){let h=l[f];if(!(h==="collection.inspect"||h==="records.watch"||h==="records.read"||h==="records.query"||h==="records.validate"||h==="records.create"||h==="records.update"||h==="records.delete"||h==="records.rename"||h==="views.list"||h==="views.execute"||h==="views.source.read"||h==="views.source.create"||h==="views.source.update"||h==="views.source.delete"||h==="definitions.contracts.current"||h==="definitions.read"||h==="definitions.create"||h==="definitions.update"||h==="definitions.type-pack.inspect"||h==="definitions.type-pack.apply"||h==="collection.setup.apply"||h==="timers.list"||h==="timers.put"||h==="timers.cancel"||h==="timers.reconcile"||h==="sync.offline-replica"||h==="notifications.background-delivery"||h==="files.list"||h==="files.read"||h==="files.add"||h==="files.replace"||h==="files.move"||h==="files.delete")){let m={instancePath:e+"/optional/"+f,schemaPath:"#/$defs/applicationCapability/enum",keyword:"enum",params:{allowedValues:MS.enum},message:"must be equal to one of the allowed values"};r===null?r=[m]:r.push(m),a++}}let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(xn(l[d],l[u])){let f={instancePath:e+"/optional",schemaPath:"#/properties/optional/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[f]:r.push(f),a++;break e}}}else{let c={instancePath:e+"/optional",schemaPath:"#/properties/optional/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[c]:r.push(c),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return ba.errors=r,a===0}function wa(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=wa.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.actions===void 0){let d={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"actions"},message:"must have required property 'actions'"};r===null?r=[d]:r.push(d),a++}if(n.scope===void 0){let d={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"scope"},message:"must have required property 'scope'"};r===null?r=[d]:r.push(d),a++}for(let d in n)if(!(d==="actions"||d==="scope")){let u={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:d},message:"must NOT have additional properties"};r===null?r=[u]:r.push(u),a++}if(n.actions!==void 0){let d=n.actions;if(Array.isArray(d)){if(d.length>6){let m={instancePath:e+"/actions",schemaPath:"#/properties/actions/maxItems",keyword:"maxItems",params:{limit:6},message:"must NOT have more than 6 items"};r===null?r=[m]:r.push(m),a++}if(d.length<1){let m={instancePath:e+"/actions",schemaPath:"#/properties/actions/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[m]:r.push(m),a++}let u=d.length;for(let m=0;m<u;m++){let b=d[m];if(!(b==="list"||b==="read"||b==="add"||b==="replace"||b==="move"||b==="delete")){let w={instancePath:e+"/actions/"+m,schemaPath:"#/properties/actions/items/enum",keyword:"enum",params:{allowedValues:dE.properties.actions.items.enum},message:"must be equal to one of the allowed values"};r===null?r=[w]:r.push(w),a++}}let f=d.length,h;if(f>1){e:for(;f--;)for(h=f;h--;)if(xn(d[f],d[h])){let m={instancePath:e+"/actions",schemaPath:"#/properties/actions/uniqueItems",keyword:"uniqueItems",params:{i:f,j:h},message:"must NOT have duplicate items (items ## "+h+" and "+f+" are identical)"};r===null?r=[m]:r.push(m),a++;break e}}}else{let u={instancePath:e+"/actions",schemaPath:"#/properties/actions/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[u]:r.push(u),a++}}if(n.scope!==void 0){let d=n.scope,u=a,f=!1,h=null,m=a;if(d&&typeof d=="object"&&!Array.isArray(d)){if(d.kind===void 0){let w={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};r===null?r=[w]:r.push(w),a++}if(d.folders===void 0){let w={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/required",keyword:"required",params:{missingProperty:"folders"},message:"must have required property 'folders'"};r===null?r=[w]:r.push(w),a++}for(let w in d)if(!(w==="kind"||w==="folders")){let g={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:w},message:"must NOT have additional properties"};r===null?r=[g]:r.push(g),a++}if(d.kind!==void 0&&d.kind!=="selected_folders"){let w={instancePath:e+"/scope/kind",schemaPath:"#/$defs/fileScope/oneOf/0/properties/kind/const",keyword:"const",params:{allowedValue:"selected_folders"},message:"must be equal to constant"};r===null?r=[w]:r.push(w),a++}if(d.folders!==void 0){let w=d.folders;if(Array.isArray(w)){if(w.length>100){let _={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/maxItems",keyword:"maxItems",params:{limit:100},message:"must NOT have more than 100 items"};r===null?r=[_]:r.push(_),a++}if(w.length<1){let _={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[_]:r.push(_),a++}let g=w.length;for(let _=0;_<g;_++){let k=w[_];if(typeof k=="string"){if(D(k)>1024){let S={instancePath:e+"/scope/folders/"+_,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};r===null?r=[S]:r.push(S),a++}if(D(k)<1){let S={instancePath:e+"/scope/folders/"+_,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[S]:r.push(S),a++}if(!$S.test(k)){let S={instancePath:e+"/scope/folders/"+_,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/pattern",keyword:"pattern",params:{pattern:"^(?!/)(?!\\.)(?!.*//)(?!.*\\\\)(?!.*/\\.)(?!(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*\\/(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*/$).+$"},message:'must match pattern "^(?!/)(?!\\.)(?!.*//)(?!.*\\\\)(?!.*/\\.)(?!(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*\\/(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*/$).+$"'};r===null?r=[S]:r.push(S),a++}}else{let S={instancePath:e+"/scope/folders/"+_,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[S]:r.push(S),a++}}let y=w.length,v;if(y>1){let _={};for(;y--;){let k=w[y];if(typeof k=="string"){if(typeof _[k]=="number"){v=_[k];let S={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/uniqueItems",keyword:"uniqueItems",params:{i:y,j:v},message:"must NOT have duplicate items (items ## "+v+" and "+y+" are identical)"};r===null?r=[S]:r.push(S),a++;break}_[k]=y}}}}else{let g={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[g]:r.push(g),a++}}}else{let w={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[w]:r.push(w),a++}var c=m===a;if(c){f=!0,h=0;var l=!0}let b=a;if(d&&typeof d=="object"&&!Array.isArray(d)){if(d.kind===void 0){let w={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};r===null?r=[w]:r.push(w),a++}for(let w in d)if(w!=="kind"){let g={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:w},message:"must NOT have additional properties"};r===null?r=[g]:r.push(g),a++}if(d.kind!==void 0&&d.kind!=="collection"){let w={instancePath:e+"/scope/kind",schemaPath:"#/$defs/fileScope/oneOf/1/properties/kind/const",keyword:"const",params:{allowedValue:"collection"},message:"must be equal to constant"};r===null?r=[w]:r.push(w),a++}}else{let w={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[w]:r.push(w),a++}var c=b===a;if(c&&f?(f=!1,h=[h,1]):c&&(f=!0,h=1,l!==!0&&(l=!0)),f)a=u,r!==null&&(u?r.length=u:r=null);else{let w={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf",keyword:"oneOf",params:{passingSchemas:h},message:"must match exactly one schema in oneOf"};r===null?r=[w]:r.push(w),a++}}}else{let d={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[d]:r.push(d),a++}return wa.errors=r,a===0}function va(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=va.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.id===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[c]:r.push(c),a++}if(n.path===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"path"},message:"must have required property 'path'"};r===null?r=[c]:r.push(c),a++}if(n.predicate===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"predicate"},message:"must have required property 'predicate'"};r===null?r=[c]:r.push(c),a++}if(n.value===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"value"},message:"must have required property 'value'"};r===null?r=[c]:r.push(c),a++}for(let c in n)if(!(c==="id"||c==="path"||c==="predicate"||c==="value")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:c},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(n.id!==void 0){let c=n.id;if(typeof c=="string"){if(D(c)>100){let d={instancePath:e+"/id",schemaPath:"#/properties/id/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[d]:r.push(d),a++}if(D(c)<1){let d={instancePath:e+"/id",schemaPath:"#/properties/id/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}if(!hf.test(c)){let d={instancePath:e+"/id",schemaPath:"#/properties/id/pattern",keyword:"pattern",params:{pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},message:'must match pattern "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"'};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.path!==void 0){let c=n.path;if(typeof c=="string"){if(D(c)>1024){let d={instancePath:e+"/path",schemaPath:"#/properties/path/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};r===null?r=[d]:r.push(d),a++}if(D(c)<1){let d={instancePath:e+"/path",schemaPath:"#/properties/path/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/path",schemaPath:"#/properties/path/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.predicate!==void 0&&n.predicate!=="contains"){let c={instancePath:e+"/predicate",schemaPath:"#/properties/predicate/const",keyword:"const",params:{allowedValue:"contains"},message:"must be equal to constant"};r===null?r=[c]:r.push(c),a++}if(n.value!==void 0){let c=n.value,d=a,u=!1,f=a;if(typeof c!="string"){let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/0/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[w]:r.push(w),a++}var l=f===a;u=u||l;let h=a;if(!(typeof c=="number"&&isFinite(c))){let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/1/type",keyword:"type",params:{type:"number"},message:"must be number"};r===null?r=[w]:r.push(w),a++}var l=h===a;u=u||l;let m=a;if(typeof c!="boolean"){let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/2/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};r===null?r=[w]:r.push(w),a++}var l=m===a;u=u||l;let b=a;if(c!==null){let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/3/type",keyword:"type",params:{type:"null"},message:"must be null"};r===null?r=[w]:r.push(w),a++}var l=b===a;if(u=u||l,u)a=d,r!==null&&(d?r.length=d:r=null);else{let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};r===null?r=[w]:r.push(w),a++}}}else{let c={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[c]:r.push(c),a++}return va.errors=r,a===0}function Yn(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=Yn.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.id===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[l]:r.push(l),a++}if(n.version===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"version"},message:"must have required property 'version'"};r===null?r=[l]:r.push(l),a++}if(n.digest===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"digest"},message:"must have required property 'digest'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="id"||l==="version"||l==="digest")){let c={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[c]:r.push(c),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(D(l)>100){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[c]:r.push(c),a++}if(D(l)<1){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[c]:r.push(c),a++}if(!xa.test(l)){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/pattern",keyword:"pattern",params:{pattern:"^[a-z0-9]+(?:[._-][a-z0-9]+)*$"},message:'must match pattern "^[a-z0-9]+(?:[._-][a-z0-9]+)*$"'};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.version!==void 0){let l=n.version;if(typeof l=="string"){if(!mf.test(l)){let c={instancePath:e+"/version",schemaPath:"#/properties/version/pattern",keyword:"pattern",params:{pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},message:'must match pattern "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"'};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/version",schemaPath:"#/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.digest!==void 0){let l=n.digest;if(typeof l=="string"){if(!da.test(l)){let c={instancePath:e+"/digest",schemaPath:"#/properties/digest/pattern",keyword:"pattern",params:{pattern:"^sha256:[0-9a-f]{64}$"},message:'must match pattern "^sha256:[0-9a-f]{64}$"'};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/digest",schemaPath:"#/properties/digest/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return Yn.errors=r,a===0}function _a(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=_a.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.access===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"access"},message:"must have required property 'access'"};r===null?r=[l]:r.push(l),a++}if(n.contracts===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contracts"},message:"must have required property 'contracts'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="capabilities"||l==="access"||l==="collection_kind"||l==="files"||l==="configuration"||l==="contracts")){let c={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[c]:r.push(c),a++}if(n.capabilities!==void 0&&(ba(n.capabilities,{instancePath:e+"/capabilities",parentData:n,parentDataProperty:"capabilities",rootData:o,dynamicAnchors:s})||(r=r===null?ba.errors:r.concat(ba.errors),a=r.length)),n.access!==void 0&&n.access!=="full_collection"){let l={instancePath:e+"/access",schemaPath:"#/properties/access/const",keyword:"const",params:{allowedValue:"full_collection"},message:"must be equal to constant"};r===null?r=[l]:r.push(l),a++}if(n.collection_kind!==void 0&&n.collection_kind!=="hosted"){let l={instancePath:e+"/collection_kind",schemaPath:"#/properties/collection_kind/const",keyword:"const",params:{allowedValue:"hosted"},message:"must be equal to constant"};r===null?r=[l]:r.push(l),a++}if(n.files!==void 0&&(wa(n.files,{instancePath:e+"/files",parentData:n,parentDataProperty:"files",rootData:o,dynamicAnchors:s})||(r=r===null?wa.errors:r.concat(wa.errors),a=r.length)),n.configuration!==void 0){let l=n.configuration;if(Array.isArray(l)){if(l.length>50){let d={instancePath:e+"/configuration",schemaPath:"#/properties/configuration/maxItems",keyword:"maxItems",params:{limit:50},message:"must NOT have more than 50 items"};r===null?r=[d]:r.push(d),a++}let c=l.length;for(let d=0;d<c;d++)va(l[d],{instancePath:e+"/configuration/"+d,parentData:l,parentDataProperty:d,rootData:o,dynamicAnchors:s})||(r=r===null?va.errors:r.concat(va.errors),a=r.length)}else{let c={instancePath:e+"/configuration",schemaPath:"#/properties/configuration/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[c]:r.push(c),a++}}if(n.contracts!==void 0){let l=n.contracts;if(Array.isArray(l)){if(l.length>20){let f={instancePath:e+"/contracts",schemaPath:"#/properties/contracts/maxItems",keyword:"maxItems",params:{limit:20},message:"must NOT have more than 20 items"};r===null?r=[f]:r.push(f),a++}let c=l.length;for(let f=0;f<c;f++)Yn(l[f],{instancePath:e+"/contracts/"+f,parentData:l,parentDataProperty:f,rootData:o,dynamicAnchors:s})||(r=r===null?Yn.errors:r.concat(Yn.errors),a=r.length);let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(xn(l[d],l[u])){let f={instancePath:e+"/contracts",schemaPath:"#/properties/contracts/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[f]:r.push(f),a++;break e}}}else{let c={instancePath:e+"/contracts",schemaPath:"#/properties/contracts/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[c]:r.push(c),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return _a.errors=r,a===0}function Aa(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=Aa.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.requirement===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"requirement"},message:"must have required property 'requirement'"};r===null?r=[c]:r.push(c),a++}if(n.operation===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"operation"},message:"must have required property 'operation'"};r===null?r=[c]:r.push(c),a++}if(n.path===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"path"},message:"must have required property 'path'"};r===null?r=[c]:r.push(c),a++}if(n.value===void 0){let c={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"value"},message:"must have required property 'value'"};r===null?r=[c]:r.push(c),a++}for(let c in n)if(!(c==="requirement"||c==="operation"||c==="path"||c==="value")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:c},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(n.requirement!==void 0){let c=n.requirement;if(typeof c=="string"){if(D(c)>100){let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[d]:r.push(d),a++}if(D(c)<1){let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}if(!hf.test(c)){let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/pattern",keyword:"pattern",params:{pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},message:'must match pattern "^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"'};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.operation!==void 0&&n.operation!=="set_add"){let c={instancePath:e+"/operation",schemaPath:"#/properties/operation/const",keyword:"const",params:{allowedValue:"set_add"},message:"must be equal to constant"};r===null?r=[c]:r.push(c),a++}if(n.path!==void 0){let c=n.path;if(typeof c=="string"){if(D(c)>1024){let d={instancePath:e+"/path",schemaPath:"#/properties/path/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};r===null?r=[d]:r.push(d),a++}if(D(c)<1){let d={instancePath:e+"/path",schemaPath:"#/properties/path/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/path",schemaPath:"#/properties/path/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(n.value!==void 0){let c=n.value,d=a,u=!1,f=a;if(typeof c!="string"){let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/0/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[w]:r.push(w),a++}var l=f===a;u=u||l;let h=a;if(!(typeof c=="number"&&isFinite(c))){let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/1/type",keyword:"type",params:{type:"number"},message:"must be number"};r===null?r=[w]:r.push(w),a++}var l=h===a;u=u||l;let m=a;if(typeof c!="boolean"){let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/2/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};r===null?r=[w]:r.push(w),a++}var l=m===a;u=u||l;let b=a;if(c!==null){let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/3/type",keyword:"type",params:{type:"null"},message:"must be null"};r===null?r=[w]:r.push(w),a++}var l=b===a;if(u=u||l,u)a=d,r!==null&&(d?r.length=d:r=null);else{let w={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};r===null?r=[w]:r.push(w),a++}}}else{let c={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[c]:r.push(c),a++}return Aa.errors=r,a===0}function ka(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=ka.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.kind===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};r===null?r=[l]:r.push(l),a++}if(n.id===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[l]:r.push(l),a++}if(n.version===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"version"},message:"must have required property 'version'"};r===null?r=[l]:r.push(l),a++}if(n.resources===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"resources"},message:"must have required property 'resources'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="kind"||l==="id"||l==="version"||l==="name"||l==="description"||l==="resources"||zS.test(l))){let c={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[c]:r.push(c),a++}if(n.kind!==void 0&&n.kind!=="mdbase.type-pack"){let l={instancePath:e+"/kind",schemaPath:"#/properties/kind/const",keyword:"const",params:{allowedValue:"mdbase.type-pack"},message:"must be equal to constant"};r===null?r=[l]:r.push(l),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(D(l)>100){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[c]:r.push(c),a++}if(D(l)<1){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[c]:r.push(c),a++}if(!xa.test(l)){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/pattern",keyword:"pattern",params:{pattern:"^[a-z0-9]+(?:[._-][a-z0-9]+)*$"},message:'must match pattern "^[a-z0-9]+(?:[._-][a-z0-9]+)*$"'};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.version!==void 0){let l=n.version;if(typeof l=="string"){if(!mf.test(l)){let c={instancePath:e+"/version",schemaPath:"#/$defs/contract/properties/version/pattern",keyword:"pattern",params:{pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},message:'must match pattern "^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"'};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/version",schemaPath:"#/$defs/contract/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.name!==void 0){let l=n.name;if(typeof l=="string"){if(D(l)>100){let c={instancePath:e+"/name",schemaPath:"#/properties/name/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[c]:r.push(c),a++}if(D(l)<1){let c={instancePath:e+"/name",schemaPath:"#/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.description!==void 0){let l=n.description;if(typeof l=="string"){if(D(l)>500){let c={instancePath:e+"/description",schemaPath:"#/properties/description/maxLength",keyword:"maxLength",params:{limit:500},message:"must NOT have more than 500 characters"};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.resources!==void 0){let l=n.resources;if(Array.isArray(l)){if(l.length>100){let d={instancePath:e+"/resources",schemaPath:"#/properties/resources/maxItems",keyword:"maxItems",params:{limit:100},message:"must NOT have more than 100 items"};r===null?r=[d]:r.push(d),a++}if(l.length<1){let d={instancePath:e+"/resources",schemaPath:"#/properties/resources/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[d]:r.push(d),a++}let c=l.length;for(let d=0;d<c;d++){let u=l[d];if(u&&typeof u=="object"&&!Array.isArray(u)){if(u.kind===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackManifestResource/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};r===null?r=[f]:r.push(f),a++}if(u.mode===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackManifestResource/required",keyword:"required",params:{missingProperty:"mode"},message:"must have required property 'mode'"};r===null?r=[f]:r.push(f),a++}if(u.source===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackManifestResource/required",keyword:"required",params:{missingProperty:"source"},message:"must have required property 'source'"};r===null?r=[f]:r.push(f),a++}if(u.target===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackManifestResource/required",keyword:"required",params:{missingProperty:"target"},message:"must have required property 'target'"};r===null?r=[f]:r.push(f),a++}if(u.digest===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackManifestResource/required",keyword:"required",params:{missingProperty:"digest"},message:"must have required property 'digest'"};r===null?r=[f]:r.push(f),a++}for(let f in u)if(!(f==="kind"||f==="mode"||f==="source"||f==="target"||f==="digest")){let h={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackManifestResource/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:f},message:"must NOT have additional properties"};r===null?r=[h]:r.push(h),a++}if(u.kind!==void 0){let f=u.kind;if(!(f==="contract"||f==="type"||f==="schema")){let h={instancePath:e+"/resources/"+d+"/kind",schemaPath:"#/$defs/typePackManifestResource/properties/kind/enum",keyword:"enum",params:{allowedValues:LS.properties.kind.enum},message:"must be equal to one of the allowed values"};r===null?r=[h]:r.push(h),a++}}if(u.mode!==void 0){let f=u.mode;if(!(f==="managed"||f==="seed")){let h={instancePath:e+"/resources/"+d+"/mode",schemaPath:"#/$defs/typePackManifestResource/properties/mode/enum",keyword:"enum",params:{allowedValues:LS.properties.mode.enum},message:"must be equal to one of the allowed values"};r===null?r=[h]:r.push(h),a++}}if(u.source!==void 0){let f=u.source;if(typeof f=="string"){if(D(f)>240){let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackManifestResource/properties/source/maxLength",keyword:"maxLength",params:{limit:240},message:"must NOT have more than 240 characters"};r===null?r=[h]:r.push(h),a++}if(D(f)<1){let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackManifestResource/properties/source/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[h]:r.push(h),a++}}else{let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackManifestResource/properties/source/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[h]:r.push(h),a++}}if(u.target!==void 0){let f=u.target;if(typeof f=="string"){if(D(f)>240){let h={instancePath:e+"/resources/"+d+"/target",schemaPath:"#/$defs/typePackManifestResource/properties/target/maxLength",keyword:"maxLength",params:{limit:240},message:"must NOT have more than 240 characters"};r===null?r=[h]:r.push(h),a++}if(D(f)<1){let h={instancePath:e+"/resources/"+d+"/target",schemaPath:"#/$defs/typePackManifestResource/properties/target/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[h]:r.push(h),a++}}else{let h={instancePath:e+"/resources/"+d+"/target",schemaPath:"#/$defs/typePackManifestResource/properties/target/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[h]:r.push(h),a++}}if(u.digest!==void 0){let f=u.digest;if(typeof f=="string"){if(!da.test(f)){let h={instancePath:e+"/resources/"+d+"/digest",schemaPath:"#/$defs/typePackManifestResource/properties/digest/pattern",keyword:"pattern",params:{pattern:"^sha256:[0-9a-f]{64}$"},message:'must match pattern "^sha256:[0-9a-f]{64}$"'};r===null?r=[h]:r.push(h),a++}}else{let h={instancePath:e+"/resources/"+d+"/digest",schemaPath:"#/$defs/typePackManifestResource/properties/digest/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[h]:r.push(h),a++}}}else{let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackManifestResource/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[f]:r.push(f),a++}}}else{let c={instancePath:e+"/resources",schemaPath:"#/properties/resources/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[c]:r.push(c),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return ka.errors=r,a===0}function Sa(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=Sa.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.manifest===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"manifest"},message:"must have required property 'manifest'"};r===null?r=[l]:r.push(l),a++}if(n.resources===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"resources"},message:"must have required property 'resources'"};r===null?r=[l]:r.push(l),a++}if(n.provides===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"provides"},message:"must have required property 'provides'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="manifest"||l==="resources"||l==="provides")){let c={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[c]:r.push(c),a++}if(n.manifest!==void 0&&(ka(n.manifest,{instancePath:e+"/manifest",parentData:n,parentDataProperty:"manifest",rootData:o,dynamicAnchors:s})||(r=r===null?ka.errors:r.concat(ka.errors),a=r.length)),n.resources!==void 0){let l=n.resources;if(Array.isArray(l)){if(l.length>100){let d={instancePath:e+"/resources",schemaPath:"#/properties/resources/maxItems",keyword:"maxItems",params:{limit:100},message:"must NOT have more than 100 items"};r===null?r=[d]:r.push(d),a++}if(l.length<1){let d={instancePath:e+"/resources",schemaPath:"#/properties/resources/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[d]:r.push(d),a++}let c=l.length;for(let d=0;d<c;d++){let u=l[d];if(u&&typeof u=="object"&&!Array.isArray(u)){if(u.source===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/required",keyword:"required",params:{missingProperty:"source"},message:"must have required property 'source'"};r===null?r=[f]:r.push(f),a++}if(u.document===void 0){let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/required",keyword:"required",params:{missingProperty:"document"},message:"must have required property 'document'"};r===null?r=[f]:r.push(f),a++}for(let f in u)if(!(f==="source"||f==="document")){let h={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:f},message:"must NOT have additional properties"};r===null?r=[h]:r.push(h),a++}if(u.source!==void 0){let f=u.source;if(typeof f=="string"){if(D(f)>240){let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackSourceResource/properties/source/maxLength",keyword:"maxLength",params:{limit:240},message:"must NOT have more than 240 characters"};r===null?r=[h]:r.push(h),a++}if(D(f)<1){let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackSourceResource/properties/source/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[h]:r.push(h),a++}}else{let h={instancePath:e+"/resources/"+d+"/source",schemaPath:"#/$defs/typePackSourceResource/properties/source/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[h]:r.push(h),a++}}if(u.document!==void 0){let f=u.document;if(typeof f=="string"){if(D(f)>262144){let h={instancePath:e+"/resources/"+d+"/document",schemaPath:"#/$defs/typePackSourceResource/properties/document/maxLength",keyword:"maxLength",params:{limit:262144},message:"must NOT have more than 262144 characters"};r===null?r=[h]:r.push(h),a++}}else{let h={instancePath:e+"/resources/"+d+"/document",schemaPath:"#/$defs/typePackSourceResource/properties/document/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[h]:r.push(h),a++}}}else{let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[f]:r.push(f),a++}}}else{let c={instancePath:e+"/resources",schemaPath:"#/properties/resources/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[c]:r.push(c),a++}}if(n.provides!==void 0){let l=n.provides;if(Array.isArray(l)){if(l.length>20){let f={instancePath:e+"/provides",schemaPath:"#/properties/provides/maxItems",keyword:"maxItems",params:{limit:20},message:"must NOT have more than 20 items"};r===null?r=[f]:r.push(f),a++}let c=l.length;for(let f=0;f<c;f++)Yn(l[f],{instancePath:e+"/provides/"+f,parentData:l,parentDataProperty:f,rootData:o,dynamicAnchors:s})||(r=r===null?Yn.errors:r.concat(Yn.errors),a=r.length);let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(xn(l[d],l[u])){let f={instancePath:e+"/provides",schemaPath:"#/properties/provides/uniqueItems",keyword:"uniqueItems",params:{i:d,j:u},message:"must NOT have duplicate items (items ## "+u+" and "+d+" are identical)"};r===null?r=[f]:r.push(f),a++;break e}}}else{let c={instancePath:e+"/provides",schemaPath:"#/properties/provides/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[c]:r.push(c),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return Sa.errors=r,a===0}function Pa(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=Pa.evaluated;if(p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.id===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[l]:r.push(l),a++}if(n.event===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"event"},message:"must have required property 'event'"};r===null?r=[l]:r.push(l),a++}if(n.presentation===void 0){let l={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"presentation"},message:"must have required property 'presentation'"};r===null?r=[l]:r.push(l),a++}for(let l in n)if(!(l==="id"||l==="event"||l==="if"||l==="debounce"||l==="minimum_interval"||l==="presentation")){let c={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};r===null?r=[c]:r.push(c),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(D(l)>100){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[c]:r.push(c),a++}if(D(l)<1){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[c]:r.push(c),a++}if(!xa.test(l)){let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/pattern",keyword:"pattern",params:{pattern:"^[a-z0-9]+(?:[._-][a-z0-9]+)*$"},message:'must match pattern "^[a-z0-9]+(?:[._-][a-z0-9]+)*$"'};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.event!==void 0&&(Yn(n.event,{instancePath:e+"/event",parentData:n,parentDataProperty:"event",rootData:o,dynamicAnchors:s})||(r=r===null?Yn.errors:r.concat(Yn.errors),a=r.length)),n.if!==void 0){let l=n.if;if(l&&typeof l=="object"&&!Array.isArray(l)){if(l.$expr===void 0){let c={instancePath:e+"/if",schemaPath:"#/properties/if/required",keyword:"required",params:{missingProperty:"$expr"},message:"must have required property '$expr'"};r===null?r=[c]:r.push(c),a++}for(let c in l)if(c!=="$expr"){let d={instancePath:e+"/if",schemaPath:"#/properties/if/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:c},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(l.$expr!==void 0){let c=l.$expr;if(typeof c=="string"){if(D(c)>4096){let d={instancePath:e+"/if/$expr",schemaPath:"#/properties/if/properties/%24expr/maxLength",keyword:"maxLength",params:{limit:4096},message:"must NOT have more than 4096 characters"};r===null?r=[d]:r.push(d),a++}if(D(c)<1){let d={instancePath:e+"/if/$expr",schemaPath:"#/properties/if/properties/%24expr/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/if/$expr",schemaPath:"#/properties/if/properties/%24expr/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}}else{let c={instancePath:e+"/if",schemaPath:"#/properties/if/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[c]:r.push(c),a++}}if(n.debounce!==void 0){let l=n.debounce;if(typeof l=="string"){if(!df.test(l)){let c={instancePath:e+"/debounce",schemaPath:"#/$defs/duration/pattern",keyword:"pattern",params:{pattern:"^[0-9]+(ms|s|m|h|d)$"},message:'must match pattern "^[0-9]+(ms|s|m|h|d)$"'};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/debounce",schemaPath:"#/$defs/duration/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.minimum_interval!==void 0){let l=n.minimum_interval;if(typeof l=="string"){if(!df.test(l)){let c={instancePath:e+"/minimum_interval",schemaPath:"#/$defs/duration/pattern",keyword:"pattern",params:{pattern:"^[0-9]+(ms|s|m|h|d)$"},message:'must match pattern "^[0-9]+(ms|s|m|h|d)$"'};r===null?r=[c]:r.push(c),a++}}else{let c={instancePath:e+"/minimum_interval",schemaPath:"#/$defs/duration/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[c]:r.push(c),a++}}if(n.presentation!==void 0){let l=n.presentation;if(l&&typeof l=="object"&&!Array.isArray(l)){if(l.title===void 0){let c={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/required",keyword:"required",params:{missingProperty:"title"},message:"must have required property 'title'"};r===null?r=[c]:r.push(c),a++}for(let c in l)if(!(c==="title"||c==="body"||c==="tag")){let d={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:c},message:"must NOT have additional properties"};r===null?r=[d]:r.push(d),a++}if(l.title!==void 0){let c=l.title;if(typeof c=="string"){if(D(c)>80){let d={instancePath:e+"/presentation/title",schemaPath:"#/properties/presentation/properties/title/maxLength",keyword:"maxLength",params:{limit:80},message:"must NOT have more than 80 characters"};r===null?r=[d]:r.push(d),a++}if(D(c)<1){let d={instancePath:e+"/presentation/title",schemaPath:"#/properties/presentation/properties/title/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/presentation/title",schemaPath:"#/properties/presentation/properties/title/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(l.body!==void 0){let c=l.body;if(typeof c=="string"){if(D(c)>160){let d={instancePath:e+"/presentation/body",schemaPath:"#/properties/presentation/properties/body/maxLength",keyword:"maxLength",params:{limit:160},message:"must NOT have more than 160 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/presentation/body",schemaPath:"#/properties/presentation/properties/body/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}if(l.tag!==void 0){let c=l.tag;if(typeof c=="string"){if(D(c)>80){let d={instancePath:e+"/presentation/tag",schemaPath:"#/properties/presentation/properties/tag/maxLength",keyword:"maxLength",params:{limit:80},message:"must NOT have more than 80 characters"};r===null?r=[d]:r.push(d),a++}if(D(c)<1){let d={instancePath:e+"/presentation/tag",schemaPath:"#/properties/presentation/properties/tag/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[d]:r.push(d),a++}}else{let d={instancePath:e+"/presentation/tag",schemaPath:"#/properties/presentation/properties/tag/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[d]:r.push(d),a++}}}else{let c={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[c]:r.push(c),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[l]:r.push(l),a++}return Pa.errors=r,a===0}function ff(n,{instancePath:e="",parentData:t,parentDataProperty:i,rootData:o=n,dynamicAnchors:s={}}={}){let r=null,a=0,p=ff.evaluated;p.dynamicProps&&(p.props=void 0),p.dynamicItems&&(p.items=void 0);let l=a,c=!1,d=null,u=a;if(n&&typeof n=="object"&&!Array.isArray(n)){if(n.homepage===void 0){let g={instancePath:e,schemaPath:"#/oneOf/0/required",keyword:"required",params:{missingProperty:"homepage"},message:"must have required property 'homepage'"};r===null?r=[g]:r.push(g),a++}if(n.redirect_uris===void 0){let g={instancePath:e,schemaPath:"#/oneOf/0/required",keyword:"required",params:{missingProperty:"redirect_uris"},message:"must have required property 'redirect_uris'"};r===null?r=[g]:r.push(g),a++}if(n.distribution!==void 0&&n.distribution!=="web"){let g={instancePath:e+"/distribution",schemaPath:"#/oneOf/0/properties/distribution/const",keyword:"const",params:{allowedValue:"web"},message:"must be equal to constant"};r===null?r=[g]:r.push(g),a++}if(n.project_url!==void 0){let g={instancePath:e+"/project_url",schemaPath:"#/oneOf/0/properties/project_url/false schema",keyword:"false schema",params:{},message:"boolean schema is false"};r===null?r=[g]:r.push(g),a++}}var m=u===a;if(m){c=!0,d=0;var f={};f.distribution=!0,f.homepage=!0,f.redirect_uris=!0,f.project_url=!0}let h=a;if(n&&typeof n=="object"&&!Array.isArray(n)){if(n.distribution===void 0){let g={instancePath:e,schemaPath:"#/oneOf/1/required",keyword:"required",params:{missingProperty:"distribution"},message:"must have required property 'distribution'"};r===null?r=[g]:r.push(g),a++}if(n.distribution!==void 0&&n.distribution!=="portable"){let g={instancePath:e+"/distribution",schemaPath:"#/oneOf/1/properties/distribution/const",keyword:"const",params:{allowedValue:"portable"},message:"must be equal to constant"};r===null?r=[g]:r.push(g),a++}if(n.platform!==void 0){let g={instancePath:e+"/platform",schemaPath:"#/oneOf/1/properties/platform/false schema",keyword:"false schema",params:{},message:"boolean schema is false"};r===null?r=[g]:r.push(g),a++}if(n.homepage!==void 0){let g={instancePath:e+"/homepage",schemaPath:"#/oneOf/1/properties/homepage/false schema",keyword:"false schema",params:{},message:"boolean schema is false"};r===null?r=[g]:r.push(g),a++}if(n.redirect_uris!==void 0){let g={instancePath:e+"/redirect_uris",schemaPath:"#/oneOf/1/properties/redirect_uris/false schema",keyword:"false schema",params:{},message:"boolean schema is false"};r===null?r=[g]:r.push(g),a++}}var m=h===a;if(m&&c?(c=!1,d=[d,1]):m&&(c=!0,d=1,f!==!0&&(f=f||{},f.distribution=!0,f.platform=!0,f.homepage=!0,f.redirect_uris=!0)),c)a=l,r!==null&&(l?r.length=l:r=null);else{let g={instancePath:e,schemaPath:"#/oneOf",keyword:"oneOf",params:{passingSchemas:d},message:"must match exactly one schema in oneOf"};r===null?r=[g]:r.push(g),a++}if(n&&typeof n=="object"&&!Array.isArray(n)){if(n.manifest_version===void 0){let g={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"manifest_version"},message:"must have required property 'manifest_version'"};r===null?r=[g]:r.push(g),a++}if(n.id===void 0){let g={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};r===null?r=[g]:r.push(g),a++}if(n.name===void 0){let g={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"name"},message:"must have required property 'name'"};r===null?r=[g]:r.push(g),a++}for(let g in n)if(!NS.call(TS.properties,g)){let y={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:g},message:"must NOT have additional properties"};r===null?r=[y]:r.push(y),a++}if(n.manifest_version!==void 0&&n.manifest_version!==1){let g={instancePath:e+"/manifest_version",schemaPath:"#/properties/manifest_version/const",keyword:"const",params:{allowedValue:1},message:"must be equal to constant"};r===null?r=[g]:r.push(g),a++}if(n.distribution!==void 0){let g=n.distribution;if(!(g==="web"||g==="portable")){let y={instancePath:e+"/distribution",schemaPath:"#/properties/distribution/enum",keyword:"enum",params:{allowedValues:TS.properties.distribution.enum},message:"must be equal to one of the allowed values"};r===null?r=[y]:r.push(y),a++}}if(n.id!==void 0){let g=n.id;if(typeof g=="string"){if(D(g)>150){let y={instancePath:e+"/id",schemaPath:"#/properties/id/maxLength",keyword:"maxLength",params:{limit:150},message:"must NOT have more than 150 characters"};r===null?r=[y]:r.push(y),a++}if(D(g)<5){let y={instancePath:e+"/id",schemaPath:"#/properties/id/minLength",keyword:"minLength",params:{limit:5},message:"must NOT have fewer than 5 characters"};r===null?r=[y]:r.push(y),a++}if(!US.test(g)){let y={instancePath:e+"/id",schemaPath:"#/properties/id/pattern",keyword:"pattern",params:{pattern:"^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*){2,}$"},message:'must match pattern "^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*){2,}$"'};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.name!==void 0){let g=n.name;if(typeof g=="string"){if(D(g)>100){let y={instancePath:e+"/name",schemaPath:"#/properties/name/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};r===null?r=[y]:r.push(y),a++}if(D(g)<1){let y={instancePath:e+"/name",schemaPath:"#/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.platform!==void 0&&n.platform!=="native"){let g={instancePath:e+"/platform",schemaPath:"#/properties/platform/const",keyword:"const",params:{allowedValue:"native"},message:"must be equal to constant"};r===null?r=[g]:r.push(g),a++}if(n.homepage!==void 0){let g=n.homepage;if(typeof g=="string"){if(!Jr.test(g)){let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};r===null?r=[y]:r.push(y),a++}if(!hn(g)){let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.project_url!==void 0){let g=n.project_url;if(typeof g=="string"){if(!Jr.test(g)){let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};r===null?r=[y]:r.push(y),a++}if(!hn(g)){let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.icon!==void 0){let g=n.icon;if(typeof g=="string"){if(!Jr.test(g)){let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};r===null?r=[y]:r.push(y),a++}if(!hn(g)){let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[y]:r.push(y),a++}}else{let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[y]:r.push(y),a++}}if(n.redirect_uris!==void 0){let g=n.redirect_uris;if(Array.isArray(g)){if(g.length>10){let k={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/maxItems",keyword:"maxItems",params:{limit:10},message:"must NOT have more than 10 items"};r===null?r=[k]:r.push(k),a++}if(g.length<1){let k={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};r===null?r=[k]:r.push(k),a++}let y=g.length;for(let k=0;k<y;k++){let S=g[k];if(typeof S=="string"){if(!hn(S)){let x={instancePath:e+"/redirect_uris/"+k,schemaPath:"#/properties/redirect_uris/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[x]:r.push(x),a++}}else{let x={instancePath:e+"/redirect_uris/"+k,schemaPath:"#/properties/redirect_uris/items/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[x]:r.push(x),a++}}let v=g.length,_;if(v>1){let k={};for(;v--;){let S=g[v];if(typeof S=="string"){if(typeof k[S]=="number"){_=k[S];let x={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/uniqueItems",keyword:"uniqueItems",params:{i:v,j:_},message:"must NOT have duplicate items (items ## "+_+" and "+v+" are identical)"};r===null?r=[x]:r.push(x),a++;break}k[S]=v}}}}else{let y={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[y]:r.push(y),a++}}if(n.installation_origins!==void 0){let g=n.installation_origins;if(g&&typeof g=="object"&&!Array.isArray(g)){for(let y in g)if(!(y==="lab"||y==="staging"||y==="production")){let v={instancePath:e+"/installation_origins",schemaPath:"#/properties/installation_origins/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};r===null?r=[v]:r.push(v),a++}g.lab!==void 0&&(Hn(g.lab,{instancePath:e+"/installation_origins/lab",parentData:g,parentDataProperty:"lab",rootData:o,dynamicAnchors:s})||(r=r===null?Hn.errors:r.concat(Hn.errors),a=r.length)),g.staging!==void 0&&(Hn(g.staging,{instancePath:e+"/installation_origins/staging",parentData:g,parentDataProperty:"staging",rootData:o,dynamicAnchors:s})||(r=r===null?Hn.errors:r.concat(Hn.errors),a=r.length)),g.production!==void 0&&(Hn(g.production,{instancePath:e+"/installation_origins/production",parentData:g,parentDataProperty:"production",rootData:o,dynamicAnchors:s})||(r=r===null?Hn.errors:r.concat(Hn.errors),a=r.length))}else{let y={instancePath:e+"/installation_origins",schemaPath:"#/properties/installation_origins/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[y]:r.push(y),a++}}if(n.requirements!==void 0&&(_a(n.requirements,{instancePath:e+"/requirements",parentData:n,parentDataProperty:"requirements",rootData:o,dynamicAnchors:s})||(r=r===null?_a.errors:r.concat(_a.errors),a=r.length)),n.provisions!==void 0){let g=n.provisions;if(g&&typeof g=="object"&&!Array.isArray(g)){if(g.type_packs===void 0){let y={instancePath:e+"/provisions",schemaPath:"#/properties/provisions/required",keyword:"required",params:{missingProperty:"type_packs"},message:"must have required property 'type_packs'"};r===null?r=[y]:r.push(y),a++}for(let y in g)if(!(y==="configuration"||y==="type_packs")){let v={instancePath:e+"/provisions",schemaPath:"#/properties/provisions/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};r===null?r=[v]:r.push(v),a++}if(g.configuration!==void 0){let y=g.configuration;if(Array.isArray(y)){if(y.length>50){let _={instancePath:e+"/provisions/configuration",schemaPath:"#/properties/provisions/properties/configuration/maxItems",keyword:"maxItems",params:{limit:50},message:"must NOT have more than 50 items"};r===null?r=[_]:r.push(_),a++}let v=y.length;for(let _=0;_<v;_++)Aa(y[_],{instancePath:e+"/provisions/configuration/"+_,parentData:y,parentDataProperty:_,rootData:o,dynamicAnchors:s})||(r=r===null?Aa.errors:r.concat(Aa.errors),a=r.length)}else{let v={instancePath:e+"/provisions/configuration",schemaPath:"#/properties/provisions/properties/configuration/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[v]:r.push(v),a++}}if(g.type_packs!==void 0){let y=g.type_packs;if(Array.isArray(y)){if(y.length>20){let _={instancePath:e+"/provisions/type_packs",schemaPath:"#/properties/provisions/properties/type_packs/maxItems",keyword:"maxItems",params:{limit:20},message:"must NOT have more than 20 items"};r===null?r=[_]:r.push(_),a++}let v=y.length;for(let _=0;_<v;_++)Sa(y[_],{instancePath:e+"/provisions/type_packs/"+_,parentData:y,parentDataProperty:_,rootData:o,dynamicAnchors:s})||(r=r===null?Sa.errors:r.concat(Sa.errors),a=r.length)}else{let v={instancePath:e+"/provisions/type_packs",schemaPath:"#/properties/provisions/properties/type_packs/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[v]:r.push(v),a++}}}else{let y={instancePath:e+"/provisions",schemaPath:"#/properties/provisions/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[y]:r.push(y),a++}}if(n.notifications!==void 0){let g=n.notifications;if(g&&typeof g=="object"&&!Array.isArray(g)){if(g.criteria===void 0){let y={instancePath:e+"/notifications",schemaPath:"#/properties/notifications/required",keyword:"required",params:{missingProperty:"criteria"},message:"must have required property 'criteria'"};r===null?r=[y]:r.push(y),a++}for(let y in g)if(!(y==="criteria"||y==="native_delivery")){let v={instancePath:e+"/notifications",schemaPath:"#/properties/notifications/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};r===null?r=[v]:r.push(v),a++}if(g.criteria!==void 0){let y=g.criteria;if(Array.isArray(y)){if(y.length>50){let _={instancePath:e+"/notifications/criteria",schemaPath:"#/properties/notifications/properties/criteria/maxItems",keyword:"maxItems",params:{limit:50},message:"must NOT have more than 50 items"};r===null?r=[_]:r.push(_),a++}let v=y.length;for(let _=0;_<v;_++)Pa(y[_],{instancePath:e+"/notifications/criteria/"+_,parentData:y,parentDataProperty:_,rootData:o,dynamicAnchors:s})||(r=r===null?Pa.errors:r.concat(Pa.errors),a=r.length)}else{let v={instancePath:e+"/notifications/criteria",schemaPath:"#/properties/notifications/properties/criteria/type",keyword:"type",params:{type:"array"},message:"must be array"};r===null?r=[v]:r.push(v),a++}}if(g.native_delivery!==void 0){let y=g.native_delivery,v=a,_=!1,k=null,S=a;if(y&&typeof y=="object"&&!Array.isArray(y)){if(y.mode===void 0){let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/required",keyword:"required",params:{missingProperty:"mode"},message:"must have required property 'mode'"};r===null?r=[P]:r.push(P),a++}if(y.firebase_project_id===void 0){let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/required",keyword:"required",params:{missingProperty:"firebase_project_id"},message:"must have required property 'firebase_project_id'"};r===null?r=[P]:r.push(P),a++}for(let P in y)if(!(P==="mode"||P==="firebase_project_id")){let C={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:P},message:"must NOT have additional properties"};r===null?r=[C]:r.push(C),a++}if(y.mode!==void 0&&y.mode!=="managed_fcm"){let P={instancePath:e+"/notifications/native_delivery/mode",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/mode/const",keyword:"const",params:{allowedValue:"managed_fcm"},message:"must be equal to constant"};r===null?r=[P]:r.push(P),a++}if(y.firebase_project_id!==void 0){let P=y.firebase_project_id;if(typeof P=="string"){if(D(P)>63){let C={instancePath:e+"/notifications/native_delivery/firebase_project_id",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/firebase_project_id/maxLength",keyword:"maxLength",params:{limit:63},message:"must NOT have more than 63 characters"};r===null?r=[C]:r.push(C),a++}if(D(P)<6){let C={instancePath:e+"/notifications/native_delivery/firebase_project_id",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/firebase_project_id/minLength",keyword:"minLength",params:{limit:6},message:"must NOT have fewer than 6 characters"};r===null?r=[C]:r.push(C),a++}if(!DS.test(P)){let C={instancePath:e+"/notifications/native_delivery/firebase_project_id",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/firebase_project_id/pattern",keyword:"pattern",params:{pattern:"^[a-z][a-z0-9-]*[a-z0-9]$"},message:'must match pattern "^[a-z][a-z0-9-]*[a-z0-9]$"'};r===null?r=[C]:r.push(C),a++}}else{let C={instancePath:e+"/notifications/native_delivery/firebase_project_id",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/properties/firebase_project_id/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[C]:r.push(C),a++}}}else{let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/0/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[P]:r.push(P),a++}var w=S===a;if(w){_=!0,k=0;var b=!0}let x=a;if(y&&typeof y=="object"&&!Array.isArray(y)){if(y.mode===void 0){let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/required",keyword:"required",params:{missingProperty:"mode"},message:"must have required property 'mode'"};r===null?r=[P]:r.push(P),a++}if(y.url===void 0){let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/required",keyword:"required",params:{missingProperty:"url"},message:"must have required property 'url'"};r===null?r=[P]:r.push(P),a++}for(let P in y)if(!(P==="mode"||P==="url")){let C={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:P},message:"must NOT have additional properties"};r===null?r=[C]:r.push(C),a++}if(y.mode!==void 0&&y.mode!=="webhook"){let P={instancePath:e+"/notifications/native_delivery/mode",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/properties/mode/const",keyword:"const",params:{allowedValue:"webhook"},message:"must be equal to constant"};r===null?r=[P]:r.push(P),a++}if(y.url!==void 0){let P=y.url;if(typeof P=="string"){if(!Jr.test(P)){let C={instancePath:e+"/notifications/native_delivery/url",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/properties/url/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};r===null?r=[C]:r.push(C),a++}if(!hn(P)){let C={instancePath:e+"/notifications/native_delivery/url",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/properties/url/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};r===null?r=[C]:r.push(C),a++}}else{let C={instancePath:e+"/notifications/native_delivery/url",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/properties/url/type",keyword:"type",params:{type:"string"},message:"must be string"};r===null?r=[C]:r.push(C),a++}}}else{let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf/1/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[P]:r.push(P),a++}var w=x===a;if(w&&_?(_=!1,k=[k,1]):w&&(_=!0,k=1,b!==!0&&(b=!0)),_)a=v,r!==null&&(v?r.length=v:r=null);else{let P={instancePath:e+"/notifications/native_delivery",schemaPath:"#/$defs/nativeNotificationDelivery/oneOf",keyword:"oneOf",params:{passingSchemas:k},message:"must match exactly one schema in oneOf"};r===null?r=[P]:r.push(P),a++}}}else{let y={instancePath:e+"/notifications",schemaPath:"#/properties/notifications/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[y]:r.push(y),a++}}}else{let g={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};r===null?r=[g]:r.push(g),a++}return ff.errors=r,a===0}var jS,IS,NS,D,US,Jr,DS,hn,OS,RS,xn,ES,$S,hf,xa,mf,da,zS,qS,df,BS,TS,MS,dE,LS,FS=I(()=>{"use strict";jS=uf,IS={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/connect/schemas/mdbase-app.v1.json",title:"mdbase connect bundled application manifest v1",type:"object",additionalProperties:!1,required:["manifest_version","id","name"],properties:{manifest_version:{const:1},distribution:{enum:["web","portable"],description:"Portable declarations use device authorization and do not claim a browser origin."},id:{type:"string",minLength:5,maxLength:150,pattern:"^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*){2,}$",description:"Stable reverse-domain application identifier. This is presentation metadata, not publisher authentication."},name:{type:"string",minLength:1,maxLength:100},platform:{const:"native",description:"Unverified native app; permits literal IPv4 loopback HTTP on any port."},homepage:{type:"string",format:"uri",pattern:"^https://"},project_url:{type:"string",format:"uri",pattern:"^https://"},icon:{type:"string",format:"uri",pattern:"^https://"},redirect_uris:{type:"array",minItems:1,maxItems:10,uniqueItems:!0,items:{type:"string",format:"uri",description:"An HTTPS URI on the homepage origin or a private-use scheme derived from the application ID."}},installation_origins:{type:"object",additionalProperties:!1,properties:{lab:{$ref:"#/$defs/installationOriginPolicy"},staging:{$ref:"#/$defs/installationOriginPolicy"},production:{$ref:"#/$defs/installationOriginPolicy"}}},requirements:{$ref:"#/$defs/requirements"},provisions:{type:"object",additionalProperties:!1,required:["type_packs"],properties:{configuration:{type:"array",maxItems:50,items:{$ref:"#/$defs/configurationProvision"}},type_packs:{type:"array",maxItems:20,items:{$ref:"#/$defs/typePackProvision"}}}},notifications:{type:"object",additionalProperties:!1,required:["criteria"],properties:{criteria:{type:"array",maxItems:50,items:{$ref:"#/$defs/notificationCriterion"}},native_delivery:{$ref:"#/$defs/nativeNotificationDelivery"}}}},oneOf:[{required:["homepage","redirect_uris"],properties:{distribution:{const:"web"},homepage:!0,redirect_uris:!0,project_url:!1}},{required:["distribution"],properties:{distribution:{const:"portable"},platform:!1,homepage:!1,redirect_uris:!1}}],$defs:{installationOriginPolicy:{type:"object",additionalProperties:!1,properties:{"app-runtime":{$ref:"#/$defs/installationOrigins"},mobile:{$ref:"#/$defs/installationOrigins"}}},installationOrigins:{type:"array",maxItems:16,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:255,format:"uri"}},identifier:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z0-9]+(?:[._-][a-z0-9]+)*$"},duration:{type:"string",pattern:"^[0-9]+(ms|s|m|h|d)$"},contract:{type:"object",additionalProperties:!1,required:["id","version","digest"],properties:{id:{$ref:"#/$defs/identifier"},version:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"}}},requirements:{type:"object",additionalProperties:!1,required:["access","contracts"],properties:{capabilities:{$ref:"#/$defs/capabilityRequirements"},access:{const:"full_collection",description:"Compatibility declaration for collection-level application authorization."},collection_kind:{const:"hosted",description:"Require a durable provider-backed collection with direct sync support."},people:{type:"object",additionalProperties:!1,required:["version"],anyOf:[{required:["required"]},{required:["optional"]}],properties:{version:{const:1},required:{$ref:"#/$defs/peoplePermissions"},optional:{$ref:"#/$defs/peoplePermissions"}}},files:{$ref:"#/$defs/fileRequirement"},configuration:{type:"array",maxItems:50,items:{$ref:"#/$defs/configurationRequirement"}},contracts:{type:"array",maxItems:20,uniqueItems:!0,items:{$ref:"#/$defs/contract"}}}},capabilityRequirements:{type:"object",additionalProperties:!1,required:["contract_version","required"],properties:{contract_version:{const:2},required:{type:"array",maxItems:32,uniqueItems:!0,items:{$ref:"#/$defs/applicationCapability"}},optional:{type:"array",maxItems:32,uniqueItems:!0,items:{$ref:"#/$defs/applicationCapability"}}}},configurationValue:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]},configurationRequirement:{type:"object",additionalProperties:!1,required:["id","path","predicate","value"],properties:{id:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},path:{type:"string",minLength:1,maxLength:1024},predicate:{const:"contains"},value:{$ref:"#/$defs/configurationValue"}}},configurationProvision:{type:"object",additionalProperties:!1,required:["requirement","operation","path","value"],properties:{requirement:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},operation:{const:"set_add"},path:{type:"string",minLength:1,maxLength:1024},value:{$ref:"#/$defs/configurationValue"}}},applicationCapability:{enum:["collection.read","records.create","records.edit","records.delete","views.manage","definitions.manage","background.schedule","offline.replica"]},peoplePermissions:{type:"array",minItems:1,uniqueItems:!0,items:{enum:["identity","members"]}},fileRequirement:{type:"object",additionalProperties:!1,required:["required","scope"],properties:{required:{$ref:"#/$defs/fileActions"},optional:{$ref:"#/$defs/fileActions"},scope:{$ref:"#/$defs/fileScope"}}},fileActions:{type:"array",minItems:1,maxItems:6,uniqueItems:!0,items:{enum:["list","read","add","replace","move","delete"]}},fileScope:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","folders"],properties:{kind:{const:"selected_folders"},folders:{type:"array",minItems:1,maxItems:100,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:1024,pattern:"^(?!/)(?!\\.)(?!.*//)(?!.*\\\\)(?!.*/\\.)(?!(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*\\/(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*/$).+$"}}}},{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"collection"}}}]},typePackProvision:{type:"object",additionalProperties:!1,required:["manifest","resources","provides"],properties:{manifest:{$ref:"#/$defs/typePackManifest"},resources:{type:"array",minItems:1,maxItems:100,items:{$ref:"#/$defs/typePackSourceResource"}},provides:{type:"array",maxItems:20,uniqueItems:!0,items:{$ref:"#/$defs/contract"}}}},typePackManifest:{type:"object",required:["kind","id","version","resources"],properties:{kind:{const:"mdbase.type-pack"},id:{$ref:"#/$defs/identifier"},version:{$ref:"#/$defs/contract/properties/version"},name:{type:"string",minLength:1,maxLength:100},description:{type:"string",maxLength:500},resources:{type:"array",minItems:1,maxItems:100,items:{$ref:"#/$defs/typePackManifestResource"}}},patternProperties:{"^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$":!0},additionalProperties:!1},typePackManifestResource:{type:"object",additionalProperties:!1,required:["kind","mode","source","target","digest"],properties:{kind:{enum:["contract","type","schema"]},mode:{enum:["managed","seed"]},upgrade_from:{oneOf:[{$ref:"#/$defs/typePackUpgradeBaseline"},{type:"array",minItems:1,items:{$ref:"#/$defs/typePackUpgradeBaseline"}}]},source:{type:"string",minLength:1,maxLength:240},target:{type:"string",minLength:1,maxLength:240},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"}}},typePackUpgradeBaseline:{type:"object",additionalProperties:!1,required:["digest","document"],properties:{digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"},document:{type:"string",maxLength:262144},version:{type:"integer",minimum:1}}},typePackSourceResource:{type:"object",additionalProperties:!1,required:["source","document"],properties:{source:{type:"string",minLength:1,maxLength:240},document:{type:"string",maxLength:262144}}},notificationCriterion:{type:"object",additionalProperties:!1,required:["id","event","presentation"],properties:{id:{$ref:"#/$defs/identifier"},event:{$ref:"#/$defs/contract"},if:{type:"object",additionalProperties:!1,required:["$expr"],properties:{$expr:{type:"string",minLength:1,maxLength:4096}}},debounce:{$ref:"#/$defs/duration"},minimum_interval:{$ref:"#/$defs/duration"},presentation:{type:"object",additionalProperties:!1,required:["title"],properties:{title:{type:"string",minLength:1,maxLength:80},body:{type:"string",maxLength:160},tag:{type:"string",minLength:1,maxLength:80}}}}},nativeNotificationDelivery:{oneOf:[{type:"object",additionalProperties:!1,required:["mode","firebase_project_id"],properties:{mode:{const:"managed_fcm"},firebase_project_id:{type:"string",minLength:6,maxLength:63,pattern:"^[a-z][a-z0-9-]*[a-z0-9]$"}}},{type:"object",additionalProperties:!1,required:["mode","url"],properties:{mode:{const:"webhook"},url:{type:"string",format:"uri",pattern:"^https://"}}}]}}},NS=Object.prototype.hasOwnProperty,D=(function(e){let t=e.length,i=0,o=0,s;for(;o<t;)i++,s=e.charCodeAt(o++),s>=55296&&s<=56319&&o<t&&(s=e.charCodeAt(o),(s&64512)===56320&&o++);return i}),US=new RegExp("^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*){2,}$","u"),Jr=new RegExp("^https://","u"),DS=new RegExp("^[a-z][a-z0-9-]*[a-z0-9]$","u"),hn=(()=>{let n=/\/|:/,e=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;return function(i){return n.test(i)&&e.test(i)}})();Wn.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};OS={type:"array",minItems:1,uniqueItems:!0,items:{enum:["identity","members"]}},RS={enum:["collection.read","records.create","records.edit","records.delete","views.manage","definitions.manage","background.schedule","offline.replica"]},xn=(function n(e,t){if(e===t)return!0;if(e&&t&&typeof e=="object"&&typeof t=="object"){if(e.constructor!==t.constructor)return!1;var i,o,s;if(Array.isArray(e)){if(i=e.length,i!=t.length)return!1;for(o=i;o--!==0;)if(!n(e[o],t[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===t.source&&e.flags===t.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===t.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===t.toString();if(s=Object.keys(e),i=s.length,i!==Object.keys(t).length)return!1;for(o=i;o--!==0;)if(!Object.prototype.hasOwnProperty.call(t,s[o]))return!1;for(o=i;o--!==0;){var r=s[o];if(!n(e[r],t[r]))return!1}return!0}return e!==e&&t!==t});la.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};ES={type:"array",minItems:1,maxItems:6,uniqueItems:!0,items:{enum:["list","read","add","replace","move","delete"]}},$S=new RegExp("^(?!/)(?!\\.)(?!.*//)(?!.*\\\\)(?!.*/\\.)(?!(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*\\/(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*/$).+$","u");ca.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};hf=new RegExp("^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$","u");pa.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};xa=new RegExp("^[a-z0-9]+(?:[._-][a-z0-9]+)*$","u"),mf=new RegExp("^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$","u"),da=new RegExp("^sha256:[0-9a-f]{64}$","u");Gn.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};ua.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};fa.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};zS=new RegExp("^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$","u"),qS={type:"object",additionalProperties:!1,required:["kind","mode","source","target","digest"],properties:{kind:{enum:["contract","type","schema"]},mode:{enum:["managed","seed"]},upgrade_from:{oneOf:[{$ref:"#/$defs/typePackUpgradeBaseline"},{type:"array",minItems:1,items:{$ref:"#/$defs/typePackUpgradeBaseline"}}]},source:{type:"string",minLength:1,maxLength:240},target:{type:"string",minLength:1,maxLength:240},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"}}};ha.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};ma.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};ya.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};df=new RegExp("^[0-9]+(ms|s|m|h|d)$","u");ga.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};uf.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};BS=ff,TS={$schema:"https://json-schema.org/draft/2020-12/schema",$id:"https://mdbase.dev/connect/schemas/mdbase-app.legacy-v1.json",title:"mdbase connect bundled application manifest v1",type:"object",additionalProperties:!1,required:["manifest_version","id","name"],properties:{manifest_version:{const:1},distribution:{enum:["web","portable"],description:"Portable declarations use device authorization and do not claim a browser origin."},id:{type:"string",minLength:5,maxLength:150,pattern:"^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*){2,}$",description:"Stable reverse-domain application identifier. This is presentation metadata, not publisher authentication."},name:{type:"string",minLength:1,maxLength:100},platform:{const:"native",description:"Unverified native app; permits literal IPv4 loopback HTTP on any port."},homepage:{type:"string",format:"uri",pattern:"^https://"},project_url:{type:"string",format:"uri",pattern:"^https://"},icon:{type:"string",format:"uri",pattern:"^https://"},redirect_uris:{type:"array",minItems:1,maxItems:10,uniqueItems:!0,items:{type:"string",format:"uri",description:"An HTTPS URI on the homepage origin or a private-use scheme derived from the application ID."}},installation_origins:{type:"object",additionalProperties:!1,properties:{lab:{$ref:"#/$defs/installationOriginPolicy"},staging:{$ref:"#/$defs/installationOriginPolicy"},production:{$ref:"#/$defs/installationOriginPolicy"}}},requirements:{$ref:"#/$defs/requirements"},provisions:{type:"object",additionalProperties:!1,required:["type_packs"],properties:{configuration:{type:"array",maxItems:50,items:{$ref:"#/$defs/configurationProvision"}},type_packs:{type:"array",maxItems:20,items:{$ref:"#/$defs/typePackProvision"}}}},notifications:{type:"object",additionalProperties:!1,required:["criteria"],properties:{criteria:{type:"array",maxItems:50,items:{$ref:"#/$defs/notificationCriterion"}},native_delivery:{$ref:"#/$defs/nativeNotificationDelivery"}}}},oneOf:[{required:["homepage","redirect_uris"],properties:{distribution:{const:"web"},homepage:!0,redirect_uris:!0,project_url:!1}},{required:["distribution"],properties:{distribution:{const:"portable"},platform:!1,homepage:!1,redirect_uris:!1}}],$defs:{installationOriginPolicy:{type:"object",additionalProperties:!1,properties:{"app-runtime":{$ref:"#/$defs/installationOrigins"},mobile:{$ref:"#/$defs/installationOrigins"}}},installationOrigins:{type:"array",maxItems:16,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:255,format:"uri"}},identifier:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z0-9]+(?:[._-][a-z0-9]+)*$"},duration:{type:"string",pattern:"^[0-9]+(ms|s|m|h|d)$"},contract:{type:"object",additionalProperties:!1,required:["id","version","digest"],properties:{id:{$ref:"#/$defs/identifier"},version:{type:"string",pattern:"^(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)\\.(0|[1-9][0-9]*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$"},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"}}},requirements:{type:"object",additionalProperties:!1,required:["access","contracts"],properties:{capabilities:{$ref:"#/$defs/capabilityRequirements"},access:{const:"full_collection",description:"Compatibility declaration for collection-level application authorization."},collection_kind:{const:"hosted",description:"Require a durable provider-backed collection with direct sync support."},files:{$ref:"#/$defs/fileRequirement"},configuration:{type:"array",maxItems:50,items:{$ref:"#/$defs/configurationRequirement"}},contracts:{type:"array",maxItems:20,uniqueItems:!0,items:{$ref:"#/$defs/contract"}}}},capabilityRequirements:{type:"object",additionalProperties:!1,required:["contract_version","required"],properties:{contract_version:{const:1},required:{type:"array",maxItems:32,uniqueItems:!0,items:{$ref:"#/$defs/applicationCapability"}},optional:{type:"array",maxItems:32,uniqueItems:!0,items:{$ref:"#/$defs/applicationCapability"}}}},configurationValue:{anyOf:[{type:"string"},{type:"number"},{type:"boolean"},{type:"null"}]},configurationRequirement:{type:"object",additionalProperties:!1,required:["id","path","predicate","value"],properties:{id:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},path:{type:"string",minLength:1,maxLength:1024},predicate:{const:"contains"},value:{$ref:"#/$defs/configurationValue"}}},configurationProvision:{type:"object",additionalProperties:!1,required:["requirement","operation","path","value"],properties:{requirement:{type:"string",minLength:1,maxLength:100,pattern:"^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$"},operation:{const:"set_add"},path:{type:"string",minLength:1,maxLength:1024},value:{$ref:"#/$defs/configurationValue"}}},applicationCapability:{enum:["collection.inspect","records.watch","records.read","records.query","records.validate","records.create","records.update","records.delete","records.rename","views.list","views.execute","views.source.read","views.source.create","views.source.update","views.source.delete","definitions.contracts.current","definitions.read","definitions.create","definitions.update","definitions.type-pack.inspect","definitions.type-pack.apply","collection.setup.apply","timers.list","timers.put","timers.cancel","timers.reconcile","sync.offline-replica","notifications.background-delivery","files.list","files.read","files.add","files.replace","files.move","files.delete"]},fileRequirement:{type:"object",additionalProperties:!1,required:["actions","scope"],properties:{actions:{type:"array",minItems:1,maxItems:6,uniqueItems:!0,items:{enum:["list","read","add","replace","move","delete"]}},scope:{$ref:"#/$defs/fileScope"}}},fileScope:{oneOf:[{type:"object",additionalProperties:!1,required:["kind","folders"],properties:{kind:{const:"selected_folders"},folders:{type:"array",minItems:1,maxItems:100,uniqueItems:!0,items:{type:"string",minLength:1,maxLength:1024,pattern:"^(?!/)(?!\\.)(?!.*//)(?!.*\\\\)(?!.*/\\.)(?!(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*\\/(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*/$).+$"}}}},{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"collection"}}}]},typePackProvision:{type:"object",additionalProperties:!1,required:["manifest","resources","provides"],properties:{manifest:{$ref:"#/$defs/typePackManifest"},resources:{type:"array",minItems:1,maxItems:100,items:{$ref:"#/$defs/typePackSourceResource"}},provides:{type:"array",maxItems:20,uniqueItems:!0,items:{$ref:"#/$defs/contract"}}}},typePackManifest:{type:"object",required:["kind","id","version","resources"],properties:{kind:{const:"mdbase.type-pack"},id:{$ref:"#/$defs/identifier"},version:{$ref:"#/$defs/contract/properties/version"},name:{type:"string",minLength:1,maxLength:100},description:{type:"string",maxLength:500},resources:{type:"array",minItems:1,maxItems:100,items:{$ref:"#/$defs/typePackManifestResource"}}},patternProperties:{"^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$":!0},additionalProperties:!1},typePackManifestResource:{type:"object",additionalProperties:!1,required:["kind","mode","source","target","digest"],properties:{kind:{enum:["contract","type","schema"]},mode:{enum:["managed","seed"]},source:{type:"string",minLength:1,maxLength:240},target:{type:"string",minLength:1,maxLength:240},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"}}},typePackSourceResource:{type:"object",additionalProperties:!1,required:["source","document"],properties:{source:{type:"string",minLength:1,maxLength:240},document:{type:"string",maxLength:262144}}},notificationCriterion:{type:"object",additionalProperties:!1,required:["id","event","presentation"],properties:{id:{$ref:"#/$defs/identifier"},event:{$ref:"#/$defs/contract"},if:{type:"object",additionalProperties:!1,required:["$expr"],properties:{$expr:{type:"string",minLength:1,maxLength:4096}}},debounce:{$ref:"#/$defs/duration"},minimum_interval:{$ref:"#/$defs/duration"},presentation:{type:"object",additionalProperties:!1,required:["title"],properties:{title:{type:"string",minLength:1,maxLength:80},body:{type:"string",maxLength:160},tag:{type:"string",minLength:1,maxLength:80}}}}},nativeNotificationDelivery:{oneOf:[{type:"object",additionalProperties:!1,required:["mode","firebase_project_id"],properties:{mode:{const:"managed_fcm"},firebase_project_id:{type:"string",minLength:6,maxLength:63,pattern:"^[a-z][a-z0-9-]*[a-z0-9]$"}}},{type:"object",additionalProperties:!1,required:["mode","url"],properties:{mode:{const:"webhook"},url:{type:"string",format:"uri",pattern:"^https://"}}}]}}};Hn.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};MS={enum:["collection.inspect","records.watch","records.read","records.query","records.validate","records.create","records.update","records.delete","records.rename","views.list","views.execute","views.source.read","views.source.create","views.source.update","views.source.delete","definitions.contracts.current","definitions.read","definitions.create","definitions.update","definitions.type-pack.inspect","definitions.type-pack.apply","collection.setup.apply","timers.list","timers.put","timers.cancel","timers.reconcile","sync.offline-replica","notifications.background-delivery","files.list","files.read","files.add","files.replace","files.move","files.delete"]};ba.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};dE={type:"object",additionalProperties:!1,required:["actions","scope"],properties:{actions:{type:"array",minItems:1,maxItems:6,uniqueItems:!0,items:{enum:["list","read","add","replace","move","delete"]}},scope:{$ref:"#/$defs/fileScope"}}};wa.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};va.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Yn.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};_a.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Aa.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};LS={type:"object",additionalProperties:!1,required:["kind","mode","source","target","digest"],properties:{kind:{enum:["contract","type","schema"]},mode:{enum:["managed","seed"]},source:{type:"string",minLength:1,maxLength:240},target:{type:"string",minLength:1,maxLength:240},digest:{type:"string",pattern:"^sha256:[0-9a-f]{64}$"}}};ka.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Sa.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Pa.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};ff.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1}});var VS,KS,yf=I(()=>{VS="/settings/record_extensions",KS="yaml-document-records-v1"});function cb(n,e){let t=n===1?fE:n===2?uE:void 0;if(!(!t||!Object.hasOwn(t,e)))return[...t[e]]}var uE,WS,fE,k3,pb,gf=I(()=>{uE={"collection.read":["describe","changes","read","query","list_views","execute_view","read_view_source","validate","read_type"],"records.create":["create"],"records.edit":["update","rename"],"records.delete":["delete"],"views.manage":["create_view_source","update_view_source","delete_view_source"],"definitions.manage":["create_type","update_type","assess_type_pack","apply_type_pack"],"background.schedule":["list_timers","put_timer","cancel_timer","reconcile_timers"],"offline.replica":["sync"]},WS=["assess_collection_setup","apply_collection_setup"],fE=Object.freeze({"collection.inspect":Object.freeze(["describe"]),"records.watch":Object.freeze(["changes"]),"records.read":Object.freeze(["read"]),"records.query":Object.freeze(["query"]),"records.validate":Object.freeze(["validate"]),"records.create":Object.freeze(["create"]),"records.update":Object.freeze(["update"]),"records.delete":Object.freeze(["delete"]),"records.rename":Object.freeze(["rename"]),"views.list":Object.freeze(["list_views"]),"views.execute":Object.freeze(["execute_view"]),"views.source.read":Object.freeze(["read_view_source"]),"views.source.create":Object.freeze(["create_view_source"]),"views.source.update":Object.freeze(["update_view_source"]),"views.source.delete":Object.freeze(["delete_view_source"]),"definitions.contracts.current":Object.freeze([]),"definitions.read":Object.freeze(["read_type"]),"definitions.create":Object.freeze(["create_type"]),"definitions.update":Object.freeze(["update_type"]),"definitions.type-pack.inspect":Object.freeze(["assess_type_pack"]),"definitions.type-pack.apply":Object.freeze(["assess_type_pack","apply_type_pack"]),"collection.setup.apply":Object.freeze(["assess_collection_setup","apply_collection_setup"]),"timers.list":Object.freeze(["list_timers"]),"timers.put":Object.freeze(["put_timer"]),"timers.cancel":Object.freeze(["cancel_timer"]),"timers.reconcile":Object.freeze(["reconcile_timers"]),"sync.offline-replica":Object.freeze(["sync"]),"notifications.background-delivery":Object.freeze([]),"files.list":Object.freeze([]),"files.read":Object.freeze([]),"files.add":Object.freeze([]),"files.replace":Object.freeze([]),"files.move":Object.freeze([]),"files.delete":Object.freeze([])});k3=Object.freeze([1,2]),pb=Object.freeze(["application-authorization-v2-issuance"])});var HS=I(()=>{});var GS,db=I(()=>{GS={access_denied:{category:"authorization",recovery:"reauthorize"},access_paused:{category:"availability",recovery:"resume_connector_access"},application_authorization_issuance_disabled:{category:"authorization",recovery:"reauthorize"},application_declaration_mismatch:{category:"authorization",recovery:"reauthorize"},application_identity_unavailable:{category:"compatibility",recovery:"upgrade_application"},application_reauthorization_required:{category:"authorization",recovery:"reauthorize"},application_semantic_version_mismatch:{category:"authorization",recovery:"reauthorize"},approval_window_blocked:{category:"authorization",recovery:"reauthorize"},authority_authorization_changed:{category:"authorization",recovery:"reauthorize"},authorization_binding_incompatible:{category:"compatibility",recovery:"upgrade_application"},authorization_cancelled:{category:"cancellation",recovery:"none"},authorization_expired:{category:"authorization",recovery:"reauthorize"},authorization_replayed:{category:"integrity",recovery:"reauthorize"},browser_required:{category:"compatibility",recovery:"none"},callback_url_required:{category:"validation",recovery:"fix_request"},capability_contract_incompatible:{category:"compatibility",recovery:"upgrade_application"},change_cursor_reset:{category:"conflict",recovery:"refresh"},collection_access_denied:{category:"authorization",recovery:"reauthorize"},collection_claimed_by_newer_runtime:{category:"compatibility",recovery:"upgrade_connector"},collection_configuration_invalid:{category:"validation",recovery:"repair_collection"},collection_contracts_missing:{category:"compatibility",recovery:"choose_collection"},collection_incompatible:{category:"compatibility",recovery:"choose_collection"},collection_invalid:{category:"validation",recovery:"repair_collection"},collection_kind_unsupported:{category:"compatibility",recovery:"choose_collection"},collection_mismatch:{category:"selection",recovery:"choose_collection"},collection_not_found:{category:"selection",recovery:"choose_collection"},collection_not_ready:{category:"selection",recovery:"choose_collection"},collection_not_selected:{category:"selection",recovery:"choose_collection"},collection_type_registry_invalid:{category:"validation",recovery:"repair_collection"},collection_unavailable:{category:"availability",recovery:"choose_collection"},collection_version_unsupported:{category:"compatibility",recovery:"upgrade_collection"},concurrent_modification:{category:"conflict",recovery:"refresh"},connector_busy:{category:"availability",recovery:"retry"},connector_identity_changed:{category:"integrity",recovery:"reauthorize"},connector_offline:{category:"availability",recovery:"retry"},connector_upgrade_required:{category:"compatibility",recovery:"upgrade_connector"},cursor_capacity_exhausted:{category:"availability",recovery:"retry"},device_authorization_failed:{category:"authorization",recovery:"reauthorize"},direct_operation_rejected:{category:"authorization",recovery:"reauthorize"},discovery_failed:{category:"availability",recovery:"retry"},durable_mutation_unsupported:{category:"compatibility",recovery:"upgrade_connector"},encrypted_relay_rejected:{category:"authorization",recovery:"reauthorize"},encryption_required:{category:"authorization",recovery:"reauthorize"},expired_token:{category:"authorization",recovery:"reauthorize"},file_changed_during_move:{category:"conflict",recovery:"refresh"},file_changed_during_read:{category:"conflict",recovery:"refresh"},file_index_warming:{category:"availability",recovery:"retry"},file_list_changed:{category:"conflict",recovery:"refresh"},file_move_failed:{category:"internal",recovery:"contact_support"},file_mutation_conflict:{category:"conflict",recovery:"resolve_conflict"},file_not_found:{category:"conflict",recovery:"refresh"},file_source_mismatch:{category:"conflict",recovery:"refresh"},file_upload_incomplete:{category:"conflict",recovery:"retry"},fresh_request_required:{category:"availability",recovery:"retry"},generation_expired:{category:"conflict",recovery:"refresh"},hosted_provider_unavailable:{category:"availability",recovery:"retry"},insufficient_access:{category:"authorization",recovery:"reauthorize"},invalid_application_authorization:{category:"validation",recovery:"fix_request"},invalid_application_manifest:{category:"validation",recovery:"fix_request"},invalid_callback:{category:"validation",recovery:"fix_request"},invalid_device_authorization_response:{category:"integrity",recovery:"contact_support"},invalid_encrypted_response:{category:"integrity",recovery:"contact_support"},invalid_loopback_url:{category:"validation",recovery:"fix_request"},invalid_mutation_id:{category:"validation",recovery:"fix_request"},invalid_operation_response:{category:"integrity",recovery:"contact_support"},invalid_path:{category:"validation",recovery:"fix_request"},invalid_preflight:{category:"conflict",recovery:"refresh"},invalid_push_payload:{category:"validation",recovery:"fix_request"},invalid_push_subscription:{category:"validation",recovery:"fix_request"},invalid_read_cursor:{category:"validation",recovery:"fix_request"},invalid_replica:{category:"authorization",recovery:"reauthorize"},invalid_request:{category:"validation",recovery:"fix_request"},invalid_token_response:{category:"integrity",recovery:"contact_support"},legacy_scope_reauthorization_required:{category:"authorization",recovery:"reauthorize"},managed_fcm_not_declared:{category:"compatibility",recovery:"fix_request"},manifest_load_failed:{category:"availability",recovery:"retry"},manifest_required:{category:"validation",recovery:"fix_request"},missing_grant_key:{category:"authorization",recovery:"reauthorize"},mutation_recovery_expired:{category:"compatibility",recovery:"none"},mutation_request_conflict:{category:"conflict",recovery:"resolve_conflict"},no_pending_mutation:{category:"conflict",recovery:"refresh"},not_authorized:{category:"authorization",recovery:"reauthorize"},not_remote_authority:{category:"compatibility",recovery:"choose_collection"},notification_criterion_not_declared:{category:"validation",recovery:"fix_request"},notification_grant_reauthorization_required:{category:"authorization",recovery:"reauthorize"},notification_reauthorization_required:{category:"authorization",recovery:"reauthorize"},notification_registration_failed:{category:"availability",recovery:"retry"},notification_unregistration_failed:{category:"availability",recovery:"retry"},notifications_not_declared:{category:"compatibility",recovery:"fix_request"},notifications_unavailable:{category:"availability",recovery:"retry"},operation_cancelled:{category:"cancellation",recovery:"none"},operation_failed:{category:"internal",recovery:"contact_support"},operation_invalid:{category:"validation",recovery:"fix_request"},operation_outcome_unknown:{category:"conflict",recovery:"resolve_outcome"},origin_denied:{category:"authorization",recovery:"reauthorize"},path_occupied:{category:"conflict",recovery:"resolve_conflict"},pending_mutation_unresolved:{category:"conflict",recovery:"resolve_outcome"},query_snapshot_changed:{category:"conflict",recovery:"refresh"},rate_limited:{category:"availability",recovery:"retry"},reconnect_required:{category:"authorization",recovery:"reauthorize"},redirect_uri_required:{category:"validation",recovery:"fix_request"},reference_updates_unsupported:{category:"compatibility",recovery:"fix_request"},registry_backup_invalid:{category:"integrity",recovery:"contact_support"},registry_busy:{category:"availability",recovery:"retry"},registry_corrupt:{category:"integrity",recovery:"repair_collection"},registry_migration_failed:{category:"internal",recovery:"contact_support"},registry_schema_incompatible:{category:"compatibility",recovery:"upgrade_connector"},relay_authorization_expired:{category:"authorization",recovery:"reauthorize"},relay_unavailable:{category:"availability",recovery:"retry"},replica_scope_denied:{category:"authorization",recovery:"reauthorize"},sandbox_unsupported:{category:"compatibility",recovery:"fix_request"},scope_changed:{category:"authorization",recovery:"reauthorize"},scope_denied:{category:"authorization",recovery:"reauthorize"},scope_epoch_stale:{category:"authorization",recovery:"reauthorize"},session_destroyed:{category:"cancellation",recovery:"none"},session_not_started:{category:"validation",recovery:"fix_request"},session_starting:{category:"availability",recovery:"retry"},stale_file_revision:{category:"conflict",recovery:"refresh"},storage_required:{category:"compatibility",recovery:"none"},sync_failed:{category:"availability",recovery:"retry"},temporarily_unavailable:{category:"availability",recovery:"retry"},timeout:{category:"availability",recovery:"retry"},timer_grant_unavailable:{category:"authorization",recovery:"reauthorize"},token_exchange_failed:{category:"availability",recovery:"retry"},transport_protocol_incompatible:{category:"compatibility",recovery:"upgrade_connector"},type_pack_provision_failed:{category:"validation",recovery:"repair_collection"},unknown_collection:{category:"selection",recovery:"choose_collection"},unsafe_file_path:{category:"validation",recovery:"fix_request"},unsupported_encryption:{category:"compatibility",recovery:"upgrade_application"},unsupported_operation:{category:"compatibility",recovery:"fix_request"}}});function mE(n,e,...[t={}]){let i=GS[n];return{problem_version:1,code:n,category:i.category,recovery:i.recovery,message:e,...t.details===void 0?{}:{details:t.details},...t.operationOutcome===void 0?{}:{operation_outcome:t.operationOutcome},...t.traceId===void 0?{}:{trace_id:t.traceId}}}function YS(n,e,...t){let i=t[0];return new ub(mE(n,e,...t),{status:i?.status,cause:i?.cause})}var ub,JS=I(()=>{db();ub=class extends Error{problem;code;status;constructor(e,t={}){super(e.message,t.cause===void 0?void 0:{cause:t.cause}),this.problem=e,this.name="MdbaseConnectError",this.code=e.code,this.status=t.status}get retryable(){return this.problem.recovery==="retry"&&this.problem.operation_outcome!=="unknown"}get requiresAuthorization(){return this.problem.category==="authorization"}get outcomeUnknown(){return this.problem.operation_outcome==="unknown"}get recovery(){return this.problem.recovery}get details(){return this.problem.details}}});function XS(n,e={}){return{actions:[...new Set([...n.required,...e.includeOptional===!1?[]:n.optional??[]])],scope:structuredClone(n.scope)}}var O3,R3,fb=I(()=>{O3=new Uint8Array([77,68,66,70]),R3=new Uint8Array([77,68,66,82])});function fr(n){let e=n.capabilities===void 0?1:n.capabilities?.contract_version;return e!==1&&e!==2&&Ca("Unsupported declared capability contract version."),e}function Ca(n){throw YS("invalid_application_manifest",n,{details:{issues:[{path:"/requirements/capabilities",keyword:"authorizationSelection",message:n,params:{}}]}})}function QS(n,e){if(e.operations!==void 0&&e.capabilities!==void 0&&Ca("Specify operations or capabilities, not both."),e.operations!==void 0&&fr(n)!==1&&Ca("Exact operations authorization is only supported for legacy v1 declarations."),e.capabilities!==void 0){let t=new Set([...n.capabilities?.required??[],...n.capabilities?.optional??[]]);e.capabilities.some(i=>!t.has(i)||cb(fr(n),i)===void 0)&&Ca("Authorization can only include capabilities declared by the application.")}}function hb(n,e){let{requirements:t}=n;if(QS(t,e),fr(t)===1){if(e.operations!==void 0)return[...new Set(e.operations)];if(e.capabilities===void 0)return[...ZS]}let i=t.capabilities,s=[...i?.required??[],...e.capabilities??i?.optional??[]].flatMap(a=>cb(fr(t),a)??[]),r=(n.provisions?.type_packs.length??0)>0||(n.provisions?.configuration?.length??0)>0;return[...new Set([...s,...fr(t)===2&&r?WS:[]])]}function mb(n){let e=n.files;if(e)return fr(n)===1?((!("actions"in e)||"required"in e||"optional"in e)&&Ca("Legacy file declarations must use exact files.actions."),{actions:[...e.actions],scope:structuredClone(e.scope)}):("actions"in e&&Ca("V2 file declarations must use required/optional file actions."),XS(e))}var ZS,eP=I(()=>{gf();fb();JS();ZS=["describe","changes","read","query"]});function _E(n,e){let t=AE(e)?e:{};if(t.dry_run===!0&&vE.has(n))return null;if(n==="file_control"){let o=typeof t.type=="string"?t.type:"";return wE.has(o)?`file_control:${o}`:null}let i=bE[n];return i==="always"?n:i==="sync_action"&&t.action==="mutate"?"sync:mutate":null}function bf(n,e){return _E(n,e)!==null}function AE(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}var yE,gE,bE,wE,vE,j3,N3,wf=I(()=>{yE=["describe","changes","read","query","list_views","execute_view","read_view_source","create_view_source","update_view_source","delete_view_source","validate","create","update","delete","rename","read_type","create_type","update_type","assess_type_pack","apply_type_pack","assess_collection_setup","apply_collection_setup","list_timers","put_timer","cancel_timer","reconcile_timers","sync"],gE=["list_files","stat_file","open_file_upload","open_file_download","move_file","delete_file","get_file_transfer_status","commit_file_upload","abort_file_transfer"],bE={describe:"never",changes:"never",read:"never",query:"never",list_views:"never",execute_view:"never",read_view_source:"never",create_view_source:"always",update_view_source:"always",delete_view_source:"always",validate:"never",create:"always",update:"always",delete:"always",rename:"always",read_type:"never",create_type:"always",update_type:"always",assess_type_pack:"never",apply_type_pack:"always",assess_collection_setup:"never",apply_collection_setup:"always",list_timers:"never",put_timer:"always",cancel_timer:"always",reconcile_timers:"always",sync:"sync_action"},wE=new Set(["open_file_upload","move_file","delete_file","commit_file_upload","abort_file_transfer"]),vE=new Set(["delete","rename"]),j3=new Set(yE),N3=new Set(gE)});var tP=I(()=>{});var $3,nP=I(()=>{$3=new TextEncoder});function oP(n,e,t=[],i=2){let o={operation_transport:Tc,authorization_binding:hr,semantic_capabilities:i},s=[...new Set(t)].filter(r=>r!==Tc).sort((r,a)=>a-r);return s.length>0&&(o.operation_transport_recovery=s),(n.some(r=>bf(r,{action:"mutate"}))||e?.actions.some(r=>r!=="list"&&r!=="read")===!0)&&(o.durable_mutation=1),o}function gb(n){return iP.includes(n)}function sP(n){return rP.includes(n)}var Tc,SE,iP,hr,yb,rP,PE,xE,F3,vf=I(()=>{wf();Tc=3,SE=2,iP=[Tc,SE],hr=5,yb=4,rP=[hr,yb],PE=2,xE=1,F3={operation_transport:[...iP],authorization_binding:[...rP],semantic_capabilities:[PE,1],durable_mutation:[xE]}});async function lP(n){let e=_f(n),i=new Uint8Array(await crypto.subtle.digest("SHA-256",$o([CE,Ot(e)]))).slice(0,16);return i[6]=i[6]&15|128,i[8]=i[8]&63|128,[Mc(i.slice(0,4)),Mc(i.slice(4,6)),Mc(i.slice(6,8)),Mc(i.slice(8,10)),Mc(i.slice(10,16))].join("-")}function cP(n){let e=[_f(n.installation_signing_public_key),_f(n.grant_agreement_public_key),_f(n.grant_signing_public_key)];if(e.some((p,l)=>e.slice(l+1).some(c=>LE(p,c))))throw new Error("Application authorization keys must be distinct.");let t=bb(n.authorization_nonce),i=bb(n.code_challenge),o=n.contracts,s=o.operation_transport_recovery??[],r=n.requested_operations.some(p=>bf(p,{action:"mutate"}))||n.requested_files?.actions.some(p=>!["list","read"].includes(p))===!0;if(!sP(n.protocol_version)||t.byteLength!==32||!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(n.application_declaration_id)||!/^[0-9a-f]{64}$/u.test(n.application_manifest_digest)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(n.issued_at)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(n.expires_at)||i.byteLength!==32||![o.operation_transport,o.authorization_binding,o.semantic_capabilities,o.durable_mutation??1].every(p=>Number.isInteger(p)&&p>0)||o.authorization_binding!==n.protocol_version||!gb(o.operation_transport)||n.protocol_version===hr&&o.operation_transport!==Tc||s.some(p=>!gb(p)||p===o.operation_transport)||new Set(s).size!==s.length||n.protocol_version===yb&&s.length>0||s.length>0&&!r||(r?o.durable_mutation!==1:o.durable_mutation!==void 0)||n.requested_operations.length===0&&n.requested_files===void 0||new Set(n.requested_operations).size!==n.requested_operations.length||n.requested_operations.some(p=>!p||p.includes("\0"))||(n.flow==="authorization_code"?n.redirect_uri===void 0||n.state===void 0:n.flow!=="device_code"||n.redirect_uri!==void 0||n.state!==void 0))throw new Error("Application authorization binding is invalid.");EE(n.requested_files);let a=n.requested_operations.map(p=>Ot(new TextEncoder().encode(p)));return $o([n.protocol_version===hr?OE:IE,wi(n.protocol_version),Ot(Af(n.application_id)),Ot(Af(n.authorization_id)),Ot(new TextEncoder().encode(n.application_declaration_id)),Ot(pP(n.application_manifest_digest)),Ot(Af(n.application_installation_id)),...e.map(Ot),Ot(new TextEncoder().encode(n.flow)),Ot(t),Ot(new TextEncoder().encode(n.issued_at)),Ot(new TextEncoder().encode(n.expires_at)),aP(n.redirect_uri),aP(n.state),Ot(new TextEncoder().encode(n.code_challenge)),wi(o.operation_transport),...n.protocol_version===hr?[wi(s.length),...s.map(wi)]:[],wi(o.authorization_binding),wi(o.semantic_capabilities),RE(o.durable_mutation),wi(a.length),...a,qE(n.requested_files),TE(n.collection_id)])}function RE(n){return n===void 0?new Uint8Array(1):$o([new Uint8Array([1]),wi(n)])}function EE(n){if(n!==void 0&&(n.actions.length===0||new Set(n.actions).size!==n.actions.length||n.scope.kind==="selected_folders"&&(n.scope.folders.length===0||new Set(n.scope.folders).size!==n.scope.folders.length||n.scope.folders.some(e=>!e||e.includes("\0")))))throw new Error("Application authorization file request is invalid.")}function qE(n){if(n===void 0)return new Uint8Array(1);let e=n.actions.map(t=>Ot(new TextEncoder().encode(t)));return $o([new Uint8Array([1]),wi(e.length),...e,Ot(new TextEncoder().encode(n.scope.kind)),...n.scope.kind==="selected_folders"?[wi(n.scope.folders.length),...n.scope.folders.map(t=>Ot(new TextEncoder().encode(t)))]:[]])}function aP(n){return n===void 0?new Uint8Array(1):$o([new Uint8Array([1]),Ot(new TextEncoder().encode(n))])}function TE(n){return n===void 0?new Uint8Array(1):$o([new Uint8Array([1]),Ot(Af(n))])}function _f(n){let e=bb(n);if(e.byteLength!==65||e[0]!==4)throw new Error("Application authorization public key is invalid.");return e}function bb(n){if(!/^[A-Za-z0-9_-]+$/u.test(n))throw new Error("Invalid base64url value.");let e=n.replaceAll("-","+").replaceAll("_","/"),t=e.padEnd(Math.ceil(e.length/4)*4,"="),i=Uint8Array.from(atob(t),o=>o.charCodeAt(0));if(ME(i)!==n)throw new Error("Non-canonical base64url value.");return i}function Af(n){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(n))throw new Error("Invalid UUID value.");let e=n.replaceAll("-","");return pP(e)}function pP(n){if(!/^[0-9a-f]+$/u.test(n)||n.length%2!==0)throw new Error("Invalid hexadecimal value.");return Uint8Array.from({length:n.length/2},(e,t)=>Number.parseInt(n.slice(t*2,t*2+2),16))}function Ot(n){return $o([wi(n.byteLength),n])}function wi(n){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n,!1),e}function $o(n){let e=new Uint8Array(n.reduce((i,o)=>i+o.byteLength,0)),t=0;for(let i of n)e.set(i,t),t+=i.byteLength;return e}function ME(n){return btoa(String.fromCharCode(...n)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function LE(n,e){return n.byteLength===e.byteLength&&n.every((t,i)=>t===e[i])}function Mc(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}var CE,IE,OE,dP=I(()=>{wf();vf();CE=new TextEncoder().encode("mdbase-connect application installation id v2\0"),IE=new TextEncoder().encode("mdbase-connect application authorization proof v4\0"),OE=new TextEncoder().encode("mdbase-connect application authorization proof v5\0")});var kf,uP=I(()=>{kf={id:"mdbase.runtime.timer.fired",version:"1.0.0",digest:"sha256:41105be7a7abf33b31ced47e1e1965242236e40ccaea286b959b0a8c591f5642"}});function hP(n,e){let t=n.protocol.slice(0,-1),i=e?.toLowerCase().split(".").reverse().join(".");return t.includes(".")&&/^[a-z][a-z0-9+.-]*$/.test(t)&&!["http","https","file","javascript","data"].includes(t)&&(!i||t===i||t.startsWith(`${i}.`))&&n.username===""&&n.password===""&&n.hostname.length>0&&n.hash===""}var jE,NE,UE,DE,$E,zE,BE,Q3,FE,e5,wb,fP,Lc,jc=I(()=>{gf();HS();yf();db();eP();fb();wf();tP();nP();vf();gf();dP();uP();yf();vf();jE="contract-setup-v1",NE="file-relay-v1",UE="protocol-usage-report-v1",DE="policy-freshness-lease-v1",$E=["application-authorization-v4","authorization-activation","encrypted-relay","policy-ack"],zE=["durable-mutation-journal-v1","durable-file-lifecycle-v1","contract-metadata-read-v1"],BE="candidate-b-activation-v1",Q3=[...pb,...zE,"mutation-replay-after-credential-retirement-v1",BE],FE="application-declaration-evidence-v1",e5=[...pb,FE,...$E,DE,"application-authorization-v5",jE,NE,UE,KS],wb=1,fP="mdbase-authority-request-proof-v1",Lc={version:"x-mdbase-proof-version",timestamp:"x-mdbase-proof-timestamp",nonce:"x-mdbase-proof-nonce",signature:"x-mdbase-proof-signature"}});function WE(n,e={}){return HE(n,e,!0)}function wP(n){let e=Ee(Ee(n).requirements);return e.capabilities===void 0?1:Ee(e.capabilities).contract_version}function HE(n,e,t){let i=XE(n,e.maxBytes??xf);if(i)return Pf([i]);let o=t?wP(n):2;if(o!==1&&o!==2)return Pf([le("/requirements/capabilities/contract_version","contractVersion","must declare supported contract version 1 or 2")]);let s=Ee(n).platform==="native",r=e.allowLocal||s?aq(n,!e.allowLocal):n,a=YE(o===1?KE:VE,r);if(!a.valid)return a;let p=[...ZE(n,e.allowLocal===!0),...o===1?sq(n):oq(n),...eq(n),...iq(n)];return p.length===0?{valid:!0,issues:[]}:Pf(p)}function Nc(n,e={}){let t=WE(n,e);if(!t.valid)throw new _b(t.issues);return wP(n)===1?{contractVersion:1,manifest:mP(n)}:{contractVersion:2,manifest:mP(n)}}function mP(n){let e=structuredClone(n);return{...e,requirements:{configuration:[],...e.requirements},provisions:{type_packs:[],configuration:[],...e.provisions},notifications:e.notifications??{criteria:[]}}}function GE(n){return n.map(e=>`${e.path||"/"} ${e.message}`).join("; ")}function YE(n,e){if(n(e))return{valid:!0,issues:[]};let t=(n.errors??[]).map(JE),i=t.filter(o=>o.keyword!=="oneOf");return Pf(i.length>0?i:t)}function JE(n){let e=n.params;return n.keyword==="required"&&typeof e.missingProperty=="string"?{path:Ab(n.instancePath,e.missingProperty),keyword:n.keyword,message:"is required",params:e}:n.keyword==="additionalProperties"&&typeof e.additionalProperty=="string"?{path:Ab(n.instancePath,e.additionalProperty),keyword:n.keyword,message:"is not allowed",params:e}:{path:n.instancePath,keyword:n.keyword,message:n.message??"is invalid",params:e}}function Ab(n,e){let t=e.replaceAll("~","~0").replaceAll("/","~1");return`${n}/${t}`}function XE(n,e){let t=vP(n,"",new WeakSet);if(t)return t;try{let i=JSON.stringify(n),o=new TextEncoder().encode(i).byteLength;return o<=e?void 0:le("/","maxBytes",`must not exceed ${e} UTF-8 bytes`,{maxBytes:e,actualBytes:o})}catch{return le("/","json","must be serializable as JSON")}}function vP(n,e,t){if(n===null||typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))return;if(typeof n!="object")return le(e||"/","json","must be a JSON value");if(t.has(n))return le(e||"/","json","must not contain circular references");let i=Object.getPrototypeOf(n);if(!Array.isArray(n)&&i!==Object.prototype&&i!==null)return le(e||"/","json","must be a plain JSON object");t.add(n);let o=Array.isArray(n)?n.map((s,r)=>[String(r),s]):Object.entries(n);for(let[s,r]of o){let a=vP(r,Ab(e,s),t);if(a)return a}t.delete(n)}function ZE(n,e){let t=Ee(n),i=t.platform==="native";for(let[o,s]of Object.entries(Ee(t.installation_origins)))for(let[r,a]of Object.entries(Ee(s)))for(let[p,l]of a.entries()){let c=`/installation_origins/${o}/${r}/${p}`;try{if(i&&(r!=="app-runtime"||!mr(l)))return[le(c,"origin","native applications require canonical IPv4 loopback HTTP app-runtime origins")];let d=new URL(l),u=(vb(d,o==="lab")||i&&mr(l))&&d.origin===l,f=r==="mobile"&&d.protocol==="capacitor:"&&/^[a-z0-9.-]+$/u.test(d.hostname)&&`${d.protocol}//${d.host}`===l,h=r==="app-runtime"&&/^chrome-extension:\/\/[a-p]{32}$/u.test(l);if(!u&&!f&&!h||l.includes("*")||d.username||d.password||d.search||d.hash)return[le(c,"origin","must be an exact HTTPS, loopback HTTP, mobile capacitor or Chrome extension origin without wildcards")]}catch{return[le(c,"origin","must be an exact installation origin")]}}if(t.distribution==="portable"){if(t.project_url===void 0)return t.icon===void 0?[]:[le("/icon","origin","requires a project_url on the same origin")];try{let o=new URL(String(t.project_url));return o.protocol!=="https:"?[le("/project_url","protocol","must use HTTPS")]:t.icon!==void 0&&new URL(String(t.icon)).origin!==o.origin?[le("/icon","origin","must use the project_url origin")]:[]}catch{return[le("/","url","contains an invalid URL")]}}try{let o=new URL(String(t.homepage));if(i?!Sf(String(t.homepage)):!vb(o,e))return[le("/homepage","protocol",i?"native applications require canonical IPv4 loopback HTTP":"must use HTTPS (or loopback HTTP in local mode)")];for(let[s,r]of t.redirect_uris.entries()){if(String(r).includes("*"))return[le(`/redirect_uris/${s}`,"url","must be an exact URI without wildcards")];let a=new URL(String(r));if(i&&["http:","https:"].includes(a.protocol)&&!Sf(String(r)))return[le(`/redirect_uris/${s}`,"origin","native HTTP(S) redirects require canonical IPv4 loopback HTTP")];if(a.origin===o.origin&&!vb(a,e)&&!(i&&Sf(String(r))))return[le(`/redirect_uris/${s}`,"protocol","must use HTTPS (or loopback HTTP in local mode)")];let p=QE(a,String(t.id));if(a.origin!==o.origin&&!p)return[le(`/redirect_uris/${s}`,"origin","must use the homepage origin or a private-use scheme matching the application ID")]}return t.icon!==void 0&&new URL(String(t.icon)).origin!==o.origin?[le("/icon","origin","must use the homepage origin")]:[]}catch{return[le("/","url","contains an invalid URL")]}}function QE(n,e){let t=n.protocol.slice(0,-1);return hP(n)&&(t===e||t.startsWith(`${e}.`))}function eq(n){let e=Ee(n),t=Ee(e.requirements),i=Array.isArray(t.contracts)?t.contracts:[],o=new Set(i.map(p=>{let l=Ee(p);return`${l.id}@${l.version}`})),s=Ee(e.provisions),r=Array.isArray(s.type_packs)?s.type_packs:[],a=[];for(let[p,l]of r.entries()){let c=Ee(l),d=Array.isArray(c.provides)?c.provides:[];for(let u of d){let f=Ee(u);o.has(`${f.id}@${f.version}`)||a.push(le(`/provisions/type_packs/${p}/provides`,"contractRequirement","may only contain contracts required by the application"))}a.push(...tq(c,`/provisions/type_packs/${p}`))}return a}function tq(n,e=""){let t=Ee(n),i=Ee(t.manifest),o=Array.isArray(i.resources)?i.resources.map(Ee):[],s=Array.isArray(t.resources)?t.resources.map(Ee):[],r=new Map(s.map(p=>[String(p.source),p.document]));if(r.size!==s.length||new Set(o.map(p=>String(p.source))).size!==o.length||o.length!==s.length)return[le(`${e}/resources`,"resourceSet","must match manifest source paths exactly")];let a=[];for(let[p,l]of o.entries()){let c=`${e}/manifest/resources/${p}`,d=String(l.source),u=r.get(d);if(typeof u!="string"){a.push(le(`${e}/resources`,"resourceSet",`is missing manifest source ${d}`));continue}_P(u)!==l.digest&&a.push(le(`${c}/digest`,"digest","does not match the embedded document")),l.upgrade_from!==void 0&&a.push(...nq(l,u,`${c}/upgrade_from`))}return a}function nq(n,e,t){if(n.kind!=="type"||n.mode!=="seed")return[le(t,"seedUpgrade","is only allowed for seed types")];let i=yP(e),o=Array.isArray(n.upgrade_from),s=(o?n.upgrade_from:[n.upgrade_from]).map(Ee),r=new Set,a=[];for(let[p,l]of s.entries()){let c=o?`${t}/${p}`:t,d=String(l.document);l.digest!==_P(d)?a.push(le(`${c}/digest`,"digest","does not match the baseline document")):r.has(l.digest)?a.push(le(`${c}/digest`,"uniqueBaseline","duplicates another upgrade baseline")):l.digest===n.digest&&a.push(le(`${c}/digest`,"seedUpgrade","must not be the resource's own document")),r.add(l.digest);let u=yP(d);!i||!u||u.kind!==i.kind||u.name!==i.name?a.push(le(`${c}/document`,"seedUpgrade","must be a type document with the same kind and name as the resource")):l.version!==void 0&&u.version!==l.version&&a.push(le(`${c}/version`,"seedUpgrade","must equal the version the baseline document declares"))}return a}function yP(n){let e=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(n)?.[1];if(e===void 0)return;let t=ab(e,{uniqueKeys:!0});if(!(t.errors.length>0||!Pn(t.contents)))return{kind:t.get("kind"),name:t.get("name"),version:t.get("version")}}function _P(n){return`sha256:${ys(it(Wv(n)))}`}function iq(n){let e=Ee(n),t=Ee(e.requirements),i=Ee(e.provisions),o=Array.isArray(t.configuration)?t.configuration:[],s=Array.isArray(i.configuration)?i.configuration:[],r=[],a=new Map;for(let[c,d]of o.entries()){let u=Ee(d),f=String(u.id),h=String(u.path),m=gP(h,u.value);m&&r.push(le(`/requirements/configuration/${c}/path`,"configurationPointer",m)),a.has(f)?r.push(le(`/requirements/configuration/${c}/id`,"uniqueRequirement",`duplicates configuration requirement ${f}`)):a.set(f,{path:h,value:u.value,index:c})}let p=new Set,l=new Set;for(let[c,d]of s.entries()){let u=Ee(d),f=String(u.requirement),h=String(u.path),m=gP(h,u.value);m&&r.push(le(`/provisions/configuration/${c}/path`,"configurationPointer",m));let b=a.get(f);if(!b){r.push(le(`/provisions/configuration/${c}/requirement`,"configurationRequirement",`references unknown configuration requirement ${f}`));continue}p.has(f)&&r.push(le(`/provisions/configuration/${c}/requirement`,"uniqueProvision",`configuration requirement ${f} may have exactly one provision`)),p.add(f),h!==b.path&&r.push(le(`/provisions/configuration/${c}/path`,"configurationRequirement",`must equal /requirements/configuration/${b.index}/path`)),JSON.stringify(u.value)!==JSON.stringify(b.value)&&r.push(le(`/provisions/configuration/${c}/value`,"configurationRequirement",`must equal /requirements/configuration/${b.index}/value`));let w=`${h}\0${JSON.stringify(u.value)}`;l.has(w)&&r.push(le(`/provisions/configuration/${c}`,"uniqueContribution","duplicates another configuration path and value contribution")),l.add(w)}for(let[c,d]of a)p.has(c)||r.push(le(`/requirements/configuration/${d.index}`,"configurationProvision",`requires one provision linked by id ${c}`));return r}function gP(n,e){if(n===VS)return rq.includes(e)?void 0:"accepts only the record extensions md and base";if(!n.startsWith("/")||new TextEncoder().encode(n).byteLength>1024)return"must be a bounded RFC 6901 JSON pointer";let t=n.slice(1).split("/");if(t.length<2||t.length>16)return"must address a value below an x-* extension namespace";let i=[];for(let o of t){if(/~(?:[^01]|$)/u.test(o))return"contains an invalid RFC 6901 escape";let s=o.replaceAll("~1","/").replaceAll("~0","~");if(s.length===0||s==="-"||/^\d+$/u.test(s)||[...s].some(r=>/\p{Cc}/u.test(r)))return"contains a disallowed object-key segment";i.push(s)}return/^x-[a-z0-9][a-z0-9-]*$/u.test(i[0])?void 0:"must be inside a top-level x-* extension namespace"}function oq(n){let e=Ee(n),t=Ee(e.requirements),i=Ee(t.capabilities),o=[];t.access!=="full_collection"&&o.push(le("/requirements/access","collectionAccess","must explicitly request full_collection; legacy or omitted access is not widened"));let s=Array.isArray(i.required)?i.required.map(String):[],a=(Array.isArray(i.optional)?i.optional.map(String):[]).find(b=>s.includes(b));a&&o.push(le("/requirements/capabilities/optional","disjoint",`must not repeat required capability ${a}`));let p=Ee(t.files),l=Array.isArray(p.required)?p.required.map(String):[],d=(Array.isArray(p.optional)?p.optional.map(String):[]).find(b=>l.includes(b));d&&o.push(le("/requirements/files/optional","disjoint",`must not repeat required file action ${d}`));let u=Ee(t.people),f=Array.isArray(u.required)?u.required.map(String):[],m=(Array.isArray(u.optional)?u.optional.map(String):[]).find(b=>f.includes(b));return m&&o.push(le("/requirements/people/optional","disjoint",`must not repeat required people permission ${m}`)),o}function sq(n){let e=Ee(n),t=Ee(e.requirements),i=Ee(t.capabilities),o=[];if(t.access!=="full_collection"&&o.push(le("/requirements/access","collectionAccess","must explicitly request full_collection; legacy or omitted access is not widened")),Object.keys(i).length===0)return o;let s=Array.isArray(i.required)?i.required.map(String):[],r=Array.isArray(i.optional)?i.optional.map(String):[],a=r.find(h=>s.includes(h));a&&o.push(le("/requirements/capabilities/optional","disjoint",`must not repeat required capability ${a}`));let p=new Set([...s,...r]),l=Ee(e.provisions);p.has("definitions.type-pack.apply")&&t.access!=="full_collection"&&o.push(le("/requirements/access","typePackAccess","must be full_collection for definitions.type-pack.apply")),Array.isArray(l.type_packs)&&l.type_packs.length>0&&!s.includes("collection.setup.apply")&&o.push(le("/requirements/capabilities/required","collectionSetupCapability","must require collection.setup.apply when bundled type packs are declared"));let c=Array.isArray(l.configuration)&&l.configuration.length>0,d=c||Array.isArray(l.type_packs)&&l.type_packs.length>0;c&&!s.includes("collection.setup.apply")&&o.push(le("/requirements/capabilities/required","collectionSetupCapability","must require collection.setup.apply when configuration provisions are declared")),p.has("collection.setup.apply")&&(t.access!=="full_collection"&&o.push(le("/requirements/access","collectionSetupAccess","must be full_collection for collection.setup.apply")),d||o.push(le("/provisions","collectionSetupProvision","must declare a configuration provision or type pack for collection.setup.apply"))),p.has("notifications.background-delivery")&&!Array.isArray(Ee(e.notifications).criteria)&&o.push(le("/notifications/criteria","notificationCapability","must be declared for notifications.background-delivery"));let u=Ee(t.files),f=Array.isArray(u.actions)?new Set(u.actions.map(String)):new Set;for(let h of["list","read","add","replace","move","delete"]){let m=`files.${h}`;p.has(m)!==f.has(h)&&o.push(le("/requirements/capabilities","fileCapability",`${m} and requirements.files.actions.${h} must be declared together`))}return o}function aq(n,e=!1){let t=Ee(n);if(t.distribution==="portable")return n;let i={...t};for(let o of["homepage","icon"])typeof i[o]=="string"&&(i[o]=bP(i[o],e));return Array.isArray(i.redirect_uris)&&(i.redirect_uris=i.redirect_uris.map(o=>typeof o=="string"?bP(o,e):o)),i}function bP(n,e){try{let t=new URL(n);return t.protocol==="http:"&&(e?Sf(n):AP(t.hostname))&&(t.protocol="https:"),t.href}catch{return n}}function mr(n){if(typeof n!="string"||!/^http:\/\/127\.0\.0\.1(?::[1-9][0-9]{0,4})?$/.test(n))return!1;try{return new URL(n).origin===n}catch{return!1}}function Sf(n){let e=/^http:\/\/[^/?#]+/.exec(n)?.[0];return mr(e)}function vb(n,e){return n.protocol==="https:"||e&&n.protocol==="http:"&&AP(n.hostname)}function AP(n){return n==="localhost"||n==="127.0.0.1"||n==="[::1]"||n==="::1"}function Pf(n){return{valid:!1,issues:n}}function le(n,e,t,i={}){return{path:n,keyword:e,message:t,params:i}}function Ee(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:{}}var xf,_b,VE,KE,rq,Ia=I(()=>{Cr();gs();CS();FS();yf();jc();xf=524288,_b=class extends Error{issues;constructor(e){super(`Invalid application manifest: ${GE(e)}`),this.issues=e,this.name="AppManifestValidationError"}},VE=jS,KE=BS;rq=["md","base"]});function Xr(n){return!1}function Oa(n){return n==="lab"||n==="staging"||n==="production"}function Qt(n){return n==="lab"}function Ra(n){try{let e=new URL(n);return e.protocol==="http:"&&e.hostname==="127.0.0.1"&&Number(e.port)>0&&e.origin===n&&!e.username&&!e.password}catch{return!1}}var bt=I(()=>{"use strict";Zd()});function Cn(n){return n.protocol==="https:"||n.protocol==="http:"?n.origin:`${n.protocol}//${n.host}`}function kb(n,e=!1,t){if(typeof n!="string"||n.length>512)return null;let i;try{i=new URL(n)}catch{return null}if(i.username||i.password||i.search||i.hash||!["","/"].includes(i.pathname)||Cn(i)!==n)return null;switch(i.protocol){case"https:":return"web";case"http:":return t==="native"&&mr(n)?"native":e&&ot(n)?"web":null;case"capacitor:":return!i.port&&/^[a-z0-9.-]{1,253}$/.test(i.hostname)?"mobile":null;case"chrome-extension:":return/^[a-p]{32}$/.test(i.host)?"extension":null;case"moz-extension:":return lq.test(i.host)?"extension":null;default:return null}}function Rt(){let n=globalThis.location;if(!n)return null;if(typeof n.origin=="string"&&n.origin!=="null")return n.origin;try{return Cn(new URL(n.href))}catch{return null}}var lq,Lt,Jn=I(()=>{"use strict";Ia();bt();lq=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;Lt=(n,e=!1,t)=>kb(n,e,t)!==null});function SP(n,e){let t=kP.get(n);return(!t||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(e.id)||e.id==="00000000-0000-0000-0000-000000000000")&&jt(),e.supersededDeclaredId!==void 0&&e.supersededDeclaredId!==n.id&&jt(),yr({...n,id:e.id,name:e.name,storage:e.supersededDeclaredId===void 0?t:{...n.storage}})}function jt(){throw A("invalid_request","invalid application declaration","application_declaration")}function Sb(n,e=new Set,t=0,i={nodes:0,chars:0}){if((++i.nodes>524288||t>64)&&jt(),typeof n=="string")return i.chars+=n.length,i.chars>524288&&jt(),n;if(n===null||typeof n=="boolean")return n;if(typeof n=="number")return Number.isFinite(n)||jt(),n;(typeof n!="object"||e.has(n)||Object.getOwnPropertySymbols(n).length)&&jt(),e.add(n);try{if(Array.isArray(n))return(n.length>524288||Object.keys(n).length!==n.length)&&jt(),Object.freeze(Array.from({length:n.length},(s,r)=>{let a=Object.getOwnPropertyDescriptor(n,String(r));return(!a||!("value"in a))&&jt(),Sb(a.value,e,t+1,i)}));Object.getPrototypeOf(n)!==Object.prototype&&Object.getPrototypeOf(n)!==null&&jt();let o=Object.create(null);for(let s of Object.keys(n)){i.chars+=s.length;let r=Object.getOwnPropertyDescriptor(n,s);(i.chars>524288||!r||!("value"in r))&&jt(),o[s]=Sb(r.value,e,t+1,i)}return Object.freeze(o)}finally{e.delete(n)}}function Cf(n){return JSON.parse(JSON.stringify(n.manifest))}function yr(n){let e=Sb(n);(!e||Array.isArray(e)||Object.keys(e).some(m=>!["id","name","origin","environment","manifest","storage","installationKind"].includes(m)))&&jt();let{id:t,name:i,origin:o,environment:s,manifest:r}=e;(typeof t!="string"||!t||t.length>256||!/^[a-z0-9][a-z0-9._-]*$/.test(t)||t==="00000000-0000-0000-0000-000000000000"||typeof i!="string"||!i.trim()||new TextEncoder().encode(i).length>100||/[\u0000-\u001f\u007f]/.test(i)||typeof o!="string"||typeof s!="string"||!Oa(s)||!r||Array.isArray(r)||typeof r!="object")&&jt(),Xr(s)&&!Ra(o)&&jt();let a=kb(o,Qt(s),r.platform==="native"?"native":void 0),p=e.installationKind??(a==="mobile"?"mobile":"app-runtime");(a===null||p!=="app-runtime"&&p!=="mobile"||a==="mobile"&&p!=="mobile"||(a==="extension"||a==="native")&&p!=="app-runtime")&&jt();let l=e.storage;l!==void 0&&(!l||Array.isArray(l)||typeof l!="object"||Object.keys(l).some(m=>!["joinDatabaseName","setupDatabaseName","applicationNamespace"].includes(m)))&&jt();let c=l,d=c?.applicationNamespace??t,u=typeof d=="string"&&d!==t?`namespace.${cg(JSON.stringify([t,d]))}`:t,f={joinDatabaseName:c?.joinDatabaseName??`mdbase.${u}.native-collection-join.v1`,setupDatabaseName:c?.setupDatabaseName??`mdbase.${u}.native-model-setup.v1`,applicationNamespace:d};for(let m of Object.values(f))(typeof m!="string"||!m||m.length>256||/[\u0000-\u001f\u007f]/.test(m))&&jt();f.joinDatabaseName===f.setupDatabaseName&&jt();let h=Object.freeze({id:t,name:i,origin:o,environment:s,installationKind:p,manifest:r,storage:Object.freeze(f)});return kP.set(h,Object.freeze({...c})),h}var kP,Ea=I(()=>{"use strict";vu();Jn();ie();bt();kP=new WeakMap});function Uc(n){if(n!==null&&typeof n=="object"){for(let e of Object.values(n))Uc(e);Object.freeze(n)}return n}function Zr(n){let e=Nc(Cf(n),{allowLocal:Qt(n.environment)}),t=Uc(e.manifest),i=t.requirements,o=fr(i),s=Uc(hb(t,{})),r=mb(i),a=Uc(oP(s,r,void 0,o)),p=i.capabilities,l=p?.contract_version===2?Object.freeze({capabilityContractVersion:2,requiredNativeCapabilities:Object.freeze([...p.required])}):null;return Object.freeze({contractVersion:e.contractVersion,manifest:t,semanticVersion:o,operations:s,...r?{files:Uc(r)}:{},contracts:a,nativeCapabilities:l})}var If=I(()=>{"use strict";jc();Ia();Ea();bt()});function xP(n,e){if(typeof n!="string"||!n.length)throw Dc();let t=new URL(n),i=e&&ot(n);if(t.origin!==n||t.username||t.password||t.protocol!=="https:"&&!i)throw Dc();return n}function Xn(n){let{environment:e,release:t}=n;if(!Oa(e)||!t||t.schema!=="mdbn-app-trust/release/1"||t.environment!==e||!/^[0-9a-f]{64}$/.test(t.assetSha256)||!t.source||t.source.repository!=="mdbase-dev/mdbase-connect"||!/^[0-9a-f]{40}$/.test(t.source.commit)||!/^[A-Za-z0-9.+-]{1,64}$/.test(t.source.version)||!Array.isArray(t.trustedRoots)||!t.trustedRoots.length||t.trustedRoots.length>64||t.trustedRoots.some(p=>!(p instanceof Uint8Array)||p.length!==32||p.every(l=>l===0))||!(t.policyPins instanceof Uint8Array)||!t.policyPins.length||t.policyPins.length>65536)throw Dc();let i=Xr(e),o=xP(t.cpOrigin,i),s=xP(t.logOrigin,i),r=n.appOrigin;if(i&&![o,s,r].every(Ra)||!Lt(r,Qt(e),n.platform))throw Dc();let a=Object.freeze({environment:e,appOrigin:r,cpOrigin:o,logOrigin:s,assetSha256:t.assetSha256,allowLoopbackHttp:Qt(e)&&new URL(r).protocol==="http:",allowNativeLoopbackHttp:n.platform==="native"&&Lt(r,!1,"native")&&new URL(r).protocol==="http:"});return CP.add(a),a}function IP(n){return!!n&&typeof n=="object"&&CP.has(n)}var CP,Dc,Qr=I(()=>{"use strict";Jn();bt();CP=new WeakSet,Dc=()=>new Error("app environment: explicit authenticated build context required")});function zo(){return Object.freeze({...Pb,trustedRoots:Object.freeze(pq.map(OP)),policyPins:OP(dq)})}var Pb,pq,dq,OP,Of=I(()=>{Pb={schema:"mdbn-app-trust/release/1",environment:"production",cpOrigin:"https://connect.mdbase.dev",logOrigin:"https://log.mdbase.dev",assetSha256:"7912e40838213e60b65848350d319a48019021317b112e3326429b250f0133d7",source:{commit:"36abd4b065be9495a7f5ae0808865a1f2279af04",repository:"mdbase-dev/mdbase-connect",version:"0.1.0-beta.141"}};Object.freeze(Pb.source);Object.freeze(Pb);pq=Object.freeze(["d9f6e481aa47ae9e0373c8994fe6edb3131d8ac3cf3cbc1be58672a8543c932d"]),dq="8281825070a2bd532b5544dfb77617d4040ca6a25820d9f6e481aa47ae9e0373c8994fe6edb3131d8ac3cf3cbc1be58672a8543c932d818350c580fb092af10eb030605bd6e478e6f158206b587b1b32ba84b3d630868fe8e5396339f0c0ed2c59324a67824c1a2028040c5070a2bd532b5544dfb77617d4040ca6a2",OP=n=>{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 Cb(n){if(!n||typeof n!="object"||Array.isArray(n))throw gr();return n}function Ib(n){return n===null||typeof n=="string"||typeof n=="boolean"||typeof n=="number"?JSON.stringify(n):Array.isArray(n)?`[${n.map(Ib).join(",")}]`:`{${Object.entries(n).filter(([,t])=>t!==void 0).sort(([t],[i])=>t<i?-1:t>i?1:0).map(([t,i])=>`${JSON.stringify(t)}:${Ib(i)}`).join(",")}}`}async function Ef(n){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Ib(n))));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function fq(n,e){let t=[[n,e]],i=0;for(;t.length;){if(++i>524288)return!1;let[o,s]=t.pop();if(o===s)continue;if(!o||!s||typeof o!="object"||typeof s!="object"||Array.isArray(o)!==Array.isArray(s))return!1;let r=Object.keys(o);if(r.length!==Object.keys(s).length)return!1;for(let a of r){if(!Object.hasOwn(s,a))return!1;t.push([o[a],s[a]])}}return!0}async function qf(n){let e=n.declaration,t=n.signal,i=n.isCurrent,o=n.fetch??globalThis.fetch,s=e.manifest,r=yr(e);function a(){try{if(!t.aborted&&n.signal===t&&n.declaration===e&&n.isCurrent===i&&e.id===r.id&&e.name===r.name&&e.origin===r.origin&&e.environment===r.environment&&e.manifest===s&&i.call(n)===!0&&!t.aborted)return}catch{}throw A("cancelled","Application registration fenced","application_registration_fenced")}a();let p,l;try{p=Xn({environment:r.environment,appOrigin:r.origin,platform:r.manifest.platform==="native"?"native":void 0,release:zo()})}catch{throw a(),A("unavailable","SDK registration environment unavailable","application_registration_unavailable")}try{l=Nc(Cf(r),{allowLocal:Qt(r.environment)}).manifest}catch{throw $c()}let c=r.environment==="local"?[]:l.installation_origins?.[r.environment]?.[r.installationKind]??[];if(l.name!==r.name||l.distribution==="portable"||new URL(l.homepage).origin!==r.origin&&!c.includes(r.origin)&&!("platform"in l&&l.platform==="native"&&r.installationKind==="app-runtime"&&mr(r.origin)))throw $c();let d=JSON.stringify({manifest:l}),u=`${p.cpOrigin}/v1/apps/register`,f=`mdbase.app.registration.v1.${encodeURIComponent(p.cpOrigin)}.${encodeURIComponent(l.id)}`,h=()=>{try{return globalThis.localStorage??null}catch{return null}},m=h()?await Ef(l).catch(()=>null):null;a();let b=x=>{if(m)try{h()?.setItem(f,JSON.stringify({v:1,digest:m,declaredId:r.id,...x}))}catch{}};{let x=null;try{let P=h()?.getItem(f);x=P?Cb(JSON.parse(P)):null}catch{x=null}if(x&&m&&x.v===1&&x.digest===m&&x.declaredId===r.id&&typeof x.id=="string"&&xb.test(x.id)&&x.id!==EP&&x.name===l.name&&typeof x.manifestDigest=="string"&&/^[0-9a-f]{64}$/.test(x.manifestDigest)&&(x.supersededDeclaredId===void 0||x.supersededDeclaredId===r.id))return Object.freeze({id:x.id,name:l.name,manifestDigest:x.manifestDigest,...x.supersededDeclaredId!==void 0?{supersededDeclaredId:r.id}:{}})}if(new TextEncoder().encode(d).length>xf+32||typeof o!="function")throw $c();let w=new AbortController,g=()=>w.abort(),y=setTimeout(g,15e3);y.unref?.(),t.addEventListener("abort",g,{once:!0});function v(){if(a(),w.signal.aborted)throw Rf()}async function _(x){let P=x.headers.get("content-length");if(!x.body||P!==null&&(!/^(0|[1-9][0-9]*)$/.test(P)||Number(P)>8192))return x.body?.cancel().catch(()=>{}),null;let C=x.body.getReader(),E=new Uint8Array(8192),O=0;try{for(;;){let L=await C.read();if(v(),L.done)break;if(O+L.value.length>E.length)return null;E.set(L.value,O),O+=L.value.length}return Mo(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(E.subarray(0,O))))}catch(L){if(L instanceof se)throw L;return null}finally{C.cancel().catch(()=>{})}}async function k(x){let P=new Uint8Array(2*xf+8192),C=0,E=x.headers.get("content-length");if(E!==null&&/^(0|[1-9][0-9]*)$/.test(E)&&Number(E)>P.length)throw x.body?.cancel().catch(()=>{}),gr();if(!x.body)throw gr();let O=x.body.getReader();try{for(;;){let L=await O.read();try{if(v(),L.done)break;if(C+L.value.length>P.length)throw gr();P.set(L.value,C),C+=L.value.length}finally{L.value?.fill(0)}}try{return Cb(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(P.subarray(0,C))))}catch{throw gr()}}finally{P.fill(0),O.cancel().catch(()=>{}),O.releaseLock()}}async function S(x){let P=Cb(x.application),C=P.id,E=P.manifest_digest;if(typeof C!="string"||!xb.test(C)||C===EP)throw gr();let O=xb.test(r.id)&&C!==r.id,L=O?$c:gr;if(O&&E!==await Ef(l).catch(()=>null))throw $c();if(v(),typeof E!="string"||!/^[0-9a-f]{64}$/.test(E)||P.name!==l.name||P.canonical_identity!==`bundle:${l.id}:sha256:${E}`||P.family_identity!==`bundle:${l.id}`||P.distribution!=="web")throw L();if(!P.application_declaration)throw A("upgrade_required","Canonical registration evidence unavailable","application_registration_unsupported");let z;try{z=Nc(P.application_declaration,{allowLocal:Qt(r.environment)}).manifest}catch{throw gr()}if(!fq(l,z))throw L();return v(),Object.freeze({id:C,name:l.name,manifestDigest:E,...O?{supersededDeclaredId:r.id}:{}})}try{for(let x=0;x<3;x++){v();let P;try{if(P=await o(u,{method:"POST",headers:{"content-type":"application/json"},body:d,signal:w.signal,credentials:"omit",redirect:"error",cache:"default",referrerPolicy:"no-referrer"}),v(),P.redirected||P.url&&P.url!==u)throw gr();if(!P.ok){if(uq.has(P.status))throw await P.body?.cancel().catch(()=>{}),Rf();let E=await _(P);throw A("forbidden","Application registration refused",E?{reason:"application_registration_refused",details:new Map([["code",E.code],["paths",[...E.paths]]])}:"application_registration_refused")}let C=await S(await k(P));return b(C),C}catch(C){if(P?.body?.cancel().catch(()=>{}),v(),C instanceof se&&C.reason!=="application_registration_unknown")throw C;if(x===2)throw Rf();await new Promise((E,O)=>{let L=()=>{clearTimeout(z),w.signal.removeEventListener("abort",L);try{v(),E()}catch(Q){O(Q)}},z=setTimeout(L,x===0?250:1e3);z.unref?.(),w.signal.addEventListener("abort",L,{once:!0}),w.signal.aborted&&L()})}}throw Rf()}finally{clearTimeout(y),t.removeEventListener("abort",g),w.abort()}}var xb,EP,uq,$c,gr,Rf,Tf=I(()=>{"use strict";Ia();Ia();Qr();ie();Ea();Of();bt();cu();xb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,EP="00000000-0000-0000-0000-000000000000",uq=new Set([408,429,500,502,503,504]),$c=()=>A("invalid_request","Application registration binding mismatch","application_registration_binding"),gr=()=>A("unavailable","Application registration evidence invalid","application_registration_response"),Rf=()=>A("outcome_unknown","Original application registration outcome unknown","application_registration_unknown")});function NP(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null}function UP(n,e,t){if(!/^[A-Za-z0-9_-]+$/.test(n))return!1;try{let i=atob(n.replaceAll("-","+").replaceAll("_","/"));return i.length===e&&(t===void 0||i.charCodeAt(0)===t)&&btoa(i).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")===n}catch{return!1}}function Nf(n,e){let t=NP(n),i=NP(t?.native_completion);if(!i||!Object.hasOwn(i,"version")||i.version!==1||Object.keys(i).length!==jP.length+1||jP.some(r=>!Object.hasOwn(i,r)||typeof i[r]!="string"))throw Ta();let o=i;for(let r of["account_id","authorization_request_id","application_id","application_installation_id","collection_id","grant_id"])if(!wq.test(o[r]))throw Ta();if(!o.application_declaration_id||!/^[0-9a-f]{64}$/.test(o.application_manifest_digest)||!UP(o.grant_signing_public_key,65,4)||!UP(o.client_noise_public_key,32))throw Ta();try{if(new URL(o.application_origin).origin!==o.application_origin)throw Ta()}catch{throw Ta()}let s={account_id:e.accountId,authorization_request_id:e.authorizationRequestId,application_id:e.applicationId,application_declaration_id:e.declarationId,application_manifest_digest:e.manifestDigest,application_installation_id:e.applicationInstallationId,application_origin:e.applicationOrigin,collection_id:e.collectionId,grant_signing_public_key:e.grantSigningPublicKey,client_noise_public_key:e.clientNoisePublicKey};if(Object.entries(s).some(([r,a])=>o[r]!==a)||e.grantId!==void 0&&o.grant_id!==e.grantId||t.collection_id!==o.collection_id||t.grant_id!==o.grant_id||t.application_origin!==o.application_origin)throw Ta();return Object.freeze({...o})}var jP,wq,Ta,Ob=I(()=>{"use strict";ie();jP=["account_id","authorization_request_id","application_id","application_declaration_id","application_manifest_digest","application_installation_id","application_origin","collection_id","grant_id","grant_signing_public_key","client_noise_public_key"],wq=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,Ta=()=>A("unauthenticated","native completion does not match the original approved preparation")});function Rb(n,e,t,i,o,s){return Nf({native_completion:n,collection_id:e.collectionId,grant_id:n?.grant_id,application_origin:o},{accountId:t,authorizationRequestId:e.authorizationRequestId,applicationId:i,applicationOrigin:o,collectionId:e.collectionId,manifestDigest:s,declarationId:n?.application_declaration_id,applicationInstallationId:n?.application_installation_id,grantSigningPublicKey:n?.grant_signing_public_key,clientNoisePublicKey:n?.client_noise_public_key})}var DP=I(()=>{"use strict";Ob()});function br(n){let e=()=>new TypeError("invalid collection display name");if(typeof n!="string"||/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(n))throw e();for(let i=0;i<n.length;i++){let o=n.charCodeAt(i);if(o>=55296&&o<=56319){let s=n.charCodeAt(++i);if(!(s>=56320&&s<=57343))throw e()}else if(o>=56320&&o<=57343)throw e()}let t=n.trim();if(!t.length||t.length>200)throw e();return t}var Fc=I(()=>{"use strict"});function Uf(n){let e=[n.account,n.installation,n.collection];if(e.some(t=>typeof t!="string"||!$P.test(t)))throw new We("invalid_scope");return`mdbase-app-${e.map(t=>t.toLowerCase()).join("-")}`}function Eb(n){let e=[n.account,n.installation];if(e.some(t=>typeof t!="string"||!$P.test(t)))throw new We("invalid_scope");return`mdbase-app-installation-${e.map(t=>t.toLowerCase()).join("-")}`}function Kc(n,e,t){return Vc(n,Uf(e),t)}function Wc(n,e,t){return Vc(n,Eb(e),t)}function Hc(n){return typeof n=="string"&&n.length>0&&n.length<=64&&!/[^A-Za-z0-9_-]/.test(n)}function Fo(n){return typeof n=="string"&&n.length>0&&n.length<=256&&!/[\u0000-\u001f\u007f]/.test(n)}function zP(n){let e=BP({cpOrigin:n.cpOrigin,appId:n.appId});if(n.storageNamespace===void 0)return e;if(!Fo(n.storageNamespace))throw new We("invalid_scope");return`mdbase-app-sign-in-namespace-v1-${JSON.stringify([n.cpOrigin,n.appId,n.storageNamespace])}`}function BP(n){let e=new URL(n.cpOrigin);if(e.origin!==n.cpOrigin||e.username||e.password||!["https:","http:"].includes(e.protocol)||!Hc(n.appId))throw new We("invalid_scope");if(n.owner===void 0)return`mdbase-app-sign-in-v1-${n.appId}-${n.cpOrigin}`;if(!Fo(n.owner))throw new We("invalid_scope");return`mdbase-app-sign-in-v2-${JSON.stringify([n.cpOrigin,n.owner,n.appId])}`}function FP(n,e,t){if(e.storageNamespace!==void 0&&(!Fo(e.owner)||e.owner.startsWith("bundle:")))throw new We("invalid_scope");let i=BP(e),o=zP(e);return e.owner===void 0?Vc(n,o,t):(async()=>{let s=await Vc(n,o,t);try{let r=await Vc(n,i,t);return{release:async()=>{await r.release(),await s.release()}}}catch(r){throw await s.release(),r}})()}function VP(n,e,t){try{return n.request(zP(e),{mode:"shared",signal:t},async()=>{})}catch(i){return Promise.reject(i)}}function Vc(n,e,t){if(!n)return Promise.reject(new We("unavailable"));if(t?.aborted)return Promise.reject(new We("aborted"));let i,o=new Promise(d=>{i=d}),s,r,a=new Promise((d,u)=>{s=d,r=u}),p=!1,l=()=>{p=!0,r(new We("aborted"))};t?.addEventListener("abort",l,{once:!0});let c=Promise.resolve().then(()=>n.request(e,{mode:"exclusive",ifAvailable:!0},async d=>{if(t?.removeEventListener("abort",l),p||t?.aborted){r(new We("aborted"));return}if(!d){r(new We("busy"));return}s({release:()=>(i(),c)}),await o}));return c.catch(()=>{t?.removeEventListener("abort",l),r(new We("unavailable"))}),a}async function KP(n){let e=n.closeTimeoutMs??5e3;if(!Number.isSafeInteger(e)||e<1||e>3e4)throw new RangeError("invalid Worker close timeout");let t=n.signal,i=Object.freeze({account:n.scope.account,installation:n.scope.installation,collection:n.scope.collection});Uf(i);let o=await Wc(n.locks,i,t),s;try{s=await Kc(n.locks,i,t)}catch(h){throw await o.release(),h}let r={release:async()=>{await s.release(),await o.release()}},a;try{if(t?.aborted)throw new We("aborted");a=n.create(i)}catch{throw await r.release(),new We(t?.aborted?"aborted":"initialization_failed")}let p,l=Object.freeze({scope:Object.freeze({account:i.account,installation:i.installation}),isCurrent:()=>!p&&!t?.aborted}),c,d=new Promise((h,m)=>{c=()=>m(new We("aborted"))}),u=()=>p??=(async()=>{t?.removeEventListener("abort",f);let h;try{await Promise.race([Promise.resolve().then(()=>a.stop()),new Promise(m=>{h=setTimeout(m,e)})])}catch{}finally{h&&clearTimeout(h)}try{a.terminate()}catch{throw new We("shutdown_failed")}await r.release()})(),f=()=>{c(),u().catch(()=>{})};t?.addEventListener("abort",f,{once:!0});try{if(t?.aborted)throw new We("aborted");if(await Promise.race([Promise.resolve().then(()=>n.initialize(a,t,i,l)),d]),t?.aborted||p)throw new We("aborted");return{worker:a,scope:i,close:u}}catch{throw await u(),new We(t?.aborted?"aborted":"initialization_failed")}}var We,$P,eo=I(()=>{"use strict";We=class extends Error{constructor(t){super(`app replica owner: ${t}`);this.reason=t;this.name="AppReplicaOwnerError"}reason},$P=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i});function GP(n){if(typeof CryptoKey!="function"||!(n instanceof CryptoKey)||n.type!=="secret"||n.extractable||n.algorithm.name!=="AES-GCM"||n.algorithm.length!==256||n.usages.length!==2||!n.usages.includes("encrypt")||!n.usages.includes("decrypt"))throw Ye();return n}function WP(n){if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!=="encrypted,key,revision,version")throw Ye();let e=n;if(e.version!==1||!Number.isSafeInteger(e.revision)||e.revision<0||!(e.encrypted instanceof Uint8Array)||e.encrypted.length<29||e.encrypted.length>HP+28)throw Ye();return{version:1,revision:e.revision,key:GP(e.key),encrypted:new Uint8Array(e.encrypted)}}var Ma,Df,HP,Gc,Ye,vq,$f,YP=I(()=>{"use strict";bt();Jn();eo();Ma="installation-sign-in",Df="original",HP=128*1024,Gc=class extends Error{constructor(t){super(`app installation storage ${t}; preserve storage and reopen`);this.reason=t}reason},Ye=(n="unavailable")=>new Gc(n),vq=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]);$f=class n{constructor(e,t){this.options=e;this.lease=t;this.namespace=JSON.stringify(e.owner===void 0?["mdbase.app-installation.v1",e.origin,e.cpOrigin,e.appId]:["mdbase.app-installation.v2",e.origin,e.cpOrigin,e.owner,e.appId])}options;lease;db=null;record=null;closing=!1;closeResult=null;namespace;static async open(e,t){let i=Object.freeze({origin:e.origin,cpOrigin:e.cpOrigin,appId:e.appId,...e.owner===void 0?{}:{owner:e.owner},...e.storageNamespace===void 0?{}:{storageNamespace:e.storageNamespace},mode:e.mode,signal:e.signal,locks:e.locks,allowLoopbackHttp:e.allowLoopbackHttp===!0,allowNativeLoopbackHttp:e.allowNativeLoopbackHttp===!0}),o=null,s=null,r=null;try{if(!Lt(i.origin,i.allowLoopbackHttp===!0,i.allowNativeLoopbackHttp?"native":void 0))throw Ye();{let l=i.cpOrigin,c=new URL(l),d=i.allowLoopbackHttp&&ot(l);if(c.origin!==l||c.username||c.password||c.protocol!=="https:"&&!d)throw Ye()}if(i.owner!==void 0&&!Fo(i.owner)||!["fresh","existing","open"].includes(i.mode)||!Hc(i.appId)||i.signal.aborted||Rt()!==i.origin||!globalThis.indexedDB||!globalThis.crypto?.subtle||typeof CryptoKey!="function")throw Ye();let a=await FP(i.locks,i,i.signal);if(o=new n(i,a),o.check(),i.mode!=="existing"){s=t(),o.check(),o.bound(s);let l=GP(await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]));o.check(),r={version:1,revision:0,key:l,encrypted:await o.encrypt(l,0,s)},s.fill(0),s=null}o.db=await o.openDatabase(r),o.check(),o.db.onversionchange=()=>{o.close()},o.record=await o.readRecord(),o.check(),s=await o.decrypt(o.record),o.check(),o.bound(s);let p={store:o,plaintext:s};return s=null,p}catch(a){throw await o?.close(),Ye(a instanceof We&&a.reason==="busy"?"busy":"unavailable")}finally{s?.fill(0),r?.encrypted.fill(0)}}isCurrent(){try{return this.check(),!0}catch{return!1}}check(){if(this.closing||this.options.signal.aborted||Rt()!==this.options.origin)throw Ye()}bound(e){if(!(e instanceof Uint8Array)||!e.length||e.length>HP)throw Ye()}aad(e){return new TextEncoder().encode(`${this.namespace}:${e}`)}async encrypt(e,t,i){this.check(),this.bound(i);let o=crypto.getRandomValues(new Uint8Array(12)),s=this.aad(t),r=new Uint8Array(i),a=null;try{a=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:o,additionalData:s},e,r)),this.check();let p=new Uint8Array(12+a.length);return p.set(o),p.set(a,12),p}finally{r.fill(0),a?.fill(0),o.fill(0),s.fill(0)}}async decrypt(e){this.check();let t=this.aad(e.revision),i=new Uint8Array(e.encrypted.subarray(0,12)),o=new Uint8Array(e.encrypted.subarray(12));try{let s=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:i,additionalData:t},e.key,o));try{return this.check(),this.bound(s),s}catch{throw s.fill(0),Ye()}}finally{i.fill(0),o.fill(0),t.fill(0)}}openDatabase(e){return new Promise((t,i)=>{this.check();let o=this.options,s=o.owner===void 0?`mdbase.app.installation.v1.${encodeURIComponent(o.cpOrigin)}.${o.appId}`:`mdbase.app.installation.v2.${encodeURIComponent(o.cpOrigin)}.${encodeURIComponent(o.owner)}.${o.appId}`,r=indexedDB.open(s,1),a=!1,p=!1,l=()=>{a=!0;try{r.transaction?.abort()}catch{}i(Ye())},c=()=>this.options.signal.removeEventListener("abort",l);this.options.signal.addEventListener("abort",l,{once:!0}),r.onblocked=l,r.onupgradeneeded=()=>{try{if(this.check(),a||!e||r.result.objectStoreNames.length)throw Ye();r.result.createObjectStore(Ma).add(e,Df),p=!0}catch{r.transaction?.abort()}},r.onerror=()=>{c(),i(Ye())},r.onsuccess=()=>{c();try{if(this.check(),a||this.options.mode==="fresh"&&!p||r.result.objectStoreNames.length!==1||!r.result.objectStoreNames.contains(Ma))throw Ye();t(r.result)}catch{r.result.close(),i(Ye())}}})}readRecord(){return new Promise((e,t)=>{if(this.check(),!this.db)throw Ye();let i=this.db.transaction(Ma,"readonly",{durability:"strict"}),o=null,s=()=>{try{i.abort()}catch{}},r=()=>this.options.signal.removeEventListener("abort",s);this.options.signal.addEventListener("abort",s,{once:!0}),i.onerror=i.onabort=()=>{r(),o?.encrypted.fill(0),t(Ye())},i.oncomplete=()=>{r();try{if(this.check(),!o)throw Ye();e(o)}catch{o?.encrypted.fill(0),t(Ye())}};let a=i.objectStore(Ma).get(Df);a.onsuccess=()=>{try{this.check(),o=WP(a.result)}catch{s()}}})}async commit(e){let t=null;try{if(this.check(),!this.record||this.record.revision>=Number.MAX_SAFE_INTEGER)throw Ye();let i=this.record;t={version:1,revision:i.revision+1,key:i.key,encrypted:await this.encrypt(i.key,i.revision+1,e)},this.check(),await new Promise((o,s)=>{if(this.check(),!this.db)throw Ye();let r=this.db.transaction(Ma,"readwrite",{durability:"strict"}),a=()=>{try{r.abort()}catch{}},p=()=>this.options.signal.removeEventListener("abort",a);this.options.signal.addEventListener("abort",a,{once:!0}),r.onerror=r.onabort=()=>{p(),s(Ye())},r.oncomplete=()=>{p();try{this.check(),o()}catch{s(Ye())}};let l=r.objectStore(Ma),c=l.get(Df);c.onsuccess=()=>{let d=null;try{if(this.check(),d=WP(c.result),d.revision!==i.revision||!vq(d.encrypted,i.encrypted))throw Ye();l.put(t,Df)}catch{a()}finally{d?.encrypted.fill(0)}}}),this.check(),i.encrypted.fill(0),this.record=t,t=null}catch{throw await this.close(),Ye()}finally{t?.encrypted.fill(0)}}close(){return this.closeResult??=(async()=>{this.closing=!0,this.db?.close(),this.db=null,this.record?.encrypted.fill(0),this.record=null,await this.lease.release()})()}}});function _e(n){if(typeof n!="string"||!_q.test(n)||U(n).every(e=>e===0))throw q("response");return n}function Kt(n,e){if(typeof n!="string"||!e.test(n))throw q("response");return n}function Ce(n,e){if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!==e.split(",").sort().join())throw q("response");return n}function Aq(n){if(typeof n!="string"||n.length>320||!/^[^\s@\u0000-\u001f\u007f]+@[^\s@\u0000-\u001f\u007f]+$/.test(n))throw q("response");return n}function La(n,e=!1){let[t,i,o,s]=e?["accountEmail","portalConfirmed","accountProvider","accountLogin"]:["account_email","account_selection_confirmed","account_provider","account_login"];return[t,i,o,s].some(r=>Object.hasOwn(n,r))?`,${t},${i}${Object.hasOwn(n,o)||Object.hasOwn(n,s)?`,${o},${s}`:""}`:""}function zf(n,e=!1){let t=La(n,e);if(!t)return{};let i=e?n.accountEmail:n.account_email,o=e?n.portalConfirmed:n.account_selection_confirmed,s=e?n.accountProvider:n.account_provider,r=e?n.accountLogin:n.account_login;if(o!==!0)throw q("response");if(t.includes(e?"accountProvider":"account_provider")){if(i!==null||s!=="github"||typeof r!="string"||!r.length||new TextEncoder().encode(r).byteLength>100||/[\s\u0000-\u001f\u007f]/.test(r))throw q("response");return{accountEmail:null,portalConfirmed:!0,accountProvider:"github",accountLogin:r}}return{accountEmail:Aq(i),portalConfirmed:!0}}function JP(n,e){if(n.portalConfirmed&&(e.portalConfirmed!==!0||n.accountEmail!==e.accountEmail||n.accountProvider!==e.accountProvider||n.accountLogin!==e.accountLogin))throw q("binding")}function jb(n){return Object.hasOwn(n,"timer_consent")||Object.hasOwn(n,"timer_grants")?",timer_consent,timer_grants":""}function Tb(n,e,t,i,o){if(!jb(n))return;if(![!0,!1,null].includes(n.timer_consent)||!Array.isArray(n.timer_grants)||n.timer_grants.length>1e3)throw q("response");let s=n.timer_grants.map(r=>{let a=Ce(r,"grant_id,collection_id,declaration_digest"),p=_e(a.collection_id);if(!t.includes(p))throw q("response");return Object.freeze({grantId:_e(a.grant_id),collectionId:p,declarationDigest:Kt(a.declaration_digest,/^[0-9a-f]{64}$/)})});if(new Set(s.map(r=>r.grantId)).size!==s.length||new Set(s.map(r=>r.collectionId)).size!==s.length||(n.timer_consent===!0?!i||!o||!s.some(r=>r.collectionId===o):s.length!==0)||new Set(s.map(r=>r.declarationDigest)).size>1)throw q("response");return n.timer_consent===null?void 0:Object.freeze({requestId:e,approved:n.timer_consent===!0,grants:Object.freeze(s.filter(r=>r.collectionId===o))})}function Mb(n){let e=Ce(n,"grantId,kind,targetDigest,channelId,pending");if(!["web_push","fcm"].includes(e.kind)||![null,"register","delete"].includes(e.pending)||e.channelId===null&&e.pending!=="register")throw q("response");return Object.freeze({grantId:_e(e.grantId),kind:e.kind,targetDigest:Kt(e.targetDigest,/^[0-9a-f]{64}$/),channelId:e.channelId===null?null:_e(e.channelId),pending:e.pending})}function Lb(n){if(!Array.isArray(n)||n.length>1e3)throw q("response");let e=new Set;return Object.freeze(n.map(t=>{let i=p=>t&&typeof t=="object"&&p in t?`,${p}`:"",o=Ce(t,`collection_id,display_name,role${i("availability")}${i("file_actions")}`),s=_e(o.collection_id);if(e.has(s)||typeof o.display_name!="string"||!o.display_name.length||o.display_name.length>1024||o.role!=="owner"&&o.role!=="editor"&&o.role!=="viewer")throw q("response");let r=zn(o.availability),a="file_actions"in o?Nb(o.file_actions):null;return e.add(s),Object.freeze({collectionId:s,displayName:o.display_name,role:o.role,...r?{availability:r}:{},...a?{fileActions:a}:{}})}))}function Nb(n,e=Bf,t=!0){if(!Array.isArray(n)||n.length>Bf.length||!t&&!n.length||new Set(n).size!==n.length||n.some(i=>!e.includes(i)))throw q("response");return Object.freeze(Bf.filter(i=>n.includes(i)))}function XP(n){let e=n.collectionHint??null;if(e!==null&&(typeof e!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(e)||e==="00000000-0000-0000-0000-000000000000"))throw q("binding");return e}function ZP(n,e,t){return n===e||t!==null&&n===`${e}?collection_hint=${t}`?n:null}var Xe,q,qb,In,_q,Bf,ja,Yc=I(()=>{"use strict";DP();Lr();ge();bt();Fc();Qr();YP();eo();Fn();Xe=class extends Error{constructor(t,i){super(`app installation sign-in: ${t}`);this.reason=t;this.server=i;this.name="AppInstallationSignInError"}reason;server},q=n=>new Xe(n),qb=new WeakSet,In=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),_q=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;Bf=["list","read","add","replace","move","delete"];ja=class n{constructor(e,t,i){this.store=e;this.state=t;this.options=i;this.request=i.fetch??((o,s)=>globalThis.fetch(o,s)),this.parent=i.signal,this.parent.addEventListener("abort",this.onAbort,{once:!0}),this.check()}store;state;options;closed=!1;busy=!1;nativeAcknowledged=!1;expiredRequestId=null;wrongAccountRequestId=null;lifetime=new AbortController;request;parent;onAbort=()=>{this.close()};static async open(e){let t=Object.freeze({...e,...e.recoveryFor?{recoveryFor:Object.freeze({...e.recoveryFor})}:{}}),i=null;try{if(!["lab","staging","production"].includes(t.environment)||!Hc(t.appId)||typeof t.appName!="string"||!t.appName.length||t.appName.length>100||t.appName.trim()!==t.appName||t.installationKind!==void 0&&t.installationKind!=="app-runtime"&&t.installationKind!=="mobile")throw q("binding");let o=t.environmentSelection;if(t.requestedCreateCollections!==void 0&&typeof t.requestedCreateCollections!="boolean"||t.freshRequestedCreateCollections!==void 0&&typeof t.freshRequestedCreateCollections!="boolean")throw q("binding");if(t.recoveryFor!==void 0){let r=Ce(t.recoveryFor,"accountId,collectionId");if(_e(r.accountId),_e(r.collectionId),!t.owner||t.requestedCreateCollections===!0||t.freshRequestedCreateCollections===!0)throw q("binding")}if(o!==void 0&&(!IP(o)||o.environment!==t.environment||o.appOrigin!==t.origin||o.cpOrigin!==t.cpOrigin||t.allowLoopbackHttp===!0&&!o.allowLoopbackHttp||t.allowNativeLoopbackHttp===!0&&!o.allowNativeLoopbackHttp))throw q("binding");i=await $f.open({...t,allowLoopbackHttp:o?.allowLoopbackHttp??t.allowLoopbackHttp,allowNativeLoopbackHttp:o?.allowNativeLoopbackHttp??t.allowNativeLoopbackHttp},()=>{let r=crypto.getRandomValues(new Uint8Array(32));try{let a=`pair_${btoa(String.fromCharCode(...r)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`;return new TextEncoder().encode(JSON.stringify({version:3,renewal:null,requestedCreateCollections:t.requestedCreateCollections??t.freshRequestedCreateCollections??!1,collectionIds:[],createCollections:!1,consentRequest:null,requestId:crypto.randomUUID(),installationId:crypto.randomUUID(),deviceId:crypto.randomUUID(),secret:a,appId:t.appId,...t.owner===void 0?{}:{owner:t.owner},kind:t.installationKind??"app-runtime",origin:t.origin,cpOrigin:t.cpOrigin,environment:t.environment,selection:null,confirmed:!1,nativeStarted:!1,proof:null,token:null,...t.recoveryFor?{recoveryFor:t.recoveryFor}:{}}))}finally{r.fill(0)}});let s=this.decode(i.plaintext,t);return new n(i.store,s,t)}catch(o){throw await i?.store.close(),o instanceof Xe?o:o instanceof Gc&&o.reason==="busy"?q("open_in_another_tab"):q("recovery_required")}finally{i?.plaintext.fill(0)}}static decode(e,t){let i=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(e)),o="version,requestId,installationId,deviceId,secret,appId,kind,origin,cpOrigin,environment,selection,confirmed,nativeStarted,proof,token",s=i?.version===1,r=`${o},requestedCreateCollections,collectionIds,createCollections,consentRequest`,a=s?{...Ce(i,o),version:3,renewal:null,requestedCreateCollections:!1,collectionIds:[],createCollections:!1,consentRequest:null}:i?.version===2?{...Ce(i,r),version:3,renewal:null}:Ce(i,`${r},renewal${Object.hasOwn(i,"collectionSelection")?",collectionSelection":""}${Object.hasOwn(i,"timerConsent")?",timerConsent":""}${Object.hasOwn(i,"timerChannel")?",timerChannel":""}${Object.hasOwn(i,"owner")?",owner":""}${Object.hasOwn(i,"collectionListing")?",collectionListing":""}${Object.hasOwn(i,"collectionRecoveries")?",collectionRecoveries":""}${Object.hasOwn(i,"recoveryFor")?",recoveryFor":""}${Object.hasOwn(i,"nativeAuthorization")?",nativeAuthorization":""}${Object.hasOwn(i,"nativeSelection")?",nativeSelection":""}${Object.hasOwn(i,"nativeGrants")?",nativeGrants":""}`);if(a.version!==3||a.appId!==t.appId||a.owner!==t.owner||a.kind!==(t.installationKind??"app-runtime")||a.origin!==t.origin||a.cpOrigin!==t.cpOrigin||a.environment!==t.environment||typeof a.confirmed!="boolean"||typeof a.nativeStarted!="boolean")throw q("recovery_required");let p=a;if(typeof p.requestedCreateCollections!="boolean"||typeof p.createCollections!="boolean"||t.requestedCreateCollections!==void 0&&t.requestedCreateCollections!==p.requestedCreateCollections)throw q("binding");if(p.collectionIds=this.collectionIds(p.collectionIds),p.recoveryFor!==void 0){let l=Ce(p.recoveryFor,"accountId,collectionId");_e(l.accountId),_e(l.collectionId)}if(p.recoveryFor===void 0!=(t.recoveryFor===void 0)||p.recoveryFor?.accountId!==t.recoveryFor?.accountId||p.recoveryFor?.collectionId!==t.recoveryFor?.collectionId||p.recoveryFor&&(p.requestedCreateCollections||p.createCollections||p.selection&&p.selection.accountId!==p.recoveryFor.accountId||p.token&&(p.nativeSelection?p.collectionIds.length!==0||p.nativeSelection.collectionId!==p.recoveryFor.collectionId:p.collectionIds.length!==1||p.collectionIds[0]!==p.recoveryFor.collectionId||p.collectionSelection?.selectedCollectionId!==p.recoveryFor.collectionId)))throw q("recovery_required");if(p.consentRequest!==null){let l=Ce(p.consentRequest,`requestId,secret,requestedCreateCollections,challenge,completed,addedCollectionIds,approvedCreateCollections${La(p.consentRequest,!0)}`);if(zf(l,!0),_e(l.requestId),Kt(l.secret,/^pair_[A-Za-z0-9_-]{43}$/),l.requestId===p.requestId||l.secret===p.secret||typeof l.requestedCreateCollections!="boolean"||typeof l.completed!="boolean"||typeof l.approvedCreateCollections!="boolean"||l.approvedCreateCollections&&!l.requestedCreateCollections||(l.challenge!==null&&Kt(l.challenge,/^[0-9a-f]{64}$/),this.collectionIds(l.addedCollectionIds),!p.token||!p.selection||l.completed&&l.challenge===null))throw q("recovery_required")}if(p.createCollections&&!p.token||p.collectionIds.length&&!p.token)throw q("recovery_required");if(p.collectionSelection!==void 0){let l=Ce(p.collectionSelection,"requestId,selectedCollectionId,createdCollectionIds");if(_e(l.requestId),!p.token||!p.collectionIds.includes(_e(l.selectedCollectionId))||this.collectionIds(l.createdCollectionIds).some(c=>!p.collectionIds.includes(c)))throw q("recovery_required")}if(_e(p.requestId),_e(p.installationId),_e(p.deviceId),Kt(p.secret,/^pair_[A-Za-z0-9_-]{43}$/),p.renewal!==null){let l=Ce(p.renewal,"requestId,secret");if(_e(l.requestId),Kt(l.secret,/^pair_[A-Za-z0-9_-]{43}$/),l.requestId===p.requestId||l.secret===p.secret)throw q("recovery_required")}if(p.timerChannel!==void 0){if(!p.token||!p.selection)throw q("recovery_required");try{p.timerChannel=Mb(p.timerChannel)}catch{throw q("recovery_required")}}if(p.timerConsent!==void 0){let l=Ce(p.timerConsent,"requestId,approved,grants");if(_e(l.requestId),!p.token||!p.selection||typeof l.approved!="boolean"||!Array.isArray(l.grants)||l.grants.length>1)throw q("recovery_required");let c=l.grants.map(u=>{let f=Ce(u,"grantId,collectionId,declarationDigest");return{grant_id:f.grantId,collection_id:f.collectionId,declaration_digest:f.declarationDigest}}),d=p.selection.portalConfirmed===!0||p.consentRequest?.portalConfirmed===!0;p.timerConsent=Tb({timer_consent:l.approved,timer_grants:c},_e(l.requestId),p.collectionIds,d,c[0]?.collection_id)}if(p.selection!==null){let l=Ce(p.selection,`accountId,connectorId,challenge,approvalMode${La(p.selection,!0)}`);if(_e(l.accountId),_e(l.connectorId),Kt(l.challenge,/^[0-9a-f]{64}$/),l.approvalMode!=="password-ak1")throw q("response");zf(l,!0)}if(p.proof!==null&&this.proof(p.proof),p.token!==null&&Kt(p.token,/^idev_[A-Za-z0-9_-]{43}$/),p.confirmed&&!p.selection||p.nativeStarted&&!p.confirmed||p.proof&&!p.nativeStarted||p.token&&!p.proof||p.collectionListing!==void 0&&(!p.token||!p.confirmed||!p.selection||!p.proof||Lb(p.collectionListing).some(l=>!p.collectionIds.includes(l.collectionId))))throw q("recovery_required");if(p.collectionRecoveries!==void 0){if(!p.token||!p.confirmed||!p.selection||!p.proof||!p.collectionRecoveries||typeof p.collectionRecoveries!="object"||Array.isArray(p.collectionRecoveries))throw q("recovery_required");let l=Object.entries(p.collectionRecoveries);if(l.length>1e3||l.some(([c,d])=>!(p.collectionIds.includes(_e(c))||p.nativeGrants?.some(u=>u.collection_id===c))||d!==null&&!_e(d)))throw q("recovery_required")}if(p.nativeAuthorization){let l=Ce(p.nativeAuthorization,"requestId,authorizationId,applicationId,manifestDigest");if(_e(l.requestId),_e(l.authorizationId),l.applicationId!==p.appId||!p.proof||!p.confirmed)throw q("recovery_required");Kt(l.manifestDigest,/^[0-9a-f]{64}$/)}if(p.nativeSelection){let l=Ce(p.nativeSelection,"requestId,authorizationRequestId,collectionId");if(_e(l.requestId),_e(l.authorizationRequestId),_e(l.collectionId),!p.token||!p.nativeAuthorization||l.requestId!==p.nativeAuthorization.requestId||l.authorizationRequestId!==p.nativeAuthorization.authorizationId)throw q("recovery_required")}if(p.nativeGrants&&(!p.token||!p.selection||!Array.isArray(p.nativeGrants)||p.nativeGrants.length>1e3||(p.nativeGrants=p.nativeGrants.map(l=>Rb(l,{requestId:p.requestId,authorizationRequestId:l.authorization_request_id,collectionId:l.collection_id},p.selection.accountId,p.appId,p.origin,l.application_manifest_digest)),new Set(p.nativeGrants.map(l=>l.collection_id)).size!==p.nativeGrants.length)))throw q("recovery_required");return p}static collectionIds(e){if(!Array.isArray(e)||e.length>1e3)throw q("response");let t=e.map(_e);if(new Set(t).size!==t.length)throw q("response");return t}static proof(e){let t=Ce(e,"sign_pk,kem_pk,noise_pk,sig");return{sign_pk:Kt(t.sign_pk,/^[0-9a-f]{64}$/),kem_pk:Kt(t.kem_pk,/^[0-9a-f]{64}$/),noise_pk:Kt(t.noise_pk,/^[0-9a-f]{64}$/),sig:Kt(t.sig,/^[0-9a-f]{128}$/)}}isCurrent(){return!this.closed&&!this.parent.aborted&&!this.lifetime.signal.aborted&&this.store.isCurrent()}check(){if(!this.isCurrent())throw q("fenced")}view(){this.check();let e=this.state,t=e.consentRequest?.portalConfirmed?e.consentRequest:e.selection;return Object.freeze({requestId:e.requestId,installationId:e.installationId,deviceId:e.deviceId,appId:e.appId,kind:e.kind,verificationUri:`${e.cpOrigin}/pair/${e.requestId}`,state:e.token?"paired":e.proof?"awaiting_approval":e.confirmed?"account_confirmed":e.selection?"account_selected":"pending",accountId:e.selection?.accountId??null,accountEmail:t?.accountEmail??null,...t?.accountProvider?{accountProvider:t.accountProvider,accountLogin:t.accountLogin}:{},collectionSelection:e.collectionSelection?Object.freeze({...e.collectionSelection,createdCollectionIds:Object.freeze([...e.collectionSelection.createdCollectionIds])}):null,nativeSelection:e.nativeSelection&&e.nativeGrants?.some(i=>i.authorization_request_id===e.nativeSelection.authorizationRequestId&&i.collection_id===e.nativeSelection.collectionId)?Object.freeze({...e.nativeSelection}):null,nativeGrants:Object.freeze([...e.nativeGrants??[]]),...e.timerConsent?{timerConsent:e.timerConsent}:{},collectionIds:Object.freeze([...e.collectionIds]),createCollections:e.createCollections,requestedCreateCollections:e.requestedCreateCollections})}async save(e){this.check();let t=new TextEncoder().encode(JSON.stringify(e));try{await this.store.commit(t),this.check(),this.state=e}catch{throw await this.close(),q("recovery_required")}finally{t.fill(0)}}async exclusive(e){if(this.check(),this.busy)throw q("busy");this.busy=!0;try{return await e()}finally{this.busy=!1}}async json(e,t,i,o){this.check(),this.wrongAccountRequestId=null;let s=new AbortController,r=()=>s.abort(),a=setTimeout(r,15e3);this.lifetime.signal.addEventListener("abort",r,{once:!0});let p=null,l=null,c=!1,d=!1,u=new Uint8Array(o?.get||e.endsWith("/exchange")?1024*1024:64*1024),f=0;try{if(p=await this.request(`${this.state.cpOrigin}${e}`,{method:o?.get?"GET":o?.patch?"PATCH":o?.delete?"DELETE":"POST",headers:{...o?{authorization:`Bearer ${o.bearer}`}:t?{authorization:`Bearer ${this.state.secret}`}:{},...i===void 0?{}:{"content-type":"application/json"}},body:i===void 0?void 0:JSON.stringify(i),credentials:"omit",redirect:"error",cache:"default",referrerPolicy:"no-referrer",signal:s.signal}),this.check(),s.signal.aborted)throw q("outcome_unknown");let h=p.headers.get("content-length");if(h!==null&&/^(0|[1-9][0-9]*)$/.test(h)&&Number(h)>u.length)throw s.abort(),q("response");if(!p.body)throw q("response");for(l=p.body.getReader();;){let{done:b,value:w}=await l.read();try{if(this.check(),s.signal.aborted)throw q("outcome_unknown");if(b){c=!0;break}if(f+w.length>u.length)throw s.abort(),q("response");u.set(w,f),f+=w.length}finally{w?.fill(0)}}d=!0;let m=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(u.subarray(0,f)));if(!m||typeof m!="object"||Array.isArray(m))throw q("response");if(!p.ok){let b=m.error;if(!o&&p.status===404&&(e==="/v1/pairing-requests"||e===`/v1/pairing-requests/${this.state.requestId}/exchange`||e===`/v1/pairing-requests/${this.state.requestId}/attest`)&&b&&typeof b=="object"&&!Array.isArray(b)&&(b.code==="installation_pairing_expired"||b.code==="installation_pairing_denied"))throw this.expiredRequestId=this.state.requestId,q(b.code==="installation_pairing_expired"?"expired":"refused");let w=Li(p.status,m,p.headers);throw new Xe(St(w)??"refused",w)}return{status:p.status,value:m}}catch(h){this.check();let m=h instanceof Xe?h:q(o?.get&&!s.signal.aborted&&!(h instanceof DOMException&&h.name==="AbortError")?d?"response":!p||p.ok?"unavailable":"refused":"outcome_unknown");throw p&&!p.ok&&qb.add(m),m}finally{u.fill(0),c||(l?.cancel()??p?.body?.cancel())?.catch(()=>{}),l?.releaseLock(),clearTimeout(a),this.lifetime.signal.removeEventListener("abort",r)}}start(e={}){let t;try{t=XP(e)}catch(i){return Promise.reject(i)}return this.exclusive(()=>this.startRequest(t))}renewExpiredPairing(){return this.exclusive(async()=>{let e=this.state;if(e.token||this.expiredRequestId!==e.requestId)throw q("recovery_required");let t=crypto.getRandomValues(new Uint8Array(32));try{let i=crypto.randomUUID(),o=`pair_${btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`;if(i===e.requestId||i===e.renewal?.requestId||o===e.secret)throw q("binding");return await this.save({...e,requestId:i,secret:o,renewal:{requestId:e.requestId,secret:e.secret}}),this.expiredRequestId=null,await this.startRequest()}finally{t.fill(0)}})}async startRequest(e=null){if(this.state.token)return this.view();let t=this.state;if(t.recoveryFor&&e!==null&&e!==t.recoveryFor.collectionId)throw q("binding");let{status:i,value:o}=await this.json("/v1/pairing-requests",!1,{installation:{app_id:t.appId,request_id:t.requestId,pairing_secret:t.secret,installation_id:t.installationId,device_id:t.deviceId,kind:t.kind,requested_create_collections:t.requestedCreateCollections,...t.recoveryFor?{recovery_collection_id:t.recoveryFor.collectionId}:{},...t.renewal?{renewal:{request_id:t.renewal.requestId,pairing_secret:t.renewal.secret}}:{}},...e?{collection_hint:e}:{}});if(i!==200&&i!==201)throw q("response");Ce(o,`pairing_id,pairing_secret,verification_uri,expires_in,installation_device,app_id,app_origin,app_name${this.recoveryTargetKeys()}`),this.assertRecoveryTarget(o);let s=ZP(o.verification_uri,`${t.cpOrigin}/pair/${t.requestId}`,e);if(o.pairing_id!==t.requestId||o.pairing_secret!==t.secret||s===null||o.installation_device!==!0||o.app_id!==t.appId||o.app_origin!==t.origin||o.app_name!==this.options.appName||!Number.isSafeInteger(o.expires_in)||o.expires_in<0||o.expires_in>600)throw q("response");return this.expiredRequestId=null,Object.freeze({...this.view(),verificationUri:s})}recoveryTargetKeys(){return this.state.recoveryFor?",recovery_collection_id":""}assertRecoveryTarget(e){if(this.state.recoveryFor&&_e(e.recovery_collection_id)!==this.state.recoveryFor.collectionId)throw q("binding")}selected(e){let t=this.state;if(this.assertRecoveryTarget(e),e.request_id!==t.requestId||e.installation_id!==t.installationId||e.device_id!==t.deviceId||e.kind!==t.kind||e.app_id!==t.appId||e.app_origin!==t.origin||e.approval_mode!=="password-ak1"||!Number.isSafeInteger(e.expires_at)||e.expires_at<0)throw q("response");let i={accountId:_e(e.account_id),connectorId:_e(e.connector_id),challenge:Kt(e.challenge,/^[0-9a-f]{64}$/),approvalMode:"password-ak1"};if(t.selection&&(i.accountId!==t.selection.accountId||i.connectorId!==t.selection.connectorId||i.challenge!==t.selection.challenge||i.approvalMode!==t.selection.approvalMode))throw q("binding");if(Object.assign(i,zf(e)),t.selection&&JP(t.selection,i),t.recoveryFor&&i.accountId!==t.recoveryFor.accountId)throw e.status==="account_selected"&&!t.selection&&!t.confirmed&&!t.nativeStarted&&!t.proof&&!t.token?(this.wrongAccountRequestId=t.requestId,q("recovery_account_mismatch")):q("binding");return this.wrongAccountRequestId=null,i}canAbandonWrongAccount(){let e=this.state;return this.isCurrent()&&e.recoveryFor!==void 0&&this.wrongAccountRequestId===e.requestId&&!e.selection&&!e.confirmed&&!e.nativeStarted&&!e.proof&&!e.token&&!e.consentRequest}exchange(){return this.exclusive(async()=>{if(this.state.token)return this.view();let{status:e,value:t}=await this.json(`/v1/pairing-requests/${this.state.requestId}/exchange`,!0);if(t.status==="pending"){if(Ce(t,"status"),e!==202||this.state.selection)throw q("response");return this.view()}let i=`status,request_id,account_id,connector_id,device_id,installation_id,kind,challenge,approval_mode,app_id,app_origin,expires_at${La(t)}${this.recoveryTargetKeys()}`;if(t.status==="account_selected"||t.status==="awaiting_approval"){if(Ce(t,i),e!==202||t.status==="awaiting_approval"&&!this.state.proof)throw q("response");let b=this.selected(t);return JSON.stringify(b)!==JSON.stringify(this.state.selection)&&await this.save({...this.state,selection:b}),this.view()}let o=Object.hasOwn(t,"collection_ids")||Object.hasOwn(t,"create_collections"),s=Object.hasOwn(t,"selected_collection_id")||Object.hasOwn(t,"created_collection_ids"),r=Object.hasOwn(t,"native_selection");if(Ce(t,`${i},connector,token,registration${o?",collection_ids,create_collections":""}${s?",selected_collection_id,created_collection_ids":""}${r?",native_selection":""}${jb(t)}`),e!==200||t.status!=="paired"||!this.state.confirmed||!this.state.proof)throw q("response");let a=this.selected(t),p=Ce(t.connector,"id,name"),l=Ce(t.registration,"device_id,sign_pk,kem_pk,noise_pk");if(p.id!==a.connectorId||p.name!==this.options.appName||l.device_id!==this.state.deviceId||l.sign_pk!==this.state.proof.sign_pk||l.kem_pk!==this.state.proof.kem_pk||l.noise_pk!==this.state.proof.noise_pk)throw q("binding");let c=o?n.collectionIds(t.collection_ids):[],d=o?t.create_collections:!1;if(typeof d!="boolean"||d&&!this.state.requestedCreateCollections)throw q("response");let u=s?this.collectionSelection(t,c,this.state.requestId):void 0,f=r?this.parseNativeSelection(t.native_selection,this.state.requestId):void 0;if(r&&(!o||s||d||c.length!==0||t.timer_consent===!0))throw q("response");if(this.state.recoveryFor&&f&&f.collectionId!==this.state.recoveryFor.collectionId||this.state.recoveryFor&&!f&&(d||c.length!==1||c[0]!==this.state.recoveryFor.collectionId||u?.selectedCollectionId!==this.state.recoveryFor.collectionId||u.createdCollectionIds.length!==0))throw q("binding");if(t.timer_consent===!0&&!u)throw q("response");let h=Tb(t,this.state.requestId,c,a.portalConfirmed===!0,u?.selectedCollectionId),m=Kt(t.token,/^idev_[A-Za-z0-9_-]{43}$/);return await this.save({...this.state,selection:a,token:m,collectionIds:c,createCollections:d,nativeSelection:f,...f?{collectionSelection:void 0}:u?{collectionSelection:u}:{},...h?{timerConsent:h}:{}}),this.view()})}parseNativeSelection(e,t){let i=Ce(e,"authorization_request_id,collection_id"),o=this.state.nativeAuthorization;if(!o||o.requestId!==t||_e(i.authorization_request_id)!==o.authorizationId)throw q("binding");return Object.freeze({requestId:t,authorizationRequestId:o.authorizationId,collectionId:_e(i.collection_id)})}pendingNativeSelection(){return this.check(),this.state.nativeSelection??null}nativeAuthorizationContext(e){this.check(),this.owned(e);let t=this.state,i=t.consentRequest&&!t.consentRequest.completed?t.consentRequest:null,o=i?.challenge??t.selection?.challenge,s=i?i.portalConfirmed:t.selection?.portalConfirmed;if(!t.proof||!t.confirmed||!s||!o||t.token&&!i)return null;let r=i?.requestId??t.requestId,a=t.nativeAuthorization;return Object.freeze({requestId:r,accountId:t.selection.accountId,appId:t.appId,challenge:o,...a?.requestId===r?{authorizationId:a.authorizationId}:{}})}attachNativeAuthorization(e,t,i){let o=Object.freeze({...t}),s=Object.freeze({...i}),r=e.isCurrent;return this.exclusive(async()=>{this.owned(e);let a=this.nativeAuthorizationContext(e);if(!a||e.isCurrent!==r||a.requestId!==o.requestId||a.challenge!==o.challenge||a.accountId!==o.accountId||s.applicationId!==a.appId||!/^[0-9a-f]{64}$/.test(s.manifestDigest)||(_e(s.authorizationId),a.authorizationId&&a.authorizationId!==s.authorizationId))throw q("binding");await this.save({...this.state,nativeAuthorization:{...s,requestId:a.requestId}});let p=a.requestId===this.state.requestId?this.state.secret:this.state.consentRequest.secret,{status:l,value:c}=await this.json(`/v1/pairing-requests/${a.requestId}/native-authorization`,!1,{authorization_request_id:s.authorizationId},{bearer:p});if(this.owned(e),e.isCurrent!==r)throw q("fenced");if(Ce(c,"request_id,authorization_request_id,account_id"),l!==200||c.request_id!==a.requestId||c.authorization_request_id!==s.authorizationId||c.account_id!==a.accountId)throw q("binding")})}completeNativeAuthorization(e,t){let i=this.consentGuard(e);return this.exclusive(async()=>{i();let o=this.state,s=o.nativeSelection,r=o.nativeAuthorization;if(!this.nativeAcknowledged||!s||!r)throw q("binding");let a=Rb(t,s,o.selection.accountId,o.appId,o.origin,r.manifestDigest);await this.save({...o,nativeGrants:[...(o.nativeGrants??[]).filter(p=>p.collection_id!==s.collectionId),a]}),i()})}collectionSelection(e,t,i){let o=_e(e.selected_collection_id),s=n.collectionIds(e.created_collection_ids);if(!t.includes(o)||s.some(r=>!t.includes(r)))throw q("response");return Object.freeze({requestId:i,selectedCollectionId:o,createdCollectionIds:Object.freeze(s)})}collectionConsentView(){this.check();let e=this.state.consentRequest;return e?Object.freeze({requestId:e.requestId,verificationUri:`${this.state.cpOrigin}/pair/${e.requestId}`,state:e.completed?"scope_updated":"pending",requestedCreateCollections:e.requestedCreateCollections,addedCollectionIds:Object.freeze([...e.addedCollectionIds]),approvedCreateCollections:e.approvedCreateCollections,accountEmail:e.accountEmail??null,...e.accountProvider?{accountProvider:e.accountProvider,accountLogin:e.accountLogin}:{},accountSelectionConfirmed:e.portalConfirmed===!0}):null}consentGuard(e){let t=e.isCurrent;return()=>{if(this.check(),this.owned(e),this.receipt(),e.isCurrent!==t)throw q("fenced")}}async consentWindow(e,t){try{return await t()}catch(i){let o=i instanceof Xe?i.server?.code:null;if((o==="installation_pairing_denied"||o==="installation_pairing_expired")&&i instanceof Xe&&i.server?.status===404){let s=this.state.consentRequest;throw s&&!s.completed&&s.requestId===e&&await this.save({...this.state,consentRequest:null}),q(o==="installation_pairing_expired"?"expired":"refused")}throw i}}startCollectionConsent(e,t=!1,i={}){let o=this.consentGuard(e),s;try{s=XP(i)}catch(a){return Promise.reject(a)}let r=async()=>{if(o(),this.state.recoveryFor||typeof t!="boolean")throw q("binding");let a=this.state.consentRequest;if(!a||a.completed){let h=crypto.getRandomValues(new Uint8Array(32));try{let m=`pair_${btoa(String.fromCharCode(...h)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`;a={requestId:crypto.randomUUID(),secret:m,requestedCreateCollections:t,challenge:null,completed:!1,addedCollectionIds:[],approvedCreateCollections:!1},await this.save({...this.state,consentRequest:a}),o()}finally{h.fill(0)}}else if(a.requestedCreateCollections!==t)throw q("binding");let p=this.state,l=p.token,c=a,{status:d,value:u}=await this.consentWindow(c.requestId,()=>this.json("/v1/pairing-requests",!1,{installation:{app_id:p.appId,request_id:c.requestId,pairing_secret:c.secret,installation_id:p.installationId,device_id:p.deviceId,kind:p.kind,requested_create_collections:c.requestedCreateCollections,reconsent:!0},...s?{collection_hint:s}:{}},{bearer:l}));o(),Ce(u,"pairing_id,pairing_secret,verification_uri,expires_in,installation_device,app_id,app_origin,app_name");let f=null;if(d!==200&&d!==201||u.pairing_id!==a.requestId||u.pairing_secret!==a.secret||(f=ZP(u.verification_uri,`${p.cpOrigin}/pair/${a.requestId}`,s))===null||u.installation_device!==!0||u.app_id!==p.appId||u.app_origin!==p.origin||u.app_name!==this.options.appName||!Number.isSafeInteger(u.expires_in)||u.expires_in<0||u.expires_in>600||l!==this.state.token)throw q("response");return Object.freeze({...this.collectionConsentView(),verificationUri:f})};return this.exclusive(async()=>{let a=this.state.consentRequest,p=a!==null&&!a.completed;try{return await r()}catch(l){if(p&&this.state.consentRequest===null&&l instanceof Xe&&(l.reason==="refused"||l.reason==="expired"))return await r();throw l}})}exchangeCollectionConsent(e){let t=this.consentGuard(e);return this.exclusive(async()=>{t();let i=this.state.consentRequest,o=this.state;if(!i)throw q("binding");if(i.completed)return this.collectionConsentView();let{status:s,value:r}=await this.consentWindow(i.requestId,()=>this.json(`/v1/pairing-requests/${i.requestId}/exchange`,!1,void 0,{bearer:i.secret}));t();let a=La(r),p=`status,request_id,account_id,connector_id,device_id,installation_id,kind,challenge,approval_mode,app_id,app_origin,expires_at${a}`,l=r.status==="scope_updated",c=l&&(Object.hasOwn(r,"selected_collection_id")||Object.hasOwn(r,"created_collection_ids")),d=l&&Object.hasOwn(r,"native_selection");if(Ce(r,`${p}${l?",added_collection_ids,approved_create_collections":""}${c?",selected_collection_id,created_collection_ids":""}${d?",native_selection":""}${l?jb(r):""}`),!l&&(s!==202||r.status!=="awaiting_approval")||l&&s!==200||r.request_id!==i.requestId||r.account_id!==o.selection.accountId||r.connector_id!==o.selection.connectorId||r.device_id!==o.deviceId||r.installation_id!==o.installationId||r.kind!==o.kind||r.app_id!==o.appId||r.app_origin!==o.origin||r.approval_mode!==o.selection.approvalMode||!Number.isSafeInteger(r.expires_at)||r.expires_at<0)throw q("binding");let u=zf(r);if(i.portalConfirmed&&!a)throw q("response");JP(i,u);let f=Kt(r.challenge,/^[0-9a-f]{64}$/);if(i.challenge!==null&&i.challenge!==f)throw q("binding");if(!l)return(i.challenge===null||a&&!i.portalConfirmed)&&await this.save({...o,consentRequest:{...i,...u,challenge:f}}),t(),this.collectionConsentView();let h=n.collectionIds(r.added_collection_ids);if(typeof r.approved_create_collections!="boolean"||r.approved_create_collections&&!i.requestedCreateCollections)throw q("response");let m=n.collectionIds([...new Set([...o.collectionIds,...h])]),b=c?this.collectionSelection(r,m,i.requestId):void 0,w=d?this.parseNativeSelection(r.native_selection,i.requestId):void 0;if(d&&(c||h.length!==0||r.approved_create_collections!==!1||r.timer_consent===!0)||r.timer_consent===!0&&!b)throw q("response");let g=Tb(r,i.requestId,h,u.portalConfirmed===!0,b?.selectedCollectionId);return await this.save({...o,collectionIds:m,nativeSelection:w,...w?{collectionSelection:void 0}:b?{collectionSelection:b}:{},...g?{timerConsent:g}:{},createCollections:o.createCollections||r.approved_create_collections,consentRequest:{...i,...u,challenge:f,completed:!0,addedCollectionIds:h,approvedCreateCollections:r.approved_create_collections}}),t(),this.collectionConsentView()})}listApprovedCollections(e){let t=this.consentGuard(e);return this.exclusive(async()=>{t();let i;try{i=await this.json("/v1/next/collections?include=file_actions",!1,void 0,{bearer:this.state.token,get:!0})}catch(c){if(t(),c instanceof Xe&&c.reason==="unavailable"&&!c.server&&!qb.has(c)&&this.state.collectionListing!==void 0)return Object.freeze(Lb(this.state.collectionListing).filter(d=>this.state.collectionIds.includes(d.collectionId)).map(d=>Object.freeze({...d,fileActions:Object.freeze([])})));if(c instanceof Xe&&(c.server||qb.has(c))&&this.state.collectionListing!==void 0){let d={...this.state};delete d.collectionListing,await this.save(d),t()}throw c}t();let{status:o,value:s}=i;if(Ce(s,"collections"),o!==200)throw q("response");let r=Lb(s.collections),a=s.collections.filter(c=>this.state.collectionIds.includes(c.collection_id)).map(c=>{let d={...c};return delete d.file_actions,d}),p={...this.state};delete p.collectionListing;let l={...p,collectionListing:a};return await this.save(new TextEncoder().encode(JSON.stringify(l)).length<=128*1024?l:p),t(),r})}collectionRecoveries(){return this.check(),Object.freeze({...this.state.collectionRecoveries})}retireCollectionScope(e,t,i=null){let o=this.consentGuard(e);return this.exclusive(async()=>{if(o(),_e(t),!(this.state.collectionIds.includes(t)||this.state.nativeGrants?.some(s=>s.collection_id===t)))throw q("binding");if(i!==null){if(_e(i),this.state.collectionRecoveries?.[t]!==i)throw q("fenced")}else if(Object.hasOwn(this.state.collectionRecoveries??{},t))return;await this.saveRecovery(t,null),o()})}freshCollectionInstallation(e,t){let i=this.consentGuard(e);return this.exclusive(async()=>{if(i(),_e(t),!Object.hasOwn(this.state.collectionRecoveries??{},t))throw q("binding");let o=this.state.collectionRecoveries[t];if(o!==null)return o;let s=crypto.randomUUID();return await this.saveRecovery(t,s),i(),s})}async saveRecovery(e,t){let i={...this.state,collectionRecoveries:{...this.state.collectionRecoveries,[e]:t}};new TextEncoder().encode(JSON.stringify(i)).length>128*1024&&delete i.collectionListing,await this.save(i)}startFileAccess(e,t,i,o){let s=this.consentGuard(e),r;try{if(_e(t),r=Nb([...i],Bf,!1),r.length!==i.length)throw q("binding")}catch{return Promise.reject(q("binding"))}return this.exclusive(async()=>{s();let a=crypto.getRandomValues(new Uint8Array(32));try{let p=crypto.randomUUID(),l=`pair_${btoa(String.fromCharCode(...a)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`,c=this.state,d=c.token,{status:u,value:f}=await this.json("/v1/pairing-requests",!1,{installation:{app_id:c.appId,request_id:p,pairing_secret:l,installation_id:c.installationId,device_id:c.deviceId,kind:c.kind,requested_create_collections:!1,reconsent:!0,file_access:{collection_id:t,actions:[...r],reason:o}}},{bearer:d});s(),Ce(f,"pairing_id,pairing_secret,verification_uri,expires_in,installation_device,app_id,app_origin,app_name");let h=`${c.cpOrigin}/pair/${p}`;if(u!==200&&u!==201||f.pairing_id!==p||f.pairing_secret!==l||f.verification_uri!==h||f.installation_device!==!0||f.app_id!==c.appId||f.app_origin!==c.origin||f.app_name!==this.options.appName||!Number.isSafeInteger(f.expires_in)||f.expires_in<0||f.expires_in>600||d!==this.state.token)throw q("response");return Object.freeze({requestId:p,secret:l,collectionId:t,actions:r,verificationUri:h,expiresAt:Date.now()+f.expires_in*1e3})}finally{a.fill(0)}})}exchangeFileAccess(e,t){let i=this.consentGuard(e);return this.exclusive(async()=>{i();let o=this.state,{status:s,value:r}=await this.json(`/v1/pairing-requests/${t.requestId}/exchange`,!1,void 0,{bearer:t.secret});if(i(),r.status==="pending"){if(Ce(r,"status"),s!==202)throw q("response");return Object.freeze({state:"pending"})}if(r.status==="account_selected"||r.status==="awaiting_approval"){if(Ce(r,`status,request_id,account_id,connector_id,device_id,installation_id,kind,challenge,approval_mode,app_id,app_origin,expires_at${La(r)}`),s!==202||r.request_id!==t.requestId||r.account_id!==o.selection?.accountId||r.installation_id!==o.installationId||r.device_id!==o.deviceId||r.app_id!==o.appId)throw q("binding");return Object.freeze({state:"pending"})}if(r.status==="declined"){if(Ce(r,"status,request_id"),s!==200||r.request_id!==t.requestId)throw q("response");return Object.freeze({state:"declined"})}if(Ce(r,"status,request_id,collection_id,file_actions"),s!==200||r.status!=="file_access_updated"||r.request_id!==t.requestId||r.collection_id!==t.collectionId)throw q("response");return Object.freeze({state:"granted",actions:Nb(r.file_actions,t.actions,!1)})})}renameApprovedCollection(e,t,i){let o;try{_e(t),o=br(i)}catch{return Promise.reject(q("binding"))}let s=this.consentGuard(e);return this.exclusive(async()=>{if(s(),!this.state.collectionIds.includes(t))throw q("refused");let{status:r,value:a}=await this.json(`/v1/next/collections/${t}/name`,!1,{display_name:o},{bearer:this.state.token,patch:!0});s();let p=Ce(a,"collection_id,display_name");if(r!==200||p.collection_id!==t||p.display_name!==o)throw q("response");return Object.freeze({collectionId:t,displayName:o})})}deleteApprovedCollection(e,t,i){let o;try{_e(t),o=br(i)}catch{return Promise.reject(q("binding"))}let s=this.consentGuard(e);return this.exclusive(async()=>{if(s(),!this.state.collectionIds.includes(t))throw q("refused");let{status:r,value:a}=await this.json(`/v1/next/collections/${t}`,!1,{confirm_name:o},{bearer:this.state.token,delete:!0});s();let p=Ce(a,"collection_id,deleted");if(r!==200||p.collection_id!==t||p.deleted!==!0)throw q("response");return Object.freeze({collectionId:t,deleted:!0})})}signOutInstallation(){return this.exclusive(async()=>{let e=this.state.token;if(!e)throw q("binding");try{let{status:t,value:i}=await this.json("/v1/next/installation",!1,void 0,{bearer:e,delete:!0});if(t!==200||i.ok!==!0||i.revoked!==!0||!Number.isSafeInteger(i.collections)||i.collections<0||i.fence!=="closed"&&i.fence!=="committed_with_degraded_fence")throw q("response");return"revoked"}catch(t){if(t instanceof Xe&&t.server?.status===401&&t.server.code==="invalid_connector")return"already_signed_out";throw t}})}hasWebPushChannel(){return this.check(),this.state.timerChannel?.kind==="web_push"}confirmPortalSelectedAccount(){return this.exclusive(async()=>{let e=this.state.selection;if(!e?.portalConfirmed)throw q("account_confirmation_required");if(this.state.confirmed||await this.save({...this.state,confirmed:!0}),this.check(),this.state.selection!==e)throw q("binding");return this.view()})}confirmSelectedAccount(e){return this.exclusive(async()=>{if(!this.state.selection||e!==this.state.selection.accountId)throw q("binding");return this.state.confirmed||await this.save({...this.state,confirmed:!0}),this.view()})}confirmedSelection(){if(this.check(),!this.state.confirmed||!this.state.selection)throw q("account_confirmation_required");let e=this.state,t=e.selection;return Object.freeze({accountId:t.accountId,connectorId:t.connectorId,installationId:e.installationId,deviceId:e.deviceId,kind:e.kind,cpOrigin:e.cpOrigin,approvalMode:t.approvalMode,isCurrent:()=>this.isCurrent()})}owned(e){let t=this.confirmedSelection();if(e.isCurrent()!==!0||e.scope.account!==t.accountId||e.scope.installation!==t.installationId)throw q("fenced")}prepareOriginalDevice(e){let t=e.isCurrent,i=()=>{try{return this.check(),this.owned(e),e.isCurrent===t}catch{return!1}};return this.exclusive(async()=>{if(!i())throw q("fenced");let o=this.state.nativeStarted?"existing":"fresh";if(this.state.nativeStarted||await this.save({...this.state,nativeStarted:!0}),!i())throw q("fenced");return Object.freeze({mode:o,pin:Object.freeze({...this.confirmedSelection(),isCurrent:i,installationOwned:i})})})}attest(e){let{runtime:t,custody:i,persistence:o,installation:s}=e,r=s.isCurrent,a=()=>{if(this.check(),this.owned(s),s.isCurrent!==r||!t.deviceCustodyCurrent(this.confirmedSelection(),i))throw q("fenced")};return this.exclusive(async()=>{if(a(),!this.state.nativeStarted)throw q("recovery_required");if(this.state.token)return this.view();if(!this.state.proof){await o.pending(new Uint8Array(i.envelope),{signal:this.lifetime.signal}),a();let d=Uint8Array.from(this.state.selection.challenge.match(/../g),f=>parseInt(f,16)),u=null;try{let f=t.signCpEnrol(d);u=f.signature,a(),await this.save({...this.state,proof:n.proof({sign_pk:In(f.signPublicKey),kem_pk:In(f.kemPublicKey),noise_pk:In(f.noisePublicKey),sig:In(u)})}),a()}finally{d.fill(0),u?.fill(0)}}let p=this.state.proof;if(p.sign_pk!==In(i.signPublicKey)||p.kem_pk!==In(i.kemPublicKey)||p.noise_pk!==In(i.noisePublicKey))throw q("binding");let{status:l,value:c}=await this.json(`/v1/pairing-requests/${this.state.requestId}/attest`,!0,p);if(a(),Ce(c,"ok"),l!==200||c.ok!==!0)throw q("response");return this.view()})}receipt(){let e=this.state,t=e.proof;if(this.check(),!e.token||!t||!e.selection)throw q("binding");let i=o=>Uint8Array.from(o.match(/../g),s=>parseInt(s,16));return Object.freeze({connectorId:e.selection.connectorId,deviceId:e.deviceId,installationId:e.installationId,signPublicKey:i(t.sign_pk),kemPublicKey:i(t.kem_pk),noisePublicKey:i(t.noise_pk)})}acknowledge(e){let{runtime:t,custody:i,persistence:o,installation:s}=e,r=s.isCurrent,a=()=>{if(this.check(),this.owned(s),s.isCurrent!==r||!t.deviceCustodyCurrent(this.confirmedSelection(),i))throw q("fenced")};return this.exclusive(async()=>{a();let p=this.receipt();if(In(p.signPublicKey)!==In(i.signPublicKey)||In(p.kemPublicKey)!==In(i.kemPublicKey)||In(p.noisePublicKey)!==In(i.noisePublicKey))throw q("binding");return await o.registered(p,{signal:this.lifetime.signal}),a(),t.acknowledgeDeviceRegistration(p),a(),this.nativeAcknowledged=!0,p})}originalTimerChannel(e){if(this.check(),this.receipt(),!this.state.timerConsent?.approved||!this.state.timerConsent.grants.some(i=>i.grantId===e))throw q("fenced");let t=this.state.timerChannel;return t?.grantId===e?t:null}retainTimerChannel(e,t){return this.exclusive(async()=>{if(this.originalTimerChannel(e),t!==null&&Mb(t).grantId!==e)throw q("binding");await this.save({...this.state,timerChannel:t===null?void 0:Mb(t)}),this.originalTimerChannel(e)})}session(e){return this.receipt(),this.confirmedHostSession(e,this.state.environment)}confirmedHostSession(e,t){let i=this.confirmedSelection();if(t!==this.state.environment)throw q("binding");let o=new URL(e);if(o.origin!==e||o.protocol!=="https:"&&!!1||o.username||o.password)throw q("binding");return Object.freeze({...i,logOrigin:e,timerConsent:()=>(this.check(),this.state.timerConsent??null),connectorBearer:async({signal:s})=>{if(this.check(),s.aborted||!this.state.token)throw q("fenced");return this.state.token}})}async close(){this.closed||(this.closed=!0,this.lifetime.abort(),this.parent.removeEventListener("abort",this.onAbort),this.state.secret="",this.state.token=null,this.state.consentRequest&&(this.state.consentRequest.secret=""),this.state.renewal&&(this.state.renewal.secret=""),this.state.renewal=null),await this.store.close()}}});function Na(n){if((typeof n!="number"||!Number.isSafeInteger(n))&&typeof n!="bigint")throw ae("shape");let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw ae("shape");return e}function Vf(n,e){let t=Na(n);if(t>BigInt(e))throw ae("shape");return Number(t)}function Vo(n){if(!(n instanceof Map))throw ae("shape");return n}function Kf(n){let e=[];for(let[t,i]of n){if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw ae("shape");e.push([t,i])}return new Map(e.sort(([t],[i])=>t-i))}function Ko(n,e){if(!(n instanceof Uint8Array)||e!==void 0&&n.length!==e)throw ae("shape");return n}function Wf(n,e){return n.length===e.length&&n.every((t,i)=>t===e[i])}function QP(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function ex(n){return btoa(String.fromCharCode(...n))}function Db(n,e){let t;try{t=new URL(n)}catch{throw ae("binding")}if(t.username||t.password||t.pathname!=="/"||t.search||t.hash||t.protocol!=="https:"&&!(e&&ot(n)))throw ae("binding");return t.origin}function tx(n,e){let t=n.headers.get("content-length");return t!==null&&/^(0|[1-9][0-9]*)$/.test(t)&&Number(t)>e}function Pq(n,e,t,i,o,s,r){let a=Ff.encode("mdbase/v1/ls-http"),p=Ff.encode(t),l=Ff.encode("/v1/rpc"),c=Ff.encode(o),d=it(c),u=it(s);c.fill(0);let f=new Uint8Array(1+a.length+p.length+1+l.length+1+16+96),h=0;for(let b of[Uint8Array.of(a.length),a,p,Uint8Array.of(0),l,Uint8Array.of(0),U(i),d,u,r])f.set(b,h),h+=b.length;let m=it(f);return f.fill(0),Object.freeze({endpoint:n,originalCallId:e,frame:s.slice(),token:o,method:t,path:"/v1/rpc",collection:i,nonce:r.slice(),bodyHash:u,tokenHash:d,digest:m})}function nx(n){return/^[0-9a-f]{64}$/.test(n)?Uint8Array.from(n.match(/../g).map(e=>parseInt(e,16))):null}function Oq(n){try{let e=ue(n).get(3);if(!(e instanceof Map))return!1;let t=e;return t.get(0)==="unauthenticated"&&(t.get(1)==="nonce"||t.get(1)==="replay")}catch{return!1}}var Ub,Jc,kq,Sq,Ff,mn,ae,xq,Cq,Iq,Ua,Xc=I(()=>{"use strict";bt();Cr();Je();ge();Fn();Ub=16*1024*1024,Jc=9*1024*1024,kq=new Set(["append","read","head","subscribe","unsubscribe","put_object","get_object","has_objects","put_snapshot","get_snapshot","endorse_snapshot","stream_join","stream_leave","stream_send"]),Sq=new Set(["host","content-length","transfer-encoding","connection","keep-alive","upgrade","te","trailer","expect","range","cookie","authorization","proxy-authorization","origin","referer","accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","date","dnt","permissions-policy","set-cookie","via"]),Ff=new TextEncoder,mn=class extends Error{constructor(t,i){super(`app log transport: ${t}`);this.reason=t;this.server=i;this.name="AppHttpLogError"}reason;server},ae=n=>new mn(n);xq=4e4,Cq=6,Iq="x-mdbase-next-nonce";Ua=class{constructor(e,t={}){this.authority=e;try{if(this.endpointId=Na(e.endpoint),this.endpoint=this.endpointId,this.collection=e.collection,this.collectionBytes=U(this.collection),this.loopback=t.allowLoopbackHttp===!0,this.base=Db(e.origin,this.loopback),!Array.isArray(e.directOrigins)||e.directOrigins.length>32)throw ae("binding");this.approved=new Set([this.base,...e.directOrigins.map(i=>Db(i,this.loopback))]),this.fetchImpl=t.fetch??globalThis.fetch,this.now=t.now??Date.now}catch{throw ae("binding")}}authority;endpoint;collection;endpointId;collectionBytes;base;approved;fetchImpl;now;loopback;commitId=(1n<<64n)-1n;spares=[];responseId=0;receiving=new Map;responseProgress(){return[...this.receiving].map(([e,t])=>({id:e,bytes:t}))}isCurrent(){try{return this.authority.isCurrent()===!0&&Na(this.authority.endpoint)===this.endpointId&&this.authority.collection===this.collection&&Db(this.authority.origin,this.loopback)===this.base}catch{return!1}}check(e){if(e.aborted||!this.isCurrent())throw ae("fenced")}request(e){if(e.length>Ub)throw ae("shape");let t=Vo(ue(e));if(t.get(0)!==0||typeof t.get(2)!="string")throw ae("shape");let i=t.get(2),o=Vo(t.get(3));if(!kq.has(i)||!Wf(Ko(o.get(0),16),this.collectionBytes))throw ae("shape");return{id:Na(t.get(1)),method:i,params:o}}response(e,t){let i=Vo(ue(e));if(i.get(0)!==1||Na(i.get(1))!==t||i.has(2)===i.has(3))throw ae("shape");return i}async fetch(e,t,i,o){this.check(i);let s=new AbortController,r=()=>s.abort();i.addEventListener("abort",r,{once:!0});let a=setTimeout(r,o);a.unref?.();try{let p=this.fetchImpl,l=(t.method??"GET")==="GET"?"no-store":"default",c=await p(e,{...t,signal:s.signal,redirect:"error",credentials:"omit",cache:l,referrerPolicy:"no-referrer"});if(!this.isCurrent()||i.aborted)throw c.body?.cancel().catch(()=>{}),ae("fenced");return this.withCleanup(c,()=>{clearTimeout(a),i.removeEventListener("abort",r)})}catch{throw clearTimeout(a),i.removeEventListener("abort",r),ae(i.aborted||!this.isCurrent()?"fenced":"unavailable")}}cleanups=new WeakMap;withCleanup(e,t){return this.cleanups.set(e,t),e}release(e){this.cleanups.get(e)?.(),this.cleanups.delete(e)}async read(e,t,i,o){let s=new Uint8Array(Math.min(1024,t)),r=0,a=null;try{if(this.check(i),tx(e,t))throw ae("integrity");if(!e.body)return s.subarray(0,0);for(a=e.body.getReader();;){let{done:p,value:l}=await a.read();try{if(this.check(i),p)break;if(r+l.length>t)throw ae("integrity");if(r+l.length>s.length){let c=new Uint8Array(Math.min(t,Math.max(s.length*2,r+l.length)));c.set(s.subarray(0,r)),s.fill(0),s=c}s.set(l,r),r+=l.length,o(l.length)}finally{l?.fill(0)}}return s.subarray(0,r)}catch(p){throw s.fill(0),(a?.cancel()??e.body?.cancel())?.catch(()=>{}),p}finally{a?.releaseLock(),this.release(e)}}async refusal(e,t,i){let o;try{let r=await this.read(e,8192,t,i);try{o=Vs(r)}finally{r.fill(0)}}catch(r){if(r instanceof mn&&r.reason==="fenced")return r;o=void 0}let s=Li(e.status,o,e.headers);return new mn(St(s)??"unavailable",s)}takeSpare(){for(let e=this.spares.pop();e;e=this.spares.pop()){let t=this.now()-e.at;if(t>=0&&t<xq)return e.nonce;e.nonce.fill(0)}return null}keepSpare(e){let t=nx(e.headers.get(Iq)??"");if(t)for(this.spares.push({nonce:t,at:this.now()});this.spares.length>Cq;)this.spares.shift().nonce.fill(0)}async freshNonce(e,t){let i=await this.fetch(`${this.base}/v1/nonce`,{},e,15e3);if(!i.ok)throw await this.refusal(i,e,t);let o=await this.read(i,128,e,t);try{this.check(e);let s=nx(new TextDecoder("utf-8",{fatal:!0}).decode(o).trim());if(!s)throw ae("shape");return s}finally{o.fill(0)}}async rpc(e,t,i,o,s,r=i,a=!0){this.check(o);let p=await this.authority.accessToken({signal:o});if(this.check(o),typeof p!="string"||!p||p.length>16*1024||/[\r\n]/.test(p))throw ae("shape");let l=a?this.takeSpare():null,c=l??await this.freshNonce(o,s);this.check(o);let d=Pq(this.endpoint,r,t,this.collection,p,e,c);c.fill(0);let u=null;try{if(u=await this.authority.signLogProof(d,{signal:o}),this.check(o),!(u instanceof Uint8Array)||u.length!==64)throw ae("shape");let f=await this.fetch(`${this.base}/v1/rpc`,{method:"POST",headers:{authorization:`Bearer ${p}`,"content-type":"application/cbor","x-mdbase-nonce":QP(d.nonce),"x-mdbase-sig":QP(u)},body:e},o,15e3);if(this.keepSpare(f),f.status===401&&this.authority.invalidateToken?.(p),!f.ok)throw await this.refusal(f,o,s);let h=await this.read(f,t==="append"?64*1024:Ub,o,s);try{this.check(o),this.response(h,i)}catch(m){throw h.fill(0),m}return l&&Oq(h)?(h.fill(0),await this.rpc(e,t,i,o,s,r,!1)):h}finally{u?.fill(0),d.frame.fill(0),d.nonce.fill(0),d.bodyHash.fill(0),d.tokenHash.fill(0),d.digest.fill(0)}}direct(e,t){let i=Vo(e),o=i.get(0),s=Vo(i.get(1)),r=i.get(2);if(typeof o!="string"||o.length>16*1024||typeof r!="number"||!Number.isSafeInteger(r))throw ae("shape");let a;try{a=new URL(o)}catch{throw ae("shape")}if(a.username||a.password||a.hash||!this.approved.has(a.origin))throw ae("binding");let p=new Headers,l=new Set;if(s.size>32)throw ae("shape");for(let[c,d]of s){if(typeof c!="string"||typeof d!="string")throw ae("shape");let u=c.toLowerCase();if(!/^[a-z0-9!#$%&'*+.^_`|~-]+$/.test(u)||Sq.has(u)||u.startsWith("proxy-")||u.startsWith("sec-")||u.startsWith("x-mdbase-")||u.startsWith("x-http-method")||l.has(u)||d.length>8*1024||/[\r\n]/.test(d))throw ae("shape");if(u==="x-amz-checksum-sha256"&&d!==ex(t))throw ae("integrity");l.add(u),p.set(u,d)}if(r-this.now()<=5e3)throw ae("unavailable");return{url:a.href,headers:p,expires:r}}timeout(e,t){let i=e.expires-this.now();if(i<=5e3)throw ae("unavailable");return Math.min(i,3e4+Math.ceil(t/(128*1024))*1e3)}async upload(e,t,i){this.check(i);let o;try{o=await this.fetch(e.url,{method:"PUT",headers:e.headers,body:t},i,this.timeout(e,t.length))}catch(s){if(this.check(i),s instanceof mn&&s.reason==="unavailable")return;throw s}try{if(this.check(i),o.ok||o.status===408||o.status===425||o.status===429||o.status>=500)return;throw ae("unavailable")}finally{o.body?.cancel().catch(()=>{}),this.release(o)}}async download(e,t,i,o,s){let r=new Uint8Array(t),a=0,p=0;try{for(let l=0;l<32&&p<5;l++){this.check(o);let c=a,d=new Headers(e.headers);c>0&&d.set("range",`bytes=${c}-${t-1}`);let u;try{u=await this.fetch(e.url,{headers:d},o,this.timeout(e,t-c))}catch{this.check(o),p++;continue}let f=null;try{if(this.check(o),[401,403,404,410].includes(u.status))throw ae("unavailable");if([408,425,429].includes(u.status)||u.status>=500){p++;continue}if(u.status!==(c===0?200:206)||tx(u,t-c)||(c>0?u.headers.get("content-range")!==`bytes ${c}-${t-1}/${t}`:u.headers.has("content-range"))||u.headers.has("content-encoding")&&u.headers.get("content-encoding")!=="identity")throw ae("integrity");let h=u.headers.get("x-amz-checksum-sha256");if(h!==null&&h!==ex(i)||!u.body)throw ae("integrity");for(f=u.body.getReader();;){let m;try{m=await f.read()}catch{this.check(o);break}try{if(this.check(o),m.done)break;if(m.value.length>t-a)throw ae("integrity");r.set(m.value,a),a+=m.value.length,s(m.value.length)}finally{m.value?.fill(0)}}}finally{(f?.cancel()??u.body?.cancel())?.catch(()=>{}),f?.releaseLock(),this.release(u)}if(a===t){if(!Wf(it(r),i))throw ae("integrity");return r}p=a>c?0:p+1}throw ae("unavailable")}catch(l){throw r.fill(0),l}}async send(e,t){let i=null,o=null,s=null,r=null,a=null,p=++this.responseId,l=0;this.receiving.set(p,l);let c=d=>{l+=d,this.receiving.set(p,l)};try{if(this.check(t.signal),Na(e.endpoint)!==this.endpointId||!(e.frame instanceof Uint8Array)||e.frame.length>Ub||e.sidecar!==void 0&&(!(e.sidecar instanceof Uint8Array)||e.sidecar.length>Jc))throw ae("shape");i=e.frame.slice(),o=e.sidecar?.slice()??null;let d=this.request(i);if(o&&d.method!=="put_object")throw ae("shape");if(d.method==="put_object"){let h=Vf(d.params.get(3),Jc),m=Ko(d.params.get(4),32),b=d.params.get(5);if(h===0||o!==null&&(b!==void 0||o.length<=1024*1024)||o===null&&h>1024*1024)throw ae("shape");let w=o??Ko(b);if(w.length!==h||!Wf(it(w),m))throw ae("integrity")}s=await this.rpc(i,d.method,d.id,t.signal,c),this.check(t.signal);let u=this.response(s,d.id);if(u.has(3)){let h=s;return s=null,h}if(d.method==="put_object"){let h=Vo(u.get(2)),m=h.get(0);if(m===0||m===2){if(h.has(1))throw ae("shape");let _=s;return s=null,_}if(m!==1||!o)throw ae("shape");let b=Ko(d.params.get(4),32),w=Ko(d.params.get(1),32);if(await this.upload(this.direct(h.get(1),b),o,t.signal),this.check(t.signal),this.commitId===d.id||this.commitId===0n)throw ae("unavailable");let g=this.commitId--;a=pe(new Map([[0,0],[1,g],[2,"commit_object"],[3,new Map([[0,this.collectionBytes],[1,w]])]]));let y=await this.rpc(a,"commit_object",g,t.signal,c,d.id);try{this.check(t.signal);let _=this.response(y,g),k=_.get(2);if(_.has(3)||!(k instanceof Map)||k.size!==1||k.get(0)!==!0)throw ae("unavailable")}finally{y.fill(0)}let v=new Map(h);return v.delete(1),v.set(0,0),u.set(2,Kf(v)),pe(Kf(u))}if(d.method==="get_object"){let h=Vo(u.get(2)),m=Vf(h.get(2),Jc),b=Ko(h.get(3),32);if(m===0||h.has(0)===h.has(1))throw ae("shape");let w=d.params.get(2),g=0,y=m;if(w!==void 0&&(!Array.isArray(w)||w.length!==2||(g=Vf(w[0],Jc),y=Vf(w[1],Jc),g>m||y>m-g)))throw ae("shape");if(h.has(0)){let _=Ko(h.get(0));if(_.length!==y||y===m&&!Wf(it(_),b))throw ae("integrity");let k=s;return s=null,k}r=await this.download(this.direct(h.get(1),b),m,b,t.signal,c),this.check(t.signal);let v=new Map(h);return v.delete(1),v.set(0,r.subarray(g,g+y)),u.set(2,Kf(v)),pe(Kf(u))}let f=s;return s=null,f}catch(d){if(d instanceof mn)throw d;if(t.signal.aborted||!this.isCurrent())throw ae("fenced");let u=null;try{u=d.server}catch{}let f=kn(u)?St(u):null;throw f&&kn(u)?new mn(f,u):ae("unavailable")}finally{this.receiving.delete(p),i?.fill(0),o?.fill(0),s?.fill(0),r?.fill(0),a?.fill(0)}}}});function ix(n,e){let t;try{t=new URL(n)}catch{throw st("binding")}if(t.username||t.password||t.pathname!=="/"||t.search||t.hash||t.protocol!=="https:"&&!(e&&ot(n)))throw st("binding");return t.origin}function rx(n){if(typeof n=="number"&&!Number.isSafeInteger(n))throw st("binding");let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw st("binding");return e}function Rq(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function Eq(n){if(!n||typeof n!="object"||Array.isArray(n))throw st("response");return n}var Zn,st,$b,Da,Zc=I(()=>{"use strict";bt();ge();Xc();Fn();Zn=class extends Error{constructor(t,i){super(`app CP authority: ${t}`);this.reason=t;this.server=i;this.name="AppCpAuthorityError"}reason;server},st=n=>new Zn(n),$b=n=>new Zn(St(n)??"unavailable",n);Da=class{constructor(e,t,i={}){this.runtime=e;this.session=t;this.tokenCache=i.tokenCache??null;try{this.endpoint=rx(t.endpoint),this.collection=t.collection,this.connectorId=t.connectorId,this.deviceId=t.deviceId;for(let o of[this.collection,this.connectorId,this.deviceId])if(U(o).every(r=>r===0))throw st("binding");if(this.rawCpOrigin=t.cpOrigin,this.rawLogOrigin=t.logOrigin,this.cpOrigin=ix(this.rawCpOrigin,i.allowLoopbackHttp===!0),this.origin=ix(this.rawLogOrigin,i.allowLoopbackHttp===!0),this.directOrigins=Object.freeze([...t.directOrigins]),this.now=i.now??Date.now,this.fetchImpl=i.fetch??globalThis.fetch,this.transport=new Ua(this,i),!this.scopeCurrent())throw st("binding");e.bindCpConnector(t)}catch{throw st("binding")}}runtime;session;endpoint;collection;origin;directOrigins;cpOrigin;connectorId;deviceId;rawCpOrigin;rawLogOrigin;now;fetchImpl;lifetime=new AbortController;authenticated=!1;token=null;tokenCache;cacheTried=!1;transport;scopeCurrent(){try{return!this.lifetime.signal.aborted&&this.session.isCurrent()===!0&&rx(this.session.endpoint)===this.endpoint&&this.session.collection===this.collection&&this.session.connectorId===this.connectorId&&this.session.deviceId===this.deviceId&&this.session.cpOrigin===this.rawCpOrigin&&this.session.logOrigin===this.rawLogOrigin}catch{return!1}}isCurrent(){return this.authenticated&&this.scopeCurrent()}check(e){if(!this.scopeCurrent())throw this.close(),st("fenced");if(e.aborted)throw st("fenced")}logTransport(){if(!this.isCurrent())throw st("fenced");return this.transport}async signLogProof(e,t){if(this.check(t.signal),!this.authenticated)throw st("fenced");return this.runtime.signLogHttp(e)}async json(e,t,i,o){this.check(o);let s=new AbortController,r=()=>s.abort();o.addEventListener("abort",r,{once:!0}),this.lifetime.signal.addEventListener("abort",r,{once:!0});let a=setTimeout(r,15e3);a.unref?.();let p=null,l=null,c=new Uint8Array(32*1024),d=0;try{let u=this.fetchImpl;if(p=await u(`${this.cpOrigin}${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,...i===void 0?{}:{"content-type":"application/json"}},body:i,signal:s.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(o),s.signal.aborted)throw st("unavailable");let f=p.headers.get("content-length");if(f!==null&&/^(0|[1-9][0-9]*)$/.test(f)&&Number(f)>c.length)throw s.abort(),p.ok?st("unavailable"):$b(Li(p.status,void 0,p.headers));if(!p.body)throw p.ok?st("response"):$b(Li(p.status,void 0,p.headers));for(l=p.body.getReader();;){let{done:h,value:m}=await l.read();try{if(this.check(o),s.signal.aborted)throw st("unavailable");if(h)break;if(d+m.length>c.length)throw s.abort(),st("response");c.set(m,d),d+=m.length}finally{m?.fill(0)}}if(!p.ok)throw $b(Li(p.status,Vs(c.subarray(0,d)),p.headers));return Eq(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c.subarray(0,d))))}catch(u){throw this.check(o),u instanceof Zn?u:st("unavailable")}finally{c.fill(0),(l?.cancel()??p?.body?.cancel())?.catch(()=>{}),l?.releaseLock(),clearTimeout(a),o.removeEventListener("abort",r),this.lifetime.signal.removeEventListener("abort",r)}}async accessToken(e){let t=null,i=null;try{if(this.check(e.signal),this.token&&this.token.expires-this.now()>5e3)return this.token.value;if(!this.token&&this.tokenCache&&!this.cacheTried){this.cacheTried=!0;let p=await this.tokenCache.read(this.cacheKey(),this.now());if(this.check(e.signal),p)return this.token={value:p.value,expires:p.expires},this.authenticated=!0,p.value}let o=await this.session.connectorBearer(e);if(this.check(e.signal),typeof o!="string"||!o||o.length>16*1024||/[^\x21-\x7e]/.test(o))throw st("binding");let s=await this.json("/v1/next/devices/challenge",o,void 0,e.signal);if(this.check(e.signal),typeof s.challenge!="string"||!/^[0-9a-f]{64}$/.test(s.challenge)||typeof s.expires_at!="number"||!Number.isSafeInteger(s.expires_at)||s.expires_at-this.now()<=5e3||(t=Uint8Array.from(s.challenge.match(/../g).map(p=>parseInt(p,16))),i=this.runtime.signCpLogToken(t),this.check(e.signal),!(i instanceof Uint8Array)||i.length!==64))throw st("response");let r=JSON.stringify({device_id:this.deviceId,challenge:s.challenge,sig:Rq(i),capabilities:["collection_mode_switch_v1"]}),a=await this.json(`/v1/next/collections/${this.collection}/log-token`,o,r,e.signal);if(this.check(e.signal),typeof a.token!="string"||!a.token||a.token.length>16*1024||/[^\x21-\x7e]/.test(a.token)||typeof a.expires_at!="number"||!Number.isSafeInteger(a.expires_at)||a.expires_at-this.now()<=5e3||a.expires_at-this.now()>16*6e4)throw st("response");return this.token={value:a.token,expires:a.expires_at},this.authenticated=!0,this.tokenCache?.write(this.cacheKey(),this.token).catch(()=>{}),a.token}catch(o){throw o instanceof Zn?o:st(this.scopeCurrent()?"unavailable":"fenced")}finally{t?.fill(0),i?.fill(0)}}cacheKey(){return[this.rawCpOrigin,this.rawLogOrigin,this.connectorId,this.deviceId,this.collection].join(" ")}invalidateToken(e){this.token?.value===e&&(this.token=null,this.tokenCache?.drop(this.cacheKey()).catch(()=>{}))}close(){this.lifetime.signal.aborted||(this.lifetime.abort(),this.token=null,this.authenticated=!1,this.runtime.retireLog())}}});function zb(n,e){if(typeof n!="string"||!n.length||n.length%2||n.length>e*2||!/^[0-9a-f]+$/.test(n))throw ke("response");return Uint8Array.from(n.match(/../g),t=>parseInt(t,16))}function Bb(n){if(!n||typeof n!="object"||Array.isArray(n))throw ke("response");return n}var en,ke,qq,Hf,ox,$a,Qc=I(()=>{"use strict";ge();bt();Fc();Fn();en=class extends Error{constructor(t,i=!1,o){super(`app cloud copy bootstrap: ${t}`);this.reason=t;this.retryable=i;this.server=o;this.name="AppCloudCopyBootstrapError"}reason;retryable;server},ke=(n,e=!1)=>new en(n,e),qq=new Set([408,429,500,502,503,504]),Hf=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),ox=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join("");$a=class{constructor(e,t,i,o,s={}){this.runtime=e;this.session=t;this.trust=i;this.persistence=o;try{if(this.storageCallbacks=Object.freeze({restore:o.restore,pending:o.pending,completed:o.completed}),this.scope=Object.freeze({accountId:t.accountId,connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId,collection:t.collection,purpose:t.purpose,cpOrigin:t.cpOrigin,logOrigin:t.logOrigin}),this.callbacks=Object.freeze({current:t.isCurrent,owned:t.installationOwned,bearer:t.connectorBearer}),this.local=Xr(i.environment),!1)throw ke("binding");this.loopback=s.allowLoopbackHttp===!0||this.local;for(let p of[this.scope.accountId,this.scope.connectorId,this.scope.deviceId,this.scope.installationId,this.scope.collection])if(U(p).every(l=>l===0))throw ke("binding");if(this.origin(this.scope.cpOrigin),this.origin(this.scope.logOrigin),i.schema!=="mdbn-app-trust/release/1"||!(["lab","staging","production"].includes(i.environment)||this.loopback&&i.environment==="test"||this.local)||i.cpOrigin!==this.scope.cpOrigin||i.logOrigin!==this.scope.logOrigin||!/^[0-9a-f]{64}$/.test(i.assetSha256)||i.source.repository!=="mdbase-dev/mdbase-connect"||!/^[0-9a-f]{40}$/.test(i.source.commit)||!i.source.version||i.source.version.length>64||!Array.isArray(i.trustedRoots)||i.trustedRoots.length<1||i.trustedRoots.length>64||!(i.policyPins instanceof Uint8Array)||!i.policyPins.length||i.policyPins.length>65536)throw ke("binding");this.trustFields=Object.freeze({schema:i.schema,environment:i.environment,assetSha256:i.assetSha256,...i.source}),this.roots=Object.freeze(i.trustedRoots.map(p=>{if(!(p instanceof Uint8Array)||p.length!==32||p.every(l=>l===0))throw ke("binding");return new Uint8Array(p)})),this.pins=new Uint8Array(i.policyPins);let r=s.displayName,a=r===void 0?void 0:br(r);if(a!==void 0&&this.scope.purpose!=="create"||(this.operation=Object.freeze({...e.registeredDeviceReceipt(),...a===void 0?{}:{displayName:a},accountId:this.scope.accountId,collection:this.scope.collection,purpose:this.scope.purpose,assetSha256:i.assetSha256,cpOrigin:this.scope.cpOrigin,logOrigin:this.scope.logOrigin}),this.request=s.fetch??globalThis.fetch,this.now=s.now??Date.now,!this.current()))throw ke("binding")}catch{throw e.retireLog(),ke("binding")}}runtime;session;trust;persistence;attempted=!1;adopted=!1;originalSignal=null;completion=null;lifetime=new AbortController;scope;callbacks;trustFields;roots;pins;operation;storageCallbacks;request;now;loopback;local;origin(e){if(this.local&&!Ra(e))throw ke("binding");let t=new URL(e);if(t.origin!==e||t.username||t.password||t.protocol!=="https:"&&!(this.loopback&&ot(e)))throw ke("binding");return t.origin}current(){try{let e=this.session,t=this.trust,i=this.trustFields;return!this.lifetime.signal.aborted&&!this.originalSignal?.aborted&&(this.adopted||this.runtime.cloudCopyCollectionCurrent(e))&&this.persistence.restore===this.storageCallbacks.restore&&this.persistence.pending===this.storageCallbacks.pending&&this.persistence.completed===this.storageCallbacks.completed&&e.isCurrent===this.callbacks.current&&e.installationOwned===this.callbacks.owned&&e.connectorBearer===this.callbacks.bearer&&this.callbacks.current.call(e)===!0&&this.callbacks.owned.call(e)===!0&&Object.entries(this.scope).every(([o,s])=>e[o]===s)&&t.cpOrigin===this.scope.cpOrigin&&t.logOrigin===this.scope.logOrigin&&t.schema===i.schema&&t.environment===i.environment&&t.assetSha256===i.assetSha256&&t.source.repository===i.repository&&t.source.commit===i.commit&&t.source.version===i.version&&t.trustedRoots.length===this.roots.length&&t.trustedRoots.every((o,s)=>Hf(o,this.roots[s]))&&Hf(t.policyPins,this.pins)}catch{return!1}}check(e){if(e.aborted||!this.current())throw this.close(),ke("fenced")}operationCopy(e){for(let t of["accountId","connectorId","deviceId","installationId","collection","purpose","cpOrigin","logOrigin","assetSha256","displayName"])if(e[t]!==this.operation[t])throw ke("response");for(let t of["signPublicKey","kemPublicKey","noisePublicKey"])if(!(e[t]instanceof Uint8Array)||!Hf(e[t],this.operation[t]))throw ke("response");return Object.freeze({...this.operation,signPublicKey:new Uint8Array(this.operation.signPublicKey),kemPublicKey:new Uint8Array(this.operation.kemPublicKey),noisePublicKey:new Uint8Array(this.operation.noisePublicKey)})}copy(e){if(!(e.genesisItem instanceof Uint8Array)||!e.genesisItem.length||e.genesisItem.length>256*1024||!/^sha256:[0-9a-f]{64}$/.test(e.expectedGenesis))throw ke("response");return Object.freeze({operation:this.operationCopy(e.operation),genesisItem:new Uint8Array(e.genesisItem),expectedGenesis:e.expectedGenesis})}async hash(e,t){let i=new TextEncoder().encode("mdbase/v1/chain"),o=new Uint8Array(1+i.length+e.length);o[0]=i.length,o.set(i,1),o.set(e,1+i.length);let s=new Uint8Array(await crypto.subtle.digest("SHA-256",o));return this.check(t),`sha256:${ox(s)}`}async json(e,t,i,o){this.check(o);let s=new AbortController,r=()=>s.abort(),a=setTimeout(r,15e3);a.unref?.(),o.addEventListener("abort",r,{once:!0}),this.lifetime.signal.addEventListener("abort",r,{once:!0});let p=new Uint8Array(1024*1024),l=0,c=null,d=null;try{let u=this.request;if(c=await u(`${this.scope.cpOrigin}${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,...i===void 0?{}:{"content-type":"application/json"}},body:i,signal:s.signal,redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer"}),this.check(o),s.signal.aborted)throw ke("unavailable",!0);if(!c.ok){let h=await this.problem(c,o),m=St(h),b=!m&&qq.has(c.status);throw new en(m??(b?"unavailable":"refused"),b,h)}let f=c.headers.get("content-length");if(f!==null&&/^(0|[1-9][0-9]*)$/.test(f)&&Number(f)>p.length)throw s.abort(),ke("response");if(!c.body)throw ke("response");for(d=c.body.getReader();;){let{done:h,value:m}=await d.read();try{if(this.check(o),s.signal.aborted)throw ke("unavailable",!0);if(h)break;if(l+m.length>p.length)throw s.abort(),ke("response");p.set(m,l),l+=m.length}finally{m?.fill(0)}}try{return Bb(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(p.subarray(0,l))))}catch{throw ke("response")}}catch(u){throw this.check(o),u instanceof en?u:ke("unavailable",!0)}finally{p.fill(0),(d?.cancel()??c?.body?.cancel())?.catch(()=>{}),d?.releaseLock(),clearTimeout(a),o.removeEventListener("abort",r),this.lifetime.signal.removeEventListener("abort",r)}}async problem(e,t){let i=new Uint8Array(8192),o=0,s=e.body?.getReader();try{for(;s;){let{done:r,value:a}=await s.read();try{if(this.check(t),r)break;if(o+a.length>i.length){o=0;break}i.set(a,o),o+=a.length}finally{a?.fill(0)}}}catch{this.check(t),o=0}finally{s?.cancel().catch(()=>{}),s?.releaseLock()}try{return Li(e.status,o?Vs(i.subarray(0,o)):void 0,e.headers)}finally{i.fill(0)}}async challenge(e,t){for(let i=0;i<3;i++)try{return await this.json("/v1/next/devices/challenge",e,void 0,t)}catch(o){if(!(o instanceof en)||o.reason!=="unavailable"||!o.retryable||i===2)throw o;this.check(t),await new Promise((s,r)=>{let a=()=>{clearTimeout(l),t.removeEventListener("abort",p),this.lifetime.signal.removeEventListener("abort",p);try{this.check(t),s()}catch(c){r(c)}},p=()=>a(),l=setTimeout(a,i===0?250:1e3);l.unref?.(),t.addEventListener("abort",p,{once:!0}),this.lifetime.signal.addEventListener("abort",p,{once:!0}),(t.aborted||this.lifetime.signal.aborted)&&a()})}throw ke("unavailable",!0)}async bootstrap(e){let{signal:t,reconcile:i}=e,o=Object.freeze({signal:t}),s=null,r=null;try{if(this.originalSignal??=t,t!==this.originalSignal||(this.check(t),this.attempted))throw ke("fenced");this.attempted=!0;let a=await this.storageCallbacks.restore.call(this.persistence,o);if(this.check(t),a.state==="completed"){let b=this.copy(a.metadata);if(await this.hash(b.genesisItem,t)!==b.expectedGenesis)throw ke("response");return this.completion=this.copy(b),b}if(a.state==="pending"){if(this.operationCopy(a.operation),i!=="explicit-unknown-outcome")throw ke("outcome_unknown")}else if(a.state!=="none")throw ke("response");await this.storageCallbacks.pending.call(this.persistence,this.operationCopy(this.operation),o),this.check(t);let p=await this.callbacks.bearer.call(this.session,o);if(this.check(t),typeof p!="string"||!p||p.length>16384||/[^\x21-\x7e]/.test(p))throw ke("binding");let l=await this.challenge(p,t);if(s=zb(l.challenge,32),s.length!==32||typeof l.expires_at!="number"||!Number.isSafeInteger(l.expires_at)||l.expires_at-this.now()<=5e3||l.expires_at-this.now()>16*6e4)throw ke("response");let c=this.scope.purpose==="create";if(r=c?this.runtime.signCloudCopyCreate(s):this.runtime.signCloudCopyJoin(s),this.check(t),r.length!==64)throw ke("response");let d;try{d=await this.json(c?"/v1/next/collections/cloud-copy":`/v1/next/collections/${this.scope.collection}/devices`,p,JSON.stringify({device_id:this.scope.deviceId,capabilities:["collection_mode_switch_v1"],challenge:l.challenge,sig:ox(r),...c?{collection_id:this.scope.collection,...this.operation.displayName===void 0?{}:{display_name:this.operation.displayName}}:{}}),t)}catch(b){throw b instanceof en&&b.reason==="unavailable"?ke("outcome_unknown"):b}if(d.collection_id!==this.scope.collection||d.log_url!==this.scope.logOrigin)throw ke("response");if(c){let b=zb(d.root_public_key,32);if(d.state!=="cloud-copy"||d.owner_account!==this.scope.accountId||!this.roots.some(w=>Hf(w,b)))throw ke("response")}else if(typeof d.enrolled_at!="number"||!Number.isSafeInteger(d.enrolled_at)||d.enrolled_at<1)throw ke("response");let u=Bb(d.device);if(u.device_id!==this.scope.deviceId||typeof u.token!="string"||!u.token||u.token.length>16384||/[^\x21-\x7e]/.test(u.token)||typeof u.expires_at!="number"||!Number.isSafeInteger(u.expires_at)||u.expires_at-this.now()<=5e3||u.expires_at-this.now()>16*6e4)throw ke("response");let f=Bb(d.genesis);if(f.seq!==1)throw ke("response");let h=zb(f.item,256*1024),m=this.copy({operation:this.operation,genesisItem:h,expectedGenesis:await this.hash(h,t)});return await this.storageCallbacks.completed.call(this.persistence,this.copy(m),o),this.check(t),this.completion=this.copy(m),m}catch(a){throw this.close(),a instanceof en?a:ke("unavailable")}finally{s?.fill(0),r?.fill(0)}}adoptCollection(e,t){let{signal:i,replicaId:o,endpoint:s,opened:r,sqliteVersion:a,cloudCopyOptIn:p}=e;try{if(this.check(i),this.adopted||!this.completion||i!==this.originalSignal||p!==!0)throw ke("binding");let l={replicaId:o,endpoint:s,opened:r,sqliteVersion:a,collection:this.scope.collection,deviceId:this.scope.deviceId,state:"cloud_copy",cloudCopyOptIn:!0,trustedRoots:this.roots.map(c=>new Uint8Array(c)),policyPins:new Uint8Array(this.pins),trustedSigners:[],expectedGenesis:this.completion.expectedGenesis};this.runtime.adoptDevice(l,t),this.adopted=!0,this.check(i)}catch(l){throw this.close(),l instanceof en?l:ke("unavailable")}}close(){this.completion=null,this.lifetime.abort(),this.runtime.retireLog()}}});function ax(n){try{if(n instanceof vi)return n;if(n instanceof Xe){if(n.reason==="outcome_unknown")return new vi("collection_delete_outcome_unknown");if(n.reason==="binding")return new vi("collection_delete_invalid");let e=Ur(n.server)?.code;if(e&&Object.hasOwn(sx,e))return new vi(sx[e]);if(n.reason==="refused"&&!n.server)return new vi("collection_delete_not_approved")}}catch{}return new vi("collection_delete_failed")}var vi,sx,lx=I(()=>{"use strict";Yc();Fn();vi=class extends Error{constructor(t){super(`collection delete: ${t}`);this.code=t;this.name="AppCollectionDeleteError"}code},sx=Object.assign(Object.create(null),{collection_name_mismatch:"collection_delete_name_mismatch",not_owner:"collection_delete_not_owner",not_found:"collection_delete_not_found",migration_frozen:"collection_delete_frozen",busy:"collection_delete_busy",not_member:"collection_delete_not_approved",device_not_enrolled:"collection_delete_not_approved",installation_collection_not_approved:"collection_delete_not_approved",installation_not_current:"collection_delete_sign_in",identity_not_current:"collection_delete_sign_in",device_revoked:"collection_delete_sign_in",invalid_request:"collection_delete_invalid"})});function cx(n){return typeof n=="string"&&/^[a-zA-Z0-9_-]{16,128}$/.test(n)}function Fb(n,e){let t=()=>{throw new Se("application_worker_binding")};if(!Array.isArray(n)||n.length!==5||n[0]!==Qn||n[1]!==e||!Number.isInteger(n[2])||n[2]<0||n[2]>Gf||n[2]===0&&n[3]!=="foreground"&&n[3]!=="approvalClosed"||n[2]!==0&&n[3]==="approvalClosed")return t();let i=n[3],o=n[4];["start","authorize","renewExpiredPairing","select","clearSelection","forget","refreshCollections","signOut","deleteCollection","requestFileAccess","pollFileAccess","foreground","approvalClosed","close"].includes(i)||t();let s=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;if(i==="requestFileAccess")return(!Array.isArray(o)||o.length!==3||typeof o[0]!="string"||!s.test(o[0])||!Array.isArray(o[1])||!o[1].length||o[1].length>6||o[1].some(r=>typeof r!="string"||!["list","read","add","replace","move","delete"].includes(r))||typeof o[2]!="string"||!o[2]||o[2].length>140)&&t(),Object.freeze([n[0],n[1],n[2],i,Object.freeze([o[0],Object.freeze([...o[1]]),o[2]])]);if(i==="pollFileAccess")(typeof o!="string"||!s.test(o))&&t();else if(i==="select"||i==="forget")(typeof o!="string"||!o||o.length>256||/[\u0000-\u001f\u007f]/.test(o))&&t();else{if(i==="deleteCollection")return(!Array.isArray(o)||o.length!==2||typeof o[0]!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(o[0])||typeof o[1]!="string"||!o[1]||o[1].length>1024)&&t(),Object.freeze([n[0],n[1],n[2],i,Object.freeze([o[0],o[1]])]);i==="authorize"?o!==null&&(typeof o!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(o)||o==="00000000-0000-0000-0000-000000000000")&&t():i==="foreground"?typeof o!="boolean"&&t():i==="approvalClosed"?o!==!0&&t():o!==null&&t()}return Object.freeze([...n])}var Qn,Gf,Se,Yf=I(()=>{"use strict";Qn="mdbn-application-worker/1",Gf=4294967295,Se=class extends Error{constructor(t){super("SDK application Worker unavailable");this.code=t;this.name="ApplicationWorkerError"}code}});function Jf(n){let e=n.cpOrigin,t=n.signal,i=n.isCurrent,o=n.open,s=()=>{let f=!1;try{f=!t.aborted&&i()===!0}catch{}if(!f)throw new Nt("application_popup_fenced")};s();let r;try{r=new URL(e)}catch{throw new Nt("application_popup_binding")}let a=n.allowLoopbackHttp===!0&&ot(e);if(r.origin!==e||r.username||r.password||r.search||r.hash||r.pathname!=="/"||r.protocol!=="https:"&&!a)throw new Nt("application_popup_binding");let p;try{p=o()}catch{throw new Nt("application_popup_unavailable")}if(p===null)throw new Nt("application_popup_blocked");if(px.has(p))throw new Nt("application_popup_binding");px.add(p);let l=!1,c=null,d=()=>{if(l){if(c)throw c;return}l=!0,t.removeEventListener("abort",u);try{p.close()}catch{throw c=new Nt("application_popup_stop_failed"),c}},u=()=>{try{d()}catch{}};t.addEventListener("abort",u,{once:!0});try{s()}catch(f){throw d(),f}return Object.freeze({close:d,get closed(){try{return l||p.closed?.()===!0}catch{return!1}},focus(){if(s(),!l){try{p.focus?.()}catch{throw new Nt("application_popup_unavailable")}s()}},navigate(f){if(s(),l)throw new Nt("application_popup_fenced");let h;try{h=new URL(f)}catch{throw new Nt("application_popup_binding")}if(h.origin!==e||h.username||h.password)throw new Nt("application_popup_binding");try{p.navigate(h.href)}catch(m){throw m instanceof Nt?m:new Nt("application_popup_unavailable")}if(s(),l)throw new Nt("application_popup_fenced")}})}function Tq(){let n=0,e=0;try{let t=globalThis.window;n=Math.max(0,Math.round(t.screenX+(t.outerWidth-ux)/2)),e=Math.max(0,Math.round(t.screenY+(t.outerHeight-fx)/2))}catch{}return`popup,width=${ux},height=${fx},left=${Number.isFinite(n)?n:0},top=${Number.isFinite(e)?e:0}`}function Xf(n,e,t,i=!1){return{cpOrigin:n,signal:e,isCurrent:t,allowLoopbackHttp:i,open(){let o=globalThis.window.open("about:blank","_blank",Tq());if(!o)return null;let s=dx.get(o);if(s)return s;let r={navigate(a){if(o.closed)throw new Nt("application_popup_fenced");o.location.href=a},close(){let a=!o.closed;if(o.close(),a)try{globalThis.window.focus()}catch{}},focus(){try{o.focus()}catch{}},closed:()=>o.closed};return dx.set(o,r),r}}}function hx(n,e,t,i,o=!1){return{cpOrigin:n,signal:e,isCurrent:t,allowLoopbackHttp:o,open(){let s=!1;return{navigate(r){let a=new URL(r);i.returnUrl!==void 0&&a.searchParams.set("return_url",i.returnUrl),s=!0,Promise.resolve().then(()=>i.open(a.href)).catch(()=>{})},close(){s&&i.close&&Promise.resolve().then(()=>i.close()).catch(()=>{})}}}}}var Nt,px,dx,ux,fx,Vb=I(()=>{"use strict";bt();Nt=class extends Error{constructor(t){super("application authorization popup unavailable");this.reason=t;this.name="ApplicationPortalError"}reason},px=new WeakSet;dx=new WeakMap,ux=620,fx=760});function Qf(n){let e=n.manifest.requirements.files;return e?Object.freeze({required:Object.freeze([...n.files?.actions??[]]),optional:Object.freeze([...e.optional??[]])}):null}function eh(n,e){return n.collections.find(t=>t.collectionId===e)?.fileActions??[]}function yx(n,e){let t=i=>n.required.includes(i)||n.optional.includes(i)&&e().includes(i);return Object.freeze({allows:t,check(i){if(!t(i))throw mx(i,n.optional.includes(i))}})}function gx(n,e,t,i){let o=e?.files,s=t?.reason;if(!Array.isArray(o)||!o.length||o.some(a=>!Mq.includes(a))||new Set(o).size!==o.length)throw A("invalid_request","Invalid file actions","access_invalid");if(typeof s!="string"||!s.trim()||s.length>140||/[\u0000-\u001f\u007f\u2028\u2029]/.test(s))throw A("invalid_request","Reason must be one line, 1-140 characters","access_invalid");let r=[];for(let a of o)if(!n?.required.includes(a)){if(!n?.optional.includes(a))throw mx(a,!1);i.includes(a)||r.push(a)}return Object.freeze(r)}function bx(n,e,t){let i=n.grant?.actions??[...new Set([...e?.required??[],...t])];return Object.freeze({status:"granted",actions:Object.freeze([...i])})}function jq(n,e){return new Promise(t=>{let i=0,o=a=>{clearInterval(r),n.removeEventListener("abort",s),t(a)},s=()=>o(!1),r=setInterval(()=>{e.closed?o(!0):++i>=3&&o(!1)},500);n.addEventListener("abort",s,{once:!0})})}async function wx(n,e,t){let i=r=>{try{e.close()}catch{}return r},o;try{o=await n.start()}catch(r){if(t.aborted)return i(Zf);throw r}let s=o.fileAccess?.requestId;for(let r=!1;;){let a=n.native().fileAccess;if(!s||a?.requestId!==s)return i(Zf);if(a.state==="granted")return i(n.granted());if(a.state==="declined")return i(Lq);if(a.state==="expired"||r||t.aborted||(r=await jq(t,e),t.aborted))return i(Zf);await n.poll(s).catch(()=>{})}}var Mq,mx,Zf,Lq,th=I(()=>{"use strict";ie();Mq=["list","read","add","replace","move","delete"];mx=(n,e)=>e?A("forbidden",`File action ${n} needs requestAccess first`,"access_required"):A("forbidden",`File action ${n} is not declared`,"access_undeclared");Zf=Object.freeze({status:"cancelled"}),Lq=Object.freeze({status:"declined"})});function Bq(n){let e=n==="contract"?"shared format for this app's notes":n==="type"?"note type for this app":n==="schema"?"set of checks for this app's note properties":"setup item this app needs";return{the:`the ${e}`,bare:e}}function sh(n){if(n===void 0)return Object.freeze([]);if(!Array.isArray(n)||n.length>Dq)throw new TypeError("setup records: at most 32 { path, document } entries");let e=new Set,t=new TextEncoder,i=0;return Object.freeze(n.map(o=>{let s=o?.path,r=o?.document;if(typeof s!="string"||!/\.md$/i.test(s)||s.length>1024||s.startsWith("/")||s.split("/").some(a=>!a||a==="."||a==="..")||e.has(s.toLowerCase())||typeof r!="string"||!r.length||(i+=t.encode(r).length+t.encode(s).length)>$q)throw new TypeError("setup records: each needs a unique relative .md path and a document (256 KiB in total)");return e.add(s.toLowerCase()),Object.freeze({path:s,document:r})}))}function Px(n,e){return n.status!=="current"||n.refusal||e.facets.contracts.assessment?.status!=="setup_required"?n:Object.freeze({...n,status:"conflict",summary:Sx,refusal:Object.freeze({code:"setup_unresolved",message:Sx})})}function tp(n,e){let t=n.review,i=n.status==="current"?"current":n.status==="conflict"?"conflict":"setup",o=[],s=[],r={},a=new Set(t.staged.map(u=>u.path));for(let u of t.packs)for(let f of u.resources){let h=Bq(f.kind),m=`T${h.the.slice(1)}`,b=f.kind==="contract"?", so other apps can work with them":"";switch(f.action){case"create":o.push({kind:"create",target:f.target,message:`Add ${h.the}${b}.`});break;case"update":o.push({kind:"update",target:f.target,message:`Update ${h.the}.`});break;case"delete":o.push({kind:"delete",target:f.target,message:`Remove ${h.the}, which this app no longer uses.`});break;case"adopt":o.push({kind:"adopt",target:f.target,message:a.has(f.target)?`Replace ${h.the} with this app's version. Yours isn't kept.`:`Use your existing ${h.bare}, which already matches this app's.`});break;case"preserve":case"conflict":{if(f.action==="preserve"&&f.reason===void 0)break;let w=f.mode==="seed",g=f.currentDigest!==void 0&&(w||!f.installed);g&&(r[f.target]=f.currentDigest),s.push({target:f.target,...g?{adoptable:{digest:f.currentDigest}}:{},message:g&&w?`Your ${h.bare} has changes that can't be combined with the version this app needs. You can replace it with this app's version.`:g?`This collection already has a ${h.bare} that differs from the one this app needs. You can replace it with this app's version.`:f.installed?`${m} was changed after this app set it up, so it can't be updated automatically.`:`${m} can't be set up automatically.`});break}default:break}}for(let u of t.configuration){let f=Vq(u.path);u.action==="add"?o.push({kind:"setting",target:f,message:f==="include"?"Include this app's files when reading the collection.":f==="record extensions"&&typeof u.value=="string"?`Read .${u.value.replace(/^\./,"")} files as notes in this collection.`:"Adjust a collection setting this app needs."}):s.push({target:f,message:"A collection setting differs from what this app needs, so it can't be changed automatically."})}let p=i==="current"?[]:e.records.map(u=>Object.freeze({path:u.path,action:u.free?"create":"skip"}));for(let u of p)u.action==="create"&&o.push({kind:"record",target:u.path,message:`Create the starter note "${zq(u.path)}".`});i==="current"&&s.length&&(i="conflict");let l=(e.newer?.major.length??0)>0||t.packs.some(u=>u.installedVersion&&jo(u.installedVersion,u.version)==="installed_newer_major"),c;i!=="current"&&!e.canManage?c={code:"setup_forbidden",message:"This app doesn't have permission to set up this collection."}:l?c={code:"installed_newer",message:"A newer version of this app set up this collection. Update the app to continue."}:s.length?c={code:"setup_conflict",message:s.length===Object.keys(r).length?`${s.length===1?"One item differs":`${s.length} items differ`} from what this app needs. Choose whether to use this app's version to continue.`:"Some items can't be set up automatically. Resolve them, then try again."}:p.some(u=>u.action==="create")&&!e.canCreateRecords&&(c={code:"setup_records_forbidden",message:"This app doesn't have permission to create notes in this collection."});let d=i==="current"?"Everything this app needs is already set up.":c?c.message:`This app will make ${Fq(o.length,"change")} to this collection.${o.every(u=>u.kind==="create"||u.kind==="record"||u.kind==="adopt"&&!a.has(u.target))?" Nothing already in it is changed.":""}`;return Object.freeze({status:i,canApply:i==="setup"&&c===void 0,digest:n.assessmentDigest,summary:d,changes:Object.freeze(o.map(u=>Object.freeze(u))),conflicts:Object.freeze(s.map(u=>Object.freeze(u))),adoptable:Object.freeze(r),packs:Object.freeze([...t.packs.map(u=>Object.freeze({id:u.id,version:u.version,status:u.status,...u.installedVersion?{installedVersion:u.installedVersion,relation:jo(u.installedVersion,u.version)}:{}})),...(e.newer?.kept??[]).map(u=>Object.freeze({id:u.id,version:u.version,status:"current",installedVersion:u.installedVersion,relation:"installed_newer"}))]),staged:t.staged,records:Object.freeze(p),...c?{refusal:Object.freeze(c)}:{}})}var Dq,$q,zq,Fq,Vq,Sx,ah=I(()=>{"use strict";yu();Dq=32,$q=256*1024,zq=n=>(n.split("/").pop()??n).replace(/\.(md|ya?ml|json)$/i,"");Fq=(n,e,t=`${e}s`)=>`${n} ${n===1?e:t}`,Vq=n=>(n.split("/").filter(Boolean).pop()??n).replace(/[_-]+/g," ");Sx="This collection is missing something this app needs, and setup can't add it. A note type this app set up may have been changed or removed. Restore it, then try again."});function Ex(){throw A("unavailable","SDK release trust unavailable: package authenticated LAB or production inputs","application_release_trust_unavailable")}var qx=I(()=>{"use strict";ie()});function Tx(n,e){let t=()=>A("unauthenticated","people scope changed","people_fenced"),i={collection:n,isCurrent:()=>e.holds(n),async request(o,s={}){if(o!=="identity"&&o!=="members")throw A("invalid_request","invalid people resource");for(let r=0;;r++){if(s.signal?.throwIfAborted(),!i.isCurrent())throw t();let a=await e.accessToken(n,r>0),{status:p,body:l}=await Yq(e,`/v1/authorities/${n}/${o}`,a,s.signal);if(!i.isCurrent())throw t();if(!(p===401&&r===0)){if(p===401)throw A("unauthenticated","people credential is no longer current","people_fenced");if(p===403){let c=l?.error?.code;throw c==="approval_required"?un("approval_required"):A("forbidden","people access was refused",o==="members"&&c==="insufficient_access"?"people_permission_declined":"people_access")}if(p===404)throw A("upgrade_required","people metadata is unsupported","people_unsupported");if(p!==200||!l)throw Yb();return l}}}};return i}async function Yq(n,e,t,i){let o=new AbortController,s=()=>o.abort();i?.addEventListener("abort",s,{once:!0});let r=setTimeout(s,Gq);r.unref?.();try{let a=await n.fetch(`${n.cpOrigin}${e}`,{method:"GET",headers:{authorization:`Bearer ${t}`},signal:o.signal,redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer"}),p=await a.text();if(p.length>Hq)throw Yb();let l=null;try{let c=JSON.parse(p);c&&typeof c=="object"&&!Array.isArray(c)&&(l=c)}catch{l=null}return{status:a.status,body:l}}catch(a){throw i?.aborted?A("cancelled","request cancelled"):a instanceof se?a:Yb()}finally{clearTimeout(r),i?.removeEventListener("abort",s)}}var Hq,Gq,Yb,Mx=I(()=>{"use strict";Lr();ie();Hq=1024*1024,Gq=15e3,Yb=()=>A("unavailable","people metadata is unavailable","people_response")});var wr,Jb=I(()=>{"use strict";wr=Object.freeze({plaintextBytes:524288,operations:64,readbacks:128,pathCodeUnits:1024})});function Z(n){throw new nn(n)}function tn(n,e){return Object.keys(n).sort().join()===e}function Xb(n){return(!n||!tn(n,"account,collection,installation")||Object.values(n).some(e=>typeof e!="string"||!Zb.test(e)||e==="00000000-0000-0000-0000-000000000000"))&&Z("binding"),Object.freeze({account:n.account,installation:n.installation,collection:n.collection})}function Lx(n){for(let e of n){let t=e.charCodeAt(0);if(t<32||t===127)return!0}return n.includes("\\")}function Jq(n){(!Array.isArray(n)||n.length!==2)&&Z("binding");let e=n.map(t=>((!t||typeof t!="object"||!tn(t,"doc,kind,mustNotExist,path")||t.kind!=="resource_put"||t.mustNotExist!==!0||typeof t.path!="string"||typeof t.doc!="string"||!t.doc.length||t.path.length>1024||!t.path.endsWith(".md")||t.path.startsWith("/")||Lx(t.path)||t.path.split("/").some(i=>!i||i==="."||i===".."))&&Z("binding"),Object.freeze({kind:"resource_put",path:t.path,doc:t.doc,mustNotExist:!0})));return(e[0].path===e[1].path||Ki.encode(JSON.stringify(e)).byteLength>_i)&&Z("binding"),Object.freeze(e)}function ip(n){return typeof n=="string"&&n.length>0&&n.length<=wr.pathCodeUnits&&!n.startsWith("/")&&!Lx(n)&&!n.split("/").some(e=>!e||e==="."||e==="..")}function Ho(n){let e=n;(!e||typeof e!="object"||!tn(e,"assessmentDigest,ops,pack,readback")||!e.pack||typeof e.pack!="object"||!tn(e.pack,"digest,id,version")||typeof e.pack.id!="string"||!e.pack.id.length||typeof e.pack.version!="string"||!e.pack.version.length||typeof e.pack.digest!="string"||!Wo.test(e.pack.digest)||typeof e.assessmentDigest!="string"||!Wo.test(e.assessmentDigest)||!Array.isArray(e.ops)||!e.ops.length||e.ops.length>wr.operations||!Array.isArray(e.readback)||!e.readback.length||e.readback.length>wr.readbacks)&&Z("binding");let t=e.ops.map(r=>{(!r||typeof r!="object"||!ip(r.path)||"baseRevision"in r&&(typeof r.baseRevision!="string"||!Wo.test(r.baseRevision)))&&Z("binding");let a="baseRevision"in r?{baseRevision:r.baseRevision}:{};return r.kind==="resource_put"?((!tn(r,"baseRevision"in r?"baseRevision,doc,kind,mustNotExist,path":"doc,kind,mustNotExist,path")||typeof r.doc!="string"||typeof r.mustNotExist!="boolean")&&Z("binding"),Object.freeze({kind:r.kind,path:r.path,doc:r.doc,...a,mustNotExist:r.mustNotExist})):((r.kind!=="resource_delete"||!tn(r,"baseRevision"in r?"baseRevision,kind,path":"kind,path"))&&Z("binding"),Object.freeze({kind:r.kind,path:r.path,...a}))}),i=new Set,o=e.readback.map(r=>((!r||typeof r!="object"||!tn(r,"doc,path")||!ip(r.path)||r.doc!==null&&typeof r.doc!="string"||i.has(r.path))&&Z("binding"),i.add(r.path),Object.freeze({path:r.path,doc:r.doc})));for(let r of t){let a=o.find(p=>p.path===r.path);(!a||a.doc!==(r.kind==="resource_put"?r.doc:null))&&Z("binding")}let s=Object.freeze({pack:Object.freeze({id:e.pack.id,version:e.pack.version,digest:e.pack.digest}),assessmentDigest:e.assessmentDigest,ops:Object.freeze(t),readback:Object.freeze(o)});return Ki.encode(JSON.stringify(s)).byteLength>_i&&Z("binding"),s}function xt(n){let e=n;(!e||typeof e!="object"||!tn(e,Object.hasOwn(e,"planKind")?"assessmentDigest,packs,planKind,provisionDigest,resourceOps,resourceReadback,sources":Object.hasOwn(e,"sourcePolicy")?"assessmentDigest,packs,provisionDigest,resourceOps,resourceReadback,sourcePolicy,sources":"assessmentDigest,packs,provisionDigest,resourceOps,resourceReadback,sources")||Object.hasOwn(e,"sourcePolicy")&&(e.sourcePolicy!=="current-only"||e.sources?.length!==0)||typeof e.assessmentDigest!="string"||!Wo.test(e.assessmentDigest)||typeof e.provisionDigest!="string"||!Wo.test(e.provisionDigest)||!Array.isArray(e.packs)||!e.packs.length&&e.planKind!=="configuration-only"||e.packs.length>16||!Array.isArray(e.resourceOps)||!Array.isArray(e.sources)||!e.resourceOps.length&&!e.sources.length||e.resourceOps.length+e.sources.length>wr.operations||!Array.isArray(e.resourceReadback)||!e.resourceReadback.length||e.resourceReadback.length+e.sources.length>wr.readbacks)&&Z("binding"),Object.hasOwn(e,"planKind")&&(e.planKind!=="configuration-only"||e.packs.length!==0||!e.resourceOps.length||e.resourceOps.some(c=>!c||c.kind!=="resource_put"||!["mdbase.yaml","mdbase.provisions.yaml"].includes(c.path)))&&Z("binding");let t=new Set,i=e.packs.map(c=>((!c||typeof c!="object"||!tn(c,"digest,id,version")||typeof c.id!="string"||!c.id.length||c.id.length>150||t.has(c.id)||typeof c.version!="string"||!c.version.length||c.version.length>256||typeof c.digest!="string"||!Wo.test(c.digest))&&Z("binding"),t.add(c.id),Object.freeze({...c}))),o=new Set,s=e.resourceReadback.map(c=>((!c||typeof c!="object"||!tn(c,"doc,path")||!ip(c.path)||o.has(c.path)||c.doc!==null&&typeof c.doc!="string")&&Z("binding"),o.add(c.path),Object.freeze({...c}))),r=e.resourceOps.map(c=>{(!c||typeof c!="object"||!ip(c.path))&&Z("binding");let d=Object.hasOwn(c,"baseRevision");d&&(typeof c.baseRevision!="string"||!Wo.test(c.baseRevision))&&Z("binding"),c.kind==="resource_put"?(!tn(c,d?"baseRevision,doc,kind,mustNotExist,path":"doc,kind,mustNotExist,path")||typeof c.doc!="string"||typeof c.mustNotExist!="boolean"||(c.mustNotExist?d:!d))&&Z("binding"):(c.kind!=="resource_delete"||!d||!tn(c,"baseRevision,kind,path"))&&Z("binding");let u=s.find(f=>f.path===c.path);return(!u||u.doc!==(c.kind==="resource_put"?c.doc:null))&&Z("binding"),Object.freeze({...c})}),a=new Set,p=e.sources.map(c=>((!c||typeof c!="object"||!tn(c,"document,id,path")||!ip(c.path)||o.has(c.path)||typeof c.id!="string"||!Zb.test(c.id)||c.id==="00000000-0000-0000-0000-000000000000"||a.has(c.id)||typeof c.document!="string"||!c.document.length)&&Z("binding"),o.add(c.path),a.add(c.id),Object.freeze({...c}))),l=Object.freeze({...e.planKind==="configuration-only"?{planKind:e.planKind}:{},...e.sourcePolicy==="current-only"?{sourcePolicy:e.sourcePolicy}:{},assessmentDigest:e.assessmentDigest,provisionDigest:e.provisionDigest,packs:Object.freeze(i),resourceOps:Object.freeze(r),resourceReadback:Object.freeze(s),sources:Object.freeze(p)});return Ki.encode(JSON.stringify(l)).byteLength>_i&&Z("binding"),l}function Et(n,e,t=0){t>8&&Z("binding");let i=n;(!i||typeof i!="object"||i.version!==1&&i.version!==2&&i.version!==3&&i.version!==4||!tn(i,i.version===1?"mutationId,ops,phase,scope,version":i.version===4?"mutationId,phase,plan,previous,scope,version":"mutationId,phase,plan,scope,version")||typeof i.mutationId!="string"||!Zb.test(i.mutationId)||i.mutationId==="00000000-0000-0000-0000-000000000000"||!(np.includes(i.phase)||i.phase==="rejected"&&(i.version===3||i.version===4)))&&Z("recovery_required");let o=Xb(i.scope);if(JSON.stringify(o)!==JSON.stringify(e)&&Z("binding"),i.version===1)return Object.freeze({version:1,scope:o,mutationId:i.mutationId,ops:Jq(i.ops),phase:i.phase});if(i.version===4){let r=Et(i.previous,e,t+1);r.phase!=="verified"&&Z("recovery_required");for(let l=r;l.mutationId===i.mutationId&&Z("binding"),l.version===4;)l=l.previous;let a=xt(i.plan);a.resourceOps.some(l=>l.kind!=="resource_put"||!l.mustNotExist&&!["mdbase.yaml","mdbase.lock.yaml","mdbase.provisions.yaml"].includes(l.path))&&Z("binding");let p=Object.freeze({version:4,scope:o,mutationId:i.mutationId,plan:a,phase:i.phase,previous:r});return Ki.encode(JSON.stringify({...p,phase:"confirmed"})).byteLength>_i&&Z("binding"),p}if(i.version===3){xt(i.plan).sourcePolicy!==void 0&&Z("binding");let r=Object.freeze({version:3,scope:o,mutationId:i.mutationId,plan:xt(i.plan),phase:i.phase});return Ki.encode(JSON.stringify({...r,phase:"confirmed"})).byteLength>_i&&Z("binding"),r}let s=Object.freeze({version:2,scope:o,mutationId:i.mutationId,plan:Ho(i.plan),phase:i.phase});return Ki.encode(JSON.stringify({...s,phase:"confirmed"})).byteLength>_i&&Z("binding"),s}function lh(n){return n.version!==2&&Z("recovery_required"),n}function Xq(n,e,t){return t(),globalThis.indexedDB||Z("recovery_required"),new Promise((i,o)=>{let s=indexedDB.open(n,1),r=!1,a=()=>{r=!0,e.removeEventListener("abort",a);try{s.transaction?.abort()}catch{}o(new nn("recovery_required"))};e.addEventListener("abort",a,{once:!0}),s.onupgradeneeded=()=>{try{t(),(r||s.result.objectStoreNames.length)&&Z("recovery_required"),s.result.createObjectStore(za)}catch{a()}},s.onerror=s.onblocked=a,s.onsuccess=()=>{e.removeEventListener("abort",a);try{t(),(r||s.result.objectStoreNames.length!==1||!s.result.objectStoreNames.contains(za))&&Z("recovery_required"),i(s.result)}catch{s.result.close(),o(new nn("recovery_required"))}}})}var za,np,Zb,_i,Wo,Ki,nn,Ba,Go=I(()=>{"use strict";bt();Jb();za="original-model-operation",np=["prepared","attempted","confirmed","verified"],Zb=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,_i=wr.plaintextBytes,Wo=/^sha256:[0-9a-f]{64}$/,Ki=new TextEncoder,nn=class extends Error{constructor(t){super("Preserve the original collection setup operation.");this.reason=t}reason};Ba=class{constructor(e){this.owner=e;this.scope=Xb(e.scope),(typeof e.isCurrent!="function"||[e.databaseName,e.applicationNamespace].some(o=>typeof o!="string"||!o.length||o.length>256||/[\u0000-\u001f\u007f]/.test(o)))&&Z("binding"),this.current=e.isCurrent,this.pins=JSON.stringify([e.databaseName,e.applicationNamespace,e.appOrigin,e.cpOrigin]);let t=new URL(e.appOrigin),i=new URL(e.cpOrigin);(t.origin!==e.appOrigin||i.origin!==e.cpOrigin||i.protocol!=="https:"&&!!1)&&Z("binding"),this.namespace=JSON.stringify([e.appOrigin,e.cpOrigin,e.applicationNamespace,this.scope.account,this.scope.installation,this.scope.collection]),this.binding=JSON.stringify(this.scope)}owner;scope;namespace;binding;stopped=!1;turn=Promise.resolve();pins;current;close(){this.stopped=!0}check(e){e.throwIfAborted();let t=!1;try{t=!this.stopped&&this.owner.isCurrent===this.current&&this.current.call(this.owner)===!0&&JSON.stringify([this.owner.databaseName,this.owner.applicationNamespace,this.owner.appOrigin,this.owner.cpOrigin])===this.pins&&JSON.stringify(Xb(this.owner.scope))===this.binding}catch{}t||(this.stopped=!0,Z("fenced"))}async exclusive(e,t){this.check(e);let i=this.turn,o,s=new Promise(a=>{o=a});this.turn=i.then(()=>s);let r;try{await new Promise((p,l)=>{let c=()=>l(e.reason);e.addEventListener("abort",c,{once:!0}),i.then(()=>{e.removeEventListener("abort",c),p()})}),this.check(e),r=await Xq(this.owner.databaseName,e,()=>this.check(e)),this.check(e);let a=await t(r);return this.check(e),a}finally{r?.close(),o()}}read(e,t){return this.check(t),new Promise((i,o)=>{let s=e.transaction(za,"readonly"),r=s.objectStore(za).get(this.namespace),a=()=>s.abort();t.addEventListener("abort",a,{once:!0}),s.onabort=s.onerror=()=>{t.removeEventListener("abort",a),o(new nn("recovery_required"))},s.oncomplete=()=>{t.removeEventListener("abort",a),i(r.result)}})}aad(e){return Ki.encode(JSON.stringify([this.namespace,1,e]))}async unwrap(e,t){if(this.check(t),e===void 0)return null;(!e||!tn(e,"ciphertext,iv,key,revision,version")||e.version!==1||!Number.isSafeInteger(e.revision)||e.revision<1||!(e.key instanceof CryptoKey)||e.key.extractable||e.key.type!=="secret"||e.key.algorithm.name!=="AES-GCM"||!e.key.usages.includes("encrypt")||!e.key.usages.includes("decrypt")||!(e.iv instanceof Uint8Array)||e.iv.byteLength!==12||!(e.ciphertext instanceof ArrayBuffer)||e.ciphertext.byteLength>_i+2048)&&Z("recovery_required");let i;try{i=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:e.iv,additionalData:this.aad(e.revision)},e.key,e.ciphertext)),this.check(t);let o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i));return(o?.version===2||o?.version===3||o?.version===4)&&i.byteLength>_i&&Z("recovery_required"),Et(o,this.scope)}catch(o){throw o instanceof nn||t.aborted?o:new nn("recovery_required")}finally{i?.fill(0)}}async commit(e,t,i,o){this.check(o);let s=(t?.revision??0)+1;Number.isSafeInteger(s)||Z("fenced");let r=t?.key??await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),a=crypto.getRandomValues(new Uint8Array(12)),p=Ki.encode(JSON.stringify(i));p.byteLength>_i&&(p.fill(0),Z("binding"));let l;try{l=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,additionalData:this.aad(s)},r,p)}finally{p.fill(0)}this.check(o);try{await new Promise((c,d)=>{let u=e.transaction(za,"readwrite",{durability:"strict"}),f=()=>u.abort();o.addEventListener("abort",f,{once:!0}),u.onerror=u.onabort=()=>{o.removeEventListener("abort",f),d(new nn("outcome_unknown"))},u.oncomplete=()=>{o.removeEventListener("abort",f),c()};let h=u.objectStore(za),m=h.get(this.namespace);m.onsuccess=()=>{try{this.check(o);let b=m.result;if(b===void 0!=(t===void 0)||b&&b.revision!==t?.revision){u.abort();return}h.put({version:1,revision:s,key:r,iv:a,ciphertext:l},this.namespace)}catch{u.abort()}}})}catch(c){throw this.stopped=!0,c}return this.check(o),i}load(e){return this.exclusive(e,async t=>this.unwrap(await this.read(t,e),e))}prepare(e,t){let i=Ho(e);return Ki.encode(JSON.stringify({version:2,scope:this.scope,mutationId:this.scope.collection,plan:i,phase:"confirmed"})).byteLength>_i&&Z("binding"),this.exclusive(t,async o=>{let s=await this.read(o,t),r=await this.unwrap(s,t);if(r){let p=lh(r);return JSON.stringify(p.plan)!==JSON.stringify(i)&&Z("binding"),p}let a=lh(Et({version:2,scope:this.scope,mutationId:crypto.randomUUID(),plan:i,phase:"prepared"},this.scope));return this.commit(o,s,a,t)})}prepareResources(e,t){let i=xt(e);return i.sourcePolicy!==void 0&&Z("binding"),Ki.encode(JSON.stringify({version:3,scope:this.scope,mutationId:this.scope.collection,plan:i,phase:"confirmed"})).byteLength>_i&&Z("binding"),this.exclusive(t,async o=>{let s=await this.read(o,t),r=await this.unwrap(s,t);if(r&&!(r.version===3&&r.phase==="rejected"))return r.version!==3&&Z("recovery_required"),JSON.stringify(r.plan)!==JSON.stringify(i)&&Z("binding"),r;let a=Et({version:3,scope:this.scope,mutationId:crypto.randomUUID(),plan:i,phase:"prepared"},this.scope);return a.version!==3&&Z("binding"),this.commit(o,s,a,t)})}prepareResourceRound(e,t,i){let o=xt(e);return this.exclusive(i,async s=>{let r=await this.read(s,i),a=await this.unwrap(r,i);a?.version===4&&a.phase==="rejected"&&(a=a.previous),(!a||a.mutationId!==t)&&Z("binding"),a.phase!=="verified"&&Z("recovery_required");let p=Et({version:4,scope:this.scope,mutationId:crypto.randomUUID(),plan:o,phase:"prepared",previous:a},this.scope);return p.version!==4&&Z("binding"),this.commit(s,r,p,i)})}advanceResource(e,t,i){return this.exclusive(i,async o=>{let s=await this.read(o,i),r=await this.unwrap(s,i);(!r||r.version!==3&&r.version!==4)&&Z("recovery_required"),r.mutationId!==e&&Z("binding"),r.phase==="rejected"&&Z("recovery_required");let a=np.indexOf(r.phase),p=np.indexOf(t);if((p<a||p>a+1)&&Z("recovery_required"),p===a)return r;let l=Et({...r,phase:t},this.scope);return l.version!==3&&l.version!==4&&Z("binding"),this.commit(o,s,l,i)})}recordResourceAttempt(e,t){return this.advanceResource(e,"attempted",t)}recordResourceConfirmed(e,t){return this.advanceResource(e,"confirmed",t)}recordResourceVerified(e,t){return this.advanceResource(e,"verified",t)}recordResourceRejected(e,t){return this.exclusive(t,async i=>{let o=await this.read(i,t),s=await this.unwrap(o,t);if((!s||s.version!==3&&s.version!==4)&&Z("recovery_required"),s.mutationId!==e&&Z("binding"),s.phase==="rejected")return s;s.phase!=="attempted"&&Z("recovery_required");let r=Et({...s,phase:"rejected"},this.scope);return r.version!==3&&r.version!==4&&Z("binding"),this.commit(i,o,r,t)})}advance(e,t,i){return this.exclusive(i,async o=>{let s=await this.read(o,i),r=await this.unwrap(s,i);r||Z("recovery_required");let a=lh(r);a.mutationId!==e&&Z("binding"),a.phase==="rejected"&&Z("recovery_required");let p=np.indexOf(a.phase),l=np.indexOf(t);return(l<p||l>p+1)&&Z("recovery_required"),l===p?a:this.commit(o,s,lh(Et({...a,phase:t},this.scope)),i)})}recordAttempt(e,t){return this.advance(e,"attempted",t)}recordConfirmed(e,t){return this.advance(e,"confirmed",t)}recordVerified(e,t){return this.advance(e,"verified",t)}}});function jx(n){if(!n||typeof n!="object")return null;let e=n;if(typeof e.mutationId!="string"||!Zq.test(e.mutationId)||!Array.isArray(e.records)||!e.records.every(i=>typeof i=="string")||typeof e.createdAt!="number"||e.state!=="pending"&&e.state!=="rejected")return null;let t=e.problem;return t!==void 0&&(!t||typeof t.code!="string"||typeof t.message!="string"||typeof t.recovery!="string")?null:{mutationId:e.mutationId,records:[...e.records],createdAt:e.createdAt,state:e.state,...t?{problem:{code:t.code,recovery:t.recovery,message:t.message,...t.reason?{reason:t.reason}:{}}}:{}}}var Zq,Nx=I(()=>{"use strict";Zq=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/});function ch(n){if(!n||typeof n!="object"||Array.isArray(n))throw yn();let e=Object.getPrototypeOf(n);if(e!==Object.prototype&&e!==null)throw yn();let t=Object.create(null);for(let i of Reflect.ownKeys(n)){if(typeof i!="string")throw yn();let o=Object.getOwnPropertyDescriptor(n,i);if(!o||!("value"in o))throw yn();o.enumerable&&(t[i]=o.value)}return t}function Qb(n){if(typeof n!="string"||!n.trim()||Qq.encode(n).byteLength>4096)throw yn();return n}function Dx(n){let e=Qb(n),t=new URL(e);if(!["http:","https:"].includes(t.protocol)||t.username||t.password)throw yn();return e}function Ux(n){let e=ch(n),t={issuer:Dx(e.issuer),subject:Qb(e.subject),name:Qb(e.name)};if(e.account_id!==void 0){if(typeof e.account_id!="string"||!e2.test(e.account_id)||e.account_id==="00000000-0000-0000-0000-000000000000")throw yn();t.account_id=e.account_id}return t}function t2(n){if(!Array.isArray(n)||Object.getPrototypeOf(n)!==Array.prototype||n.length>1e3)throw yn();for(let t of Reflect.ownKeys(n)){let i=Object.getOwnPropertyDescriptor(n,t);if(typeof t!="string"||!i||!("value"in i))throw yn()}let e=[];for(let t=0;t<n.length;t++){let i=Object.getOwnPropertyDescriptor(n,String(t));if(!i||!("value"in i))throw yn();e.push(i.value)}return e}function Fa(n,e){try{let t=ch(e);if(n==="identity"){let o=Ux(t);return t.person_settings_url!==void 0&&(o.person_settings_url=Dx(t.person_settings_url)),o}if(n!=="members")throw yn();return{members:t2(t.members).map(o=>{let s=ch(o),r=Ux(s),a=s.role;if(a!=="owner"&&a!=="editor"&&a!=="viewer")throw yn();return{...r,role:a}})}}catch{throw yn()}}function $x(n,e){try{if(e instanceof se)switch(e.code){case"forbidden":return{code:"forbidden",reason:n==="members"&&e.reason==="people_permission_declined"?"people_permission_declined":"people_access"};case"unauthenticated":case"cancelled":return{code:"unauthenticated",reason:"people_fenced"};case"upgrade_required":return{code:"upgrade_required",reason:"people_unsupported"}}}catch{}return{code:"unavailable",reason:"people_response"}}function zx(n){let e=ch(n);if(!(e.code==="forbidden"&&["people_permission_declined","people_access"].includes(e.reason)||e.code==="unauthenticated"&&e.reason==="people_fenced"||e.code==="upgrade_required"&&e.reason==="people_unsupported"||e.code==="unavailable"&&["people_response","people_busy"].includes(e.reason))||Object.keys(e).length!==2)throw yn();return A(e.code,"people metadata request failed",e.reason)}function ph(n,e){if(!e.peopleAuthority)throw A("upgrade_required","people metadata is unsupported","people_unsupported");return new jr(n,e.peopleAuthority)}var yn,Qq,e2,rp=I(()=>{"use strict";ie();iu();yn=()=>A("unavailable","invalid people response","people_response"),Qq=new TextEncoder,e2=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/});function ei(n){if(!Yo(n)||Object.keys(n).some(i=>i!=="adopt"))throw ce("binding");if(n.adopt===void 0)return Object.freeze({});let e=n.adopt;if(!Yo(e)||Object.keys(e).length>256)throw ce("binding");let t={};for(let[i,o]of Object.entries(e)){if(!Wi(i)||typeof o!="string"||!sp.test(o))throw ce("binding");t[i]=o}return Object.freeze({adopt:Object.freeze(t)})}function n2(n){if(!Yo(n)||!op(n,"configuration,packs,staged")||!Array.isArray(n.packs)||n.packs.length>16||!Array.isArray(n.configuration)||n.configuration.length>64||!Array.isArray(n.staged)||n.staged.length>1024)throw ce("binding");let e=n.packs.map(o=>{if(!Yo(o)||!op(o,"id,installedVersion,resources,status,version")||!Wi(o.id,150)||!Wi(o.version,128)||!["current","install","upgrade","downgrade","reconfigure","conflict"].includes(o.status)||!(o.installedVersion===null||Wi(o.installedVersion,128))||!Array.isArray(o.resources)||o.resources.length>1024)throw ce("binding");let s=o.resources.map(r=>{if(!Yo(r)||!op(r,"action,installed,kind,mode,target",["currentDigest","reason"])||!Wi(r.target)||!Wi(r.kind,64)||r.mode!=="managed"&&r.mode!=="seed"||typeof r.installed!="boolean"||!["create","update","delete","adopt","preserve","conflict"].includes(r.action)||r.currentDigest!==void 0&&(typeof r.currentDigest!="string"||!sp.test(r.currentDigest))||r.reason!==void 0&&!Wi(r.reason,8192))throw ce("binding");return Object.freeze({...r})});return Object.freeze({id:o.id,version:o.version,status:o.status,installedVersion:o.installedVersion,resources:Object.freeze(s)})}),t=n.configuration.map(o=>{if(!Yo(o)||!op(o,"action,path,requirement",["value"])||!Wi(o.requirement,256)||!Wi(o.path,1024)||o.action!=="add"&&o.action!=="conflict"||!(o.value===void 0||o.value===null||["string","number","boolean"].includes(typeof o.value)))throw ce("binding");return Object.freeze({...o})}),i=n.staged.map(o=>{if(!Yo(o)||!op(o,"document,path")||!Wi(o.path)||typeof o.document!="string"||o.document.length>512*1024)throw ce("binding");return Object.freeze({path:o.path,document:o.document})});return Object.freeze({packs:Object.freeze(e),configuration:Object.freeze(t),staged:Object.freeze(i)})}function Jo(n,e=!1){let t=n;if(!t||typeof t!="object"||Object.keys(t).sort().join(",")!==(e?"assessmentDigest,review,status":"assessmentDigest,status")||!["current","provision","conflict"].includes(t.status)||typeof t.assessmentDigest!="string"||!sp.test(t.assessmentDigest))throw ce("binding");return Object.freeze({status:t.status,assessmentDigest:t.assessmentDigest,...e?{review:n2(t.review)}:{}})}function Bx(n){let e=Object.freeze({account:n.scope.account,installation:n.scope.installation,collection:n.scope.collection});if(Object.values(e).some(t=>!Va.test(t)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/.test(t))||!Va.test(n.generation))throw ce("binding");return{scope:e,generation:n.generation,binding:JSON.stringify([e.account,e.installation,e.collection])}}function Ka(n){try{return new TextEncoder().encode(JSON.stringify(n)).byteLength<=i2}catch{return!1}}function Fx(n,e,t){t=Object.freeze({...t});let i=Bx(e),o=!1,s=null,r=null,a=0,p={},l=t.setupTurn,c=()=>{l?.owner===p&&(l.owner=null)},d=()=>{if(o||t.signal.aborted||t.isCurrent()!==!0)throw ce()},u=(m,b,w)=>{d();let g=[1,i.binding,i.generation,m,b,w];if(!Ka(g))throw ce("binding");n.postMessage(g)},f=()=>{if(!o){o=!0,c(),n.onmessage=n.onmessageerror=null;try{n.postMessage([1,i.binding,i.generation,0,"closed",null])}catch{}n.close()}},h=()=>{try{f()}finally{t.onProtocolFailure()}};return n.onmessageerror=h,n.onmessage=m=>{let b=m.data;try{if(d(),Array.isArray(b)&&b.length===6&&b[0]===1&&b[1]===i.binding&&b[2]===i.generation&&b[3]===0&&b[4]==="detach"&&b[5]===null){h();return}if(!Array.isArray(b)||b.length!==6||b[0]!==1||b[1]!==i.binding||b[2]!==i.generation||!Number.isInteger(b[3])||b[3]<1||b[3]>4294967295||!a2.includes(b[4])||!Ka(b))throw ce("binding");let w=b[3],g=b[4],y=b[5];if(w<=a)throw ce("binding");if(a=w,r2(g)){let k=null;try{let S=t.ledger?.()??null;if(!S)throw ce("recovery_required");if(g==="ledgerList"){if(y!==null)throw ce("binding");k=S.list(s2)}else if(g==="ledgerRemove"){if(typeof y!="string"||!Va.test(y))throw ce("binding");S.remove(y)}else{if(!Array.isArray(y)||y.length!==2||typeof y[0]!="string"||!Va.test(y[0])||typeof y[1]!="string"||y[1].length>o2)throw ce("binding");S.put(y[0],y[1])}}catch(S){u(w,"error",S instanceof ti?S.reason:"recovery_required");return}u(w,"result",k);return}if(s){u(w,"error","busy");return}if(l&&l2(g)&&l.owner!==null&&l.owner!==p){u(w,"error","busy");return}let v=async()=>{d();let k=null;switch(g){case"resourcesAssess":case"resourcesApply":{let S=t.resourceSetup;if(!S)throw ce("recovery_required");if(g==="resourcesAssess"){let x=Array.isArray(y);if(x&&y.length!==2)throw ce("binding");k=x?Jo(await S.assess(y[0],t.signal,ei(y[1])),!0):Jo(await S.assess(y,t.signal))}else{if(!Array.isArray(y)||y.length!==2&&y.length!==3||typeof y[1]!="string"||!sp.test(y[1]))throw ce("binding");k=xt(y.length===3?await S.apply(y[0],y[1],t.signal,ei(y[2])):await S.apply(y[0],y[1],t.signal))}d();break}case"peopleIdentity":case"peopleMembers":{if(y!==null)throw ce("binding");let S=t.peopleAuthority;if(!S)throw A("upgrade_required","people metadata is unsupported","people_unsupported");let x=()=>{if(d(),S.collection!==i.scope.collection||S.isCurrent()!==!0)throw A("unauthenticated","people scope changed","people_fenced")};x();let P=dh(g),C=await S.request(P,{signal:t.signal});if(x(),k=Fa(P,C),x(),!Ka([1,i.binding,i.generation,w,"result",k]))throw A("unavailable","invalid people response","people_response");break}case"load":if(y!==null)throw ce("binding");c(),k=await t.journal.load(t.signal);break;case"prepare":k=await t.journal.prepare(Ho(y),t.signal),d(),l&&(l.owner=p);break;case"prepareResources":k=await t.journal.prepareResources(xt(y),t.signal),d(),l&&(l.owner=p);break;case"prepareResourceRound":if(!Array.isArray(y)||y.length!==2||typeof y[1]!="string")throw ce("binding");k=await t.journal.prepareResourceRound(xt(y[0]),y[1],t.signal),d(),l&&(l.owner=p);break;case"assess":if(y!=="ready"&&y!=="setup_required")throw ce("binding");t.assess(y);break;case"foreground":if(typeof y!="boolean")throw ce("binding");t.foreground(y);break;case"recordResourceRejected":{if(typeof y!="string"||!Va.test(y))throw ce("binding");let S=t.resourceSetup?.rejected;if(!S||await S(y,t.signal)!==!0)throw ce("recovery_required");d(),k=await t.journal.recordResourceRejected(y,t.signal),c();break}default:if(typeof y!="string"||!Va.test(y))throw ce("binding");k=await t.journal[g](y,t.signal),(g==="recordVerified"||g==="recordResourceVerified")&&c()}d(),u(w,"result",k)},_=s=Promise.resolve().then(v).catch(k=>{if(!(o||t.signal.aborted))try{let S=dh(g);u(w,"error",S?$x(S,k):k instanceof nn||k instanceof ti?k.reason:"recovery_required")}catch{h()}});_.finally(()=>{s===_&&(s=null)}).catch(()=>{})}catch{h()}},n.start(),{close(){return r||(r=Promise.resolve().then(async()=>{f(),await s}),r)}}}function uh(n,e,t){t=Object.freeze({...t});let i=Bx(e),o=!1,s=1,r=null,a=new Map,p=()=>{if(o||t.signal.aborted||t.isCurrent()!==!0)throw ce()},l=()=>{if(o)return;o=!0,t.signal.removeEventListener("abort",l),n.onmessage=n.onmessageerror=null;let v=r;r=null,v?.finish(void 0,ce(ew(v.action)?"fenced":"outcome_unknown"));for(let _ of a.values())_(void 0,ce("fenced"));a.clear();try{n.postMessage([1,i.binding,i.generation,0,"detach",null])}catch{}try{n.close()}finally{t.onClose()}};t.signal.addEventListener("abort",l,{once:!0}),n.onmessageerror=l,n.onmessage=v=>{try{p();let _=v.data;if(!Array.isArray(_)||_.length!==6||_[0]!==1||_[1]!==i.binding||_[2]!==i.generation||!Ka(_))throw ce();if(_[3]===0&&_[4]==="closed"&&_[5]===null){l();return}let k=a.get(_[3]);if(k&&["result","error"].includes(_[4])){a.delete(_[3]),k(_[4]==="result"?_[5]:void 0,_[4]==="error"?ce(_[5]==="binding"?"binding":"recovery_required"):void 0);return}if(!r||_[3]!==r.id||!["result","error"].includes(_[4]))throw ce();let S=r,x=_[4]==="error"?dh(S.action)&&_[5]!=="busy"?zx(_[5]):_[5]==="busy"?ce("busy"):ce(["binding","fenced","recovery_required","outcome_unknown"].includes(_[5])?_[5]:"recovery_required"):void 0;r=null,S.finish(_[4]==="result"?_[5]:void 0,x)}catch{l()}},n.start();let c=(v,_,k)=>{try{if(p(),k.aborted)throw ce();if(r)throw ce("busy");if(s>4294967295)throw l(),ce()}catch(x){return Promise.reject(x)}let S=s++;return new Promise((x,P)=>{let C=!1,E=()=>O(void 0,ce(ew(v)?"fenced":"outcome_unknown")),O=(L,z)=>{C||(C=!0,k.removeEventListener("abort",E),z?P(z):x(L))};r={id:S,action:v,finish:O},k.addEventListener("abort",E,{once:!0});try{let L=[1,i.binding,i.generation,S,v,_];if(!Ka(L))throw ce("binding");n.postMessage(L)}catch(L){r=null,O(void 0,L),l()}})},d=(v,_)=>{try{if(p(),s>4294967295)throw l(),ce()}catch(S){return Promise.reject(S)}let k=s++;return new Promise((S,x)=>{a.set(k,(P,C)=>C?x(C):S(P));try{let P=[1,i.binding,i.generation,k,v,_];if(!Ka(P))throw ce("binding");n.postMessage(P)}catch(P){a.delete(k),x(P)}})},u=Object.freeze({async list(){let v=await d("ledgerList",null);if(!Array.isArray(v))throw ce("recovery_required");return v.flatMap(_=>{try{let k=jx(JSON.parse(String(_)));return k?[k]:[]}catch{return[]}})},async put(v){await d("ledgerPut",[v.mutationId,JSON.stringify(v)])},async remove(v){await d("ledgerRemove",v)}}),f=(v,_)=>{let k=ew(v)?"fenced":"outcome_unknown";try{if(p(),_.aborted)throw ce()}catch{throw ce(k)}},h=async(v,_,k)=>{let S=await c(v,_,k);f(v,k);let x=Et(S,i.scope);return f(v,k),x},m=async(v,_,k)=>{let S=await h(v,_,k);if(f(v,k),S.version!==2)throw ce("recovery_required");return S},b=async(v,_,k)=>{let S=await h(v,_,k);if(f(v,k),S.version!==3&&S.version!==4)throw ce("recovery_required");return S},w=Object.freeze({scope:i.scope,async load(v){let _=await c("load",null,v);f("load",v);let k=_===null?null:Et(_,i.scope);return f("load",v),k},prepare:(v,_)=>m("prepare",Ho(v),_),recordAttempt:(v,_)=>m("recordAttempt",v,_),recordConfirmed:(v,_)=>m("recordConfirmed",v,_),recordVerified:(v,_)=>m("recordVerified",v,_),async prepareResources(v,_){let k=await b("prepareResources",xt(v),_);if(f("prepareResources",_),k.version!==3)throw ce("recovery_required");return k},async prepareResourceRound(v,_,k){let S=await b("prepareResourceRound",[xt(v),_],k);if(f("prepareResourceRound",k),S.version!==4)throw ce("recovery_required");return S},recordResourceAttempt:(v,_)=>b("recordResourceAttempt",v,_),recordResourceConfirmed:(v,_)=>b("recordResourceConfirmed",v,_),recordResourceVerified:(v,_)=>b("recordResourceVerified",v,_),recordResourceRejected:(v,_)=>b("recordResourceRejected",v,_)}),g=t.people===!0?Object.freeze({collection:i.scope.collection,isCurrent(){try{return p(),!0}catch{return!1}},async request(v,_={}){if(v!=="identity"&&v!=="members")throw A("invalid_request","invalid people resource");let k=v==="identity"?"peopleIdentity":"peopleMembers",S=_.signal??t.signal;try{let x=await c(k,null,S);f(k,S);let P=Fa(v,x);return f(k,S),P}catch(x){try{f(k,S)}catch{throw A("unauthenticated","people scope changed","people_fenced")}throw x instanceof ti?A(x.reason==="busy"?"unavailable":"unauthenticated","people metadata request failed",x.reason==="busy"?"people_busy":"people_fenced"):x}}}):void 0,y=Object.freeze({async assess(v,_,k){let S=k!==void 0,x=await c("resourcesAssess",S?[v,ei(k)]:v,_);f("resourcesAssess",_);let P=Jo(x,S);return f("resourcesAssess",_),P},async apply(v,_,k,S){if(!sp.test(_))throw ce("binding");let x=await c("resourcesApply",S===void 0?[v,_]:[v,_,ei(S)],k);f("resourcesApply",k);let P=xt(x);return f("resourcesApply",k),P}});return Object.freeze({journal:w,close:l,resourceSetup:y,ledger:u,...g?{peopleAuthority:g}:{},async assess(v,_){await c("assess",v,_),f("assess",_)},async setForeground(v,_){await c("foreground",v,_),f("foreground",_)}})}var sp,Yo,Wi,op,i2,Va,ti,ce,r2,o2,s2,a2,dh,ew,l2,no=I(()=>{"use strict";Go();ie();Nx();rp();sp=/^sha256:[0-9a-f]{64}$/,Yo=n=>!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.getPrototypeOf(n)===Object.prototype,Wi=(n,e=4096)=>typeof n=="string"&&n.length>0&&n.length<=e;op=(n,e,t=[])=>{let i=e.split(",");return i.every(o=>Object.hasOwn(n,o))&&Object.keys(n).every(o=>i.includes(o)||t.includes(o))};i2=512*1024+8192,Va=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,ti=class extends Error{constructor(t){super(`app collection control: ${t}`);this.reason=t;this.name="AppCollectionControlError"}reason},ce=(n="fenced")=>new ti(n);r2=n=>n==="ledgerList"||n==="ledgerPut"||n==="ledgerRemove",o2=16*1024,s2=448*1024,a2=["load","prepare","prepareResources","prepareResourceRound","recordAttempt","recordConfirmed","recordVerified","recordResourceAttempt","recordResourceConfirmed","recordResourceVerified","recordResourceRejected","assess","foreground","peopleIdentity","peopleMembers","resourcesAssess","resourcesApply","ledgerList","ledgerPut","ledgerRemove"],dh=n=>n==="peopleIdentity"?"identity":n==="peopleMembers"?"members":null,ew=n=>n==="load"||n==="assess"||n==="foreground"||n==="resourcesAssess"||n==="resourcesApply"||dh(n)!==null,l2=n=>n==="load"||n==="prepare"||n==="prepareResources"||n==="prepareResourceRound"||n.startsWith("record")});function iw(n){if(!/^sha256:[a-f0-9]{64}$/.test(n))throw Hi();return Uint8Array.from(n.slice(7).match(/../g),e=>parseInt(e,16))}function tw(n){if(!(n instanceof Map)||[...n.keys()].some(e=>typeof e!="number"))throw Hi();return n}function fh(n,e){if(!(n instanceof Uint8Array)||n.length!==e)throw Hi();return n.slice()}function nw(n){if(n instanceof yt)return n.value;if(n instanceof Map){if([...n.keys()].some(e=>typeof e!="string"))throw Hi();return Object.fromEntries([...n].map(([e,t])=>[e,nw(t)]))}if(Array.isArray(n))return n.map(nw);if(n===null||["string","boolean","number"].includes(typeof n))return n;throw Hi()}async function ap(n,e,t,i){let o=pe(new Map([[0,1],[1,e],...t].sort(([r],[a])=>Number(r)-Number(a)))),s;try{s=await n.declaredSetup(o,i);let r=tw(ue(s));if(r.get(0)!==1)throw Hi();let a=r.get(1),p=a==="review"?[0,1,2,3,4,5,6,7,8,9,10]:a==="pending"?[0,1,2]:a==="receipt"?[0,1,3]:a==="cancelled"?[0,1]:[];if(r.size!==p.length||p.some(f=>!r.has(f)))throw Hi();if(a==="cancelled")return{kind:a};if(a==="receipt")return{kind:a,receipt:kt.dec(r.get(3))};let l=fh(r.get(2),16);if(a==="pending")return{kind:a,ticket:l};if(a!=="review"||!["ready","setup_required","incompatible"].includes(r.get(3))||typeof r.get(8)!="string")throw Hi();let c=tw(r.get(9)),d=r.get(10);if(!(c instanceof Map)||c.size!==2||![c.get(0),c.get(1)].every(f=>Number.isSafeInteger(f)&&Number(f)>=0&&Number(f)<=256)||!Array.isArray(d)||d.length>32)throw Hi();let u=d.map(f=>{let h=tw(f);if(h.size!==2||typeof h.get(0)!="string"||!["create","skip"].includes(h.get(1)))throw Hi();return Object.freeze({path:h.get(0),action:h.get(1)})});return{kind:a,ticket:l,revision:fh(r.get(4),32),declaration:Vx(fh(r.get(7),32)),application:r.get(8),promoted:c.get(0),retained:c.get(1),records:Object.freeze(u),assessment:Jo({status:r.get(3)==="ready"?"current":r.get(3)==="incompatible"?"conflict":"provision",assessmentDigest:"sha256:"+Vx(fh(r.get(5),32)),review:nw(r.get(6))},!0)}}finally{o.fill(0),s?.fill(0)}}var Hi,Vx,Kx=I(()=>{"use strict";Je();ie();no();At();Hi=()=>A("internal","Invalid Native setup reply.","declared_setup_codec"),Vx=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")});function c2(n){return new Promise((e,t)=>{if(n?.aborted)return t(A("cancelled","Setup cancelled."));let i=()=>{clearTimeout(o),t(A("cancelled","Setup cancelled."))},o=setTimeout(()=>{n?.removeEventListener("abort",i),e()},100);n?.addEventListener("abort",i,{once:!0})})}function Wx(n){let{client:e,journal:t}=n,i=n.operations.includes("assess_collection_setup")&&n.operations.includes("apply_collection_setup"),o=new WeakMap,s=new WeakSet,r=!1;async function a(f){if(r)throw A("rate_limited","A setup operation is already running.");r=!0;try{return await f()}finally{r=!1}}async function p(f,h){if(f||await e.readyForRead(h),await n.assertCurrent(),h?.aborted)throw A("cancelled","Setup cancelled.");if(f&&(f.closed||e.currentSession()!==f))throw io()}async function l(f,h){try{await ap(f,"cancel",[[2,h]],AbortSignal.timeout(1e3))}catch{}}async function c(f={}){await p(void 0,f.signal);let h=await e.readyForRead(f.signal);await p(h,f.signal);let m=await Ef(n.manifest);await p(h,f.signal);let b=ei(f.adopt===void 0?{}:{adopt:f.adopt}),w=sh(f.records),g=[];b.adopt&&Object.keys(b.adopt).length&&g.push([3,new Map(Object.entries(b.adopt).map(([v,_])=>[v,iw(_)]))]),w.length&&g.push([4,w.map(v=>new Map([[0,v.path],[1,v.document]]))]);let y;try{let v=await ap(h,"assess",g,f.signal);await p(h,f.signal);for(let _=0;v.kind==="pending";_++){if(y=v.ticket,_>=512)throw lp();await c2(f.signal),await p(h,f.signal),v=await ap(h,"poll",[[2,y]],f.signal),await p(h,f.signal)}if(v.kind!=="review")throw lp();if(y=v.ticket,v.declaration!==m||v.application!==n.manifest?.id)throw io();if(v.records.length!==w.length||v.records.some((_,k)=>_.path!==w[k].path))throw lp();return{s:h,review:v,options:{records:w,...b.adopt?{adopt:Object.freeze({...b.adopt})}:{}}}}catch(v){throw y&&await l(h,y),v}}async function d(f){await p(void 0,f);let h=await t.load();if(await p(void 0,f),!h)return;let m;try{m=await e.receipt(h,f)}catch(b){throw Xo(h,b)}if(await p(void 0,f),m.mutation!==h||m.state!=="confirmed"&&m.state!=="rejected")throw Xo(h);await t.clear(h)}let u={async assess(f={}){let h=await u.plan(f),m=o.get(h);return m&&(await l(m.session,m.review.ticket),await p(m.session,f.signal)),h.status==="current"?"ready":h.status==="conflict"?"incompatible":"setup_required"},async plan(f={}){return a(async()=>{if(await p(void 0,f.signal),!i){if(n.operations.includes("apply_collection_setup")||n.operations.includes("assess_collection_setup"))throw lp();let g=tp({status:"current",assessmentDigest:`sha256:${"0".repeat(64)}`,review:{configuration:[],packs:[],staged:[]}},{canManage:!1,canCreateRecords:!1,records:[]});return s.add(g),g}await d(f.signal);let{s:h,review:m,options:b}=await c(f),w=tp(m.assessment,{canManage:!0,canCreateRecords:h.hello.grant.capabilities.includes("records.create"),records:m.records.map(g=>({path:g.path,free:g.action==="create"}))});if(m.promoted){let g=Object.freeze([...w.changes,{kind:"record",target:"Existing files",message:`Recognize ${m.promoted} existing ${m.promoted===1?"file":"files"} as notes, preserving their contents.`}]);w=Object.freeze({...w,changes:g,summary:`This app will make ${g.length} ${g.length===1?"change":"changes"} to this collection.`})}return o.set(w,{session:h,review:m,options:b,consumed:!1}),w})},async apply(f,h={}){return a(async()=>{if(s.has(f))return await p(void 0,h.signal),"ready";let m=o.get(f);if(!m)throw new TypeError("setup.apply needs the original plan returned by setup.plan");if(m.consumed)throw io();if(f.refusal)throw A(f.refusal.code==="setup_conflict"?"conflict":"forbidden",f.refusal.message,f.refusal.code);if(await p(m.session,h.signal),f.status==="current"){let b=await c({signal:h.signal});if(await l(b.s,b.review.ticket),b.review.assessment.status!=="current")throw io();return"ready"}m.consumed=!0;for(let b=0;;b++){let w=crypto.randomUUID(),g;try{g=await t.begin(w)}catch(_){throw Xo(w,_)}if(g!==w)throw Xo(g);let y=!1,v=!1;try{await p(m.session,h.signal),y=!0;let _=await ap(m.session,"apply",[[2,m.review.ticket],[3,U(w)],[4,m.review.revision],[5,iw(f.digest)]],h.signal);if(await n.assertCurrent(),_.kind!=="receipt"||_.receipt.mutation!==w)throw Xo(w);let k=_.receipt.state==="pending"?await e.awaitReceipt(w,3e4,h.signal):_.receipt;if(await n.assertCurrent(),k.mutation!==w||k.state!=="confirmed"&&k.state!=="rejected")throw Xo(w);if(v=!0,await t.clear(w),k.state==="rejected"||(k.conflicts?.length??0)>0||k.status!==void 0&&k.status!=="applied")throw io(w,k.problem);let S=await c({signal:h.signal});if(S.review.assessment.status!=="current")throw lp();return await l(S.s,S.review.ticket),"ready"}catch(_){if(!y||v||Hm(_)&&_.code!=="outcome_unknown"){if(await t.clear(w),!v&&Hm(_)&&_.code==="not_found"){if(b)throw io(w,_);await p(m.session,h.signal);let k=await c({...m.options,signal:h.signal});try{if(await p(m.session,h.signal),k.s!==m.session||k.review.assessment.assessmentDigest!==f.digest||k.review.assessment.status!=="provision"||k.review.promoted!==m.review.promoted||k.review.retained!==m.review.retained||k.review.records.some((S,x)=>S.action!==m.review.records[x]?.action))throw io(w,_)}catch(S){throw await l(k.s,k.review.ticket),S}m={...m,review:k.review};continue}throw new se((oe(_)?_:io()).toProblem(),{mutationId:w,cause:_})}throw Xo(w,_)}}})}};return Object.freeze(u)}var io,Xo,lp,Hx=I(()=>{"use strict";ie();ge();Rl();no();ah();Tf();Kx();io=(n,e)=>new se(A("conflict","This collection changed since setup was reviewed. Review it again.","setup_changed").toProblem(),{...n?{mutationId:n}:{},...e?{cause:e}:{}}),Xo=(n,e)=>new se(A("outcome_unknown","Reconcile the original setup before trying again.","setup_outcome_unknown").toProblem(),{mutationId:n,...e?{cause:e}:{}}),lp=()=>A("unavailable","Native setup is unavailable.","resource_setup_unavailable")});function Yx(n){let e=new Uint8Array([...n.aad,...new TextEncoder().encode("\0declared-setup-attempt-v1")]),t=()=>A("unavailable","Protected Native setup attempt storage is unavailable.","grant_storage");async function i(){let s=await n.grant();await n.assertCurrent(s);let r=await n.store();if(!r.getSetupAttempt||!r.putSetupAttemptIfAbsent||!r.deleteSetupAttempt)throw t();return{grant:s,store:r}}async function o(s,r){let a;try{if(s.length<29||s.length>2048)throw t();a=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:s.slice(0,12),additionalData:e},r.refreshKey,s.slice(12)));let p=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a)),l=Array.from(r.noisePublicKey,c=>c.toString(16).padStart(2,"0")).join("");if(p.version!==1||!Gx.test(p.mid)||p.noise!==l||Object.keys(p).sort().join(",")!=="mid,noise,version")throw t();return await n.assertCurrent(r),p.mid}catch{throw t()}finally{a?.fill(0)}}return{async load(){let{grant:s,store:r}=await i(),a=await r.getSetupAttempt(s.collection);return await n.assertCurrent(s),a?o(a,s):void 0},async begin(s){if(!Gx.test(s))throw t();let{grant:r,store:a}=await i(),p=crypto.getRandomValues(new Uint8Array(12)),l=new TextEncoder().encode(JSON.stringify({version:1,mid:s,noise:Array.from(r.noisePublicKey,u=>u.toString(16).padStart(2,"0")).join("")})),c;try{c=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:p,additionalData:e},r.refreshKey,l))}finally{l.fill(0)}await n.assertCurrent(r);let d=await a.putSetupAttemptIfAbsent(r.collection,new Uint8Array([...p,...c]));return o(d,r)},async clear(s){let{grant:r,store:a}=await i(),p=await a.getSetupAttempt(r.collection);p&&await o(p,r)===s&&(await n.assertCurrent(r),await a.deleteSetupAttempt(r.collection,p))}}}var Gx,Jx=I(()=>{"use strict";ie();Gx=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/});function cp(){throw A("unauthenticated","the stored grant belongs to another app","grant_storage")}function Xx(n,e,t={}){let i=globalThis.indexedDB;if(!i)throw A("unavailable","IndexedDB is not available here","grant_storage");let o=t.owner;if(o!==void 0&&!Fo(o))throw A("invalid_request","invalid grant store owner","grant_storage");let s=o===void 0?`mdbase.app-grants.v1.${encodeURIComponent(n)}.${e}`:`mdbase.app-grants.v2.${encodeURIComponent(n)}.${encodeURIComponent(o)}.${e}`,r=h=>h===void 0||o===void 0||h.owner===o?h:cp(),a=h=>o===void 0||h===void 0||h.owner===o,p=h=>o===void 0?h:{...h,owner:o},l=null,c=()=>l??=new Promise((h,m)=>{let b=i.open(s,2);b.onupgradeneeded=()=>{for(let w of[rw,Zo,Wa])b.result.objectStoreNames.contains(w)||b.result.createObjectStore(w)},b.onsuccess=()=>{b.result.onversionchange=()=>{b.result.close(),l=null},h(b.result)},b.onerror=()=>{l=null,m(A("unavailable","grant storage could not be opened","grant_storage"))}}),d=async(h,m,b)=>{let w=await c();return new Promise((g,y)=>{let v=w.transaction([...h],m,{durability:"strict"}),_,k=!1;v.oncomplete=()=>k?g(_):y(A("unavailable","grant storage returned no result","grant_storage")),v.onabort=v.onerror=()=>y(A("unavailable","grant storage transaction failed","grant_storage"));try{b(v,S=>{_=S,k=!0})}catch{try{v.abort()}catch{}}})},u=(h,m,b)=>d([h],m,(w,g)=>b(w.objectStore(h),g)),f=(h,m)=>u(h,"readonly",(b,w)=>{let g=b.get(m);g.onsuccess=()=>w(g.result)});return{getSetupAttempt:async h=>r(await f(Wa,h))?.bytes,putSetupAttemptIfAbsent:async(h,m)=>r(await u(Wa,"readwrite",(b,w)=>{let g=b.get(h);g.onsuccess=()=>{if(g.result!==void 0)return w(g.result);let y=p({bytes:m.slice()});b.add(y,h).onsuccess=()=>w(y)}})).bytes,deleteSetupAttempt:async(h,m)=>{await u(Wa,"readwrite",(w,g)=>{let y=w.get(h);y.onsuccess=()=>{if(!a(y.result))return g("refused");let v=y.result?.bytes;if(!v||v.length!==m.length||!v.every((_,k)=>_===m[k]))return g("done");w.delete(h).onsuccess=()=>g("done")}})==="refused"&&cp()},getIdentity:async()=>r(await f(rw,"installation")),putIdentityIfAbsent:async h=>r(await u(rw,"readwrite",(m,b)=>{let w=m.get("installation");w.onsuccess=()=>{if(w.result!==void 0)return b(w.result);let g=p(h);m.add(g,"installation").onsuccess=()=>b(g)}})),getGrant:async h=>r(await f(Zo,h)),listGrants:async()=>(await u(Zo,"readonly",(h,m)=>{let b=h.getAll();b.onsuccess=()=>m(b.result)})).map(h=>r(h)),putGrant:async h=>{await u(Zo,"readwrite",(b,w)=>{let g=b.get(h.collection);g.onsuccess=()=>{if(!a(g.result))return w("refused");b.put(p(h),h.collection).onsuccess=()=>w("done")}})==="refused"&&cp()},deleteGrant:async h=>{await u(Zo,"readwrite",(b,w)=>{let g=b.get(h);g.onsuccess=()=>{if(!a(g.result))return w("refused");b.delete(h).onsuccess=()=>w("done")}})==="refused"&&cp()},clearGrants:async()=>{await d([Zo,Wa],"readwrite",(m,b)=>{let w=!1,g=2,y=()=>{--g===0&&b(w?"refused":"done")};for(let v of[Zo,Wa]){let _=m.objectStore(v);if(o===void 0){_.clear().onsuccess=y;continue}let k=_.openCursor();k.onsuccess=()=>{let S=k.result;if(!S)return y();a(S.value)?S.delete():w=!0,S.continue()}}})==="refused"&&cp()}}}var rw,Zo,Wa,Zx=I(()=>{"use strict";eo();ie();rw="identity",Zo="grants",Wa="native-setup-attempts"});var rC={};ls(rC,{MdbaseAppGrants:()=>lw,deliverAppGrantCallback:()=>h2,mergeCollectionEntries:()=>y2});function u2(n){try{let e=Uint8Array.from(atob(n.replaceAll("-","+").replaceAll("_","/")),t=>t.charCodeAt(0));return e.length===32&&rn(e)===n}catch{return!1}}function h2(n){let e=globalThis.BroadcastChannel;if(!e)throw A("unavailable","BroadcastChannel is not available","authorization_callback");let t=new e(iC);t.postMessage({type:"callback",url:String(n)}),t.close()}function m2(){return{subscribe(n){let e=globalThis.BroadcastChannel;if(!e)throw A("unavailable","BroadcastChannel is not available","authorization_callback");let t=new e(iC);return t.onmessage=i=>{let o=i.data;o?.type==="callback"&&typeof o.url=="string"&&n(o.url)},()=>t.close()}}}function y2(n,e){let t=new Map;for(let i of n)t.set(i.collectionId,Object.freeze({collectionId:i.collectionId,displayName:i.displayName,kind:"cloud_copy",availability:i.availability??Object.freeze({state:"available"}),role:i.role}));for(let i of e)t.has(i.collectionId)||t.set(i.collectionId,Object.freeze({collectionId:i.collectionId,displayName:i.displayName,kind:"private",availability:i.availability,role:i.role}));return[...t.values()].sort((i,o)=>i.displayName.localeCompare(o.displayName)||i.collectionId.localeCompare(o.collectionId))}async function aw(n,e){let t=new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},n,e));if(t.length!==64)throw A("internal","unexpected signature length","authorization_signature");let i=0n;for(let s of t.subarray(32))i=i<<8n|BigInt(s);if(i<=Qx/2n)return t;let o=Qx-i;for(let s=63;s>=32;s--)t[s]=Number(o&0xffn),o>>=8n;return t}async function g2(n,e,t,i){let o=Math.floor(Date.now()/1e3),s=crypto.randomUUID(),r=[fP,wb,"POST",e,await nC(t),await nC(i),o,s].join(`
|
|
130
|
-
`);return{[Lc.version]:String(wb),[Lc.timestamp]:String(o),[Lc.nonce]:s,[Lc.signature]:rn(await aw(n,new TextEncoder().encode(r)))}}async function ow(n,e){let t=await crypto.subtle.generateKey({name:e,namedCurve:"P-256"},!1,n);return{privateKey:t.privateKey,publicKey:rn(new Uint8Array(await crypto.subtle.exportKey("raw",t.publicKey)))}}async function b2(){let n;try{n=await crypto.subtle.generateKey({name:"X25519"},!1,["deriveBits"])}catch{throw A("unavailable","this browser cannot keep a non-extractable X25519 key","browser_unsupported")}if(n.privateKey.extractable)throw A("unavailable","the Noise key must be non-extractable","browser_unsupported");return{privateKey:n.privateKey,publicKey:new Uint8Array(await crypto.subtle.exportKey("raw",n.publicKey))}}function w2(n){return{publicKey:n.noisePublicKey.slice(),dh:async e=>{let t=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:t},n.noisePrivateKey,256))}}}function v2(n,e){let t=new AbortController,i=()=>t.abort(),o=setTimeout(i,e);return o.unref?.(),n?.addEventListener("abort",i,{once:!0}),n?.aborted&&t.abort(),{signal:t.signal,done:()=>{clearTimeout(o),n?.removeEventListener("abort",i)}}}async function _2(n,e){let t=globalThis.navigator?.locks;if(t)return t.request(n,{mode:"exclusive"},e);let i=mh.get(n)??Promise.resolve(),o,s=new Promise(r=>{o=r});mh.set(n,s),await i;try{return await e()}finally{o(),mh.get(n)===s&&mh.delete(n)}}var p2,iC,ro,d2,Qx,f2,rn,hh,eC,tC,nC,yh,Ha,sw,Gi,mh,lw,oC=I(()=>{"use strict";jc();Qr();Ea();vu();If();qx();Tf();ge();Lr();ie();Fy();qo();Ts();bd();Yl();iu();Mx();Hx();Jx();Wm();Zx();Ob();p2=new Set(["owner","editor","viewer"]),iC="mdbase.app-grant.v1",ro=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,d2=15e3;Qx=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),f2=new TextEncoder().encode("mdbase-next client noise key v1\0");rn=n=>{let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")},hh=n=>crypto.getRandomValues(new Uint8Array(n)),eC=n=>{let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n),e},tC=(...n)=>{let e=new Uint8Array(n.reduce((i,o)=>i+o.length,0)),t=0;for(let i of n)e.set(i,t),t+=i.length;return e};nC=async n=>rn(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n))));yh=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),Ha=(n,e)=>!!e&&n.collection===e.collection&&n.owner===e.owner&&yh(n.noisePublicKey,e.noisePublicKey),sw=(n,e)=>Ha(n,e)&&yh(n.refresh,e.refresh),Gi=()=>A("cancelled","the stored grant changed during this operation"),mh=new Map;lw=class{constructor(e){this.options=e;this.declaration=yr(e.declaration),this.cpOrigin=Xn({environment:this.declaration.environment,appOrigin:this.declaration.origin,release:Ex()}).cpOrigin;try{this.redirect=new URL(e.redirectUri)}catch{throw A("invalid_request","redirectUri must be an absolute URL","redirect_uri")}if(this.redirect.origin!==this.declaration.origin||this.redirect.hash)throw A("invalid_request","redirectUri must be on the app's origin, without a fragment","redirect_uri");this.fetcher=e.fetch??globalThis.fetch.bind(globalThis),this.callbacks=e.callbacks??m2(),this.storeValue=e.store??null}options;declaration;cpOrigin;redirect;fetcher;callbacks;storeValue;registration=null;tokens=new Map;refreshing=new Map;forgotten=new Set;epoch=0;register(){let e=this.registration??=qf({declaration:this.options.declaration,signal:new AbortController().signal,isCurrent:()=>!0,fetch:this.fetcher});return e.catch(()=>{this.registration===e&&(this.registration=null)}),e}ownerValue=null;owner(){return this.ownerValue??=mk(Zr(this.declaration).manifest.id,wu(this.declaration))}async store(){if(this.storeValue)return this.storeValue;let e=this.owner();return this.storeValue=Xx(this.cpOrigin,(await this.register()).id,{owner:e})}async identity(){let e=await this.store(),t=await e.getIdentity();if(t)return t;let i=await ow(["sign"],"ECDSA");return e.putIdentityIfAbsent({version:1,privateKey:i.privateKey,publicKey:i.publicKey})}async request(e,t,i){let o=v2(i,d2);try{let s;try{s=await this.fetcher(`${this.cpOrigin}${e}`,{...t,redirect:"error",signal:o.signal})}catch{throw i?.aborted?A("cancelled","request cancelled"):A("unavailable","cannot reach the control plane","control_unreachable")}let r=null;try{let a=await s.json();a&&typeof a=="object"&&!Array.isArray(a)&&(r=a)}catch{r=null}return{status:s.status,body:r}}finally{o.done()}}async authorize(e){e=Object.freeze({...e});let t=await this.prepareAuthorization(e).catch(i=>{throw e.popup.close(),i});try{e.popup.navigate(t.authorizationUri);let{collectionId:i}=await t.finish(e);return{collectionId:i}}finally{t.cancel();try{e.popup.close()}catch{}}}async prepareAuthorization(e={}){if(e=Object.freeze({...e}),e.collection!==void 0&&!ro.test(e.collection))throw A("invalid_request","collection must be a UUID");if(e.expectedAccountId!==void 0&&(!ro.test(e.expectedAccountId)||!e.authorizationNonce))throw A("invalid_request","original account and challenge required","authorization_binding");if(e.authorizationNonce!==void 0&&(!/^[A-Za-z0-9_-]{43}$/.test(e.authorizationNonce)||!u2(e.authorizationNonce)))throw A("invalid_request","invalid original challenge","authorization_binding");let t=new AbortController,i=e.signal?AbortSignal.any([e.signal,t.signal]):t.signal,o=this.epoch,s=()=>{if(i.aborted)throw A("cancelled","authorization fenced","authorization_cancelled");if(o!==this.epoch)throw Gi()};s();let r=await this.register(),a=Zr(this.declaration),p=await this.identity(),l=await ow(["deriveBits"],"ECDH"),c=await ow(["sign"],"ECDSA"),d=await b2(),u=rn(hh(32)),f=rn(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(u)))),h=rn(hh(24)),m=crypto.randomUUID(),b=new Date,w={protocol_version:hr,authorization_id:m,application_id:r.id,application_declaration_id:String(a.manifest.id),application_manifest_digest:r.manifestDigest,application_installation_id:await lP(p.publicKey),installation_signing_public_key:p.publicKey,grant_agreement_public_key:l.publicKey,grant_signing_public_key:c.publicKey,flow:"authorization_code",authorization_nonce:e.authorizationNonce??rn(hh(32)),issued_at:b.toISOString(),expires_at:new Date(b.getTime()+10*6e4).toISOString(),redirect_uri:this.redirect.href,state:h,code_challenge:f,contracts:a.contracts,requested_operations:[...a.operations],...a.files?{requested_files:a.files}:{},...e.collection?{collection_id:e.collection}:{}},g={binding:w,signature:rn(await aw(p.privateKey,cP(w)))},y=tC(f2,eC(16),U(m),eC(32),d.publicKey),v={public_key:rn(d.publicKey),signature:rn(await aw(c.privateKey,y))};s();let _=await this.request("/oauth/authorization_request",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:r.id,redirect_uri:this.redirect.href,code_challenge:f,code_challenge_method:"S256",state:h,operations:a.operations.join(","),...e.collection?{collection_id:e.collection}:{},application_authorization:JSON.stringify(g),client_noise_key:JSON.stringify(v)})},i);s();let k=_.body?.authorization_uri;if(_.status!==200||_.body?.authorization_id!==m||typeof k!="string"||!k.startsWith(`${this.cpOrigin}/oauth/authorize?`))throw A("unavailable",`authorization could not be started (${_.status})`,"authorization_start");let S=null,x=this.awaitCallback(h,{navigate(){},close(){},get closed(){return S?.closed===!0}},{popup:{navigate(){},close(){}},signal:i,timeoutMs:e.timeoutMs});x.catch(()=>{});let P=!1;return Object.freeze({applicationId:r.id,manifestDigest:r.manifestDigest,authorizationId:m,authorizationUri:k,cancel:()=>t.abort(),finish:async C=>{if(C=Object.freeze({...C}),P)throw A("invalid_request","original authorization already consumed","authorization_binding");P=!0,S=C.popup;let E=()=>t.abort();C.signal?.addEventListener("abort",E,{once:!0}),C.signal?.aborted&&t.abort();try{s();let O=C.collection??e.collection;if(O!==void 0&&!ro.test(O))throw A("invalid_request","invalid approved collection","authorization_binding");if(e.collection&&O!==e.collection)throw A("forbidden","a different collection was approved","collection_mismatch");if(e.expectedAccountId&&!O)throw A("invalid_request","original Private choice required","authorization_binding");let L=await x;s();let z=await this.request("/oauth/token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:L,client_id:r.id,redirect_uri:this.redirect.href,code_verifier:u})},i);s();let Q=e.expectedAccountId?Nf(z.body,{accountId:e.expectedAccountId,authorizationRequestId:m,applicationId:r.id,declarationId:w.application_declaration_id,manifestDigest:r.manifestDigest,applicationInstallationId:w.application_installation_id,applicationOrigin:this.redirect.origin,collectionId:O,grantSigningPublicKey:c.publicKey,clientNoisePublicKey:rn(d.publicKey)}):void 0,V=await this.saveTokens(z,{noise:d,signing:c.privateKey,collection:O,check:s});return s(),{collectionId:V,...Q?{nativeCompletion:Q}:{}}}finally{C.signal?.removeEventListener("abort",E),t.abort()}}})}awaitCallback(e,t,i){let o=Math.min(Math.max(i.timeoutMs??6e5,1e3),18e5);return new Promise((s,r)=>{let a=null,p=f=>{c(),clearTimeout(d),clearInterval(u),i.signal?.removeEventListener("abort",l),f()},l=()=>p(()=>r(A("cancelled","authorization cancelled","authorization_cancelled"))),c=this.callbacks.subscribe(f=>{let h;try{h=new URL(f)}catch{return}if(h.origin!==this.redirect.origin||h.pathname!==this.redirect.pathname||h.searchParams.get("state")!==e)return;if(h.searchParams.get("error"))return p(()=>r(A("forbidden","access was not approved","authorization_denied")));let b=h.searchParams.get("code");if(!b)return p(()=>r(A("unavailable","the authorization callback has no code","authorization_callback")));p(()=>s(b))}),d=setTimeout(()=>p(()=>r(A("cancelled","authorization timed out","authorization_timed_out"))),o),u=setInterval(()=>{let f=!1;try{f=t.closed===!0}catch{f=!1}if(!f){a=null;return}a??=Date.now(),Date.now()-a>=3e3&&p(()=>r(A("cancelled","the authorization window was closed","authorization_cancelled")))},500);i.signal?.addEventListener("abort",l,{once:!0}),i.signal?.aborted&&l()})}async saveTokens(e,t){let i=e.body;if(e.status!==200||!i)throw e.status===400&&i&&typeof i.error=="string"&&i.error==="invalid_grant"?A("unauthenticated","the grant is no longer valid","grant_invalid"):e.status===400?un("sync_required"):A("unavailable",`token request failed (${e.status})`,"token_error");let o=i.access_token,s=i.refresh_token,r=i.collection_id,a=i.expires_in,p=i.refresh_expires_in;if(typeof o!="string"||typeof s!="string"||typeof r!="string"||!ro.test(r)||typeof a!="number"||!(a>0)||typeof p!="number"||!(p>0))throw A("unavailable","invalid token response","token_response");let l=r.toLowerCase();if(t.collection&&t.collection.toLowerCase()!==l)throw A("forbidden","a different collection was approved","collection_mismatch");if(t.previous&&t.previous.collection!==l)throw A("unavailable","the token names another collection","token_response");let c=t.previous?.refreshKey??await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),d=hh(12),u=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:d,additionalData:this.aad(l)},c,new TextEncoder().encode(s))),f=t.noise??{privateKey:t.previous.noisePrivateKey,publicKey:t.previous.noisePublicKey},h=t.signing??t.previous?.signingPrivateKey,m={version:1,collection:l,noisePrivateKey:f.privateKey,noisePublicKey:f.publicKey,refreshKey:c,refresh:tC(d,u),refreshExpiresAt:Date.now()+p*1e3,...h?{signingPrivateKey:h}:{},...t.previous?.owner?{owner:t.previous.owner}:{}},b=this.epoch;return await this.withLock(l,"commit",async()=>{let w=await this.store();if(b!==this.epoch||t.previous&&!sw(t.previous,await w.getGrant(l)))throw Gi();t.check?.(),await w.putGrant(m);let g=await w.getGrant(l);if(!g||!yh(m.noisePublicKey,g.noisePublicKey)||!yh(m.refresh,g.refresh))throw Gi();t.check?.(),this.tokens.set(l,{access:o,expiresAt:Date.now()+a*1e3,collection:l,owner:g.owner,noisePublicKey:g.noisePublicKey.slice()}),this.forgotten.delete(l)}),l}aad(e){return new TextEncoder().encode(`mdbase.app-grant.v2\0${this.cpOrigin}\0${this.owner()}\0${e}`)}async accessToken(e,t=!1){let i=await this.heldGrant(e),o=this.tokens.get(e);if(!t&&o&&Ha(i,o)&&o.expiresAt-Date.now()>6e4)return o.access;let s=this.refreshing.get(e);if(s&&sw(i,s.grant)){let p=await s.work;return await this.assertCurrent(i),p}let r=this.withLock(e,"refresh",async()=>{let p=await this.assertCurrent(i);return this.refresh(e,p)}),a={grant:i,work:r};this.refreshing.set(e,a);try{let p=await r;return await this.assertCurrent(i),p}finally{this.refreshing.get(e)===a&&this.refreshing.delete(e)}}withLock(e,t,i){return _2(`mdbase.app-grant.${t}:${JSON.stringify([this.cpOrigin,this.owner(),e])}`,i)}async heldGrant(e){let t=await(await this.store()).getGrant(e);if(!t)throw un("sync_required");return{...t,noisePublicKey:t.noisePublicKey.slice(),refresh:t.refresh.slice()}}async assertCurrent(e){let t=await(await this.store()).getGrant(e.collection);if(!Ha(e,t))throw Gi();return t}async refresh(e,t){if(t.refreshExpiresAt<=Date.now())throw un("sync_required");let i;try{let p=await crypto.subtle.decrypt({name:"AES-GCM",iv:t.refresh.slice(0,12),additionalData:this.aad(e)},t.refreshKey,t.refresh.slice(12));i=new TextDecoder().decode(p)}catch{throw A("unauthenticated","the stored grant could not be read","grant_storage")}let o=await this.register(),s=new URLSearchParams({grant_type:"refresh_token",refresh_token:i,client_id:o.id}),r=t.signingPrivateKey?await g2(t.signingPrivateKey,"/oauth/token",s.toString(),i):{},a=await this.request("/oauth/token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...r},body:s});try{await this.saveTokens(a,{previous:t})}catch(p){throw oe(p,"unauthenticated")&&p.reason==="grant_invalid"&&await this.withLock(e,"commit",async()=>{let l=await this.store();if(!sw(t,await l.getGrant(e)))throw Gi();await l.deleteGrant(e),this.forgotten.add(e);let c=this.tokens.get(e);c&&Ha(t,c)&&this.tokens.delete(e)}),p}return a.body.access_token}async route(e,t){for(let i=0;;i++){let o=await this.accessToken(e,i>0),s=await this.request(`/v1/next/collections/${encodeURIComponent(e)}/route`,{headers:{authorization:`Bearer ${o}`}},t);if(s.status===401&&i===0)continue;if(s.status===401)throw A("unauthenticated","the control plane refused the access token");if(s.status===409)throw A("unauthenticated","this app's key is not registered with its grant","client_key_required");if(s.status!==200||!s.body)throw A("unavailable",`control plane answered ${s.status}`,"control_error");let r=s.body;if(typeof r.collection!="string"||r.collection.toLowerCase()!==e||!Array.isArray(r.targets))throw A("unauthenticated","the route does not match this collection's grant","route_mismatch");let p=zn(r.availability)??(js(r,null).length?{state:"available"}:{state:"unavailable",reason:r.reason==="no_device_registered"?"no_device_registered":"device_offline"});return{token:o,route:r,availability:p}}}async verifiedStoredNativeGrant(e){let t=await this.register(),i=await(await this.store()).getGrant(e.collection_id);return!!i&&e.application_id===t.id&&e.application_origin===this.declaration.origin&&i.owner===this.owner()&&rn(i.noisePublicKey)===e.client_noise_public_key}async collections(e={}){let t=await(await this.store()).listGrants(),i=[];for(let s of t)(e.bindings===void 0||e.bindings.some(r=>r.collection_id===s.collection&&r.application_origin===this.declaration.origin&&rn(s.noisePublicKey)===r.client_noise_public_key))&&i.push(s);let o=new Set(i.map(s=>s.collection));for(let s of i){let r;try{r=await this.accessToken(s.collection)}catch(l){if(oe(l)&&(l.code==="unauthenticated"&&l.reason==="grant_invalid"||l.code==="forbidden"&&l.reason==="sync_required"))continue;throw l}await this.assertCurrent(s);let a=await this.request("/v1/next/apps/collections",{headers:{authorization:`Bearer ${r}`}},e.signal);if(await this.assertCurrent(s),a.status===401)throw await this.withLock(s.collection,"commit",async()=>{await this.assertCurrent(s);let l=this.tokens.get(s.collection);if(l?.access!==r||!Ha(s,l))throw Gi();this.tokens.delete(s.collection)}),A("unauthenticated","the control plane refused the collection listing token");if(a.status!==200||!Array.isArray(a.body?.collections))throw A("unavailable",`control plane answered ${a.status}`,"control_error");let p=[];for(let l of a.body.collections){let c=typeof l.collection=="string"?l.collection.toLowerCase():"";if(!ro.test(c)||p.some(f=>f.collectionId===c))continue;let d=zn(l.availability);if(l.state!=="synced_e2e"&&!d)continue;let u=o.has(c)?d??{state:"opening"}:{state:"unavailable",reason:"sync_required"};p.push(Object.freeze({collectionId:c,displayName:typeof l.name=="string"?l.name:"Collection",operations:Object.freeze(Array.isArray(l.operations)?l.operations.filter(f=>typeof f=="string"):[]),availability:Object.freeze(u),role:p2.has(l.role)?l.role:null}))}return p}return[]}async availability(e,t={}){let i=e.toLowerCase();try{return(await this.route(i,t.signal)).availability}catch(o){if(oe(o)&&o.details instanceof Map&&typeof o.details.get("availability")=="string")return zn({state:"unavailable",reason:o.details.get("availability")});throw o}}async waitForAvailable(e,t={}){let i=Date.now()+Math.min(Math.max(t.timeoutMs??6e4,0),6e5),o=Math.max(t.intervalMs??3e3,1e3),s=null;for(;;){if(t.signal?.aborted)throw A("cancelled","wait cancelled");let r=await this.availability(e,t.signal?{signal:t.signal}:{});if((!s||r.state!==s.state||r.state==="unavailable"&&s.state==="unavailable"&&r.reason!==s.reason)&&t.onAvailability?.(r),s=r,r.state==="available"||r.state==="unavailable"&&(r.reason==="sync_required"||r.reason==="access_removed"))return r;let a=i-Date.now();if(a<=0)return r;await new Promise(p=>{let l=setTimeout(c,Math.min(o,a));function c(){clearTimeout(l),t.signal?.removeEventListener("abort",c),p()}t.signal?.addEventListener("abort",c,{once:!0})})}}connector(e){let t=e.toLowerCase();if(!ro.test(t))throw A("invalid_request","collection must be a UUID");let i=null,o=this.options.webSocket,s;return gd({description:`app-grant:${t}`,open:async(r,a)=>{let p=await(s??=this.heldGrant(t));await this.assertCurrent(p);let c=await Mi({description:`app-grant:${t}`,staticKey:w2(p),target:async d=>{await this.assertCurrent(p);let{token:u,route:f,availability:h}=await this.route(t,d);if(await this.assertCurrent(p),h.state==="unavailable")throw un(h.reason);if(!ro.test(f.grant))throw A("unauthenticated","the route names no grant","route_mismatch");let m=js(f,i)[0];if(!m)throw un("device_offline");let b=new Uint8Array(32);for(let w=0;w<32;w++)b[w]=parseInt(m.noise_pk.slice(2*w,2*w+2),16);return{prologue:Ti(U(m.relay_collection),U(f.grant),U(m.device)),remoteStatic:b,device:m.device,openCarrier:async w=>{await this.assertCurrent(p);let g=await Ms(m.url,{accessToken:u,collection:m.relay_collection,grant:f.grant,device:m.device,devicePublicKey:b},o,w);try{return await this.assertCurrent(p),g}catch(y){throw g.close(),y}}}}}).open(r,a);try{await this.assertCurrent(p)}catch(d){throw c.port.close(),d}return w_(c.port,p),i=c.device??null,c},get target(){return i}})}people(e,t){let i=e.toLowerCase();if(!ro.test(i))throw A("invalid_request","collection must be a UUID");return new jr(t,Tx(i,{cpOrigin:this.cpOrigin,fetch:this.fetcher,accessToken:(o,s)=>this.accessToken(o,s),holds:o=>!this.forgotten.has(o)}))}setup(e){let t=Zr(this.declaration),i,o=async()=>{let r=e.currentSession(),a=r&&__(r);if(!a||a.collection!==e.collection||(i??=a,!Ha(i,a)))throw Gi();return i};return Wx({assertCurrent:async()=>this.assertCurrent(await o()),journal:Yx({store:()=>this.store(),grant:o,assertCurrent:r=>this.assertCurrent(r),aad:this.aad(e.collection)}),client:e,manifest:t.manifest,operations:t.operations})}async forget(e,t={}){let i=e.toLowerCase(),o=t.expectedNoisePublicKey;await this.withLock(i,"commit",async()=>{let s=await this.store(),r=await s.getGrant(i);if(o!==void 0&&r&&rn(r.noisePublicKey)!==o)throw Gi();await s.deleteGrant(i),this.forgotten.add(i),this.tokens.delete(i)})}async forgetAllGrants(){this.epoch++;let e=await this.store(),t=[];try{t=(await e.listGrants()).map(o=>o.collection).sort()}catch{}for(let o of t)this.forgotten.add(o);let i=async(o,s)=>o.length?this.withLock(o[0],"commit",()=>i(o.slice(1),s)):s();await i(t,async()=>{if(this.tokens.clear(),typeof e.clearGrants=="function"){await e.clearGrants();return}for(let o of await e.listGrants())await e.deleteGrant(o.collection),this.forgotten.add(o.collection);if((await e.listGrants()).length)throw A("unavailable","grant storage could not be cleared","grant_storage")}),this.tokens.clear()}}});function cC(n){let e=0,t=0;try{let i=n?.records.status.pending;e=typeof i=="number"&&i>0?i:0}catch{e=0}try{t=n?.records.ledger?.getSnapshot().pending.length??0}catch{t=0}return Math.max(e,t)}function pC(n=0){let e=n===1?"1 change hasn't":n>1?`${n} changes haven't`:"Some changes haven't";return A("conflict",`${e} reached mdbase yet. Wait for them to finish, or sign out anyway and lose them on this device.`,{reason:"sign_out_pending_writes",details:n})}var dC=I(()=>{"use strict";ie()});function pp(n,e){return new Promise((t,i)=>{if(e.aborted){i(e.reason);return}let o=()=>{clearTimeout(s),i(e.reason)},s=setTimeout(()=>{e.removeEventListener("abort",o),t()},n);e.addEventListener("abort",o,{once:!0})})}var cw=I(()=>{"use strict"});function wh(n,e){if(typeof n!="string"||!e.test(n))throw de("invalid_request","timer_input");return encodeURIComponent(n)}function so(n,e){if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!==e.split(",").sort().join())throw de("invalid_request","timer_input");return n}function uC(n){let e=so(n,"id,fire_at");if(wh(e.id,pw),typeof e.fire_at!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(e.fire_at)||!Number.isFinite(Date.parse(e.fire_at)))throw de("invalid_request","timer_input");return{id:e.id,fire_at:e.fire_at}}function dw(n){if(typeof n!="string"||!n.length||n.length>100)throw de("invalid_request","timer_input")}function O2(n,e,t){let i=`${n}/${wh(t[0],I2)}`;if(e==="list"&&t.length===1)return{path:i,method:"GET",write:!1};if(e==="put"&&t.length===3){let o=so(t[2],"criterion_id,fire_at");return dw(o.criterion_id),uC({id:t[1],fire_at:o.fire_at}),{path:`${i}/${wh(t[1],pw)}`,method:"PUT",body:o,write:!0}}if(e==="cancel"&&t.length===3){let o=t[2];if(o!==void 0&&(!Number.isSafeInteger(o)||o<1))throw de("invalid_request","timer_input");return{path:`${i}/${wh(t[1],pw)}${o===void 0?"":`?generation=${o}`}`,method:"DELETE",write:!0}}if((e==="reconcile"||e==="reconcileWithReceipt")&&t.length===2){let o=so(t[1],`criterion_id,timers${e==="reconcileWithReceipt"?",recovery":""}`);if(dw(o.criterion_id),!Array.isArray(o.timers)||o.timers.length>1e4)throw de("invalid_request","timer_input");let s=o.timers.map(uC);if(new Set(s.map(r=>r.id)).size!==s.length)throw de("invalid_request","timer_input");if(e==="reconcileWithReceipt"){let r=so(o.recovery,"protocol_version,operation_id,expected_revision");if(r.protocol_version!==1||typeof r.operation_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(r.operation_id)||!Number.isSafeInteger(r.expected_revision)||r.expected_revision<0||r.expected_revision>=Number.MAX_SAFE_INTEGER)throw de("invalid_request","timer_input")}return{path:`${i}/reconcile`,method:"POST",body:{...o,timers:s},write:!0}}if(e==="lookupOperation"&&t.length===2&&typeof t[1]=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(t[1]))return{path:`${i}/operations/${t[1]}`,method:"GET",write:!1};throw de("invalid_request","timer_input")}function hC(n,e){let t=fC(e.scope),i=e.generation,o=`/v1/next/collections/${e.scope.collection}/background-grants/${e.grantId}/timers`,s=!1,r=0,a=null,p=null,l=()=>{if(s||e.signal.aborted||!e.isCurrent())throw de("unauthenticated","timer_fenced")},c=()=>{if(p)return p;s=!0,e.signal.removeEventListener("abort",d),a?.ctrl.abort();try{n.postMessage([1,t,i,"close"])}finally{n.removeEventListener("message",u),n.close()}return p=Promise.resolve().then(async()=>{await a?.work})},d=()=>{c()},u=f=>{let h=f.data;if(!Array.isArray(h)||h[0]!==1||h[1]!==t||h[2]!==i){c();return}if(h.length===4&&h[3]==="close"){c();return}if(h.length===5&&h[4]==="cancel"&&Number.isSafeInteger(h[3])&&h[3]>0){a&&a.id===h[3]&&a.ctrl.abort();return}if(h.length!==6||!Number.isSafeInteger(h[3])||h[3]<=r||a||typeof h[4]!="string"||!Array.isArray(h[5])){c();return}let m=h[3],b=h[4],w=h[5],g=new AbortController;r=m;let y=!1,v=b!=="list"&&b!=="lookupOperation",_=Promise.resolve().then(async()=>{let k=setTimeout(()=>g.abort(),1e4),S,x,P=new Uint8Array(dp),C=0,E=()=>{x?.cancel().catch(()=>{})};g.signal.addEventListener("abort",E,{once:!0});try{l(),g.signal.throwIfAborted();let O=o.slice(0,-7)+"/notifications/channels",L,z,Q=null;if(b==="vapid"&&w.length===0){if(!e.journal)throw de("upgrade_required","native_timer_channel_journal_unavailable");e.journal.read(),L={path:"/v1/notifications/vapid-public-key",method:"GET",write:!1}}else if(b==="registerChannel"&&w.length===1){if(!e.journal)throw de("upgrade_required","native_timer_channel_journal_unavailable");let Y=w[0],ee=so(Y,`kind,criteria,${Y?.kind==="web_push"?"subscription":"token"}`);if(!["web_push","fcm"].includes(ee.kind)||!Array.isArray(ee.criteria)||!ee.criteria.length||ee.criteria.length>100||(ee.criteria.forEach(dw),new Set(ee.criteria).size!==ee.criteria.length))throw de("invalid_request","timer_input");let $e;if(ee.kind==="fcm"){if(typeof ee.token!="string"||ee.token.length<16||ee.token.length>4096||/[\s\u0000-\u001f\u007f]/.test(ee.token))throw de("invalid_request","timer_input");$e={transport:"fcm",token:ee.token}}else{let $=so(ee.subscription,"endpoint,expirationTime,keys"),J=so($.keys,"p256dh,auth");if(typeof $.endpoint!="string"||$.endpoint.length>2048||typeof J.p256dh!="string"||typeof J.auth!="string"||!/^[A-Za-z0-9_-]{87}$/.test(J.p256dh)||!/^[A-Za-z0-9_-]{22}$/.test(J.auth))throw de("invalid_request","timer_input");let be;try{be=new URL($.endpoint)}catch{throw de("invalid_request","timer_input")}if(be.protocol!=="https:"||be.username||be.password||be.hash||be.href!==$.endpoint||$.expirationTime!==null&&(!Number.isFinite($.expirationTime)||$.expirationTime<0))throw de("invalid_request","timer_input");$e={subscription:$}}L={path:O,method:"POST",write:!0,body:{installation_id:e.scope.installation,criteria:[...ee.criteria].sort(),...$e}};let mt=new TextEncoder().encode(JSON.stringify(L.body)),j;try{j=[...new Uint8Array(await crypto.subtle.digest("SHA-256",mt))].map($=>$.toString(16).padStart(2,"0")).join("")}finally{mt.fill(0)}l(),g.signal.throwIfAborted();let W=e.journal.read();if(Q=W,W?.pending)throw de("outcome_unknown","timer_channel_reapproval_required");z={grantId:e.grantId,kind:ee.kind,targetDigest:j,channelId:W?.channelId??null,pending:"register"}}else if(b==="unregisterChannel"&&w.length===1&&["web_push","fcm"].includes(w[0])){if(!e.journal)throw de("upgrade_required","native_timer_channel_journal_unavailable");let Y=e.journal.read();if(Q=Y,!Y){n.postMessage([1,t,i,m,!0,void 0]);return}if(Y.pending==="register")throw de("outcome_unknown","timer_channel_reapproval_required");if(Y.kind!==w[0]||!Y.channelId)throw de("invalid_request","timer_channel_kind");z={...Y,pending:"delete"},L={path:`${O}/${Y.channelId}`,method:"DELETE",write:!0}}else L=O2(o,b,w);v=L.write;let V=L.body===void 0?void 0:JSON.stringify(L.body);if(V&&new TextEncoder().encode(V).length>dp)throw de("invalid_request","timer_input");let te=await e.bearer();if(l(),g.signal.throwIfAborted(),typeof te!="string"||!/^(idev_|ct_)[A-Za-z0-9_-]{43}$/.test(te))throw de("unauthenticated","timer_credential");z&&(await e.journal.write(z),l(),g.signal.throwIfAborted()),y=v;let G=e.fetch;if(S=await G(`${e.cpOrigin}${L.path}`,{method:L.method,body:V,headers:{authorization:`Bearer ${te}`,...V===void 0?{}:{"content-type":"application/json"}},credentials:"omit",redirect:"error",cache:L.method==="GET"?"no-store":"default",referrerPolicy:"no-referrer",signal:g.signal}),l(),g.signal.throwIfAborted(),S.redirected)throw de("unavailable","timer_response");if(b==="unregisterChannel"&&S.status===204){await e.journal.write(null),l(),g.signal.throwIfAborted(),n.postMessage([1,t,i,m,!0,void 0]);return}if(S.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json"||!S.body)throw de("unavailable","timer_response");let K=S.headers.get("content-length");if(K&&/^\d+$/.test(K)&&Number(K)>dp)throw de("unavailable","timer_response");for(x=S.body.getReader();;){let Y=await x.read();try{if(l(),g.signal.throwIfAborted(),Y.done)break;if(C+Y.value.length>dp)throw de("unavailable","timer_response");P.set(Y.value,C),C+=Y.value.length}finally{Y.value?.fill(0)}}let X=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(P.subarray(0,C)));if(b==="unregisterChannel"&&S.status===404&&X?.error?.code==="channel_not_found"){await e.journal.write(null),l(),g.signal.throwIfAborted(),n.postMessage([1,t,i,m,!0,void 0]);return}if(!S.ok)throw S.status>=500?de("unavailable","timer_http"):X?.error?.operation_outcome==="unknown"?de("outcome_unknown","timer_write_unknown"):(z&&(await e.journal.write(Q),l(),g.signal.throwIfAborted()),y=!1,A(S.status===401||S.status===403?"unauthenticated":S.status===409?"conflict":S.status===404?"upgrade_required":S.status===429?"rate_limited":"invalid_request","Native timer request was refused.","timer_refused"));if(l(),g.signal.throwIfAborted(),b==="registerChannel"){if(typeof X?.channel_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(X.channel_id))throw de("unavailable","timer_channel_response");await e.journal.write({...z,channelId:X.channel_id,pending:null}),l(),g.signal.throwIfAborted(),n.postMessage([1,t,i,m,!0,{channelId:X.channel_id,installationId:e.scope.installation,criteria:L.body.criteria}])}else n.postMessage([1,t,i,m,!0,X])}catch(O){let L=y?de("outcome_unknown","timer_write_unknown"):O instanceof se?O:de(g.signal.aborted?"cancelled":"unavailable","timer_request");s||n.postMessage([1,t,i,m,!1,L.code,L.reason])}finally{clearTimeout(k),g.signal.removeEventListener("abort",E),P.fill(0),(x?.cancel()??S?.body?.cancel())?.catch(()=>{}),x?.releaseLock(),a?.id===m&&(a=null)}});a={id:m,ctrl:g,work:_}};n.addEventListener("message",u),n.start(),e.signal.addEventListener("abort",d,{once:!0});try{l()}catch(f){throw c(),f}return Object.freeze({close:c})}function mC(n,e,t){let i=fC(e.scope),o=e.generation,s=!1,r=0,a=null,p=()=>{if(s)return;s=!0,t.signal.removeEventListener("abort",p);let y=a;a=null,y?.signal?.removeEventListener("abort",y.abort),y?.reject(de(y.write?"outcome_unknown":"cancelled","timer_port_closed"));try{n.postMessage([1,i,o,"close"])}finally{n.removeEventListener("message",l),n.close(),t.onClose()}},l=y=>{let v=y.data;if(!Array.isArray(v)||v[0]!==1||v[1]!==i||v[2]!==o){p();return}if(v.length===4&&v[3]==="close"){p();return}let _=a;if(!_||v[3]!==_.id||!(v.length===6&&v[4]===!0||v.length===7&&v[4]===!1&&typeof v[5]=="string"&&Sr(v[5]))){p();return}a=null,_.signal?.removeEventListener("abort",_.abort),v[4]?_.resolve(v[5]):_.reject(A(v[5],"Native timer request could not complete.",typeof v[6]=="string"?v[6]:void 0))},c=(y,v,_,k=!1)=>{if(s||t.signal.aborted||_.signal?.aborted)return Promise.reject(de("cancelled","timer_port_closed"));if(a||d&&!k)return Promise.reject(de("unavailable","timer_port_busy"));if(r>=Number.MAX_SAFE_INTEGER)return p(),Promise.reject(de("unavailable","timer_port_closed"));let S=++r,x=y!=="list"&&y!=="lookupOperation"&&y!=="vapid";return new Promise((P,C)=>{let E=()=>{try{n.postMessage([1,i,o,S,"cancel"])}catch{p()}C(de(x?"outcome_unknown":"cancelled","timer_request_cancelled"))};a={id:S,write:x,resolve:P,reject:C,abort:E,signal:_.signal},_.signal?.addEventListener("abort",E,{once:!0});try{if(new TextEncoder().encode(JSON.stringify(v)).length>dp)throw de("invalid_request","timer_input");n.postMessage([1,i,o,S,y,v])}catch(O){a=null,_.signal?.removeEventListener("abort",E),C(O)}})},d=!1,u=()=>{if(s||t.signal.aborted)throw de("cancelled","timer_port_closed")},f=y=>{if(!y?.length||y.length>100||y.some(v=>typeof v!="string"||!v.length||v.length>100)||new Set(y).size!==y.length)throw de("invalid_request","timer_channel_criteria_required");return[...y].sort()},h=(y,v)=>{let _=so(y,"channelId,installationId,criteria");if(typeof _.channelId!="string"||_.installationId!==e.scope.installation||JSON.stringify(_.criteria)!==JSON.stringify(v))throw de("outcome_unknown","timer_channel_response");return{channelId:_.channelId,installationId:e.scope.installation,criteria:[...v]}},m=async(y,v)=>{if(u(),y.signal?.throwIfAborted(),d||a)throw de("unavailable","timer_port_busy");d=!0;try{return await v()}finally{d=!1}},b=y=>m(y,async()=>{let v=f(y.criteria);if(y.installationId!==void 0&&y.installationId!==e.scope.installation)throw de("invalid_request","timer_channel_installation");let _=y.serviceWorker;if(!_?.pushManager||typeof _.pushManager.getSubscription!="function"||typeof _.pushManager.subscribe!="function")throw de("invalid_request","timer_push_platform");let k=await c("vapid",[],y,!0);if(u(),y.signal?.throwIfAborted(),typeof k.public_key!="string"||!/^[A-Za-z0-9_-]{87}$/.test(k.public_key))throw de("unavailable","timer_vapid_response");let S=atob(k.public_key.replace(/-/g,"+").replace(/_/g,"/")),x=Uint8Array.from(S,E=>E.charCodeAt(0));if(x.length!==65||x[0]!==4||btoa(S).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")!==k.public_key)throw de("unavailable","timer_vapid_response");let P=await _.pushManager.getSubscription();if(u(),y.signal?.throwIfAborted(),P){let E=P.options.applicationServerKey;if(!E||E.byteLength!==x.length||new Uint8Array(E).some((O,L)=>O!==x[L]))throw de("invalid_request","timer_push_key_changed")}if(!P&&(P=await _.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:x}),s||t.signal.aborted||y.signal?.aborted))throw await P.unsubscribe(),de("cancelled","timer_port_closed");let C=P.toJSON();return h(await c("registerChannel",[{kind:"web_push",criteria:v,subscription:{endpoint:C.endpoint,expirationTime:C.expirationTime??null,keys:C.keys}}],y,!0),v)}),w=y=>m(y,async()=>{let v=f(y.criteria);if(y.installationId!==void 0&&y.installationId!==e.scope.installation)throw de("invalid_request","timer_channel_installation");return{...h(await c("registerChannel",[{kind:"fcm",criteria:v,token:y.token}],y,!0),v),transport:"fcm"}}),g=(y,v)=>m(v,async()=>{if(await c("unregisterChannel",["web_push"],v,!0),u(),v.signal?.throwIfAborted(),y){let _=await y.pushManager.getSubscription();u(),v.signal?.throwIfAborted(),_&&await _.unsubscribe(),u(),v.signal?.throwIfAborted()}});return n.addEventListener("message",l),n.start(),t.signal.addEventListener("abort",p,{once:!0}),t.signal.aborted&&p(),Object.freeze({list:(y,v)=>c("list",[y],v),put:(y,v,_,k)=>c("put",[y,v,_],k),cancel:(y,v,_,k)=>c("cancel",[y,v,_],k),reconcile:(y,v,_)=>c("reconcile",[y,v],_),reconcileWithReceipt:(y,v,_)=>c("reconcileWithReceipt",[y,v],_),lookupOperation:(y,v,_)=>c("lookupOperation",[y,v],_),registerWebPush:b,unregisterWebPush:g,registerFcm:w,unregisterFcm:y=>m(y,async()=>{await c("unregisterChannel",["fcm"],y,!0)}),close:p})}var I2,pw,dp,de,fC,uw=I(()=>{"use strict";ie();I2=/^[A-Za-z0-9._-]{1,64}$/,pw=/^[A-Za-z0-9._:-]{1,128}$/,dp=2*1024*1024,de=(n,e)=>A(n,"Native timer request could not complete.",e),fC=n=>JSON.stringify([n.account,n.installation,n.collection])});function Qo(n,e=null){if(n instanceof Ue)return n;let t=n?.name??"",i=n instanceof Error?n.message:String(n),o=n?.resultCode,s=typeof o=="number"?o&255:null;return t==="QuotaExceededError"||/quota/i.test(i)||s===13?new Ue("Full",i,e):s===11||s===26||/malformed|not a database|SQLITE_CORRUPT|SQLITE_NOTADB/i.test(i)?new Ue("Corrupt",i,e):t==="NoModificationAllowedError"||s===5||s===6||/SQLITE_BUSY|SQLITE_LOCKED|NoModificationAllowed/i.test(i)?new Ue("Busy",i,e):s===1||s===19||s===20||s===25||/SQLITE_ERROR|SQLITE_CONSTRAINT|syntax/i.test(i)?new Ue("Sql",i,e):new Ue("Other",i,e)}function fw(n){if(typeof n=="bigint")return n;if(typeof n=="number"&&Number.isSafeInteger(n))return BigInt(n);throw new Ue("Other","SQLite integer is not losslessly represented")}var Ue,yC,gC,bC,wC,vC,R2,vh,hw=I(()=>{"use strict";Ue=class extends Error{constructor(t,i,o=null){super(`${t}${o===null?"":`@${o}`}(${i})`);this.kind=t;this.detail=i;this.stmt=o;this.name="IndexError"}kind;detail;stmt},yC=1,gC=2,bC=3,wC=4,vC=5;R2="CREATE TABLE IF NOT EXISTS _mdbn_host(k TEXT PRIMARY KEY, v) WITHOUT ROWID",vh=class n{constructor(e,t,i){this.sqlite3=e;this.db=t;this.info=i}sqlite3;db;info;cache=new Map;closed=!1;static open(e,t,i={}){try{let o=i.synchronous??"NORMAL";if(o!=="NORMAL"&&o!=="FULL")throw new Ue("Other","unsupported synchronous profile");if(i.pragmas!==!1&&(t.exec("PRAGMA locking_mode=EXCLUSIVE"),t.exec("PRAGMA journal_mode=WAL"),t.exec(`PRAGMA synchronous=${o}`)),i.verifyPragmas&&(String(t.selectValue("PRAGMA locking_mode")).toLowerCase()!=="exclusive"||String(t.selectValue("PRAGMA journal_mode")).toLowerCase()!=="wal"||t.selectValue("PRAGMA synchronous")!==(o==="FULL"?2:1)))throw new Ue("Other","SQLite did not apply the requested storage profile");let s=t.selectValue("SELECT count(*) FROM sqlite_master WHERE name='_mdbn_host'")>0,r=t.selectValue("SELECT count(*) FROM sqlite_master");t.exec(R2);let a="Fresh";return s?a=t.selectValue("SELECT v FROM _mdbn_host WHERE k='clean'")===1?"Existing":"Unclean":r>0&&(a="Unclean"),t.exec("INSERT OR REPLACE INTO _mdbn_host(k, v) VALUES ('clean', 0)"),new n(e,t,{durability:"Disposable",opened:a,sqliteVersion:e.capi.sqlite3_libversion_number(),quotaSuspect:i.quotaSuspect??!1})}catch(o){throw Qo(o)}}prepare(e){let t=this.cache.get(e);return t||(t=this.db.prepare(e),this.cache.set(e,t)),t}bind(e,t){e.clearBindings(),t.forEach((i,o)=>{let s=o+1;switch(i.kind){case"Null":e.bind(s,null);break;case"Integer":e.bind(s,i.value);break;case"Real":e.bind(s,i.value);break;case"Text":e.bind(s,i.value);break;case"Blob":e.bindAsBlob(s,i.value);break}})}column(e,t){let i=this.sqlite3.capi;switch(i.sqlite3_column_type(e.pointer,t)){case vC:return{kind:"Null"};case yC:{let o=i.sqlite3_column_int64(e.pointer,t);return{kind:"Integer",value:fw(o)}}case gC:return{kind:"Real",value:i.sqlite3_column_double(e.pointer,t)};case bC:return{kind:"Text",value:e.getString(t)};case wC:return{kind:"Blob",value:e.getBlob(t)??new Uint8Array(0)};default:return{kind:"Null"}}}run(e,t){if(this.closed)throw new Ue("Other","index closed");let i=this.sqlite3.capi,o=e.mode==="Transaction",s=[],r=0,a=0,p=13,l=c=>{if(t){if(!Number.isSafeInteger(c)||c<0||c>t.maxBytes-p)throw new Ue("Full","index reply byte budget exceeded");p+=c}};if(t&&([t.maxBytes,t.maxRows,t.maxValues,t.maxColumns].some(c=>!Number.isSafeInteger(c)||c<0)||t.maxBytes<p))throw new Ue("Full","invalid index reply budget");if(o)try{this.db.exec("BEGIN IMMEDIATE")}catch(c){throw Qo(c)}for(let c=0;c<e.stmts.length;c++){let d=e.stmts[c];try{let u=this.prepare(d.sql);try{this.bind(u,d.params);let f=u.columnCount;if(t&&(!Number.isSafeInteger(f)||f<0||f>t.maxColumns))throw new Ue("Full","index reply column budget exceeded");l(24);let h=[];for(;u.step();){if(t&&++r>t.maxRows)throw new Ue("Full","index reply row budget exceeded");for(let m=0;m<f;m++){if(t){if(++a>t.maxValues)throw new Ue("Full","index reply value budget exceeded");let b=i.sqlite3_column_type(u.pointer,m);if(b===bC||b===wC)l(5),l(i.sqlite3_column_bytes(u.pointer,m));else if(b===yC||b===gC)l(9);else if(b===vC)l(1);else throw new Ue("Other","unknown SQLite value type")}h.push(this.column(u,m))}}s.push({columns:f,values:h,changes:fw(i.sqlite3_changes(this.db.pointer)),lastInsertRowid:fw(i.sqlite3_last_insert_rowid(this.db.pointer))})}finally{u.reset()}}catch(u){if(o)try{this.db.exec("ROLLBACK")}catch{}throw Qo(u,c)}}if(o)try{this.db.exec("COMMIT")}catch(c){try{this.db.exec("ROLLBACK")}catch{}throw Qo(c)}return s}close(e={}){if(!this.closed){this.closed=!0;for(let t of this.cache.values())try{t.finalize()}catch{}if(this.cache.clear(),e.markClean!==!1)try{this.db.exec("INSERT OR REPLACE INTO _mdbn_host(k, v) VALUES ('clean', 1)")}catch{}this.db.close()}}}});function L2(n){let e=new mw(n);if(!e.take(8).every((r,a)=>r===AC[a]))throw qt();let t=e.byte();if(t===1)throw e.done(),new Ue("Other","app database reset requires explicit recovery; automatic wipe refused");if(t!==0)throw qt();let i=e.byte();if(i>1)throw qt();let o=e.count(gn.maxStatements,8),s=[];for(let r=0;r<o;r++){let a=e.text(gn.maxSqlBytes),p=e.count(gn.maxParameters,1),l=[];for(let c=0;c<p;c++)l.push(e.value());s.push({sql:a,params:l})}return e.done(),{mode:i===0?"Transaction":"Autocommit",stmts:s}}function j2(n,e){if(!Array.isArray(n)||n.length!==e)throw qt();let t=new _h(2);t.u32(n.length);let i=0;for(let o of n){if(!Number.isSafeInteger(o.columns)||o.columns<0||o.columns>gn.maxColumns)throw ao();if(!Array.isArray(o.values)||(o.columns===0?o.values.length!==0:o.values.length%o.columns!==0))throw qt();if(i+=o.columns===0?0:o.values.length/o.columns,i>gn.maxRows||o.values.length>gn.maxValues)throw ao();t.u32(o.columns),t.int(o.changes,!1),t.int(o.lastInsertRowid,!0),t.u32(o.values.length);for(let s of o.values)t.value(s)}return t.done()}function N2(n,e){let t=n instanceof Ue?n.kind:"Other",i={Sql:0,Corrupt:1,Full:2,Busy:3,Other:4},o=new _h(3);o.byte(i[t]);let s=n instanceof Ue?n.stmt:null;return e!==null&&s!==null&&Number.isSafeInteger(s)&&s>=0&&s<e?(o.byte(1),o.u32(s)):o.byte(0),o.data(kC.encode("app index operation failed; reopen and reconcile")),o.done()}function _C(n,e,t){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<0||t<0||e>4294967295||t>4294967295||e>n.buffer.byteLength||t>n.buffer.byteLength-e)throw qt()}function SC(n,e){let t=!1,i=!1;return(o,s)=>{if(t)throw i=!0,n.fence(),qt();t=!0,i=!1;try{let r=e();if(_C(r.memory,o,s),s>gn.maxBytes)throw n.fence(),ao();let a=n.run(new Uint8Array(r.memory.buffer,o,s).slice()),p=r.alloc(a.length);if(_C(r.memory,p,a.length),i||p===0||p<o+s&&o<p+a.length)throw qt();return new Uint8Array(r.memory.buffer,p,a.length).set(a),BigInt(p)<<32n|BigInt(a.length)}catch(r){throw n.fence(),r}finally{t=!1}}}var AC,gn,E2,q2,T2,qt,ao,M2,kC,mw,_h,Ah,PC=I(()=>{"use strict";hw();AC=Uint8Array.of(77,68,66,73,68,88,0,1),gn=Object.freeze({maxBytes:4*1024*1024,maxStatements:16384,maxValues:131072,maxRows:4096,maxColumns:100,maxSqlBytes:100*1024,maxParameters:100}),E2=-(1n<<63n),q2=(1n<<63n)-1n,T2=(1n<<64n)-1n,qt=()=>new Ue("Other","invalid app index ABI"),ao=()=>new Ue("Full","app index ABI budget exceeded"),M2=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),kC=new TextEncoder,mw=class{constructor(e){this.bytes=e;if(e.length>gn.maxBytes)throw ao();this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}bytes;pos=0;values=0;view;take(e){if(!Number.isSafeInteger(e)||e<0||e>this.bytes.length-this.pos)throw qt();let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}byte(){return this.take(1)[0]}u32(){let e=this.pos;return this.take(4),this.view.getUint32(e,!0)}count(e,t){let i=this.u32();if(i>e)throw ao();if(i>Math.floor((this.bytes.length-this.pos)/t))throw qt();return i}data(e){return this.take(this.count(e,1))}text(e){return M2.decode(this.data(e))}value(){if(++this.values>gn.maxValues)throw ao();switch(this.byte()){case 0:return{kind:"Null"};case 1:{let e=this.pos;return this.take(8),{kind:"Integer",value:this.view.getBigInt64(e,!0)}}case 2:{let e=this.pos;this.take(8);let t=this.view.getFloat64(e,!0);if(!Number.isFinite(t))throw qt();return{kind:"Real",value:t}}case 3:return{kind:"Text",value:this.text(gn.maxBytes)};case 4:return{kind:"Blob",value:this.data(gn.maxBytes).slice()};default:throw qt()}}done(){if(this.pos!==this.bytes.length)throw qt()}};_h=class{parts=[];length=0;values=0;constructor(e){this.put(AC),this.byte(e)}put(e){if(e.length>gn.maxBytes-this.length)throw ao();this.length+=e.length,this.parts.push(e)}byte(e){this.put(Uint8Array.of(e))}u32(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw qt();let t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,e,!0),this.put(t)}int(e,t){if(typeof e!="bigint"||e<(t?E2:0n)||e>(t?q2:T2))throw qt();let i=new Uint8Array(8),o=new DataView(i.buffer);t?o.setBigInt64(0,e,!0):o.setBigUint64(0,e,!0),this.put(i)}data(e){this.u32(e.length),this.put(e)}value(e){if(++this.values>gn.maxValues)throw ao();switch(e.kind){case"Null":this.byte(0);return;case"Integer":this.byte(1),this.int(e.value,!0);return;case"Real":{if(!Number.isFinite(e.value))throw qt();this.byte(2);let t=new Uint8Array(8);new DataView(t.buffer).setFloat64(0,e.value,!0),this.put(t);return}case"Text":this.byte(3),this.data(kC.encode(e.value));return;case"Blob":this.byte(4),this.data(e.value);return;default:throw qt()}}done(){let e=new Uint8Array(this.length),t=0;for(let i of this.parts)e.set(i,t),t+=i.length;return e}};Ah=class{constructor(e){this.index=e}index;fenced=!1;get needsRecovery(){return this.fenced||this.index.needsRecovery}fence(){this.fenced=!0,this.index.fence()}run(e){let t=null;try{if(this.needsRecovery)throw qt();let i=L2(e);t=i.stmts.length;let o=gn;return j2(this.index.run(i,o),t)}catch(i){return this.fence(),N2(i,t)}}}});function gw(n){let e=[n.account,n.installation,n.collection];if(e.some(i=>!U2.test(i)))throw new Ue("Other","invalid app storage scope");let t=`mdbase-app-${e.map(i=>i.toLowerCase()).join("-")}`;return{vfs:t,directory:`.${t}`}}async function xC(n,e){let t=gw(e),i,o,s;try{i=await n.installOpfsSAHPoolVfs({name:t.vfs,directory:t.directory,initialCapacity:6}),i.isPaused?.()&&await i.unpauseVfs(),o=new i.OpfsSAHPoolDb("/app.db");let r=vh.open(n,o,{synchronous:"FULL",verifyPragmas:!0});if(s=new yw(r),r.info.opened==="Unclean"){let a=s.run({mode:"Autocommit",stmts:[{sql:"PRAGMA quick_check",params:[]}]}),p=a[0]?.values;if(a.length!==1||p?.length!==1||p[0]?.kind!=="Text"||p[0].value!=="ok")throw s=void 0,r.close({markClean:!1}),o=void 0,new Ue("Corrupt","app database integrity check failed; recovery required")}return{index:s,pool:i}}catch(r){let a=!1;try{s?s.close():o?.close()}catch{a=!0}try{i?.pauseVfs?.()}catch{a=!0}let p=Qo(r);throw new Ue(a?"Other":p.kind,"app SQLite open failed; recovery required",p.stmt)}}var U2,yw,CC=I(()=>{"use strict";hw();U2=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;yw=class{constructor(e){this.inner=e}inner;fenced=!1;closed=!1;get info(){return this.inner.info}get needsRecovery(){return this.fenced}fence(){this.fenced=!0}run(e,t){if(this.closed||this.fenced)throw new Ue("Other","app database fenced or closed; reopen and reconcile");try{return t?this.inner.run(e,t):this.inner.run(e)}catch(i){this.fenced=!0;let o=Qo(i);throw new Ue(o.kind,"app SQLite operation failed; reopen and reconcile",o.stmt)}}reset(){throw new Ue("Other","app database reset requires explicit recovery; automatic wipe refused")}close(){this.closed||(this.closed=!0,this.inner.close({markClean:!this.fenced}))}}});function IC(n){let e=Object.freeze({...n});if(!/^[0-9a-f]{64}$/.test(e.wasmSha256)||!Number.isSafeInteger(e.maxWasmBytes)||e.maxWasmBytes<1||e.maxWasmBytes>4*1024*1024||typeof e.loadWasm!="function"||typeof e.initialize!="function")throw Ya("binding");return async({scope:t,signal:i})=>{let o=Object.freeze({account:t.account,installation:t.installation,collection:t.collection});gw(o);let s=()=>{if(i.aborted||Object.entries(o).some(([y,v])=>t[y]!==v))throw Ya("fenced")};s();let r=globalThis.WorkerGlobalScope;if(typeof r!="function"||!(globalThis instanceof r))throw Ya("unsupported");let a=await e.loadWasm({signal:i});if(s(),!(a instanceof Uint8Array)||a.byteLength<1||a.byteLength>e.maxWasmBytes)throw Ya("binding");let p=new Uint8Array(a),l=new Uint8Array(await crypto.subtle.digest("SHA-256",p));if(s(),Array.from(l,y=>y.toString(16).padStart(2,"0")).join("")!==e.wasmSha256)throw Ya("binding");let c=await e.initialize({wasmBinary:p,print(){},printErr(){}});s();let d=await xC(c,o),u=d.index,f=new Ah(u),h={import:y=>SC(f,y),fence:()=>f.fence(),get needsRecovery(){return f.needsRecovery}},m=y=>({kind:"Text",value:y}),b=Object.freeze({list(y){let[v]=u.run({mode:"Autocommit",stmts:[{sql:"SELECT v FROM _mdbn_host WHERE k >= 'w:' AND k < 'w;' ORDER BY k LIMIT 1024",params:[]}]}),_=[],k=0;for(let S of v?.values??[])if(S.kind==="Text"){if(k+=S.value.length,k>y)break;_.push(S.value)}return _},put(y,v){u.run({mode:"Autocommit",stmts:[{sql:"INSERT OR REPLACE INTO _mdbn_host(k, v) VALUES (?, ?)",params:[m(`w:${y}`),m(v)]}]})},remove(y){u.run({mode:"Autocommit",stmts:[{sql:"DELETE FROM _mdbn_host WHERE k = ?",params:[m(`w:${y}`)]}]})}}),w=null,g=()=>w??=Promise.resolve().then(async()=>{try{u.close(),await d.pool.pauseVfs()}catch{throw f.fence(),Ya("unavailable")}});return(i.aborted||Object.entries(o).some(([y,v])=>t[y]!==v))&&f.fence(),Object.freeze({sql:h,opened:{Fresh:"fresh",Existing:"existing",Unclean:"unclean"}[u.info.opened],sqliteVersion:u.info.sqliteVersion,ledger:b,close:g})}}var bw,Ya,OC=I(()=>{"use strict";CC();PC();bw=class extends Error{constructor(t){super(`app collection SQL: ${t}`);this.reason=t;this.name="AppCollectionSqlError"}reason},Ya=n=>new bw(n)});var Ja,D2,$2,lo,on,Xa,kh=I(()=>{"use strict";Ja="original-join",D2=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,$2="00000000-0000-0000-0000-000000000000",lo=class extends Error{constructor(t){super(`app collection join: ${t}`);this.reason=t;this.name="AppCollectionJoinError"}reason},on=(n="recovery_required")=>new lo(n),Xa=class{options;key;busy=!1;constructor(e){let t=Object.freeze({account:e.scope.account,installation:e.scope.installation,collection:e.scope.collection});if(Object.values(t).some(i=>typeof i!="string"||!D2.test(i)||i===$2)||typeof e.databaseName!="string"||!e.databaseName.length||e.databaseName.length>256||/[\u0000-\u001f\u007f]/.test(e.databaseName)||typeof e.isCurrent!="function")throw on("binding");this.options=Object.freeze({databaseName:e.databaseName,scope:t,isCurrent:e.isCurrent}),this.key=JSON.stringify([t.account,t.installation,t.collection])}check(e){if(e.aborted||this.options.isCurrent()!==!0)throw on("fenced")}marker(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).sort().join()!=="account,collection,installation,phase,version")throw on();let t=e;if(t.version!==1||t.phase!=="attempted"&&t.phase!=="completed"||Object.entries(this.options.scope).some(([i,o])=>t[i]!==o))throw on();return t}open(e){if(this.check(e),!globalThis.indexedDB)throw on();return new Promise((t,i)=>{let o=indexedDB.open(this.options.databaseName,1),s=!1,r=()=>e.removeEventListener("abort",a),a=()=>{s=!0,r();try{o.transaction?.abort()}catch{}i(on())};e.addEventListener("abort",a,{once:!0}),o.onblocked=o.onerror=a,o.onupgradeneeded=()=>{try{if(this.check(e),s||o.result.objectStoreNames.length)throw on();o.result.createObjectStore(Ja)}catch{try{o.transaction?.abort()}catch{}}},o.onsuccess=()=>{r();try{if(this.check(e),s||o.result.objectStoreNames.length!==1||!o.result.objectStoreNames.contains(Ja))throw on();t(o.result)}catch{o.result.close(),i(on())}}})}async change(e,t){if(this.check(t),this.busy)throw on("busy");this.busy=!0;let i=null;try{return i=await this.open(t),this.check(t),await new Promise((o,s)=>{this.check(t);let r=i.transaction(Ja,"readwrite",{durability:"strict"}),a=null,p,l=()=>{try{r.abort()}catch{}},c=()=>t.removeEventListener("abort",l);t.addEventListener("abort",l,{once:!0}),r.onabort=r.onerror=()=>{c(),s(p??on())},r.oncomplete=()=>{c();try{if(this.check(t),!a)throw on();o(Object.freeze(a))}catch{s(on())}};let d=r.objectStore(Ja),u=d.get(this.key);u.onsuccess=()=>{try{this.check(t);let f=u.result;if(f===void 0){if(e!=="prepare")throw on();d.add({version:1,...this.options.scope,phase:"attempted"},this.key),a={outcomeMode:"fresh",phase:"attempted"}}else{let h=this.marker(f);e==="complete"&&h.phase!=="completed"&&d.put({...h,phase:"completed"},this.key),a={outcomeMode:"existing",phase:e==="complete"?"completed":h.phase}}}catch(f){p=f,l()}}})}catch(o){throw o instanceof lo?o:on()}finally{i?.close(),this.busy=!1}}prepare(e){return this.change("prepare",e.signal)}async syncedBefore(e){return await this.synced("read",e.signal)===!0}async markSynced(e){await this.synced("mark",e.signal)}async synced(e,t){let i=null;try{i=await this.open(t),this.check(t);let o=JSON.stringify([this.options.scope.account,this.options.scope.installation,this.options.scope.collection,"synced"]);return await new Promise(s=>{let r=i.transaction(Ja,e==="mark"?"readwrite":"readonly"),a=!1;r.onabort=r.onerror=()=>s(!1),r.oncomplete=()=>s(e==="mark"||a);let p=r.objectStore(Ja);if(e==="mark")p.put({version:1,synced:!0},o);else{let l=p.get(o);l.onsuccess=()=>{let c=l.result;a=!!c&&c.version===1&&c.synced===!0}}})}catch{return!1}finally{i?.close()}}async complete(e){await this.change("complete",e.signal)}}});function ww(n){let e=[n.account,n.installation,n.collection];if(e.some(o=>typeof o!="string"||!z2.test(o))||typeof n.isCurrent!="function")throw ct();let t=JSON.stringify(e.map(o=>o.toLowerCase())),i=n.isCurrent.bind(n);return{binding:t,current:()=>{try{return i()===!0&&JSON.stringify([n.account,n.installation,n.collection].map(o=>o.toLowerCase()))===t}catch{return!1}}}}function qC(n,e,t,i,o){let s=ww(e),r=!1,a=()=>{if(!r){r=!0,n.onmessage=null,n.onmessageerror=null;try{n.postMessage([1,s.binding,"close"])}catch{}n.close(),i()}},p=()=>{if(r||!s.current())throw a(),ct()};return n.onmessageerror=a,n.onmessage=l=>{try{p();let c=l.data;if(!Array.isArray(c)||c[0]!==1||c[1]!==s.binding)throw ct();if(c.length===3&&c[2]==="close"){a();return}if(c.length===5&&B2.includes(c[2])){let u=c[2],f=c[3],h=c[4],m=RC(u);if(!o||!Number.isInteger(f)||f<1||f>4294967295||!(h instanceof Uint8Array)||!h.length||h.length>m)throw ct();p(),o(u,f,h);return}if(c.length!==4||c[2]!=="frame"||!(c[3]instanceof Uint8Array)||c[3].length===0||c[3].length>Rr)throw ct();let d=ue(new Uint8Array(c[3]));p(),t(d)}catch{a()}},n.start(),{close:a,send(l){try{p();let c=pe(l);if(!c.length||c.length>Rr)throw ct();p(),n.postMessage([1,s.binding,"frame",c],[c.buffer])}catch{throw a(),ct()}},control(l,c,d){try{p();let u=RC(l);if(!Number.isInteger(c)||c<1||c>4294967295||!(d instanceof Uint8Array)||!d.length||d.length>u||!(d.buffer instanceof ArrayBuffer)||d.byteOffset!==0||d.byteLength!==d.buffer.byteLength)throw ct();p(),n.postMessage([1,s.binding,l,c,d],[d.buffer])}catch{throw a(),ct()}},current:p}}function V2(n){if(!(n instanceof Map))return!1;let e=n;return e.get(0)===0&&F2.has(e.get(2))}function Sh(n,e,t,i){if(!ww(t).current())throw ct();let s;try{s=n.connect({collection:t.collection})}catch{throw e.close(),ct()}let r;try{r=qC(e,t,p=>{if(s.send(p),i&&V2(p))try{i()}catch{}},()=>s.close(),(p,l,c)=>{let d;try{if(p==="bases-request"&&typeof n.executeBases=="function")d=n.executeBases(s,c);else if((p==="bases-list-views-request"||p==="bases-read-view-source-request")&&typeof n.discoverBases=="function")d=n.discoverBases(s,p==="bases-list-views-request"?"list-views":"read-view-source",c);else throw ct()}finally{c.fill(0)}try{r.current(),r.control(EC(p),l,d)}catch(u){throw d.byteLength&&d.fill(0),u}}),s.onframe=p=>{try{r.send(p)}catch{}},s.onclose=()=>r.close()}catch{throw s.close(),e.close(),ct()}let a=Object.freeze({async assess(p,l,c){if(l.throwIfAborted(),r.current(),!n.setupResources)throw ct();let d=c===void 0?n.setupResources(s,"assess",p):n.setupResources(s,"assess",p,void 0,c);return r.current(),l.throwIfAborted(),d},async apply(p,l,c,d){if(c.throwIfAborted(),r.current(),!n.setupResources)throw ct();let u=d===void 0?n.setupResources(s,"apply",p,l):n.setupResources(s,"apply",p,l,d);return r.current(),c.throwIfAborted(),u},async rejected(p,l){if(l.throwIfAborted(),r.current(),!n.resourceRejected)return!1;let c=n.resourceRejected(s,p);return r.current(),l.throwIfAborted(),c}});return{close:()=>r.close(),resourceSetup:a}}function Ph(n,e){let t=ww(e),i=!1,o=!1,s,r=null,a=[],p=()=>A("cancelled","Bases read cancelled"),l=1;return{description:"app-local",close(){o=!0,s?s.close():n.close()},async open(c,d){if(i)throw ct();if(!t.current()||d?.aborted||o)throw n.close(),ct();i=!0;let u,f=s=qC(n,e,b=>u?.onframe?.(b),()=>{let b=r;r=null;let w=a.splice(0);b?.finish(void 0,p());for(let g of w)g.finish(void 0,p());u?.onclose?.(ct())},(b,w,g)=>{if(!r||b!==r.response||w!==r.id)throw g.fill(0),ct();let y=r;r=null,y.finish(g),h()});function h(){if(r||a.length===0)return;let b=a.shift();r=b;try{if(f.current(),r!==b){h();return}if(l>4294967295)throw f.close(),ct();b.id=l++,f.control(b.kind,b.id,b.request)}catch(w){r===b&&(r=null),b.finish(void 0,w),h()}}let m=(b,w,g)=>{try{if(f.current(),g?.aborted)throw p();if(!(w instanceof Uint8Array)||!w.length||w.length>128*1024)throw A("invalid_request","Bases request bytes exceed bound");if(a.length>=32)throw A("unavailable","Bases read queue is full","bases_read_backpressure")}catch(v){return Promise.reject(v)}let y=new Uint8Array(w);return new Promise((v,_)=>{let k=!1,S=(C,E)=>{if(r!==x&&y.byteLength&&y.fill(0),k){C?.byteLength&&C.fill(0);return}k=!0,g?.removeEventListener("abort",P),E!==void 0?_(E):v(C)},x={kind:b,request:y,response:EC(b),finish:S},P=()=>{let C=a.indexOf(x);C!==-1&&a.splice(C,1),r===x&&x.id===void 0&&(r=null),S(void 0,p())};a.push(x),g?.addEventListener("abort",P,{once:!0}),h()})};u={onframe:null,onclose:null,send:b=>f.send(b),close:()=>f.close(),readAppBases:(b,w)=>m("bases-request",b,w),readAppBasesDiscovery(b,w,g){return b!=="list-views"&&b!=="read-view-source"?Promise.reject(A("invalid_request","unknown native Bases read")):m(b==="list-views"?"bases-list-views-request":"bases-read-view-source-request",w,g)}};try{if(d?.aborted||o)throw ct();return await Ds({connect:()=>u}).open(c,d)}catch{throw f.close(),ct()}}}}var z2,ct,B2,EC,RC,F2,xh=I(()=>{"use strict";Je();ie();su();Ol();z2=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/iu,ct=()=>A("unavailable","app local facade unavailable; reopen and reconcile");B2=["bases-request","bases-response","bases-list-views-request","bases-list-views-response","bases-read-view-source-request","bases-read-view-source-response"],EC=n=>n==="bases-request"?"bases-response":n==="bases-list-views-request"?"bases-list-views-response":"bases-read-view-source-response",RC=n=>n.endsWith("request")?128*1024:n==="bases-response"?Rr:1024*1024;F2=new Set(["submit","resolve_hold","open_upload","upload_chunk","commit_upload","abort_upload","fetch_file","read_file","ack_chunks"])});function TC(n){let e=Object.freeze({...n,setupJournal:Object.freeze({...n.setupJournal})}),t=IC(e.sql);if(typeof e.handoff!="function")throw Yi("binding");let i=new Set;return async o=>{let s=JSON.stringify([o.scope.account,o.scope.installation,o.scope.collection]);if(i.has(s))throw Yi("fenced");i.add(s);let{host:r,installation:a,signal:p,collection:l,setupPolicy:c}=o,d=a.isCurrent,u=l.displayName,f=he=>{if(X())try{o.onProgress?.(he)}catch{}},h=Object.freeze({account:o.scope.account,installation:o.scope.installation,collection:o.scope.collection}),m=JSON.stringify([h.account,h.installation,h.collection]),b=new AbortController,w=!1,g=!0,y=null,v=null,_=null,k=null,S=null,x=null,P=null,C=null,E="setup_required",O=null,L=!1,z=null,Q=!1,V=null,te=new Map,G=null,K=new Set,X=()=>{try{return!w&&!b.signal.aborted&&!p.aborted&&o.signal===p&&o.host===r&&o.installation===a&&a.isCurrent===d&&d.call(a)===!0&&o.collection===l&&o.setupPolicy===c&&a.scope.account===h.account&&a.scope.installation===h.installation&&JSON.stringify([o.scope.account,o.scope.installation,o.scope.collection])===m&&l.collectionId===h.collection}catch{return!1}},Y=()=>{if(!X())throw Yi("fenced")},ee=()=>{for(let he of[...K])try{he()}catch{}},$e=()=>{if(_)return _;w=!0,E="setup_required",y!==null&&clearTimeout(y),y=null,z!==null&&clearTimeout(z),z=null;try{O?.close()}catch{}O=null;try{r.onLogWork?.(null)}catch{}p.removeEventListener("abort",mt);let he=[...te.values()];return te.clear(),_=Promise.resolve().then(async()=>{let me=!1;try{await S?.close()}catch{me=!0}try{await k?.close()}catch{me=!0}for(let Fe of he){try{await Fe.timers?.close()}catch{me=!0}try{await Fe.control.close()}catch{me=!0}try{Fe.data.port1.postMessage([1,JSON.stringify([h.account,h.installation,h.collection]),"close"])}catch{me=!0}for(let Rn of[Fe.data.port1,Fe.data.port2,Fe.command.port1,Fe.command.port2])try{Rn.close()}catch{me=!0}}try{P?.port1.postMessage([1,JSON.stringify([h.account,h.installation,h.collection]),"close"])}catch{me=!0}for(let Fe of[P?.port1,P?.port2,C?.port1,C?.port2])try{Fe?.close()}catch{me=!0}await v?.catch(()=>{});try{x?.close()}catch{me=!0}if(me)throw Yi("unavailable");K.clear(),i.delete(s)}),b.abort(),ee(),_},mt=()=>{$e().catch(()=>{})},j=null,W=0,$=()=>{let he=St(G);if(he!==null)return he==="collection_migrating"?Math.min(6e5,Math.max(5e3,G?.retryAfterMs??3e4)):3e5;let me=Math.min(6e4,1e3*2**Math.min(Math.max(W,ye),6));return j?.kind==="offline"?qe?me:null:j?.kind==="server_busy"||j?.kind==="rate_limited"?j.retryAfterMs??me:ye||j?me:250},J=()=>{let he=null;try{he=r.serverProblem()}catch{he=null}let me=null;try{me=r.transportHealth()}catch{me=null}W=me?W+1:0;let Fe=JSON.stringify(me)===JSON.stringify(j);(he!==G||!Fe)&&(G=he,j=me,ee())},be=Number.POSITIVE_INFINITY,ye=0,we=0,et=!1,qe=null,Dt=he=>{let me=he&&typeof he=="object"&&typeof he.code=="string"?he.code:null;try{console.debug("mdbase: sync turn failed",{reason:j?.kind??St(G)??me??"unknown",failures:ye})}catch{}},tt=()=>{if(g||Date.now()-we>=W2)return!1;try{return r.pendingWrites()>0}catch{return!1}},Ve=()=>{if(!X())return;if(!g&&!tt()&&!Q){v||O?.suspend();return}if(y!==null||v)return;let he=Q?0:$();Q=!1,he!==null&&(y=setTimeout(()=>{if(y=null,!X())return;let me=g&&Date.now()>=be;me&&(be=Number.POSITIVE_INFINITY);let Fe=v=me?r.wakeCollectionLog({signal:b.signal}):r.driveCollection({signal:b.signal});Fe.then(()=>{v===Fe&&(v=null),ye=0,et=!0,X()&&J(),qe?.(),Ve()},Rn=>{v===Fe&&(v=null),ye++,X()&&J(),Dt(Rn),qe?.(),Ve()})},he))},On=()=>{X()&&(Q=!0,y!==null&&clearTimeout(y),y=null,Ve())},Ar=he=>{L!==he&&(L=he,ee())},Pi=he=>{if(z!==null&&clearTimeout(z),z=null,he){Ar(!1);return}if(!O?.available){Ar(V===null);return}O.suspended||(z=setTimeout(()=>{z=null,X()&&!O?.live&&Ar(!0)},K2))},rs=he=>{if(Y(),he){(!O?.live||j?.kind==="offline")&&(be=0),ye=0,W=0,j?.kind==="offline"&&(Q=!0);try{O?.resume(),O&&!O.live&&Pi(!1)}catch{}}else g&&(we=Date.now());g=he,y!==null&&clearTimeout(y),y=null,Ve()},os=()=>new Promise((he,me)=>{let Fe,Rn=null,En=nt=>{qe=null,Rn!==null&&clearTimeout(Rn),b.signal.removeEventListener("abort",xi),nt?me(nt):he()},xi=()=>En(Yi("fenced"));b.signal.addEventListener("abort",xi,{once:!0}),qe=()=>{if(!X()){En(Yi("fenced"));return}if(V!==null){En();return}let nt="first_turn";if(et)try{nt=typeof r.initialSync=="function"?r.initialSync():null}catch{nt="unavailable"}if(nt===null||nt==="offline"||j?.kind==="offline"){En();return}let ii=null;if(nt==="waiting_for_key"&&typeof r.keyWaitDetail=="function")try{ii=r.keyWaitDetail()}catch{ii=null}let ss=nt+(ii?JSON.stringify(ii):"");if(ss!==Fe){Fe=ss;try{console.debug("mdbase: waiting for the first sync",{...ii,reason:nt})}catch{}}},Rn=setTimeout(()=>En(),H2),qe()});p.addEventListener("abort",mt,{once:!0});try{Y(),x=new Ba({...e.setupJournal,scope:h,isCurrent:X});let he=new Xa({databaseName:e.joinDatabaseName,scope:h,isCurrent:X}),me=await he.prepare({signal:b.signal});Y(),f("joining"),await r.bootstrapCloudCopy({scope:h,collectionCurrent:X,purpose:"join",outcomeMode:me.outcomeMode,signal:b.signal,...me.outcomeMode==="existing"?{reconcile:"explicit-unknown-outcome"}:{},fetch:e.fetch,allowLoopbackHttp:e.allowLoopbackHttp,allowNativeLoopbackHttp:e.allowNativeLoopbackHttp}),Y(),await he.complete({signal:b.signal}),Y();let Fe=r.registeredReceipt();if(Fe.installationId!==h.installation)throw Yi("binding");let Rn=null,En=async He=>{let Ze=await t(He);return Rn=Ze.ledger??null,Ze};f("opening_store"),await r.openCollectionSql({signal:b.signal,replicaId:Fe.deviceId,endpoint:0,openSql:En}),Y(),f("connecting_log");let xi=Date.now()+G2;for(let He=0;;He++)try{await r.startCollectionLog({signal:b.signal,fetch:e.fetch,allowLoopbackHttp:e.allowLoopbackHttp}),Y();break}catch(Ze){Y();let dt=Ze instanceof Zn&&Ze.reason==="unavailable"?Ze.server:null;if(!kn(dt)||dt.status!==503||dt.code!=="busy"||St(dt)!==null||He+1>=Y2)throw Ze;let Ci=dt.retryAfterMs??1e3*2**He;if(Date.now()+Ci>=xi||(await pp(Ci,b.signal),Y(),Date.now()>=xi))throw Ze}let nt=await he.syncedBefore({signal:b.signal});Y(),f("syncing"),await r.waitForVerifiedRead({signal:b.signal,cold:!nt,onProgress:f}),Y(),r.onLogWork?.(On),Ve();try{O=typeof r.openLogPush=="function"?r.openLogPush({push:He=>{X()&&(r.pushLog(He),On())},live:Pi,ended:He=>{V=He,On(),Pi(!1),qe?.(),ee()}}):null}catch{O=null}O?(O.start(),Pi(!1)):L=!0,nt&&(f("syncing"),await os()),Y(),f("checking_setup"),he.markSynced({signal:b.signal}).catch(()=>{});let ii=await x.load(b.signal);Y();let ss=ii&&ii.version!==1&&(ii.phase==="attempted"||ii.phase==="confirmed")?"reconcile-original":ii===null&&c==="approved-new-collection"?"approved-new":"inspect",as=crypto.randomUUID(),Qw=e.people===!0?{people:!0}:{},EI={owner:null},ev=(He,Ze,dt,Ci)=>Fx(Ze,{scope:h,generation:as},{journal:x,resourceSetup:r.attachDataFacade(He),signal:b.signal,isCurrent:X,ledger:()=>X()?Rn:null,setupTurn:EI,assess(kr){Y(),E=kr,ee()},foreground:dt,onProtocolFailure:Ci,...e.people===!0?{peopleAuthority:r.peopleAuthority()}:{}});S=r.openTimersPort({scope:h,generation:as,signal:b.signal}),Y(),P=new MessageChannel,C=new MessageChannel,k=ev(P.port1,C.port1,rs,mt),Y();let tv=He=>{if(P&&C&&He.dataPort===P.port2){let dt={data:P,command:C,control:k,timers:S};P=null,C=null,k=null,S=null;try{r.detachDataFacade(dt.data.port1)}catch{}dt.timers?.close().catch(()=>{}),dt.control?.close().catch(()=>{});for(let Ci of[dt.data.port1,dt.command.port1])try{Ci.close()}catch{}return}let Ze=te.get(He.dataPort);if(Ze){te.delete(He.dataPort);try{r.detachDataFacade(Ze.data.port1)}catch{}Ze.timers?.close().catch(()=>{}),Ze.control.close().catch(()=>{});for(let dt of[Ze.data.port1,Ze.command.port1])try{dt.close()}catch{}}},qI=Object.freeze({scope:h,generation:as,isCurrent:X,setForeground:rs,attach:()=>{if(!X()||V!==null)return null;let He=new MessageChannel,Ze=new MessageChannel,dt=null,Ci=null;try{dt=r.openTimersPort({scope:h,generation:as,signal:b.signal});let kr=null;return Ci=ev(He.port1,Ze.port1,()=>{},()=>{kr&&tv(kr)}),kr=Object.freeze({schema:"mdbn-app-collection/1",scope:h,generation:as,displayName:u,setupMode:ss==="reconcile-original"?ss:"inspect",dataPort:He.port2,controlPort:Ze.port2,...Qw,...dt?{timerPort:dt.port}:{}}),te.set(He.port2,{data:He,command:Ze,control:Ci,timers:dt}),kr}catch{try{r.detachDataFacade(He.port1)}catch{}dt?.close().catch(()=>{}),Ci?.close().catch(()=>{});for(let kr of[He.port1,He.port2,Ze.port1,Ze.port2])kr.close();return null}},detach:tv}),TI={get state(){return X()?E:"setup_required"},get problem(){return X()?G:null},get health(){return X()?j:null},get live(){return X()?!L:null},get ended(){return X()?V:null},connection:qI,close:$e,subscribe(He){return Y(),K.add(He),()=>{K.delete(He)}}};return e.handoff(Object.freeze({schema:"mdbn-app-collection/1",scope:h,generation:as,displayName:u,setupMode:ss,dataPort:P.port2,controlPort:C.port2,...Qw,...S?{timerPort:S.port}:{}})),Y(),Ve(),Object.freeze(TI)}catch(he){throw await $e(),he}}}async function Ch(n,e){if(n.schema!=="mdbn-app-collection/1"||Za.has(n.dataPort)||Za.has(n.controlPort)||n.dataPort===n.controlPort||!["inspect","approved-new","reconcile-original"].includes(n.setupMode)||n.people!==void 0&&n.people!==!0||e.signal.aborted||n.timerPort&&(Za.has(n.timerPort)||n.timerPort===n.dataPort||n.timerPort===n.controlPort))throw Yi("binding");Za.add(n.dataPort),Za.add(n.controlPort),n.timerPort&&Za.add(n.timerPort);let t=Object.freeze({...n.scope}),i=n.generation,o=n.setupMode,s=n.people===!0,r=n.dataPort,a=n.controlPort,p=e.signal,l=!1,c=null,d=null,u=null,f,h=()=>{if(!l){l=!0,p.removeEventListener("abort",h);for(let m of[()=>f?.close(),()=>d?.close(),()=>c?.close(),()=>u?.close(),()=>r.close(),()=>a.close()])try{m()}catch{}}};p.addEventListener("abort",h,{once:!0});try{if(u=Ph(r,{...t,isCurrent:()=>!l&&!p.aborted}),d=uh(a,{scope:t,generation:i},{signal:p,isCurrent:()=>!l,onClose:h,...s?{people:!0}:{}}),n.timerPort&&(f=new Ns(mC(n.timerPort,{scope:t,generation:i},{signal:p,onClose:()=>{}}),{criteria:e.timerCriteria??[]})),c=await Ei.connect({app:e.app,connector:u,reconnect:!1,signal:p,ledger:d.ledger}),l||p.aborted)throw c.close(),Yi("fenced");let m=s?ph(c,d):void 0;return Object.freeze({client:c,resourceSetup:d.resourceSetup,...m?{people:m}:{},journal:d.journal,scope:t,setupMode:o,close:h,...f?{timers:f}:{},assess:(b,w)=>d.assess(b,w),setForeground:(b,w)=>d.setForeground(b,w)})}catch(m){throw h(),m}}var K2,W2,H2,G2,Y2,up,Yi,Za,vw=I(()=>{"use strict";Fn();Zc();cw();Ps();Zy();uw();OC();kh();Go();no();xh();rp();K2=1e4,W2=12e4,H2=2e3,G2=15e3,Y2=3,up=class extends Error{constructor(t){super(`app web collection: ${t}`);this.reason=t;this.name="AppWebCollectionError"}reason},Yi=n=>new up(n);Za=new WeakSet});var Ut,Ih,J2,Oh,MC=I(()=>{"use strict";vw();Ut=class extends Error{constructor(t){super("SDK application connection unavailable");this.code=t;this.name="ApplicationUiConnectionError"}code},Ih=new WeakSet,J2=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,Oh=class{app;signal;current=null;pending=null;opening=null;retiring=null;closing=null;epoch=0;timerCriteria;constructor(e,t,i=[]){this.app=Object.freeze({...e}),this.signal=t,this.timerCriteria=Object.freeze([...i]),t.addEventListener("abort",this.abort,{once:!0})}abort=()=>{this.close().catch(()=>{})};connection(e){let t=this.current?.public;return t?.id===e&&t.isCurrent()?t:null}owned(){return this.current?.public.isCurrent()?this.current.ui:null}adopt(e,t){let i=t.caller,o=t.isCurrent,s=[e.dataPort,e.controlPort,...e.timerPort?[e.timerPort]:[]];if(s.some(g=>!(g instanceof MessagePort))||new Set(s).size!==s.length||s.some(g=>Ih.has(g))){for(let g of new Set(s))g instanceof MessagePort&&!Ih.has(g)&&(Ih.add(g),g.close());return Promise.reject(new Ut("application_connection_binding"))}for(let g of s)Ih.add(g);let r=g=>{for(let y of s)y.close();return Promise.reject(new Ut(g))};if(this.pending||this.current||this.retiring)return r("application_connection_busy");if(this.closing||this.signal.aborted||i.aborted||!o())return r("application_connection_fenced");let a=Object.freeze({...e.scope}),p=e.generation,l=e.displayName;if(e.schema!=="mdbn-app-collection/1"||Object.keys(a).sort().join()!=="account,collection,installation"||Object.values(a).some(g=>!J2.test(g)||g==="00000000-0000-0000-0000-000000000000")||typeof p!="string"||!p||p.length>256||typeof l!="string"||!l.trim()||new TextEncoder().encode(l).length>4096||!["inspect","approved-new","reconcile-original"].includes(e.setupMode))return r("application_connection_binding");if(e.people!==!0)return r("application_connection_people_unavailable");let c=Object.freeze({...e,scope:a,generation:p,displayName:l}),d=new AbortController,u=this.epoch;this.opening=d;let f=()=>d.abort();i.addEventListener("abort",f,{once:!0});let h=AbortSignal.any([this.signal,d.signal]),m=()=>!h.aborted&&!this.closing&&!this.retiring&&this.epoch===u&&o(),b=null,w=Promise.resolve().then(async()=>{if(!m()||i.aborted)throw new Ut("application_connection_fenced");if(b=await Ch(c,{app:this.app,signal:h,timerCriteria:this.timerCriteria}),!m()||i.aborted)throw new Ut("application_connection_fenced");if(b.client.collection!==a.collection||b.client.link!=="open")throw new Ut("application_connection_binding");if(!b.people)throw new Ut("application_connection_people_unavailable");let g=b,y=b.people,v=Object.freeze({id:a.collection,scope:a,generation:p,displayName:l,records:g.client,files:g.client.files,people:y,...g.timers?{timers:g.timers}:{},isCurrent:()=>m()&&this.current?.ui===g&&g.client.link==="open"});return this.current={public:v,ui:g,lifetime:d},v}).catch(g=>{d.abort(),b?.close();for(let y of s)y.close();throw g}).finally(()=>{i.removeEventListener("abort",f),this.pending===w&&(this.pending=null,this.opening=null)});return this.pending=w,w}retire(){if(this.retiring)return this.retiring;++this.epoch;let e=this.current,t=this.pending;this.opening?.abort(),e?.lifetime.abort();let i=Promise.resolve().then(async()=>{await t?.catch(()=>{}),e?.ui.close(),this.current===e&&(this.current=null)});return this.retiring=i,i.then(()=>{this.retiring===i&&(this.retiring=null)},()=>{}),i}close(){return this.closing?this.closing:(this.closing=Promise.resolve().then(()=>this.retire()),this.signal.removeEventListener("abort",this.abort),++this.epoch,this.opening?.abort(),this.current?.lifetime.abort(),this.closing)}}});function nT(n){if(n.capabilityContractVersion!==2)throw A("upgrade_required","unsupported readiness capability projection","readiness_capability_version");if(!Array.isArray(n.contracts)||n.contracts.length>128||!Array.isArray(n.requiredNativeCapabilities)||n.requiredNativeCapabilities.length>64)throw Ct("unsupported");let e=n.contracts.map(i=>{if(!i||!el(i.id,256)||!el(i.version,128)||!tT.test(i.digest))throw Ct("unsupported");return Object.freeze({id:i.id,version:i.version,digest:i.digest})}),t=n.requiredNativeCapabilities.map(i=>{if(!el(i,128))throw Ct("unsupported");return i});if(new Set(e.map(i=>JSON.stringify([i.id,i.version]))).size!==e.length||new Set(t).size!==t.length||n.typeIssues!==void 0&&n.typeIssues!=="block"&&n.typeIssues!=="degrade")throw Ct("unsupported");return Object.freeze({capabilityContractVersion:2,typeIssues:n.typeIssues??"block",contracts:Object.freeze(e),requiredNativeCapabilities:Object.freeze(t)})}function iT(n){let e=n instanceof Map?n.get("path"):null;return typeof e=="string"&&e?e:null}function Qa(n,e){return Object.freeze({reason:n,...n==="fenced"&&e?{detail:e}:{}})}function _w(n){if(!oe(n))return;let e=n.details instanceof Map?n.details.get("condition"):void 0,t=X2.find(i=>i===e);if(t)return t;if(n.code==="unauthenticated")return"read_unauthenticated";if(n.code==="cancelled")return"read_cancelled"}function Aw(n){try{if(oe(n)){if(n.code==="unauthenticated"||n.code==="cancelled")return"fenced";if(n.code==="too_large")return"budget";if(n.code==="upgrade_required"||n.code==="forbidden")return"unsupported";if(n.reason==="readiness_changed"||n.reason==="cursor_stale"||n.reason==="cursor_expired")return"changed";if(n.reason==="readiness_busy")return"busy";if(n.reason==="readiness_catalog_response")return"catalog_response"}}catch{}return"unavailable"}function Sw(n){let e=n.status;return JSON.stringify([e.mode,e.confirmedThrough,e.headKnown,e.pending,e.holds,e.unresolved,e.connection,e.installing,e.resyncing,e.incidents.map(t=>t.kind),e.confirmedHead])}function tl(n){return JSON.stringify(n,(e,t)=>typeof t=="bigint"?`${t}n`:t instanceof Map?[...t.entries()]:t instanceof Uint8Array?[...t]:t)}function jC(n,e,t){return new kw(n,e,t)}var X2,Z2,Q2,eT,LC,tT,el,Ct,kw,Pw=I(()=>{"use strict";ie();X2=["binding_invalid","binding_aborted","binding_not_current","readiness_closed","read_aborted","session_closed","session_replaced","session_collection_mismatch","read_unauthenticated","read_cancelled"],Z2=4096,Q2=2*1024*1024,eT=64,LC=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,tT=/^sha256:[0-9a-f]{64}$/,el=(n,e=4096)=>typeof n=="string"&&!!n.trim()&&new TextEncoder().encode(n).length<=e,Ct=(n,e)=>A(n==="fenced"?"unauthenticated":n==="budget"?"too_large":"unavailable","collection readiness unavailable",{reason:`readiness_${n}`,...e?{details:new Map([["condition",e]])}:{}});kw=class{constructor(e,t,i){this.client=e;if(this.declared=nT(t),!LC.test(i.collection)||i.collection==="00000000-0000-0000-0000-000000000000"||!LC.test(i.generation))throw Ct("fenced","binding_invalid");this.binding=Object.freeze({collection:i.collection,generation:i.generation,signal:i.signal,isCurrent:i.isCurrent.bind(i)}),this.readSignal=AbortSignal.any([this.binding.signal,this.lifetime.signal]),this.check(),this.binding.signal.addEventListener("abort",this.abort,{once:!0})}client;declared;binding;lifetime=new AbortController;readSignal;listeners=new Set;snapshotValue=Object.freeze({checking:!1,assessment:null,problem:null});watch=null;stops=[];pending=null;epoch=0;dirty=!1;scheduled=!1;retries=0;failures=0;closed=!1;lastStatus=null;assessedSession;assessedEpoch;assessedCatalog=null;probing=null;probeAgain=!1;abort=()=>{this.close()};getSnapshot(){if(this.snapshotValue.assessment)try{this.check(void 0,this.assessedSession,this.assessedEpoch)}catch(e){let t=Aw(e);t==="fenced"&&!this.closed&&!this.binding.signal.aborted&&this.binding.isCurrent()===!0&&(t="changed"),this.retryLater(t)||this.publish({checking:!1,assessment:null,problem:Qa(t,_w(e))})}return this.snapshotValue}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}publish(e){this.snapshotValue=Object.freeze(e);for(let t of this.listeners)try{t()}catch{}}check(e,t,i){e?.throwIfAborted();let o=this.fenceDetail(e);if(o)throw Ct("fenced",o);if(t?.closed)throw Ct("fenced","session_closed");if(t&&t!==this.client.currentSession())throw Ct("fenced","session_replaced");if(t&&t.hello.collection!==this.binding.collection)throw Ct("fenced","session_collection_mismatch");if(i!==void 0&&(i!==this.epoch||this.watch?.state!=="active"))throw Ct("changed")}fenceDetail(e){if(this.binding.signal.aborted)return"binding_aborted";if(this.closed)return"readiness_closed";if(e?.aborted)return"read_aborted";if(this.binding.isCurrent()!==!0)return"binding_not_current"}invalidate=()=>{if(this.closed)return;if(this.pending||!this.snapshotValue.assessment||this.assessedCatalog===null||this.client.link!=="open"){this.recheck();return}if(this.probing){this.probeAgain=!0;return}let e=this.snapshotValue.assessment,t=this.assessedCatalog,i=this.client.describe(this.readSignal).then(o=>{this.closed||this.snapshotValue.assessment!==e||tl(o)!==t&&this.recheck()},()=>{this.closed||this.recheck()});this.probing=i.finally(()=>{this.probing=null,this.probeAgain&&!this.closed&&(this.probeAgain=!1,this.invalidate())})};recheck(){this.closed||(this.epoch++,this.dirty=!0,this.publish({checking:!0,assessment:null,problem:null}),this.schedule())}schedule(){if(this.closed||this.pending||this.scheduled||!this.dirty||this.watch?.state!=="active"||this.client.link!=="open")return;this.scheduled=!0;let e=()=>{this.scheduled=!1,!this.closed&&this.dirty&&!this.pending&&this.watch?.state==="active"&&this.client.link==="open"&&this.refresh(void 0,!0).catch(()=>{})};this.retries?setTimeout(e,Math.min(5e3,100*2**this.retries,this.retrySince===null?5e3:Math.max(0,15e3-(Date.now()-this.retrySince)))):queueMicrotask(e)}retrySince=null;retryLater(e,t=!1){if(this.closed)return!1;if((e==="busy"||e==="changed")&&(this.retrySince??=Date.now(),Date.now()-this.retrySince>=15e3))return this.dirty=!1,this.publish({checking:!1,assessment:null,problem:Qa("busy_timeout")}),!0;if(e==="unavailable"&&t&&this.failures<5)this.failures++;else if(e!=="changed"&&e!=="busy")return!1;return this.dirty=!0,this.retries=Math.min(this.retries+1,6),this.publish({checking:!0,assessment:null,problem:null}),this.schedule(),!0}attach(){this.watch||(this.watch=this.client.watchChanges(void 0,this.invalidate),this.stops.push(this.watch.subscribe(this.invalidate),this.client.onLink(this.invalidate),this.client.onStatus(()=>{let e=Sw(this.client);e!==this.lastStatus&&(this.lastStatus=e,this.invalidate())})))}start(e){return this.refresh(e)}refresh(e,t=!1){try{if(this.check(e),this.pending)throw Ct("busy")}catch(a){return Promise.reject(a)}t||(this.retrySince=null);let i=AbortSignal.any([this.binding.signal,this.lifetime.signal,...e?[e]:[]]),o,s,r=Promise.resolve().then(async()=>{this.check(i),this.attach();let a=await this.client.readyForRead(i);this.check(i,a),await this.watch.ready,this.check(i,a);let p=this.epoch;this.dirty=!1,this.check(i,a,p);let l=await this.inventory(i,a,p),c=await this.client.describe(this.readSignal);this.check(i,a,p);let d=this.evaluate(c,a),u=tl(c);for(let b of d.paths){let w=l.find(y=>y.path===b);if(!w)throw Ct("changed");let g=await this.client.resources.get(b,this.readSignal);if(this.check(i,a,p),g.path!==w.path||g.revision!==w.revision||g.size!==w.size||g.state!=="confirmed")throw Ct("changed")}let f=await this.inventory(i,a,p);if(JSON.stringify(l)!==JSON.stringify(f))throw Ct("changed");this.check(i,a,p);let h=Object.freeze({collection:this.binding.collection,generation:this.binding.generation,resources:Object.freeze(f)}),m=Object.freeze({status:d.status,problem:d.reason?Qa(d.reason):null,witness:h,...d.unavailable.length?{unavailableTypes:Object.freeze(d.unavailable)}:{}});return o=a,s=p,this.retries=0,this.failures=0,this.retrySince=null,this.assessedSession=a,this.assessedEpoch=p,this.assessedCatalog=u,this.publish({checking:!1,assessment:m,problem:m.problem}),this.check(i,a,p),m}).catch(a=>{let p=i.aborted||this.closed?"fenced":Aw(a);throw this.retryLater(p,t)||this.publish({checking:!1,assessment:null,problem:Qa(p,this.fenceDetail(i)??_w(a))}),a});return this.pending=r,this.publish({checking:!0,assessment:null,problem:null}),r.finally(()=>{this.pending===r&&(this.pending=null),this.schedule()}).catch(()=>{}),r.then(a=>{try{if(this.check(i,o,s),this.snapshotValue.assessment!==a)throw Ct("changed");return a}catch(p){let l=i.aborted?"fenced":Aw(p);throw this.snapshotValue.assessment===a&&!this.retryLater(l)&&this.publish({checking:!1,assessment:null,problem:Qa(l,this.fenceDetail(i)??_w(p))}),p}})}async inventory(e,t,i){let o=[],s=new Set,r,a="",p=0;for(let l=0;l<eT;l++){this.check(e,t,i);let c=await this.client.resources.list({text:!1,limit:128,...r?{cursor:r}:{},signal:this.readSignal});this.check(e,t,i);for(let d of c.resources){if(!el(d.path)||d.path<=a||!el(d.revision,128)||!Number.isSafeInteger(d.size)||d.size<0||d.state!=="confirmed")throw Ct("catalog_response");a=d.path;let u=Object.freeze({path:d.path,revision:d.revision,size:d.size,state:d.state});if(p+=new TextEncoder().encode(JSON.stringify(u)).length,o.length>=Z2||p>Q2)throw Ct("budget");o.push(u)}if(c.complete===!0&&c.cursor===void 0)return o;if(c.complete!==!1||!el(c.cursor)||s.has(c.cursor))throw Ct("catalog_response");s.add(c.cursor),r=c.cursor}throw Ct("budget")}evaluate(e,t){let i=e.issues.filter(d=>d.severity==="error"),o=new Set;for(let d of i){let u=iT(d.details);if(!u)return{status:"incompatible",reason:"catalog_invalid",paths:[],unavailable:[]};o.add(u)}let s={status:"incompatible",reason:"catalog_invalid",paths:[],unavailable:[]};if(this.declared.requiredNativeCapabilities.some(d=>!t.hello.grant.capabilities.includes(d)))return{status:"incompatible",reason:"capability_missing",paths:[],unavailable:[]};let r=new Set,a=new Set,p=new Set;for(let d of e.contracts){let u=JSON.stringify([d.id,d.version]);if(a.has(u))return{status:"incompatible",reason:"catalog_response",paths:[],unavailable:[]};a.add(u)}for(let d of e.types){if(p.has(d.name))return{status:"incompatible",reason:"catalog_response",paths:[],unavailable:[]};p.add(d.name)}let l,c=[];for(let d of this.declared.contracts){let u=e.contracts.find(f=>f.id===d.id&&f.version===d.version);if(!u){l??="contract_missing";continue}if(u.digest!==d.digest)return{status:"incompatible",reason:"contract_mismatch",paths:[],unavailable:[]};if(r.add(u.path),o.has(u.path))return s;if(!u.implementedBy.length){l??="implementation_missing";continue}for(let f of u.implementedBy){let h=e.types.find(m=>m.name===f);if(!h||!h.implements.some(m=>m.contract===d.id&&m.version===d.version))return{status:"incompatible",reason:"catalog_response",paths:[],unavailable:[]};if(r.add(h.path),o.has(h.path)){if(this.declared.typeIssues!=="degrade")return s;c.some(m=>m.name===h.name)||c.push(Object.freeze({name:h.name,path:h.path,contract:Object.freeze({id:d.id,version:d.version}),problem:Object.freeze({code:"readiness_type_invalid"})}))}}}return{status:l?"setup_required":"ready",...l?{reason:l}:{},paths:[...r].sort(),unavailable:c}}async close(){if(!this.closed){this.closed=!0,this.dirty=!1,this.lifetime.abort(),this.binding.signal.removeEventListener("abort",this.abort);for(let e of this.stops.splice(0))e();this.watch?.(),this.watch=null,this.publish({checking:!1,assessment:null,problem:Qa("fenced",this.fenceDetail())})}await this.pending?.catch(()=>{})}}});function oT(n){let e=o=>o?Object.freeze({code:`readiness_${o.reason}`,...o.detail?{detail:o.detail}:{}}):null,t=e(n.problem),i=n.assessment?.unavailableTypes;return Object.freeze({checking:n.checking,assessment:n.assessment?Object.freeze({status:n.assessment.status,problem:e(n.assessment.problem),...i?.length?{unavailableTypes:i}:{}}):null,problem:t})}var NC,rT,fp,Ji,Rh,UC=I(()=>{"use strict";nc();ie();Pw();NC=["configuration","files"],rT=["people","notifications"],fp=class extends Error{constructor(t,i){super("SDK application readiness unavailable");this.code=t;this.detail=i;this.name="ApplicationReadinessError"}code;detail},Ji=(n,e=!1,t)=>Object.freeze({checking:e,assessment:null,problem:n?Object.freeze({code:n,...t?{detail:t}:{}}):null});Rh=class{connection;signal;observed;native;sources;listeners=new Set;stops=[];pending=null;closing=null;checking=!1;closed=!1;advisory=Promise.resolve();lastReady=null;constructor(e){this.connection=e.connection,this.signal=e.signal,this.observed=e.isCurrent,this.sources=Object.freeze({configuration:e.configuration,files:e.files,people:e.people,notifications:e.notifications}),this.native=e.nativeRequirements?jC(this.connection.records,e.nativeRequirements,{collection:this.connection.id,generation:this.connection.generation,signal:this.signal,isCurrent:()=>this.current()}):null,this.native&&this.stops.push(this.native.subscribe(this.changed));for(let t of Object.values(this.sources))t&&this.stops.push(t.subscribe(this.changed));this.signal.addEventListener("abort",this.abort,{once:!0})}fenceDetail(){try{return this.signal.aborted?"scope_aborted":this.closed?"scope_closed":this.observed()!==!0?"observer_not_current":this.connection.isCurrent()?this.connection.records.collection!==this.connection.id?"collection_mismatch":null:"connection_not_current"}catch{return"currentness_check_failed"}}current(){return this.fenceDetail()===null}connectionProblem(){if(!this.closed&&!this.signal.aborted&&this.connection.records.collection===this.connection.id&&this.connection.records.link==="closed"){let e=this.connection.records.linkProblem;if(oe(e)){let t=Lo(e);return t&&t.key!=="unknown"?t.key:e.code}}return"readiness_fenced"}changed=()=>{for(let e of[...this.listeners])try{e()}catch{}};abort=()=>{this.close().catch(()=>{})};subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getSnapshot(){let e=this.current(),t=Ji(e?"readiness_unsupported":"readiness_fenced"),i=t;if(e&&this.native){let u=this.native.getSnapshot(),f=u.assessment?.witness,h=f&&f.collection!==this.connection.id?"native_witness_collection_mismatch":f&&f.generation!==this.connection.generation?"native_witness_generation_mismatch":null;i=h?Ji("readiness_fenced",!1,h):oT(u)}let o=u=>{if(!e)return t;let f=this.sources[u];if(!f)return Ji(`${u}_unsupported`);try{let h=f.getSnapshot();return Object.freeze({checking:h.checking,assessment:h.assessment?Object.freeze({...h.assessment,problem:h.assessment.problem?Object.freeze({...h.assessment.problem}):null}):null,problem:h.problem?Object.freeze({...h.problem}):null})}catch{return Ji(`${u}_unavailable`)}},s=Object.freeze({capabilities:i,contracts:i,configuration:o("configuration"),files:o("files"),people:o("people"),notifications:o("notifications")}),r=[s.capabilities,s.contracts,s.configuration,s.files],a=e&&(this.checking||r.some(u=>u.checking)),p=null,l=null;if(!e)l=Object.freeze({code:"readiness_fenced"});else if(!a){let u=["capabilities","contracts",...NC].find(f=>s[f].problem);if(l=u?s[u].problem:null,u&&l?.code==="readiness_fenced"&&!l.detail&&(l=Object.freeze({...l,detail:`${u}_facet`})),r.every(f=>f.assessment!==null)){let f=r.find(w=>w.assessment?.status==="incompatible"),h=r.find(w=>w.assessment?.status==="setup_required"),m=f??h,b=i.assessment?.unavailableTypes;p=Object.freeze({status:f?"incompatible":h?"setup_required":"ready",problem:m?.assessment?.problem??null,...b?.length?{unavailableTypes:b}:{}})}}let c=this.fenceDetail();if(c)return this.lastReady=null,Object.freeze({checking:!1,assessment:null,problem:Object.freeze({code:this.connectionProblem(),detail:c}),facets:Object.freeze({capabilities:Ji("readiness_fenced",!1,c),contracts:Ji("readiness_fenced",!1,c),configuration:Ji("readiness_fenced",!1,c),files:Ji("readiness_fenced",!1,c),people:Ji("readiness_fenced",!1,c),notifications:Ji("readiness_fenced",!1,c)})});let d=!l||/_(changed|busy)$/.test(l.code);if(l===null&&p!==null&&!a)this.lastReady=Object.freeze({checking:a,assessment:p,problem:l,facets:s});else{if(this.lastReady&&d&&(a||p===null)&&(this.lastReady.assessment?.status==="ready"||!this.checking))return Object.freeze({...this.lastReady,facets:s});this.lastReady=null}return Object.freeze({checking:a,assessment:p,problem:l,facets:s})}refresh(e={}){let t=e.signal,i=this.fenceDetail()??(t?.aborted?"caller_aborted":null);if(i)return Promise.reject(new fp("application_readiness_fenced",i));if(this.pending)return Promise.reject(new fp("application_readiness_busy"));this.checking=!0;let o=Promise.resolve().then(async()=>{if(!this.current())return this.getSnapshot();await this.advisory,this.native&&await this.native.start();for(let s of NC){let r=this.sources[s];if(!this.current())break;r&&await r.refresh()}return this.getSnapshot()}).finally(()=>{if(this.pending!==o)return;this.pending=null,this.checking=!1;let s=(async()=>{for(let r of rT){let a=this.sources[r];if(!this.current())break;a&&await a.refresh().catch(()=>{})}})();this.advisory=s,this.changed()}).then(()=>this.getSnapshot());return this.pending=o,this.changed(),o.then(s=>{let r=this.fenceDetail()??(t?.aborted?"caller_aborted":null);if(r)throw new fp("application_readiness_fenced",r);return s})}close(){return this.closing?this.closing:(this.closed=!0,this.checking=!1,this.signal.removeEventListener("abort",this.abort),this.closing=Promise.resolve().then(async()=>{for(let e of this.stops.splice(0))e();for(let e of Object.values(this.sources))await e?.close();await this.native?.close(),await this.pending?.catch(()=>{}),await this.advisory,this.listeners.clear()}),this.changed(),this.closing)}}});function sT(n){let e=new Set,t=[],i=[];for(let o of n.review?.packs??[]){if(o.status!=="conflict"&&o.status!=="downgrade")continue;let s=o.installedVersion?jo(o.installedVersion,o.version):"unknown";s==="installed_newer"&&!o.resources.some(r=>r.action==="conflict")?(e.add(o.id),i.push(Object.freeze({id:o.id,version:o.version,installedVersion:o.installedVersion}))):s==="installed_newer_major"&&t.push(o.id)}return Object.freeze({kept:Object.freeze(i),compatible:e,major:Object.freeze(t)})}function aT(n,e){let t=n,i=t.provisions?.type_packs;return!e.size||!Array.isArray(i)?n:{...t,provisions:{...t.provisions,type_packs:i.filter(o=>!(typeof o?.manifest?.id=="string"&&e.has(o.manifest.id)))}}}function $C(n){return new Proxy({},{get(e,t){let i=Reflect.get(n,t,n);return typeof i!="function"?i:async(...o)=>{let s=o.find(a=>a instanceof AbortSignal),r=Date.now()+lT;for(let a=25;;a=Math.min(a*2,500))try{return await i.apply(n,o)}catch(p){if(!(p instanceof ti&&p.reason==="busy")||!s)throw p;if(Date.now()+a>r)throw ze("busy_timeout");await cT(a,s)}}}})}function BC(n,e){let t=Object.freeze({...n,scope:Object.freeze({...n.scope}),journal:$C(n.journal)});if(e&&(e=$C(e)),Object.values(t.scope).some(j=>!DC.test(j)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/.test(j))||!DC.test(t.generation)||!["inspect","approved-new","reconcile-original"].includes(t.setupMode))throw ze("binding");let i=JSON.stringify([t.scope.account,t.scope.installation,t.scope.collection]),o=new AbortController,s=AbortSignal.any([t.signal,o.signal]),r=new Set,a=vr(),p=null,l=null,c=!1,d,u=null,f=!1,h=!1,m=0,b=!1,w=!1,g=null,y=null,v=()=>{try{return JSON.stringify([t.client.link,Sw(t.client)])}catch{return null}},_=[],k=new WeakMap;function S(j,W){if(j?.throwIfAborted(),c||s.aborted||t.isCurrent()!==!0||JSON.stringify([t.journal.scope.account,t.journal.scope.installation,t.journal.scope.collection])!==i||W&&(W.closed||t.client.currentSession()!==W||W.hello.collection!==t.scope.collection))throw ze("fenced")}function x(j){a=Object.freeze(j);for(let W of r)try{W()}catch{}}function P(){if(c)return;let j=v();if(j!==null&&j===y)return;if(y=j,p||!a.assessment||u===null||t.client.link!=="open"){C();return}if(f){h=!0;return}f=!0;let W=a,$=u;t.client.describe(s).then(J=>{!c&&a===W&&tl(J)!==$&&C()},()=>{c||C()}).finally(()=>{f=!1,h&&!c&&(h=!1,y=null,P())})}function C(){c||(b=!0,p||x(vr(null,!0)),E())}function E(){c||p||w||!b||(w=!0,setTimeout(()=>{if(w=!1,c||p||!b)return;let j=ee(!1,{},void 0,!0);g=p,j.catch(()=>{})},m?Math.min(5e3,250*2**m):50))}function O(){if(a.assessment)try{S(void 0,d)}catch{c||s.aborted||t.isCurrent()!==!0?x(vr("configuration_fenced")):(b=!0,y=null,x(vr(null,!0)),E())}return a}async function L(j,W,$){let J=await t.client.awaitReceipt(j.mutationId,12e4,s);if(S(W,$),J.mutation!==j.mutationId||J.state!=="confirmed"||J.status!=="applied"||(J.conflicts?.length??0)!==0||J.published==="publishing"||J.published==="not_published")throw ze("recovery_required");return J}async function z(j,W,$){let J,be=0,ye=0,we=new Set,et=new Set,qe=new TextEncoder;for(let Dt=0;Dt<64;Dt++){S(W,$);let tt=await t.client.resources.list({text:!1,limit:128,...J===void 0?{}:{cursor:J},signal:s});if(S(W,$),tt.resources.length>128)throw ze("recovery_required");for(let Ve of tt.resources){let On=qe.encode(Ve.path).length;if(be++,ye+=On+128,!Ve.path||On>4096||et.has(Ve.path)||Ve.state!=="confirmed"||!xw.test(Ve.revision)||!Number.isSafeInteger(Ve.size)||Ve.size<0||be>4096||ye>2*1024*1024||j.has(Ve.path))throw ze("recovery_required");et.add(Ve.path)}if(tt.complete===!0&&tt.cursor===void 0)return;if(tt.complete!==!1||!tt.resources.length||typeof tt.cursor!="string"||!tt.cursor||qe.encode(tt.cursor).length>4096||we.has(tt.cursor))throw ze("recovery_required");we.add(tt.cursor),J=tt.cursor}throw ze("recovery_required")}async function Q(j,W,$){let J=j.version===2?j.plan.readback:j.plan.resourceReadback,be=new Set(J.filter(ye=>ye.doc===null).map(ye=>ye.path));be.size&&await z(be,W,$);for(let ye of J){if(ye.doc===null)continue;let we=await t.client.resources.get(ye.path,s);if(S(W,$),we.path!==ye.path||we.text!==ye.doc||we.state!=="confirmed")throw ze("recovery_required")}if(j.version!==2)for(let ye of j.plan.sources){let we=await t.client.get(ye.id,void 0,s);if(S(W,$),we.id!==ye.id||we.path!==ye.path||we.state.state!=="confirmed"||we.state.hold||we.state.unresolved)throw ze("recovery_required")}}async function V(j,W,$){return await L(j,W,$),j.phase==="attempted"&&(j=j.version===2?await t.journal.recordConfirmed(j.mutationId,s):await t.journal.recordResourceConfirmed(j.mutationId,s),S(W,$)),j.phase==="verified"||(await Q(j,W,$),j.phase==="confirmed"&&(j=j.version===2?await t.journal.recordVerified(j.mutationId,s):await t.journal.recordResourceVerified(j.mutationId,s),S(W,$))),j}async function te(j,W){let $=await t.journal.load(s);if(S(j,W),!$)return{journaled:!1,previous:null};if($=Et($,t.scope),$.version===1||$.phase==="prepared")throw ze("recovery_required");if($.phase==="attempted"&&($.version===3||$.version===4)&&t.journal.recordResourceRejected){let J=await t.client.awaitReceipt($.mutationId,12e4,s);S(j,W),J.mutation===$.mutationId&&J.state==="rejected"&&($=Et(await t.journal.recordResourceRejected($.mutationId,s),t.scope),S(j,W))}if($.version===1)throw ze("recovery_required");return $.phase==="rejected"?{journaled:!0,previous:$.version===4?$.previous:null}:{journaled:!0,previous:await V($,j,W)}}async function G(j,W){let $=t.compiledManifest.manifest,J=await Cw(e.assess($,s,j),j),be=J;J.status==="conflict"&&!J.review&&(be=await e.assess($,s,ei({})));let ye=sT(be);if(!ye.compatible.size)return{assessed:J,manifest:$,newer:ye};let we=aT($,ye.compatible),et=W?j??ei({}):j;return J=await Cw(e.assess(we,s,et),et),{assessed:J,manifest:we,newer:ye}}async function K(j,W,$={}){S(W);let J=await t.client.readyForRead(s);S(W,J),_.length||(y=v(),_.push(t.client.onStatus(P),t.client.onLink(P))),b=!1;let{journaled:be,previous:ye}=await te(W,J);if(!e)throw ze("unsupported");let we=null;try{we=tl(await t.client.describe(s))}catch{}S(W,J);let et=await G($.decisions,!1),qe=et.assessed,Dt=et.manifest;if(S(W,J),!xw.test(qe.assessmentDigest)||!["current","provision","conflict"].includes(qe.status))throw ze("response");if($.expected!==void 0&&qe.assessmentDigest!==$.expected)throw Iw();let tt=!be&&t.setupMode==="approved-new";if(qe.status==="provision"&&(j||tt)){if(t.setupMode==="reconcile-original")throw ze("recovery_required");if(!(t.compiledManifest.operations.includes("apply_collection_setup")||t.compiledManifest.operations.includes("apply_type_pack"))||!J.hello.grant.capabilities.includes("definitions.manage"))throw ze("not_authorized");let rs=$.records??[];if(rs.length&&!J.hello.grant.capabilities.includes("records.create"))throw ze("not_authorized");let os=xt(await Cw(e.apply(Dt,qe.assessmentDigest,s,$.decisions),$.decisions));if(S(W,J),os.assessmentDigest!==qe.assessmentDigest)throw ze("response");if(os.sources.length)throw ze("unsupported_source_provision");let he=rs.length?xt({...os,sources:rs.map(nt=>({id:crypto.randomUUID(),path:nt.path,document:nt.document}))}):os,me;if(ye){if(!t.journal.prepareResourceRound)throw ze("recovery_required");me=await t.journal.prepareResourceRound(he,ye.mutationId,s)}else me=await t.journal.prepareResources(he,s);if(S(W,J),me=Et(me,t.scope),me.version!==3&&me.version!==4||me.phase!=="prepared"||JSON.stringify(me.plan)!==JSON.stringify(he))throw ze("recovery_required");let Fe=Et(await t.journal.recordResourceAttempt(me.mutationId,s),t.scope);if(S(W,J),Fe.version!==3&&Fe.version!==4||Fe.mutationId!==me.mutationId||Fe.phase!=="attempted"||JSON.stringify(Fe.plan)!==JSON.stringify(he))throw ze("recovery_required");let Rn=[...he.resourceOps,...he.sources.map(nt=>({kind:"create",id:nt.id,path:nt.path,document:nt.document}))],En=await t.client.submit(Rn,{mutationId:me.mutationId,wait:"confirmed",signal:s});if(S(W,J),En.length!==1||En[0].mutationId!==me.mutationId)throw ze("recovery_required");let xi;try{xi=await En[0].confirmed}catch(nt){throw S(W,J),En[0].receipt.state!=="rejected"||!t.journal.recordResourceRejected?nt:(await t.journal.recordResourceRejected(me.mutationId,s),S(W,J),Iw(me.mutationId,nt))}if(S(W,J),xi.state!=="confirmed"||xi.status!=="applied"||(xi.conflicts?.length??0)!==0)throw ze("recovery_required");await V(Fe,W,J),b=!1,y=v();try{we=tl(await t.client.describe(s))}catch{we=null}if(qe=await e.assess(Dt,s),S(W,J),qe.status!=="current"||!xw.test(qe.assessmentDigest))throw ze("recovery_required")}let Ve=qe.status==="conflict"?et.newer.major.length?"installed_newer":"configuration_conflict":null,On=Ve?Object.freeze({code:Ve}):null,Ar=Object.freeze({status:qe.status==="current"?"ready":qe.status==="conflict"?"incompatible":"setup_required",problem:On});d=J,u=we;let Pi=Object.freeze({checking:!1,assessment:Ar,problem:On});return m=0,x(b?vr(null,!0):Pi),S(W,J),Pi}function X(j={}){try{S(j.signal)}catch(J){return Promise.reject(J)}let W=p,$=(W?W.then(()=>{},()=>{}):Promise.resolve()).then(()=>Y(j));return p=$,$.finally(()=>{p===$&&(p=null)}).catch(()=>{}),$}async function Y(j){let W=sh(j.records),$=ei(j.adopt===void 0?{}:{adopt:j.adopt}),J=AbortSignal.any([s,...j.signal?[j.signal]:[]]),be=await t.client.readyForRead(s);if(S(J,be),await te(J,be),!e)throw ze("unsupported");let{assessed:ye,newer:we}=await G($,!0);if(S(J,be),!ye.review)throw ze("response");let et=[];if(ye.status!=="current")for(let tt of W){let Ve=await t.client.find({path:tt.path},void 0,s);S(J,be),et.push({path:tt.path,free:Ve===null})}let qe=be.hello.grant.capabilities,Dt=tp(ye,{records:et,canManage:qe.includes("definitions.manage")&&(t.compiledManifest.operations.includes("apply_collection_setup")||t.compiledManifest.operations.includes("apply_type_pack")),canCreateRecords:qe.includes("records.create"),newer:we});return k.set(Dt,Object.freeze({decisions:$,records:W.filter(tt=>et.some(Ve=>Ve.path===tt.path&&Ve.free))})),Dt}function ee(j,W={},$,J=!1){try{S(W.signal)}catch(we){return Promise.reject(we)}if(p&&p===g){let we=p;return we.then(()=>{},()=>{}).then(()=>p&&p!==we?Promise.reject(ze("busy")):ee(j,W,$))}if(p)return Promise.reject(ze("busy"));let be=AbortSignal.any([s,...W.signal?[W.signal]:[]]),ye=Promise.resolve().then(()=>K(j,be,$)).catch(we=>{let et=s.aborted||be.aborted,qe=oe(we)&&we.reason==="configuration_busy_timeout";qe&&(b=!1);let Dt=!et&&!qe&&(b||zC(we));throw Dt&&zC(we)&&(b=!0,m=Math.min(m+1,4)),!et&&!qe&&!b&&J&&m<5&&!c&&t.isCurrent()===!0&&(m++,b=!0,Dt=!0),x(Dt?vr(null,!0):vr(et?"configuration_fenced":qe?"configuration_busy_timeout":"configuration_unavailable")),we});return p=ye,x(vr(null,!0)),ye.finally(()=>{p===ye&&(p=null),g===ye&&(g=null),E()}).catch(()=>{}),ye.then(we=>(S(be,d),we))}let $e=()=>{if(!l){c=!0,t.signal.removeEventListener("abort",mt),o.abort();for(let W of _.splice(0))W();x(vr("configuration_fenced"));let j=p;l=Promise.resolve().then(async()=>{await j})}return l},mt=()=>{$e().catch(()=>{})};return t.signal.addEventListener("abort",mt,{once:!0}),Object.freeze({getSnapshot:O,subscribe(j){return r.add(j),()=>{r.delete(j)}},assess:j=>ee(!1,j),configure:j=>ee(!0,j),plan:X,async apply(j,W={}){let $=k.get(j);if(!$)throw new TypeError("setup.apply needs a plan returned by setup.plan");if(j.refusal)throw A(j.refusal.code==="setup_conflict"?"conflict":j.refusal.code==="installed_newer"?"upgrade_required":"forbidden",j.refusal.message,j.refusal.code);if(j.status==="current"){await ee(!1,W,{decisions:$.decisions,expected:j.digest});return}await ee(!0,W,{decisions:$.decisions,expected:j.digest,records:$.records})},close:$e})}var DC,xw,ze,Iw,Cw,lT,cT,zC,vr,FC=I(()=>{"use strict";ie();Go();Pw();no();yu();ah();DC=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,xw=/^sha256:[0-9a-f]{64}$/,ze=n=>A("unavailable","application configuration unavailable",`configuration_${n}`),Iw=(n,e)=>new se(A("conflict","This collection changed since the setup was reviewed. Review it again.","setup_changed").toProblem(),{...n?{mutationId:n}:{},...e===void 0?{}:{cause:e}}),Cw=async(n,e)=>{try{return await n}catch(t){throw e?.adopt&&Object.keys(e.adopt).length&&oe(t,"unavailable")&&t.reason==="resource_setup_unavailable"?Iw(void 0,t):t}};lT=15e3,cT=(n,e)=>new Promise((t,i)=>{if(e.aborted){i(e.reason);return}let o=()=>{clearTimeout(s),i(e.reason)},s=setTimeout(()=>{e.removeEventListener("abort",o),t()},n);e.addEventListener("abort",o,{once:!0})});zC=n=>oe(n)&&n.reason==="configuration_busy",vr=(n=null,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n?Object.freeze({code:n}):null})});function VC(n){return{issuer:n.issuer,subject:n.subject,name:n.name,...n.accountId===void 0?{}:{account_id:n.accountId}}}function KC(n){let e=n.scope,t=e.account,i=e.installation,o=e.collection,s=n.generation,r=n.signal,a=n.people,p=n.isCurrent.bind(n),l=typeof a?.current=="function"?a.current.bind(a):void 0,c=typeof a?.members=="function"?a.members.bind(a):void 0,d=new Set,u=es(null),f=!1,h=!1,m=null;function b(){try{return f||r.aborted||p()!==!0?!1:!f&&!r.aborted&&n.scope===e&&n.generation===s&&n.signal===r&&n.people===a&&!!s&&s.length<=256&&[t,i,o].every(k=>typeof k=="string"&&!!k&&k.length<=128)&&e.account===t&&e.installation===i&&e.collection===o}catch{return!1}}function w(k){u=b()?k:_r;for(let S of[...d])try{S()}catch{}b()||(u=_r)}function g(){return b()||(u=_r),u}function y(){if(!f){f=!0,r.removeEventListener("abort",y),u=_r;for(let k of[...d])try{k()}catch{}d.clear()}}r.addEventListener("abort",y,{once:!0}),r.aborted&&y();function v(k,S){return!b()||S?.aborted?Promise.reject(hp()):new Promise((x,P)=>{let C=!1,E=(z,Q)=>{C||(C=!0,S?.removeEventListener("abort",O),r.removeEventListener("abort",O),d.delete(L),Q!==void 0?P(Q):x(z))},O=()=>E(void 0,hp()),L=()=>{b()||O()};d.add(L),S?.addEventListener("abort",O,{once:!0}),r.addEventListener("abort",O,{once:!0}),k.then(()=>{!b()||S?.aborted?O():E(g())},()=>E(void 0,hp())),(!b()||S?.aborted)&&O()})}function _(k={}){let S=k.signal;if(!b()||S?.aborted)return Promise.reject(hp());if(m)return Promise.reject(A("unavailable","People readiness READ is occupied","people_readiness_busy"));let x=Promise.resolve().then(async()=>{if(!b())return _r;if(!l||!c)return es("people_unsupported");try{let C=await l({signal:r});if(!b()||(Fa("identity",{...VC(C),...C.personSettingsUrl===void 0?{}:{person_settings_url:C.personSettingsUrl}}),!b()))return _r;let E=await c({signal:r});return b()?!Array.isArray(E)||E.length>1e3?es("people_response"):(Fa("members",{members:Array.from(E,O=>({...VC(O),role:O.role}))}),b()?pT:_r):_r}catch{return es(b()?"people_unavailable":"people_fenced")}});m=x,w(es(null,!0));let P=x.then(C=>(w(C),g()),()=>(w(es("people_unavailable")),g())).finally(()=>{m===x&&(m=null)});return v(P,S)}return Object.freeze({getSnapshot:g,subscribe(k){return f?()=>{}:(d.add(k),()=>{d.delete(k)})},start(k={}){return h?v(m??Promise.resolve(g()),k.signal):!b()||k.signal?.aborted?Promise.reject(hp()):(h=!0,_(k))},refresh:_,close:y})}var es,_r,pT,hp,WC=I(()=>{"use strict";rp();ie();es=(n,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n===null?null:Object.freeze({code:n})}),_r=es("people_fenced"),pT=Object.freeze({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null}),hp=()=>A("cancelled","People readiness ended","people_readiness_fenced")});function Eh(n){if(!n||!Array.isArray(n.criteria))return Object.freeze([]);let e=n.criteria.filter(t=>t?.event?.id===kf.id&&t.event.version===kf.version&&t.event.digest===kf.digest).map(t=>t.id);return Object.freeze([...new Set(e)])}var Ow=I(()=>{"use strict";jc()});function HC(n){let e=n.scope,t=e.account,i=e.installation,o=e.collection,s=n.generation,r=n.signal,a=n.isCurrent.bind(n),p=n.notifications,l=p?.declaration,c=p?.timerNamespace,d=n.timers,u=typeof d?.list=="function"?d.list.bind(d):void 0,f=new Set,h=Ai(null),m=!1,b=!1,w=null;function g(){try{return m||r.aborted||a()!==!0?!1:!m&&!r.aborted&&n.signal===r&&n.scope===e&&n.generation===s&&!!s&&s.length<=256&&[t,i,o].every(x=>typeof x=="string"&&!!x&&x.length<=128)&&e.account===t&&e.installation===i&&e.collection===o&&n.notifications===p&&p?.declaration===l&&p?.timerNamespace===c&&n.timers===d}catch{return!1}}function y(x){h=g()?x:qh;for(let P of[...f])try{P()}catch{}g()||(h=qh)}function v(){return g()||(h=qh),h}function _(){if(!m){m=!0,r.removeEventListener("abort",_),h=qh;for(let x of[...f])try{x()}catch{}f.clear()}}r.addEventListener("abort",_,{once:!0}),r.aborted&&_();function k(x,P){return!g()||P?.aborted?Promise.reject(mp()):new Promise((C,E)=>{let O=!1,L=(V,te)=>{O||(O=!0,P?.removeEventListener("abort",z),r.removeEventListener("abort",z),f.delete(Q),te!==void 0?E(te):C(V))},z=()=>L(void 0,mp()),Q=()=>{g()||z()};f.add(Q),P?.addEventListener("abort",z,{once:!0}),r.addEventListener("abort",z,{once:!0}),x.then(()=>{!g()||P?.aborted?z():L(v())},()=>L(void 0,mp())),(!g()||P?.aborted)&&z()})}function S(x={}){let P=x.signal;if(!g()||P?.aborted)return Promise.reject(mp());if(w)return Promise.reject(A("unavailable","Notification readiness READ is occupied","notification_readiness_busy"));let C=Promise.resolve().then(async()=>{if(!g())return Ai("notifications_fenced");if(l===null&&p&&Object.hasOwn(p,"declaration"))return Object.freeze({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null});if(!u&&Eh(l).length)return Ai("notifications_consent_required");if(!l||typeof l!="object"||!u||typeof c!="string"||!/^[A-Za-z0-9._-]{1,64}$/.test(c))return Ai("notifications_unsupported");try{let O=await u(c,{signal:r});return g()?!O||O.namespace!==c||!Array.isArray(O.timers)||O.timers.length>1e4?Ai("notifications_response"):Ai("notifications_unsupported"):Ai("notifications_fenced")}catch{return Ai(g()?"notifications_unavailable":"notifications_fenced")}});w=C,y(Ai(null,!0));let E=C.then(O=>(y(O),v()),()=>(y(Ai("notifications_unavailable")),v())).finally(()=>{w===C&&(w=null)});return k(E,P)}return Object.freeze({getSnapshot:v,subscribe(x){return m?()=>{}:(f.add(x),()=>{f.delete(x)})},start(x={}){return b?k(w??Promise.resolve(v()),x.signal):!g()||x.signal?.aborted?Promise.reject(mp()):(b=!0,S(x))},refresh:S,close:_})}var dT,Ai,qh,mp,GC=I(()=>{"use strict";ie();Ow();dT=n=>Object.freeze({code:n}),Ai=(n,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n===null?null:dT(n)}),qh=Ai("notifications_fenced"),mp=()=>A("cancelled","Notification readiness ended","notification_readiness_fenced")});function XC(n){let e=new Set,t=!1,i=()=>{if(t||!n.isCurrent())return YC;let s=n.declaration;if(!s)return Rw;let r;try{r=n.grant()}catch{return uT}return r?s.required.some(a=>!r.actions.includes(a))?JC("files_access_missing"):n.scope==="collection"&&r.scope.kind!=="collection"?JC("files_scope_missing"):Rw:Rw},o=i();return Object.freeze({getSnapshot:()=>t||!n.isCurrent()?YC:o,subscribe(s){return t?()=>{}:(e.add(s),()=>{e.delete(s)})},async refresh(){let s=i();if(s!==o){o=s;for(let r of[...e])try{r()}catch{}}return o},close(){t=!0,e.clear()}})}var Th,Rw,YC,uT,JC,ZC=I(()=>{"use strict";Th=n=>Object.freeze(n),Rw=Th({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null}),YC=Th({checking:!1,assessment:null,problem:Object.freeze({code:"files_fenced"})}),uT=Th({checking:!1,assessment:null,problem:Object.freeze({code:"files_unavailable"})}),JC=n=>Th({checking:!1,assessment:Object.freeze({status:"incompatible",problem:Object.freeze({code:n})}),problem:null})});var Mh,QC=I(()=>{"use strict";MC();UC();FC();WC();GC();Ow();ql();th();ZC();Mh=class{constructor(e,t,i,o="block",s=()=>[]){this.typeIssues=o;this.consented=s;this.compiled=e,this.signal=i,this.ui=new Oh(t,i,Eh(this.compiled.manifest.notifications)),i.addEventListener("abort",this.abort,{once:!0})}typeIssues;consented;ui;signal;compiled;listeners=new Set;selected=null;epoch=0;opening=null;retiring=null;closing=null;changed=()=>{for(let e of[...this.listeners])try{e()}catch{}};abort=()=>{this.close().catch(()=>{})};subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}connection(e){return this.ui.connection(e)}getReadiness(){return this.selected?.readiness.getSnapshot()??null}selectedId(){return this.selected?.connection.id??null}adopt(e,t,i){let o=this.epoch,s=()=>!this.signal.aborted&&!this.closing&&!this.retiring&&this.epoch===o&&i(),r=!!this.opening||!!this.selected||!!this.retiring||!!this.closing,a=this.ui.adopt(e,{caller:t,isCurrent:s});if(r)return a;let p=null,l=[],c=a.then(d=>{if(!s()||t.aborted)throw new Ut("application_connection_fenced");let u=this.ui.owned();if(!u)throw new Ut("application_connection_binding");let f=Qf(this.compiled);f&&I_(d.files,yx(f,()=>this.consented(d.id)));let h=new AbortController,m=AbortSignal.any([this.signal,h.signal]);p=h;let b=()=>s()&&d.isCurrent(),w={scope:d.scope,generation:d.generation,signal:m,isCurrent:b},g=BC({client:d.records,compiledManifest:this.compiled,journal:u.journal,...w,setupMode:u.setupMode},u.resourceSetup);l.push(()=>g.close());let y={getSnapshot:g.getSnapshot,subscribe:g.subscribe,refresh:g.assess,close:g.close},v=KC({people:d.people,...w});l.push(()=>v.close());let _=this.compiled.manifest.notifications,k=HC({notifications:{declaration:_?.criteria?.length?_:null},timers:d.timers,...w});l.push(()=>k.close());let S=this.compiled.manifest.requirements.files?.scope?.kind,x=XC({declaration:f,scope:typeof S=="string"?S:null,grant:()=>d.files.grant,isCurrent:b});l.push(()=>x.close());let P=this.compiled.nativeCapabilities?{...this.compiled.nativeCapabilities,contracts:this.compiled.manifest.requirements.contracts,typeIssues:this.typeIssues}:null,C=new Rh({connection:d,nativeRequirements:P,signal:m,isCurrent:b,configuration:y,files:x,people:v,notifications:k}),E=C.subscribe(this.changed);return this.selected={connection:d,lifetime:h,readiness:C,configuration:g,unsubscribe:E},p=null,l.length=0,this.changed(),d}).catch(async d=>{p?.abort();let f=(await Promise.allSettled([this.ui.retire(),...l.map(h=>Promise.resolve().then(h))])).find(h=>h.status==="rejected");throw f?.status==="rejected"?f.reason:d}).finally(()=>{this.opening===c&&(this.opening=null)});return this.opening=c,c}assess(e={}){return!this.selected||!this.selected.connection.isCurrent()||this.retiring||this.closing?Promise.reject(new Ut("application_connection_fenced")):this.selected.readiness.refresh(e)}async configure(e={}){let t=this.selected,i=this.epoch;if(!t||!t.connection.isCurrent()||this.retiring||this.closing)throw new Ut("application_connection_fenced");if(await t.configuration.configure(e),e.signal?.aborted||this.epoch!==i||this.selected!==t||!t.connection.isCurrent())throw new Ut("application_connection_fenced");return t.readiness.refresh(e)}planSetup(e={}){let t=this.selected;return!t||!t.connection.isCurrent()||this.retiring||this.closing?Promise.reject(new Ut("application_connection_fenced")):t.configuration.plan(e)}async applySetup(e,t={}){let i=this.selected,o=this.epoch;if(!i||!i.connection.isCurrent()||this.retiring||this.closing)throw new Ut("application_connection_fenced");if(await i.configuration.apply(e,t),t.signal?.aborted||this.epoch!==o||this.selected!==i||!i.connection.isCurrent())throw new Ut("application_connection_fenced");return i.readiness.refresh(t)}retire(){if(this.retiring)return this.retiring;++this.epoch;let e=this.selected,t=this.opening;e?.lifetime.abort(),e?.unsubscribe();let i=this.ui.retire(),o=Promise.resolve().then(async()=>{let r=(await Promise.allSettled([i,t?.catch(()=>{}),e?.readiness.close()])).find(a=>a.status==="rejected");if(r?.status==="rejected")throw r.reason;this.selected===e&&(this.selected=null)});return this.retiring=o,this.changed(),o.then(()=>{this.retiring===o&&(this.retiring=null),this.changed()},()=>{}),o}close(){return this.closing?this.closing:(this.signal.removeEventListener("abort",this.abort),this.closing=Promise.resolve().then(async()=>{await this.retire(),await this.ui.close(),this.listeners.clear()}),this.closing)}}});function eI(n){return typeof n=="string"&&fT.includes(n)}var fT,tI=I(()=>{"use strict";fT=["joining","opening_store","connecting_log","syncing","loading_snapshot","replaying","waiting_for_key","verifying_read","checking_setup"]});function Ew(n,e){return!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!==e.split(",").sort().join()?nl():n}function qw(n){(typeof n!="string"||!hT.test(n)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/.test(n))&&nl()}function nI(n){let e=Ew(n,"rpc,action,value");if((!Number.isSafeInteger(e.rpc)||e.rpc<1||e.rpc>4294967295)&&nl(),e.action==="cancel")e.value!==null&&nl();else if(e.action==="prepare"){let t=Ew(e.value,`requestId,accountId,appId,challenge${Object.hasOwn(e.value,"authorizationId")?",authorizationId":""}`);for(let i of["requestId","accountId","appId"])qw(t[i]);t.authorizationId!==void 0&&qw(t.authorizationId),(typeof t.challenge!="string"||!/^[0-9a-f]{64}$/.test(t.challenge))&&nl()}else if(e.action==="finish"){let t=Ew(e.value,"requestId,authorizationRequestId,collectionId");for(let i of Object.keys(t))qw(t[i])}else nl();return Object.freeze({...e,value:e.value===null?null:Object.freeze({...e.value})})}var hT,nl,iI=I(()=>{"use strict";Yf();hT=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,nl=()=>{throw new Se("application_worker_binding")}});function Tw(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Se("application_worker_binding");let e=n;if(!["not_started","starting","signed_out","authorizing","unselected","opening","setup_required","ready","blocked","closed"].includes(e.status)||!(e.openingProgress==null||typeof e.openingProgress=="string")||!Array.isArray(e.collections)||e.collections.length>1024||!(e.selectedCollectionId===null||typeof e.selectedCollectionId=="string")||!(e.problem===null||typeof e.problem=="string"&&/^[a-z0-9_-]{1,128}$/.test(e.problem)))throw new Se("application_worker_binding");return Object.freeze({...e,openingProgress:eI(e.openingProgress)?e.openingProgress:null})}var Mw,Lh,rI=I(()=>{"use strict";tI();iI();Yf();Mw=class extends Error{constructor(t){super("SDK application operation unavailable");this.code=t;this.name="ApplicationWorkerReplyError"}code};Lh=class{port;binding;owner;nextId=0;active=null;portal=null;fault=null;stopping=null;stopReply=null;watch=null;abandoned=!1;constructor(e,t,i){if(!cx(t))throw new Se("application_worker_binding");this.port=e,this.binding=t,this.owner=Object.freeze({...i}),e.addEventListener("message",this.message),e.addEventListener("messageerror",this.messageError),e.start()}id(){if(this.nextId===Gf)throw new Se("application_worker_stop_failed");return++this.nextId}send(e,t,i){let o=Fb([Qn,this.binding,e,t,i],this.binding);try{this.port.postMessage(o)}catch{throw this.quarantine("application_worker_unavailable"),this.fault}}request(e,t,i,o){if(this.fault||this.stopping||i.aborted)return Promise.reject(this.fault??new Se("application_worker_fenced"));if(this.active)return Promise.reject(new Se("application_worker_busy"));let s;try{s=this.id(),Fb([Qn,this.binding,s,e,t],this.binding)}catch(p){return Promise.reject(p)}if(o){if(!["authorize","renewExpiredPairing","requestFileAccess"].includes(e))return Promise.reject(new Se("application_worker_binding"));this.portal?.life.abort();try{this.portal?.value.close()}catch{return this.quarantine("application_worker_stop_failed"),Promise.reject(this.fault)}this.portal={id:s,value:o,caller:i,life:new AbortController,lastRpc:0,busy:!1},this.watchPortal()}let r,a=new Promise(p=>{r=p});return new Promise((p,l)=>{let c={id:s,caller:i,done:a,finish:r,resolve:p,reject:l,fenced:!1,reply:!1,handoff:null,cancel:()=>{c.fenced=!0,l(new Se("application_worker_fenced"))}};this.active=c,i.addEventListener("abort",c.cancel,{once:!0});try{this.send(s,e,t)}catch(d){l(d)}i.aborted&&c.cancel()})}drain(){return this.fault?Promise.reject(this.fault):this.active?.done??Promise.resolve()}setForeground(e){!this.stopping&&!this.fault&&this.send(0,"foreground",e)}watchPortal(){this.watch!==null&&clearInterval(this.watch),this.watch=null;let e=this.portal;!e||!("closed"in e.value)||(this.watch=setInterval(()=>{if(this.portal!==e||this.stopping||this.fault){clearInterval(this.watch),this.watch=null;return}let t=!1;try{t=e.value.closed===!0}catch{}if(t){clearInterval(this.watch),this.watch=null,e.lastRpc===0&&(this.portal=null);try{this.send(0,"approvalClosed",!0)}catch{}}},500))}messageError=()=>this.quarantine("application_worker_unavailable");quarantine(e){if(!this.fault){this.fault=new Se(e),this.active&&(this.active.fenced=!0,this.active.reject(this.fault)),this.stopReply?.reject(this.fault);try{this.owner.failed?.(this.fault)}catch{}}}message=e=>{try{let t=e.data;if(!Array.isArray(t)||t.length!==5||t[0]!==Qn||t[1]!==this.binding||!Number.isInteger(t[3])||t[3]<0||t[3]>Gf)throw new Se("application_worker_binding");if(this.fault)return;let[,,i,o,s]=t;if(i==="nativeSnapshot"){if(o!==0)throw new Se("application_worker_binding");let l=Tw(s);this.stopping||this.owner.snapshot(l);return}if(i==="fatal"){if(o!==0)throw new Se("application_worker_binding");this.quarantine("application_worker_stop_failed");return}if(i==="nativeAuthorization"){let l=nI(s),c=this.portal;if(!c||c.id!==o||this.stopping||c.caller.aborted||l.rpc<=c.lastRpc)throw new Se("application_worker_fenced");if(c.lastRpc=l.rpc,l.action==="cancel")c.life.abort();else if(c.busy)throw new Se("application_worker_binding");l.action!=="cancel"&&(c.busy=!0);let d=AbortSignal.any([c.caller,c.life.signal]);Promise.resolve().then(()=>{if(!this.owner.nativeAuthorization)throw new Se("application_worker_unavailable");return this.owner.nativeAuthorization(l,c.value,d)}).then(u=>{if(d.aborted||this.portal!==c||this.stopping)throw new Se("application_worker_fenced");this.port.postMessage([Qn,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!0,value:u}])},()=>{this.port.postMessage([Qn,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!1}])}).catch(()=>{try{this.port.postMessage([Qn,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!1}])}catch{}}).finally(()=>{c.busy=!1});return}if(i==="portal"){if(!s||!["navigate","close"].includes(s.action))throw new Se("application_worker_binding");let l=this.portal;if(!l||l.id!==o)return;if(s.action==="close")l.life.abort(),l.value.close(),this.portal=null;else{if(this.stopping||typeof s.uri!="string"||s.uri.length>8192)throw new Se("application_worker_binding");l.value.navigate(s.uri)}return}if(i==="handoff"&&o===0){if(!s||s.schema!=="mdbn-app-collection/1")throw new Se("application_worker_binding");let l=[s.dataPort,s.controlPort,...s.timerPort?[s.timerPort]:[]];if(l.some(c=>!(c instanceof MessagePort)))throw new Se("application_worker_binding");if(this.stopping||!this.owner.attached){for(let c of l)c.close();return}this.owner.attached(s);return}if(i==="handoff"){let l=this.active;if(!l||l.id!==o||l.reply||l.handoff)throw new Se("application_worker_binding");if(this.stopping){if(!s||s.schema!=="mdbn-app-collection/1")throw new Se("application_worker_binding");for(let c of[s.dataPort,s.controlPort,...s.timerPort?[s.timerPort]:[]]){if(!(c instanceof MessagePort))throw new Se("application_worker_binding");c.close()}l.handoff=Promise.resolve();return}l.handoff=Promise.resolve().then(()=>this.owner.handoff(s,l.caller)),l.handoff.catch(()=>{});return}if(i!=="reply"||!s||typeof s.ok!="boolean"||!s.ok&&(!s.problem||typeof s.problem.code!="string"||s.problem.code.length>128))throw new Se("application_worker_binding");let r=this.stopReply;if(r&&r.id===o){if(s.ok){let l=Tw(s.snapshot);if(l.status!=="closed"||l.selectedCollectionId!==null)throw new Se("application_worker_stop_failed");r.resolve()}else r.reject(new Se("application_worker_stop_failed"));return}let a=this.active;if(!a||a.id!==o||a.reply)throw new Se("application_worker_binding");a.reply=!0;let p=s.ok?Tw(s.snapshot):null;this.settle(a,p,s.ok?null:Object.freeze({code:s.problem.code}))}catch{this.quarantine("application_worker_binding")}};async settle(e,t,i){try{if(await e.handoff,e.fenced||e.caller.aborted||this.stopping||this.fault)throw this.fault??new Se("application_worker_fenced");if(i)throw new Mw(i.code);t&&e.resolve(t)}catch(o){e.reject(o)}finally{e.caller.removeEventListener("abort",e.cancel),this.active===e&&(this.active=null),e.finish()}}abandon(){if(this.abandoned)return;this.abandoned=!0,this.fault||(this.fault=new Se("application_worker_fenced")),this.watch!==null&&(clearInterval(this.watch),this.watch=null);let e=this.active;e&&(e.fenced=!0,e.reject(this.fault),e.finish(),this.active=null),this.stopReply?.reject(this.fault),this.stopReply=null,this.portal?.life.abort();try{this.portal?.value.close()}catch{}this.portal=null;try{this.owner.releaseWorker()}catch{}this.port.removeEventListener("message",this.message),this.port.removeEventListener("messageerror",this.messageError),this.port.close()}close(){if(this.stopping)return this.stopping;let e=this.active;return e&&(e.fenced=!0,e.reject(new Se("application_worker_fenced"))),this.stopping=Promise.resolve().then(async()=>{if(this.fault)throw new Se("application_worker_stop_failed");this.portal?.life.abort(),this.portal?.value.close(),this.portal=null;let t=this.id();if(await new Promise((i,o)=>{this.stopReply={id:t,resolve:i,reject:o};try{this.send(t,"close",null)}catch(s){o(s)}}),await e?.done,this.fault)throw new Se("application_worker_stop_failed");this.owner.releaseWorker(),this.port.removeEventListener("message",this.message),this.port.removeEventListener("messageerror",this.messageError),this.port.close()}).catch(t=>{throw this.quarantine("application_worker_stop_failed"),t}),this.stopping}}});var oI={};ls(oI,{ApplicationRuntime:()=>jw,ApplicationRuntimeError:()=>ni});var ni,Lw,jw,sI=I(()=>{"use strict";dC();QC();bt();th();rI();Vb();ni=class extends Error{constructor(t){super("SDK application runtime unavailable");this.code=t;this.name="ApplicationRuntimeError"}code},Lw=()=>{let n=Object.freeze({checking:!1,assessment:null,problem:null});return Object.freeze({checking:!1,assessment:null,problem:null,facets:Object.freeze({capabilities:n,contracts:n,configuration:n,files:n,people:n,notifications:n})})},jw=class{lifetime=new AbortController;scope;worker;cpOrigin;lab;listeners=new Set;unsubscribe;raw=Object.freeze({status:"not_started",collections:Object.freeze([]),selectedCollectionId:null,signIn:null,problem:null,timing:null});snapshot=Object.freeze({...this.raw,readiness:Lw()});pending=null;closing=null;epoch=0;loggedProblem=null;assessing=!1;retiring=!1;closed=!1;stopped=!1;stopFailed=!1;constructor(e){this.cpOrigin=e.cpOrigin,this.lab=Qt(e.declaration.environment),this.scope=new Mh(e.compiledManifest,{name:e.declaration.name,version:"1"},this.lifetime.signal,e.typeIssues,t=>eh(this.raw,t)),this.worker=new Lh(e.port,e.binding,{snapshot:t=>{this.closed||(this.raw=t,this.followSession(),this.publish())},handoff:(t,i)=>{let o=this.epoch;return this.scope.adopt(t,i,()=>!this.closed&&this.epoch===o).then(()=>{this.portsFailed=null},s=>{throw this.portsFailed=t.scope.collection,s})},attached:t=>this.attached(t),releaseWorker:e.releaseWorker,...e.nativeAuthorization?{nativeAuthorization:e.nativeAuthorization}:{},failed:t=>{this.closed||(this.raw=Object.freeze({...this.raw,status:"blocked",problem:t.code}),this.publish())}}),this.unsubscribe=this.scope.subscribe(()=>this.publish())}portsFailed=null;attached(e){let t=()=>{for(let o of[e.dataPort,e.controlPort,...e.timerPort?[e.timerPort]:[]])try{o.close()}catch{}};if(this.closed){t();return}let i=this.lifetime.signal;this.queue(()=>this.action(async()=>{if(this.raw.selectedCollectionId!==e.scope.collection)return t(),this.snapshot;this.scope.selectedId()!==null&&(++this.epoch,await this.retireOwn());let o=this.epoch;return await this.scope.adopt(e,i,()=>!this.closed&&this.epoch===o).catch(s=>{throw this.portsFailed=e.scope.collection,s}),this.portsFailed=null,this.complete(this.raw,i)},i)).catch(()=>{this.closed||this.publish()})}followSession(){if(this.pending)return;let e=this.raw.status==="ready"||this.raw.status==="setup_required",t=this.raw.selectedCollectionId,i=this.scope.selectedId();if(i!==null&&(i!==t||!e&&this.raw.status!=="opening"&&this.raw.status!=="authorizing")){let o=this.lifetime.signal;this.queue(()=>this.action(async()=>(this.scope.selectedId()===i&&(++this.epoch,await this.retireOwn()),this.publish(),this.snapshot),o)).catch(()=>{})}}connection(e){return this.closed?null:this.scope.connection(e)}getSnapshot(){return this.snapshot}getNativeSnapshot(){return this.raw}async queue(e){for(;this.pending&&!this.closed;)await this.pending.catch(()=>{});return e()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}publish(){if(this.closed)this.snapshot=Object.freeze({...this.raw,status:this.stopped?"closed":"blocked",problem:this.stopped?null:this.stopFailed?"application_stop_failed":"application_closing",selectedCollectionId:null,readiness:Lw()});else{let e=this.scope.getReadiness()??Lw(),t=this.raw.status,i=this.raw.problem,o,s=this.raw.selectedCollectionId,r=this.retiring&&e.problem?.code==="readiness_fenced",a=s!==null&&(this.scope.getReadiness()===null||r)&&this.portsFailed!==s;if((t==="ready"||t==="setup_required")&&a)t="opening";else if(t==="ready"||t==="setup_required"){let l=this.assessing&&!e.assessment&&e.problem?.code!=="readiness_fenced";if(t=e.checking||l?"opening":e.assessment?.status==="ready"?"ready":e.assessment?.status==="setup_required"?"setup_required":"blocked",t==="blocked"){let c=e.problem??e.assessment?.problem;i=c?.code??"application_readiness_unavailable",o=c?.detail}}let p=`${i}:${o??""}`;if(t==="blocked"&&i&&p!==this.loggedProblem){this.loggedProblem=p;try{o?console.error("mdbase application blocked:",i,o):console.error("mdbase application blocked:",i)}catch{}}else t!=="blocked"&&(this.loggedProblem=null);this.snapshot=Object.freeze({...this.raw,status:t,problem:i,openingProgress:t==="opening"?e.checking?"checking_setup":this.raw.openingProgress??null:null,collections:Object.freeze(this.raw.collections.map(l=>Object.freeze({...l}))),readiness:e})}for(let e of[...this.listeners])try{e()}catch{}}retireOwn(){return this.retiring=!0,this.scope.retire()}settled(){return this.assessing=!1,this.publish(),this.snapshot}signal(e){return e.signal?AbortSignal.any([this.lifetime.signal,e.signal]):this.lifetime.signal}action(e,t){if(this.closed||t.aborted)return Promise.reject(new ni("application_fenced"));if(this.pending)return Promise.reject(new ni("application_busy"));this.assessing=!0;let i=Promise.resolve().then(async()=>{if(this.closed||t.aborted)throw new ni("application_fenced");let o=await e();if(this.closed||t.aborted)throw new ni("application_fenced");return o}).finally(async()=>{(this.assessing||this.retiring)&&(this.assessing=!1,this.retiring=!1,this.publish()),await this.worker.drain(),this.pending===i&&(this.pending=null)});return this.pending=i,i}async complete(e,t){if(this.closed||t.aborted)throw new ni("application_fenced");let i=!!(e.selectedCollectionId&&this.scope.connection(e.selectedCollectionId));if(this.raw=e,this.assessing=i,this.publish(),i){try{await this.scope.assess({signal:t}).catch(()=>{})}finally{this.assessing=!1}this.publish()}if(this.closed||t.aborted)throw new ni("application_fenced");return this.snapshot}start(e={}){let t=this.signal(e);return this.action(async()=>this.complete(await this.worker.request("start",null,t),t),t)}authorizeReserved(e,t={},i=null){let o=this.signal(t);return this.action(async()=>this.complete(await this.worker.request("authorize",i,o,e),o),o).catch(s=>{throw e.close(),s})}authorize(e={}){let t=this.signal(e),i;try{i=Jf(Xf(this.cpOrigin,t,()=>!this.closed,this.lab))}catch(o){return Promise.reject(o)}return this.authorizeReserved(i,e)}select(e,t={}){let i=this.signal(t);return this.action(async()=>{if(this.raw.selectedCollectionId===e&&(this.raw.status==="ready"||this.raw.status==="setup_required")&&this.scope.connection(e)?.isCurrent())return this.snapshot.status==="blocked"?this.complete(this.raw,i):this.snapshot;++this.epoch;let o=this.retireOwn();if(this.publish(),await o,this.closed||i.aborted)throw new ni("application_fenced");return this.complete(await this.worker.request("select",e,i),i)},i)}assess(e={}){let t=this.signal(e);return this.action(async()=>(await this.scope.assess({signal:t}),this.settled()),t).then(i=>i.readiness)}configure(e={}){let t=this.signal(e);return this.action(async()=>(await this.scope.configure({signal:t}),this.settled()),t)}planSetup(e={}){let t=this.signal(e);return this.closed||t.aborted?Promise.reject(new ni("application_fenced")):this.scope.planSetup({...e,signal:t})}applySetup(e,t={}){let i=this.signal(t);return this.action(async()=>(await this.scope.applySetup(e,{signal:i}),this.settled()),i)}clearSelection(e={}){let t=this.signal(e);return this.action(async()=>(++this.epoch,await this.retireOwn(),this.complete(await this.worker.request("clearSelection",null,t),t)),t)}forget(e,t={}){let i=this.signal(t);return this.action(async()=>(this.raw.selectedCollectionId===e&&(++this.epoch,await this.retireOwn()),this.complete(await this.worker.request("forget",e,i),i)),i)}refreshCollections(e={}){let t=this.signal(e);return this.action(async()=>(this.raw=await this.worker.request("refreshCollections",null,t),this.publish(),this.snapshot),t)}signOut(e={}){let t=this.signal(e),i=this.raw.selectedCollectionId,o=e.discard!==!0&&i?cC(this.scope.connection(i)):0;return o>0?Promise.reject(pC(o)):this.action(async()=>(++this.epoch,await this.retireOwn(),this.complete(await this.worker.request("signOut",null,t),t)),t)}deleteCollection(e,t,i={}){let o=this.signal(i);return this.action(async()=>(await this.worker.request("deleteCollection",[e,t],o),this.raw.selectedCollectionId===e&&(++this.epoch,await this.retireOwn()),this.complete(await this.worker.request("forget",e,o),o)),o)}requestFileAccess(e,t,i,o,s={}){let r=this.signal(s);return this.action(async()=>(this.raw=await this.worker.request("requestFileAccess",[t,i,o],r,e),this.publish(),this.snapshot),r).catch(a=>{throw e.close(),a})}pollFileAccess(e){let t=this.lifetime.signal;return this.action(async()=>(this.raw=await this.worker.request("pollFileAccess",e,t),this.publish(),this.snapshot),t)}setForeground(e){this.closed||this.worker.setForeground(e)}abandon(){this.closed||(this.closed=!0,this.stopped=!0,++this.epoch,this.unsubscribe(),this.listeners.clear(),this.closing=Promise.resolve(),this.worker.abandon(),this.lifetime.abort())}close(){return this.closing?this.closing:(this.closed=!0,++this.epoch,this.lifetime.abort(),this.unsubscribe(),this.closing=Promise.resolve().then(async()=>{await Promise.all([this.scope.close(),this.worker.close()]),await this.pending?.catch(()=>{}),this.stopped=!0,this.publish(),this.listeners.clear()}).catch(()=>{throw this.stopFailed=!0,this.publish(),new ni("application_stop_failed")}),this.publish(),this.closing)}}});var aM={};ls(aM,{ACCOUNT_KEY_STATES:()=>cy,API_VERSIONS:()=>sd,AppHost:()=>Zw,COLLECTION_UNAVAILABLE_REASONS:()=>$y,CborError:()=>Ie,Client:()=>xd,DESCRIBE_TYPING_MAX_PATHS:()=>Pl,DESCRIBE_TYPING_MAX_TYPES:()=>Sl,DEVICE_KINDS:()=>ly,ERROR_CODES:()=>Pp,FilesApi:()=>_s,Float64:()=>yt,HOLD_COMPARE_SCHEME:()=>tc,HOLD_TITLE:()=>ec,IkInitiator:()=>Rs,IkResponder:()=>Xd,LiveQuery:()=>Ss,MAX_CONVENIENCE_BYTES:()=>ad,MAX_DEPTH:()=>tm,MDBASE_NOTIFICATION_CLICK:()=>eg,MDBASE_NOTIFICATION_TYPE:()=>Ql,MdbaseApplicationUnavailableError:()=>yp,MdbaseClient:()=>Ei,MdbaseConnect:()=>ol,MdbaseError:()=>se,MdbasePeopleClient:()=>jr,NoiseError:()=>rt,PERSON_CONTRACT:()=>Gy,PROBLEM_CODES:()=>sk,PresenceApi:()=>ks,READ_MANY_MAX_CONCURRENCY:()=>Xm,READ_MANY_MAX_REFS:()=>Jm,RecordReader:()=>Il,SESSION_LIFETIME_MS:()=>Ly,SLOW_OPENING_MS:()=>bu,SchemaError:()=>ne,Session:()=>go,TEMPORAL_HINTS:()=>Vp,TimersApi:()=>Ns,WasmRuntime:()=>$s,Write:()=>_o,applicationPhase:()=>ic,approvalReadiness:()=>pA,bytesEqual:()=>HI,clientPrologue:()=>Ti,collectionUnavailableError:()=>un,compareVersions:()=>lg,connect:()=>my,controlRouteResolver:()=>L0,createMdbase:()=>lI,createViewSource:()=>hd,decode:()=>ue,describeDiagnostic:()=>hu,describeError:()=>Lo,describeHold:()=>J0,diffEdits:()=>Jp,duplexCarrier:()=>By,effectiveCapabilities:()=>cI,encode:()=>pe,encodeSecret:()=>qn,fileGrant:()=>Ym,formatSas:()=>fA,framedPort:()=>id,fromHex:()=>cs,generateKeyPair:()=>Es,handleMdbaseNotificationClick:()=>G0,handleMdbasePush:()=>H0,holdCompareLink:()=>rg,holdNotice:()=>X0,inProcessConnector:()=>Ds,indexedDbKeyStorage:()=>Wy,isCollectionUnavailableReason:()=>Ls,isConfirmed:()=>M0,isErrorCode:()=>Sr,isMdbaseError:()=>oe,isReadyPhase:()=>hk,isValid:()=>KI,keyPairFromSecret:()=>w0,loadOrCreateClientKey:()=>E0,localLinkConnector:()=>C0,localLinkFirstPayload:()=>Vy,mdbaseError:()=>A,memoryKeyStorage:()=>Ky,memoryWriteLedgerStore:()=>vd,nextRelayConnector:()=>x0,noiseChannel:()=>jy,noiseConnector:()=>Mi,orderTargets:()=>js,parseCollectionAvailability:()=>zn,parseHoldCompareLink:()=>Y0,parseMdbaseNativeNotification:()=>tg,parseMdbasePush:()=>ou,parseVersion:()=>Ks,pipeCloseError:()=>To,portPair:()=>g_,problemCodeOf:()=>sg,queryPages:()=>cd,readMany:()=>ld,readMdbaseNotificationData:()=>ng,readViewSourceRecord:()=>fd,recoveryFor:()=>JI,relayConnector:()=>k0,relayPipeCarrier:()=>Ms,resolveRecordLinks:()=>O_,revisionOf:()=>si,routeFromControl:()=>Hy,sameIdentity:()=>nu,showMdbaseNotification:()=>ig,staticKeyOf:()=>Yd,streamCarrier:()=>_0,structMap:()=>WI,summarizeStatus:()=>eu,syncStatusText:()=>Z0,toHex:()=>ri,toPlain:()=>bs,toValue:()=>ut,updateViewSource:()=>md,uuidv7:()=>Ln,valueEquals:()=>Ir,versionRelation:()=>jo,webSocketCarrier:()=>qs,wire:()=>Nm});Je();ge();ie();At();At();Ps();Zm();iy();ql();ql();ry();Rl();Ol();Oi();ge();ie();qo();Ts();Yl();function k0(n){let e=U(n.collection),t=n.grant?U(n.grant):null;return Mi({description:`relay:${n.collection}`,staticKey:n.staticKey,target:async()=>{let i=await n.resolveRoute();if(!i)throw A("unavailable","no device of this collection is online","no_device_online");return{prologue:Ti(e,t,U(i.targetDevice)),remoteStatic:i.noisePublicKey,device:i.targetDevice,openCarrier:o=>i.pipe?Ms(i.url,{accessToken:i.pipe.accessToken,collection:i.pipe.collection,grant:n.grant??"",device:i.targetDevice,devicePublicKey:i.noisePublicKey},n.webSocket,o):qs(i.url,n.webSocket,o)}}})}Fy();Ts();qo();Je();ge();ie();At();qo();Ts();var G1=new Uint8Array(16);function Vy(n,e){if(n.length!==32)throw A("invalid_request","the link token is 32 bytes");let t=Qi.dec(e);if(t.kind!=="request"||t.method!=="hello")throw A("internal","expected the hello request");return pe(new Map([[0,n],[1,t.params]]))}function C0(n){let e=U(n.collection),t=n.staticKey??Es(),i=null;return Mi({description:"localhost-link",staticKey:t,firstPayload:o=>Vy(i.token,o),target:async()=>{i=typeof n.link=="function"?await n.link():n.link;let o=i;if(!Number.isInteger(o.port)||o.port<=0||o.port>65535)throw A("unavailable","invalid local link port","daemon_not_running");let s=Ti(e,null,n.localOnly?G1:U(o.device));return{prologue:s,preamble:s,remoteStatic:o.noisePublicKey,openCarrier:r=>qs(`ws://127.0.0.1:${o.port}/v1/plugin`,n.webSocket,r)}}})}Ty();ie();function Ky(){let n=new Map;return{get:async e=>n.get(e),put:async(e,t)=>{n.set(e,t)},putIfAbsent:async(e,t)=>{let i=n.get(e);return i||(n.set(e,t),t)},delete:async e=>{n.delete(e)}}}function Wy(n="mdbase-keys",e="keys"){let t=globalThis.indexedDB;if(!t)throw A("invalid_request","IndexedDB is not available here; pass another KeyStorage");let i=()=>new Promise((r,a)=>{let p=t.open(n,1);p.onupgradeneeded=()=>p.result.createObjectStore(e),p.onsuccess=()=>r(p.result),p.onerror=()=>a(p.error)}),o=async(r,a)=>{let p=await i();try{return await new Promise((l,c)=>{let d=p.transaction(e,r),u,f=!1;d.oncomplete=()=>f?l(u):c(A("unavailable","key storage transaction completed without a result","key_storage")),d.onabort=()=>c(d.error??A("unavailable","key storage transaction aborted","key_storage")),d.onerror=()=>c(d.error??A("unavailable","key storage transaction failed","key_storage"));try{a(d.objectStore(e),h=>{u=h,f=!0})}catch(h){d.abort(),c(h)}})}finally{p.close()}},s=(r,a)=>o(r,(p,l)=>{let c=a(p);c.onsuccess=()=>l(c.result)});return{get:r=>s("readonly",a=>a.get(r)),put:(r,a)=>s("readwrite",p=>p.put(a,r)).then(()=>{}),putIfAbsent:(r,a)=>o("readwrite",(p,l)=>{let c=p.get(r);c.onsuccess=()=>{if(c.result!==void 0){l(c.result);return}try{let d=p.add(a,r);d.onsuccess=()=>l(a)}catch{p.transaction.abort()}}}),delete:r=>s("readwrite",a=>a.delete(r)).then(()=>{})}}function R0(){return globalThis.crypto?.subtle}async function Y1(){let n=R0();if(!n)return null;try{let e=await n.generateKey({name:"X25519"},!1,["deriveBits"]),t=new Uint8Array(await n.exportKey("raw",e.publicKey));return{kind:"webcrypto",privateKey:e.privateKey,publicKey:t}}catch{return null}}function J1(n){return n.kind==="raw"?{publicKey:n.publicKey,nonExtractable:!1,dh:e=>sr.getSharedSecret(n.secretKey,e)}:{publicKey:n.publicKey,nonExtractable:!n.privateKey.extractable,dh:async e=>{let t=R0(),i=await t.importKey("raw",e,{name:"X25519"},!1,[]),o=await t.deriveBits({name:"X25519",public:i},n.privateKey,256);return new Uint8Array(o)}}}var X1=Ky(),I0=new WeakMap;function O0(n,e){if(e&&(n.kind!=="webcrypto"||n.privateKey.extractable!==!1||n.privateKey.type!=="private"||n.privateKey.algorithm.name!=="X25519"||!n.privateKey.usages.includes("deriveBits")))throw A("invalid_request","a non-extractable X25519 key is required; explicitly reauthorize incompatible stored identities","key_storage")}async function E0(n,e={}){let t=e.storage??(globalThis.indexedDB?Wy():X1),i=e.requireNonExtractable,o=I0.get(t);o||(o=new Map,I0.set(t,o));let s=o.get(n);s||(s=(async()=>{let r=await t.get(n);if(r)return r;let a=await Y1();if(!a){if(i)throw A("invalid_request","this platform cannot keep a non-extractable X25519 key","key_storage");let p=sr.utils.randomSecretKey();a={kind:"raw",secretKey:p,publicKey:sr.getPublicKey(p)}}return O0(a,i),t.putIfAbsent?t.putIfAbsent(n,a):(await t.put(n,a),a)})(),o.set(n,s));try{let r=await s;return O0(r,i),J1(r)}finally{o.get(n)===s&&o.delete(n)}}py();var q0={collection_not_yet_migrated:"Your collection needs an upgrade on your computer; your changes are safe",collection_migrating:"Your collection is being upgraded; changes will sync when it's done",update_required:"Update the app to keep syncing",account_suspended:"Syncing is paused: your account is suspended"},T0={offline:"You're offline",unreachable:"Can't reach the sync service",server_busy:"The sync service is busy; trying again shortly",rate_limited:"Syncing is paused for a moment",auth:"Sign in again to keep syncing"};function eu(n,e,t,i){let o=n.mode!=="local_only"&&t&&Object.hasOwn(T0,t.kind)?t.kind:null,s={pending:n.pending,holds:n.holds,conflicts:n.unresolved,confirmedThrough:n.mode==="local_only"?null:n.confirmedThrough,health:o,live:n.mode==="local_only"||typeof i!="boolean"?null:i},r=n.pending>0?`, ${n.pending} change${n.pending===1?"":"s"} waiting`:"";if(n.mode==="local_only")return{...s,kind:"local",text:n.pending?`Saving${r}`:"Saved on this device"};if(e&&Object.hasOwn(q0,e))return{...s,kind:e,text:`${q0[e]}${r}`};if(n.installing)return{...s,kind:"installing",text:`Loading the collection (${n.installing.done}/${n.installing.total})`};if(o){let p=n.pending?`. ${n.pending} change${n.pending===1?" is":"s are"} saved on this device and will sync later`:"";return{...s,kind:o==="offline"||o==="unreachable"?"offline":n.confirmedThrough<n.headKnown?"catching_up":"synced",text:`${T0[o]}${p}`}}if(n.connection!=="online")return{...s,kind:"offline",text:`Offline; synced through ${n.confirmedThrough}${r}`};if(n.confirmedThrough<n.headKnown)return{...s,kind:"catching_up",text:`Catching up (${n.confirmedThrough}/${n.headKnown})${r}`};let a=s.live===!1?". Live updates are paused; changes from other devices appear when you come back to this app":"";return{...s,kind:"synced",text:`Synced through ${n.confirmedThrough}${r}${a}`}}function M0(n){return n.state==="confirmed"}uy();Yl();Zd();Je();Lr();ie();function Hy(n,e){for(let t of n.targets??[]){if(!/^[0-9a-f]{64}$/i.test(t.noise_pk)||!t.url||!t.device)continue;let i={url:t.url,targetDevice:t.device,noisePublicKey:cs(t.noise_pk)};return t.relay_collection&&(i.pipe={collection:t.relay_collection,accessToken:e}),i}return null}function L0(n){let e;try{e=new URL(n.server)}catch{throw A("invalid_request","The control plane requires an HTTPS origin")}if(e.protocol!=="https:"&&!!1||e.username||e.password||e.pathname!=="/"||e.search||e.hash)throw A("invalid_request","The control plane requires an HTTPS origin without credentials, path, query or fragment");let t=`${e.origin}/v1/next/collections/${encodeURIComponent(n.collection)}/route`,i=n.fetch??globalThis.fetch.bind(globalThis);return async()=>{let o=await n.accessToken(),s;try{s=await i(t,{headers:{authorization:`Bearer ${o}`},redirect:"error"})}catch{throw A("unavailable","cannot reach the control plane","control_unreachable")}if(s.status===401)throw A("unauthenticated","the control plane refused the access token");if(s.status===409)throw A("unauthenticated","this app's key is not registered with its grant","client_key_required");if(!s.ok)throw A("unavailable",`control plane answered ${s.status}`,"control_error");let r=await s.json(),a=zn(r.availability);if(a?.state==="unavailable")throw un(a.reason);let p=Hy(r,o);if(!p&&r.reason==="no_device_registered")throw A("unavailable","this collection has no device set up to serve it","no_device_registered");return p}}Lr();iu();Zy();ie();var Ql="mdbase.notification",eg="mdbase.notification.click",B0=/^[\x21-\x7e]{1,256}$/,oR=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Nr=n=>A("invalid_request",n,"invalid_push_payload"),sR=()=>A("upgrade_required","The push uses an envelope version this SDK does not support.","unsupported_push_version");function V0(n){if(typeof n=="string")try{n=JSON.parse(n)}catch{throw Nr("The push payload is not JSON.")}else if(n&&typeof n=="object"&&typeof n.json=="function")try{n=n.json()}catch{throw Nr("The push payload is not JSON.")}if(!n||typeof n!="object"||Array.isArray(n))throw Nr("The push payload is not an object.");return n}function Us(n,e,t){return typeof n=="string"&&n.length>=e&&n.length<=t}function K0(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n;return!Us(e.title,1,80)||e.body!==void 0&&!Us(e.body,0,160)||e.tag!==void 0&&!Us(e.tag,1,80)?null:Object.freeze({title:e.title,...typeof e.body=="string"&&e.body.length?{body:e.body}:{},...typeof e.tag=="string"?{tag:e.tag}:{}})}function W0(n,e,t){if(n.type!==Ql)throw Nr("The payload is not an mdbase notification.");if(e!==1)throw typeof e=="number"&&Number.isSafeInteger(e)&&e>1?sR():Nr("The payload has no valid envelope version.");if(!Us(n.signal_id,1,256)||!B0.test(n.signal_id)||!Us(n.cursor,1,256)||!B0.test(n.cursor)||!Us(n.criterion_id,1,100)||!oR.test(n.criterion_id))throw Nr("The payload is not an mdbase notification.");return Object.freeze({version:1,signalId:n.signal_id,criterionId:n.criterion_id,cursor:n.cursor,presentation:t})}function ou(n){let e=V0(n),t=W0(e,e.version,K0(e.presentation));if(!t.presentation)throw Nr("The push has no valid presentation.");return t}function tg(n){if(!n||typeof n!="object"||Array.isArray(n))throw Nr("The native notification data is not an object.");let e=n,t=typeof e.version=="string"&&/^[1-9][0-9]{0,8}$/.test(e.version)?Number(e.version):e.version;return W0(e,t,null)}function ng(n){try{return tg(n)}catch{return null}}function aR(n){return{type:Ql,version:n.version,signal_id:n.signalId,criterion_id:n.criterionId,cursor:n.cursor}}async function ig(n,e,t={}){let i=ou(e),o=i.presentation;return await n.showNotification(o.title,{...o.body?{body:o.body}:{},...o.tag?{tag:o.tag}:{},...t.icon?{icon:t.icon}:{},...t.badge?{badge:t.badge}:{},data:aR(i)}),i}function Qy(n){return globalThis[n]}function lR(n){let e=globalThis.location;if(typeof e?.origin=="string"&&e.origin!=="null")return e.origin;try{return n?new URL(n).origin:null}catch{return null}}function F0(n,e,t){let i=()=>A("invalid_request",`The notification click ${t} must be on the app's own origin.`,"click_target_cross_origin");if(typeof n!="string")throw i();if(e===null){if(!n.startsWith("/")||n.startsWith("//")||n.startsWith("/\\"))throw i();return n}let o;try{o=new URL(n,`${e}/`)}catch{throw i()}if(o.origin!==e)throw i();return o.href}function H0(n,e={}){let t;try{t=V0(n.data?.text()??null)}catch{return!1}if(t.type!==Ql)return!1;let i=e.registration??Qy("registration");if(!i)throw A("invalid_request","No service worker registration to show the notification.","push_registration_missing");let o={...e.icon?{icon:e.icon}:{},...e.badge?{badge:e.badge}:{}};return n.waitUntil((async()=>{try{ou(t)}catch(s){let r=s instanceof se&&s.reason==="unsupported_push_version"?K0(t.presentation):null;if(!r)throw s;return await i.showNotification(r.title,{...r.body?{body:r.body}:{},...r.tag?{tag:r.tag}:{},...o}),null}return ig(i,t,o)})()),!0}function G0(n,e={}){let t=ng(n.notification.data);if(!t)return!1;n.notification.close();let i=e.clients??Qy("clients"),o=Qy("registration")?.scope,s=lR(o),r=e.scope===void 0?o:F0(e.scope,s,"scope"),a=e.url===void 0?r??"/":F0(e.url,s,"url");return i&&n.waitUntil((async()=>{let l=(await i.matchAll({type:"window",includeUncontrolled:!0})).find(d=>!r||d.url.startsWith(r));if(!l)return i.openWindow(a);await l.focus();let c={type:eg,notification:t};return l.postMessage(c),l})()),!0}su();Je();ie();ge();var $s=class n{constructor(e){this.instance=e}instance;ports=new Map;timer=null;opened=!1;get x(){if(!this.instance)throw A("unavailable","runtime instance was discarded after an ABI failure");return this.instance}discard(){this.instance=null,this.timer&&clearInterval(this.timer),this.timer=null;for(let e of[...this.ports.values()])e.end();this.ports.clear()}static async instantiate(e){return new n(await this.load(e))}static async load(e,t){let i=null,o=null,s=t?.(()=>{if(!o)throw A("unavailable","runtime imports called before initialization");return o})??{},r=new TextDecoder,a={host_app_sql:(c,d)=>0n,host_now_ms:()=>Date.now(),host_local_date:(c,d,u,f)=>{try{let h=r.decode(new Uint8Array(i.buffer,d,u)),m=new Intl.DateTimeFormat("en-CA",{timeZone:h,year:"numeric",month:"2-digit",day:"2-digit"}).format(c);return/^\d{4}-\d{2}-\d{2}$/.test(m)?(new Uint8Array(i.buffer,f,10).set(new TextEncoder().encode(m)),10):0}catch{return 0}},host_default_zone:(c,d)=>{let u=new TextEncoder().encode(Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"),f=Math.min(u.length,d);return new Uint8Array(i.buffer,c,f).set(u.subarray(0,f)),f},host_random:(c,d)=>{let u=new Uint8Array(i.buffer,c,d);for(let f=0;f<d;f+=65536)globalThis.crypto.getRandomValues(u.subarray(f,f+65536))}},{instance:p}=await WebAssembly.instantiate(e,{env:{...a,...s}}),l=p.exports;return o=l,i=l.memory,l}put(e){if(e.length===0)return[0,0];let t=this.x.alloc(e.length);return new Uint8Array(this.x.memory.buffer,t,e.length).set(e),[t,e.length]}takeOut(e){let t=Number(e>>32n),i=Number(e&0xffffffffn);if(i===0)return new Uint8Array(0);let o=new Uint8Array(this.x.memory.buffer,t,i).slice();return this.x.dealloc(t,i),o}info(){let e=ue(this.takeOut(this.x.rt_info())),t=i=>{let[o,s]=i;return{major:o,minor:s}};return{abiMajor:e.get(0),runtimeVersion:e.get(1),sem:t(e.get(2)),serves:e.get(3).map(t)}}open(e){let t=this.x;if(this.opened)throw A("unavailable","runtime is already open");let i=e.queryExecutionProfile,o;if(i!==void 0){if(i!=="memory_constrained"&&i!=="desktop")throw A("invalid_request","unknown query execution profile");if(typeof t.rt_open_profile!="function")throw A("unavailable","runtime does not support explicit query profile initialization");o=i==="memory_constrained"?0:1}let s=qn(new Map([[0,U(e.collection)],[1,U(e.replicaId)],[2,U(e.deviceId)],[3,e.mode==="local_only"?0:1],[4,e.signSecretKey],[5,e.kemSecretKey],[6,e.e2e??!1]])),r;try{let a=this.put(s);r=this.takeOut(o===void 0?t.rt_open(...a):t.rt_open_profile(...a,o))}catch(a){throw this.discard(),a}finally{s.fill(0)}if(r.length)throw A("unavailable",`runtime failed to open: ${new TextDecoder().decode(r)}`);this.markOpened()}markOpened(){this.opened=!0,this.timer??=setInterval(()=>this.tick(),1e3),this.timer.unref?.()}tick(){this.x.rt_tick(Date.now()),this.flush()}connect(e={}){let t=null,i=!1,o=[],s={onframe:null,onclose:null,send:r=>{if(i)throw A("unavailable","port closed");let a=pe(r);if(t===null){let p=e.grant&&e.clientKey?new Uint8Array([...U(e.grant),...e.clientKey]):new Uint8Array(0),l=ue(this.takeOut(this.x.rt_hello(...this.put(p),...this.put(a)))),c=BigInt(l[0]),d=ue(l[1]);queueMicrotask(()=>{s.onframe?.(d),c===0n&&s.end()}),c!==0n&&(t=c,this.ports.set(c,s),this.flush());return}this.x.rt_frame(t,...this.put(a)),this.flush()},close:()=>{i||(i=!0,t!==null&&(this.ports.delete(t),this.x.rt_close(t)),s.onclose?.())},deliver:r=>s.onframe?s.onframe(r):o.push(r),end:()=>{i||(i=!0,t!==null&&this.ports.delete(t),s.onclose?.())}};return s}sessionForPort(e){for(let[t,i]of this.ports)if(i===e)return t;return null}flush(){let e=this.takeOut(this.x.rt_poll());if(!e.length)return;let t=ue(e),i=new Set(t.filter(o=>o[1]===null).map(o=>BigInt(o[0])));for(let o of t){let[s,r]=o,a=this.ports.get(BigInt(s));if(a)if(r===null)a.end();else{let p=ue(r);if(i.has(BigInt(s))){if(p instanceof Map){let l=p;l.get(0)===2&&l.get(1)==="closed"&&a.deliver(p)}}else queueMicrotask(()=>a.deliver(p))}}}dispose(){this.timer&&clearInterval(this.timer);for(let e of[...this.ports.values()])e.close()}};var ec="mdbase protected your edit",cR={conflict:{cause:"This file was also changed on another device while you were editing it.",detail:"Your version is kept here and is not synced until you choose what to keep."},unknown_provenance:{cause:"This file changed on disk in a way mdbase could not trace to an app or a sync.",detail:"The bytes on disk are kept here and are not synced until you confirm them."},deleted_elsewhere:{cause:"This file was deleted on another device after you edited it.",detail:"Your version is kept here; nothing is deleted until you choose."},read_only:{cause:"Changed with view access.",detail:"Edit access will not sync these changes. Submit or discard them."},editor_busy:{cause:"An editor still has this file open with unsaved changes.",detail:"mdbase waits so that it never overwrites what you are typing."},suspect_write:{cause:"The last write to this file looked incomplete, for example after a crash.",detail:"The file is kept aside and is not synced until you confirm it."}},pR={keep_mine:{label:"Keep mine",description:"Sync the version on this device.",resolution:"keep_mine",needs:"records.edit",discardsMine:!1},take_theirs:{label:"Take theirs",description:"Replace this file with the synced version.",resolution:"take_theirs",needs:"records.edit",discardsMine:!0},keep_both:{label:"Keep both",description:"Save your version as a copy next to the synced one.",resolution:"keep_both",needs:"records.edit",discardsMine:!1},delete:{label:"Delete",description:"Accept the deletion and remove this file here too.",resolution:"delete",needs:"records.delete",discardsMine:!0},use:{label:"Use merged",description:"Sync the document you merged.",resolution:"use",needs:"records.edit",discardsMine:!1},compare:{label:"Compare side by side",description:"Open both versions to merge them.",discardsMine:!1}},dR={conflict:["keep_mine","take_theirs","compare","keep_both"],unknown_provenance:["keep_mine","take_theirs","compare","keep_both"],deleted_elsewhere:["keep_mine","delete"],read_only:["keep_mine","take_theirs","compare","keep_both"],editor_busy:["keep_mine","take_theirs","compare"],suspect_write:["keep_mine","take_theirs","compare","keep_both"]},tc="mdbase://hold/compare",au=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function rg(n,e){if(!au.test(n)||!au.test(e))throw new Error("holdCompareLink: collection and id are UUIDs");return`${tc}?collection=${n.toLowerCase()}&id=${e.toLowerCase()}`}function Y0(n){if(typeof n!="string"||n.length>512||!n.startsWith(`${tc}?`))return null;let e=new URLSearchParams(n.slice(tc.length+1)),t=e.get("collection")??"",i=e.get("id")??"";return!au.test(t)||!au.test(i)?null:{collectionId:t.toLowerCase(),id:i.toLowerCase()}}function J0(n,e){let t=n.reason==="read_only",i=n.theirs!==void 0,o=(e.canCompare??!0)&&i,s=p=>!p||!e.capabilities||e.capabilities.includes(p),r=dR[n.reason].filter(p=>p==="compare"?o:(!t||e.host===!0)&&(p!=="take_theirs"||i||t)).map(p=>{let l={action:p,...pR[p]};return t&&p==="take_theirs"&&(l.label="Discard local changes",l.description="Discard unsynced changes on this device.",l.needs="collection.read"),l}).filter(p=>s(p.needs)),a=cR[n.reason];return{id:n.id,path:n.path,reason:n.reason,title:ec,cause:a.cause,detail:a.detail,since:n.since,saves:n.saves,hasTheirs:i,actions:r,reversible:!t,reversibleNote:t?"Copy before discarding.":"You can change your mind later: resolving is an ordinary change, and the previous version stays in the collection's history. Keep both if you want your version kept as a file as well.",compareLink:o?rg(e.collectionId,n.id):null}}function X0(n){return n.length?n.length===1?`${ec}: ${n[0].path} is waiting for your choice.`:`${ec}: ${n.length} files are waiting for your choice.`:null}function Z0(n){let e=(i,o)=>`${i} ${o}`,t=`, plus ${e(n.pending,"pending")}, plus ${e(n.holds,"held")}`;return n.mode==="local_only"?`Saved on this device${t}`:`Confirmed through ${n.confirmedThrough}${t}`}nc();yu();nc();var bu=15e3,fk=(n,e)=>{try{return!!n&&n.id===e&&n.isCurrent()}catch{return!1}},gu=(n,e)=>Lo(n,e?{cpOrigin:e}:{}),Ws=(n,e)=>gu(n,e);function ic(n,e={}){let t=ER(n,e),i=qR(t,n,e);return i.kind==="opening"&&n.status==="opening"&&n.selectedCollectionId===i.collectionId&&n.openingProgress?{...i,progress:n.openingProgress}:i}function ER(n,e){let t=e.cpOrigin,i=n.selection,o=i?.requested??null;if(n.status==="closed")return{kind:"closed"};if(n.problem==="application_not_yet_available"||n.problem==="application_worker_unavailable"||n.problem==="browser_unsupported"||n.problem==="application_storage_unavailable")return{kind:"unavailable",problem:Ws(n.problem,t)};if(i?.state==="invalid")return{kind:"problem",collectionId:null,problem:Ws(i.problem??"application_selection_invalid",t)};let s=n.signIn?.state==="paired";if(i?.state==="approving"||n.status==="authorizing"){let l=i?.approval??null;return s?l?.kind==="add"?{kind:"authorizing",purpose:"add",collectionId:null}:{kind:"authorizing",purpose:"approve",collectionId:l?.collectionId??o?.collectionId??null}:{kind:"authorizing",purpose:"sign_in",collectionId:l?.collectionId??o?.collectionId??null}}if(n.status==="not_started"||n.status==="starting"){let l=o?.collectionId??null;return l&&n.status==="starting"?{kind:"opening",collectionId:l,displayName:o?.displayName??null,slow:!!e.slow}:{kind:"starting"}}if(n.status==="signed_out")return{kind:"signed_out",notice:n.problem?gu(n,t):null};if(n.status==="blocked"){let l=n.selectedCollectionId??o?.collectionId??null;return n.problem==="recovery_account_mismatch"?{kind:"problem",collectionId:l,problem:Lo(n,{cpOrigin:t,recoveryAccountLabel:n.recoveryAccountLabel})}:{kind:"problem",collectionId:l,problem:l&&n.removedScopeIds?.includes(l)?Ws("installation_scope_removed",t):gu(n,t)??Ws("open_failed",t)}}if(i?.state==="approval_required"&&o?.collectionId&&n.removedScopeIds?.includes(o.collectionId))return{kind:"problem",collectionId:o.collectionId,problem:Ws("installation_scope_removed",t)};if(i?.state==="approval_required"&&o?.collectionId)return{kind:"needs_approval",collectionId:o.collectionId,displayName:o.displayName,declined:i.problem==="application_selection_not_approved"};if(i?.state==="pending"&&o?.collectionId)return{kind:"opening",collectionId:o.collectionId,displayName:o.displayName,slow:!!e.slow};let r=i?.usable??(n.status==="ready"||n.status==="setup_required"?n.collections.find(l=>l.collectionId===n.selectedCollectionId)??null:null);if(n.status==="setup_required"&&r)return n.readiness.assessment?.status==="incompatible"?{kind:"problem",collectionId:r.collectionId,problem:gu(n.readiness,t)??Ws("incompatible",t)}:{kind:"needs_setup",collectionId:r.collectionId,collection:r};if(n.status==="ready"&&r&&fk(e.connection,r.collectionId))return{kind:"ready",collectionId:r.collectionId,collection:r,connection:e.connection,rechecking:n.readiness.checking,problem:null,unavailableTypes:n.readiness.assessment?.unavailableTypes??[]};let a=n.status==="opening"||n.status==="ready"||i?.state==="opening"||i?.state==="usable",p=n.selectedCollectionId??o?.collectionId??null;if(a&&p){let l=n.collections.find(c=>c.collectionId===p)?.displayName??o?.displayName??null;return{kind:"opening",collectionId:p,displayName:l,slow:!!e.slow}}return{kind:"choosing",lastApproval:i?.lastApproval??null}}function qR(n,e,t){let i=t.previous;return i?.kind==="needs_setup"&&n.kind==="opening"&&n.collectionId===i.collectionId&&e.selectedCollectionId===i.collectionId&&e.readiness.checking?i:!i||i.kind!=="ready"||n.kind==="ready"||!fk(t.connection,i.collectionId)||e.selectedCollectionId!==i.collectionId?n:n.kind==="opening"&&n.collectionId===i.collectionId?{...i,connection:t.connection,rechecking:!0,problem:null}:n.kind==="problem"&&n.problem.transient?{...i,connection:t.connection,rechecking:!0,problem:n.problem}:n}function hk(n,e){return n?.kind==="ready"&&(e===void 0||n.collectionId===e)}Ea();nc();Jn();If();Ia();bt();var cq=["http","https","file","javascript","data","blob","about","capacitor","chrome-extension","moz-extension"];function PP(n,e,t){if(typeof n!="string"||!n||n.length>2048||n.includes("*"))return!1;let i=e&&typeof e=="object"?e.redirect_uris:void 0;if(!Array.isArray(i)||!i.includes(n))return!1;let{id:o,homepage:s,platform:r}=e,a;try{a=new URL(n)}catch{return!1}if(a.username||a.password||a.hash)return!1;if(a.protocol==="https:"||a.protocol==="http:"){let l;try{l=new URL(String(s))}catch{return!1}return a.origin===l.origin&&(a.protocol==="https:"||r==="native"&&mr(a.origin)||t&&ot(a.origin))}let p=a.protocol.slice(0,-1);return typeof o=="string"&&p.includes(".")&&/^[a-z][a-z0-9+.-]*$/.test(p)&&!cq.includes(p)&&(p===o||p.startsWith(`${o}.`))&&a.hostname.length>0}Tf();Qr();Jn();ie();Of();bt();var Bo={runtime:{sha256:"7d5cf20f69ef22db5eee56fa28a71a5cadab1d4014aedfc3ee5a12ccf21fff6b",bytes:3798410,maxBytes:3798410,source:{repository:"mdbase-dev/mdbase-connect",commit:"056880a91db3971c10ff80cd5b5ed4a81a6b28db"}},sqlite:{sha256:"2ee8f3dab694532afc8840e07703127287662d08b74e6ff50491ce63f00d5752",bytes:868907,maxBytes:11e5,initializer:{sha256:"a6d3fe46aa3f924e7686329f97b0564549ef1f787e0c19924179aef7f72bcc01",bytes:642742},asyncProxy:{sha256:"9f1970e05ee07a79332498858740b705eeb1dcee03bc150f6f690bc0fb5f0a06",bytes:32505}}};var Mf={},mq=Object.freeze({sha256:Bo.runtime.sha256,bytes:Bo.runtime.bytes,maxBytes:Bo.runtime.maxBytes}),yq=Object.freeze({sha256:Bo.sqlite.sha256,bytes:Bo.sqlite.bytes,maxBytes:Bo.sqlite.maxBytes}),zc=()=>A("unavailable","SDK packaged application assets unavailable","application_packaged_assets_unavailable");function qP(n,e,t){if(!Oa(n))throw zc();let i=zo();Xn({environment:n,appOrigin:e,platform:t,release:i});let o,s;try{let p=new URL(Mf.url);if(Cn(p)!==e||p.username||p.password||p.search||p.hash||(o=new URL("../native/runtime.wasm",Mf.url),s=new URL("../native/sqlite3.wasm",Mf.url),Cn(o)!==e||Cn(s)!==e))throw zc()}catch{throw zc()}let r=(p,l)=>Object.freeze({url:p.href,...l}),a=async p=>{let l=globalThis.WorkerGlobalScope;if(typeof l!="function"||!(globalThis instanceof l))throw zc();let c=new URL("../native/sqlite3.js",Mf.url),{default:d}=await import(c.href);return globalThis.sqlite3ApiConfig={disable:{vfs:{opfs:!0,"opfs-wl":!0}}},d(p)};return Object.freeze({release:()=>zo(),runtime:r(o,mq),sqlite:r(s,yq),initializeSqlite:a})}Of();bt();Qr();Jn();var Vt=class extends Error{constructor(t){super("SDK collection selection unavailable");this.code=t;this.name="ApplicationSelectionError"}code},Bc=n=>typeof n=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n)&&n!=="00000000-0000-0000-0000-000000000000",Ft=(n,e,t=null)=>Object.freeze({requestedCollectionId:n,source:e,problem:t});function TP(n,e){return n.source!=="none"?n:e.storedId!==void 0&&e.storedId!==null?Bc(e.storedId)?Ft(e.storedId,"stored"):Ft(null,"stored","application_selection_invalid"):e.collections.length>1024||e.collections.some(t=>!Bc(t.collectionId))||new Set(e.collections.map(t=>t.collectionId)).size!==e.collections.length?Ft(null,"none","application_selection_metadata"):e.preferredId!==void 0&&e.preferredId!==null?Bc(e.preferredId)&&e.collections.some(t=>t.collectionId===e.preferredId)?Ft(e.preferredId,"preferred"):Ft(null,"preferred","application_selection_metadata"):e.collections.length===1?Ft(e.collections[0].collectionId,"sole"):Ft(null,"none")}var Lf=class{port;origin;parameter;fallback;listeners=new Set;snapshot=Ft(null,"none");stopListening=null;started=!1;closed=!1;constructor(e,t={},i=null){let o,s;try{o=new URL(e),s=new URL(t.fallbackPath??"/",o)}catch{throw new Vt("application_selection_binding")}let r=t.parameter??"collection";if(!Lt(e,!0)||Cn(o)!==e||Cn(s)!==e||s.username||s.password||s.search||s.hash||typeof r!="string"||!/^[a-z][a-zA-Z0-9_.-]{0,63}$/.test(r)||["code","state","error","error_description"].includes(r))throw new Vt("application_selection_binding");this.origin=e,this.parameter=r,this.fallback=s.href,this.port=i}getSnapshot(){return this.snapshot}subscribe(e){return this.check(),this.listeners.add(e),()=>{this.listeners.delete(e)}}start(){return this.check(),this.started?this.snapshot:(this.started=!0,this.stopListening=this.port?.listen(()=>{this.closed||this.publish(this.read())})??null,this.publish(this.read()),this.snapshot)}check(){if(this.closed)throw new Vt("application_selection_fenced")}url(){let e;try{e=new URL(this.port.href())}catch{throw new Vt("application_selection_binding")}if(Cn(e)!==this.origin||e.username||e.password)throw new Vt("application_selection_binding");return e}read(){if(!this.port)return Ft(null,"none");let e;try{e=this.url().searchParams.getAll(this.parameter)}catch{return Ft(null,"url","application_selection_binding")}return e.length===0?Ft(null,"none"):e.length!==1?Ft(null,"url","application_selection_duplicate"):e[0]===""?Ft(null,"url","application_selection_empty"):Bc(e[0])?Ft(e[0],"url"):Ft(null,"url","application_selection_invalid")}publish(e){if(!(this.snapshot.requestedCollectionId===e.requestedCollectionId&&this.snapshot.source===e.source&&this.snapshot.problem===e.problem)){this.snapshot=e;for(let t of[...this.listeners])try{t()}catch{}}}select(e,t={}){if(this.check(),e!==null&&!Bc(e))throw new Vt("application_selection_invalid");let i=t.history??"replace";if(i!=="push"&&i!=="replace")throw new Vt("application_selection_binding");if(this.port){let o=this.url(),s=o.href;e===null?o.searchParams.delete(this.parameter):o.searchParams.set(this.parameter,e),o.href!==s&&this.port.write(o.href,i)}return this.publish(Ft(e,e===null?"none":"user")),this.snapshot}returnUrl(e){this.check();try{let t=new URL(e,this.origin);if(Cn(t)===this.origin&&!t.username&&!t.password)return t.href}catch{}return this.fallback}close(){if(this.closed)return;this.closed=!0;let e=this.stopListening;this.stopListening=null,e?.(),this.listeners.clear()}};function MP(){if(typeof window>"u"||!window.location||!window.history)return null;let n=window;return Object.freeze({href:()=>n.location.href,write:(e,t)=>{t==="push"?n.history.pushState(n.history.state,"",e):n.history.replaceState(n.history.state,"",e)},listen:e=>(n.addEventListener("popstate",e),()=>n.removeEventListener("popstate",e))})}var gq=n=>typeof n=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n)&&n!=="00000000-0000-0000-0000-000000000000",qa=n=>n.status==="ready"||n.status==="setup_required",LP=n=>n.signIn?.state==="paired"&&(n.status==="unselected"||n.status==="blocked"||qa(n)),bq=n=>n.status==="not_started"||n.status==="starting"||n.status==="signed_out"||n.status==="authorizing",Fi=(n,e)=>e===null?null:n.collections.find(t=>t.collectionId===e)??null,jf=class{browser;session;memory;preferredId;schedule;listeners=new Set;stops=[];value;key="";startTarget=null;startApplied=!1;attempted=void 0;lastRequested=null;opening=null;approval=null;lastApproval=null;declined=null;remembered=void 0;queued=!1;started=!1;closed=!1;constructor(e){this.browser=e.browser,this.session=e.session,this.memory=e.memory??null,this.preferredId=e.preferredId??null,this.schedule=e.schedule??(t=>{setTimeout(t,0)}),this.value=this.derive(),this.key=JSON.stringify(this.value)}getSnapshot(){return this.value}subscribe(e){return this.check(),this.listeners.add(e),()=>{this.listeners.delete(e)}}start(){return this.check(),this.started?this.value:(this.started=!0,this.browser.start(),this.stops.push(this.browser.subscribe(this.changed),this.session.subscribe(this.changed)),this.changed(),this.value)}select(e,t={}){this.check(),this.startTarget=null,this.browser.select(e,t.history?{history:t.history}:{}),this.declined=null,this.refresh(),e===null&&this.remember(null);let i=this.session.getSnapshot();return e!==null&&i.selectedCollectionId===e&&i.status==="opening"?(this.attempted=e,Promise.resolve(this.value)):this.whenIdle(async()=>{let o=this.session.getSnapshot();this.requested().requestedCollectionId===e&&((e===null?o.selectedCollectionId===null&&o.status!=="opening":o.selectedCollectionId===e&&qa(o)||!Fi(o,e))||await this.run(e,t,!0))}).then(()=>this.value)}chooseAnother(e={}){return this.select(null,{...e,history:"push"})}approve(e,t={}){if(this.check(),e!=null&&!gq(e))return Promise.reject(new Vt("application_selection_invalid"));if(this.approval&&!this.approval.settled)return Promise.reject(new Vt("application_selection_busy"));e!=null&&e!==this.requested().requestedCollectionId&&(this.startTarget=null,this.browser.select(e,t.history?{history:t.history}:{}));let i=this.session.getSnapshot().signIn,o=i?.nativeSelection?.requestId??i?.collectionSelection?.requestId??null,s,r=e===null?null:this.requested().requestedCollectionId;try{s=this.session.authorize({...t.signal?{signal:t.signal}:{},collectionHint:r})}catch(c){return Promise.reject(c)}let a=r===null?"add":"collection",p=new Set(this.session.getSnapshot().collections.map(c=>c.collectionId)),l={receipt:o,kind:a,collectionId:r,before:p,settled:!1};return this.approval=l,this.lastApproval=null,this.declined=null,this.attempted=void 0,this.refresh(),s.then(()=>(l.settled=!0,this.changed(),this.value),c=>{if(this.approval===l){this.approval=null;let d=c?.code;(d==="cancelled"||d==="aborted")&&(this.lastApproval=Object.freeze({kind:a,outcome:"closed",collectionId:r}))}throw this.changed(),c})}clearLastApproval(){this.check(),this.lastApproval=null,this.refresh()}reauthorize(e={}){this.check();let t=this.value.usable?.collectionId??this.requested().requestedCollectionId;return t===null?Promise.reject(new Vt("application_selection_empty")):this.approve(t,e)}resync(){this.closed||(this.attempted=void 0,this.approval=null,this.changed())}close(){if(!this.closed){this.closed=!0;for(let e of this.stops.splice(0))try{e()}catch{}this.browser.close(),this.listeners.clear()}}check(){if(this.closed)throw new Vt("application_selection_fenced")}requested(){let e=this.browser.getSnapshot(),t=this.startTarget;return t&&e.source==="user"&&e.requestedCollectionId===t.requestedCollectionId?t:e}changed=()=>{this.closed||(this.refresh(),!(this.queued||!this.started)&&(this.queued=!0,this.schedule(()=>{this.queued=!1,this.reconcile()})))};refresh(){let e=this.requested().requestedCollectionId;e!==this.lastRequested&&(this.lastRequested=e,this.attempted=void 0,this.declined!==e&&(this.declined=null));let t=this.derive(),i=JSON.stringify(t);if(t.state==="usable"&&this.remember(t.usable.collectionId),i!==this.key){this.key=i,this.value=Object.freeze(t);for(let o of[...this.listeners])try{o()}catch{}}}remember(e){if(!(!this.memory||this.remembered===e)){this.remembered=e;try{this.memory.write(e)}catch{}}}derive(){let e=this.session.getSnapshot(),t=this.requested(),i=t.requestedCollectionId,o=Fi(e,i),s=qa(e)?Fi(e,e.selectedCollectionId):null,r,a=null;t.problem?(r="invalid",a=t.problem):this.approval?r="approving":i===null?r="none":s?.collectionId===i?r="usable":e.selectedCollectionId===i&&(e.status==="blocked"||e.status==="opening")?r=e.status==="blocked"?"blocked":"opening":LP(e)?o?r="opening":this.session.listing?.()?r="pending":(r="approval_required",this.declined===i&&(a="application_selection_not_approved")):r="pending";let p=this.approval?Object.freeze({kind:this.approval.kind,collectionId:this.approval.collectionId,reopenable:this.approval.settled}):null;return Object.freeze({state:r,problem:a,approval:p,lastApproval:this.lastApproval,usable:s?Object.freeze({...s}):null,requested:Object.freeze({collectionId:i,source:t.source,displayName:o?.displayName??null,approved:o!==null})})}async whenIdle(e){for(;this.opening;)await this.opening;this.check(),await e()}run(e,t={},i=!1){this.attempted=e;let o=t.signal?{signal:t.signal}:{},s=Promise.resolve().then(()=>e===null?this.session.clear(o):this.session.open(e,o)),r=s.then(()=>{},()=>{}).finally(()=>{this.opening===r&&(this.opening=null,this.changed())});return this.opening=r,i?s.then(()=>{}):r}async reconcile(){if(this.closed||this.opening)return;let e=this.session.getSnapshot();if(this.approval)if(this.approval.settled&&e.status==="signed_out"&&e.problem!==null){let o=this.approval;this.approval=null,this.attempted=void 0,this.lastApproval=Object.freeze({kind:o.kind,outcome:e.problem==="approval_window_closed"?"closed":"declined",collectionId:o.collectionId}),this.refresh()}else{if(!this.approval.settled||bq(e))return;let o=e.signIn?.nativeSelection;if(o&&o.requestId!==this.approval.receipt&&!Fi(e,o.collectionId)&&this.session.listing?.())return;this.finishApproval(e)}if(!LP(e))return;if(!this.startApplied)if(this.browser.getSnapshot().source==="none"){let o=null;try{o=this.memory?.read()??null}catch{}if(o!==null&&!Fi(e,o)&&this.session.listing?.())return;this.startApplied=!0;let s=TP(this.browser.getSnapshot(),{storedId:o,preferredId:this.preferredId,collections:e.collections});s.requestedCollectionId!==null&&!s.problem&&(this.browser.select(s.requestedCollectionId,{history:"replace"}),this.startTarget=s,this.refresh())}else this.startApplied=!0;let t=this.requested(),i=t.requestedCollectionId;if(!t.problem){if(i===null){this.attempted!==null&&e.selectedCollectionId!==null&&qa(e)&&this.run(null);return}if(e.selectedCollectionId===i&&(qa(e)||e.status==="opening")){this.attempted=i;return}!Fi(e,i)||this.attempted===i||this.run(i)}}finishApproval(e){let t=this.approval,i=t.receipt;this.approval=null,this.attempted=void 0;let o=u=>u!==null&&Fi(e,u)?t.before.has(u)?"unchanged":"added":e.approval?.outcome==="closed"?"closed":"declined",s=e.signIn?.collectionSelection,r=e.signIn?.nativeSelection,p=(r&&r.requestId!==i&&Fi(e,r.collectionId)?r.collectionId:null)??(s&&s.requestId!==i&&Fi(e,s.selectedCollectionId)?s.selectedCollectionId:null);if(p!==null){p!==this.requested().requestedCollectionId&&(this.startTarget=null,this.browser.select(p,{history:"replace"})),this.lastApproval=Object.freeze({kind:t.kind,outcome:o(p),collectionId:p}),this.refresh(),e.selectedCollectionId===p&&(qa(e)||e.status==="opening")?this.attempted=p:this.run(p);return}let l=this.requested().requestedCollectionId;l!==null&&!Fi(e,l)&&(this.declined=l);let c=t.kind==="add"?e.collections.find(u=>!t.before.has(u.collectionId))?.collectionId??null:null,d=t.kind==="add"?c:t.collectionId??l;this.lastApproval=Object.freeze({kind:t.kind,outcome:o(d),collectionId:d}),this.refresh()}};Yf();Vb();ie();th();cu();eo();vu();var vx="mdbn-app-tabs/1",Kb="\0mdbn-port";var ep=n=>typeof n=="string"&&/^[0-9a-f-]{36}$/.test(n);function Nq(n){if(!n||typeof n!="object")return null;let e=n;switch(e.k){case"join":case"leave":return ep(e.tab)?e:null;case"leader":case"bye":case"fault":case"signedOut":case"signedIn":return ep(e.leader)?e:null;case"joined":return ep(e.tab)&&ep(e.leader)&&typeof e.binding=="string"?e:null;case"m":return ep(e.tab)&&typeof e.up=="boolean"&&Number.isSafeInteger(e.s)&&e.s>=0?e:null;default:return null}}function Wb(n){if(!n||typeof n!="object")return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function Hb(n,e,t=0){return n instanceof MessagePort?{[Kb]:e(n)}:t>=6?n:Array.isArray(n)?n.map(i=>Hb(i,e,t+1)):Wb(n)?Object.fromEntries(Object.entries(n).map(([i,o])=>[i,Hb(o,e,t+1)])):n}function Gb(n,e,t,i=0){if(Wb(n)&&Object.keys(n).length===1&&Number.isSafeInteger(n[Kb])){let o=e(n[Kb]);return t.push(o),o}return i>=6?n:Array.isArray(n)?n.map(o=>Gb(o,e,t,i+1)):Wb(n)?Object.fromEntries(Object.entries(n).map(([o,s])=>[o,Gb(s,e,t,i+1)])):n}var nh=class{constructor(e,t){this.send=e;this.up=t;this.next=t?1:2}send;up;streams=new Map;next;bridge(e,t){this.streams.set(t,e),e.onmessage=i=>{let o=i.ports.length?Hb(i.data,s=>{let r=this.next;return this.next+=2,this.bridge(s,r),r}):i.data;try{this.send(t,o)}catch{}}}deliver(e,t){let i=this.streams.get(e);if(!i)return;let o=[],s=Gb(t,r=>{let a=new MessageChannel;return this.bridge(a.port1,r),a.port2},o);try{i.postMessage(s,o)}catch{for(let r of o)r.close()}}close(){for(let e of this.streams.values()){e.onmessage=null;try{e.close()}catch{}}this.streams.clear()}},ih=class{constructor(e,t,i,o=()=>{}){this.env=t;this.lost=i;this.signedInElsewhere=o;this.base=e.storageNamespace===void 0?`${vx}/${e.cpOrigin}/${e.appId}/${e.build}`:`${vx}/namespace/${JSON.stringify([e.cpOrigin,e.appId,e.build,e.storageNamespace])}`}env;lost;signedInElsewhere;tab=crypto.randomUUID();base;channel=null;presence=null;leading=null;hub=null;follower=null;signingOut=!1;announced=!1;joining=null;get leader(){return this.leading!==null}open(){if(this.channel)return this.channel;let e=new this.env.BroadcastChannel(this.base);return e.onmessage=t=>this.received(Nq(t.data)),this.channel=e,e}post(e){this.channel?.postMessage(e)}hold(e,t,i){return new Promise((o,s)=>{let r=p=>{if(!p){o(null);return}return new Promise(l=>o(l))};(t?this.env.locks.request(e,{ifAvailable:!0},r):this.env.locks.request(e,{signal:i},r)).catch(s)})}async elect(e){if(e.throwIfAborted(),this.open(),this.presence??=await this.hold(`${this.base}/tab/${this.tab}`,!0),e.throwIfAborted(),this.leading||(this.leading=await this.hold(`${this.base}/leader`,!0)),this.leading)return e.aborted&&(this.resign(),e.throwIfAborted()),{kind:"leader"};let t=new AbortController,i=()=>t.abort();e.addEventListener("abort",i,{once:!0});let o=this.hold(`${this.base}/leader`,!1,t.signal),s;try{s=await new Promise((c,d)=>{o.then(u=>{u&&c({release:u})},()=>{}),this.joining={resolve:c,reject:d},e.addEventListener("abort",()=>d(e.reason),{once:!0}),this.post({k:"join",tab:this.tab})})}catch(c){throw this.joining=null,t.abort(),c}finally{e.removeEventListener("abort",i)}if(this.joining=null,"release"in s)return this.leading=s.release,e.aborted&&(this.resign(),e.throwIfAborted()),{kind:"leader"};e.aborted&&(t.abort(),e.throwIfAborted());let r=new MessageChannel,a=this.tab,p=new nh((c,d)=>this.post({k:"m",tab:a,up:!0,s:c,d}),!0);p.bridge(r.port2,0);let l={leader:s.leader,tunnel:p,wait:t,port:r.port1,left:!1,signedOut:!1};return this.follower=l,o.then(c=>{if(c){if(this.follower!==l||l.left){c();return}this.leading=c,this.departed(l)}},()=>{}),{kind:"follower",port:r.port1,binding:s.binding,leave:()=>this.leave(l)}}lead(e){!this.leading||this.hub||(this.hub={followers:new Map,worker:e,faulted:!1},this.post({k:"leader",leader:this.tab}))}fault(){!this.hub||this.hub.faulted||(this.hub.faulted=!0,this.post({k:"fault",leader:this.tab}))}signedOut(){this.hub&&(this.signingOut=!0,this.post({k:"signedOut",leader:this.tab}))}signedIn(){!this.hub||this.announced||this.signingOut||(this.announced=!0,this.post({k:"signedIn",leader:this.tab}))}resign(){let e=this.hub,t=this.signingOut;this.hub=null,this.signingOut=!1,this.announced=!1,e&&this.post({k:"bye",leader:this.tab,...t?{signedOut:!0}:{}});let i=this.leading;if(this.leading=null,i?.(),e){for(let o of e.followers.values())o.watch.abort(),o.tunnel.close();e.followers.clear()}}leave(e){e.left||(e.left=!0,e.wait.abort(),e.tunnel.close(),this.follower===e&&(this.follower=null,this.post({k:"leave",tab:this.tab})))}departed(e,t=!1){e.left||this.follower!==e||(e.left=!0,e.wait.abort(),e.tunnel.close(),this.follower=null,this.lost(t||e.signedOut))}release(){this.joining?.reject(new DOMException("released","AbortError")),this.joining=null,this.follower&&this.leave(this.follower),this.resign();let e=this.presence;this.presence=null,e?.(),this.channel&&(this.channel.onmessage=null,this.channel.close(),this.channel=null)}received(e){if(!e)return;let t=this.hub,i=this.follower;switch(e.k){case"join":{if(!t||t.followers.has(e.tab)||e.tab===this.tab)return;let o=crypto.randomUUID(),s=new MessageChannel,r=e.tab,a=new nh((l,c)=>this.post({k:"m",tab:r,up:!1,s:l,d:c}),!1);a.bridge(s.port1,0);let p=new AbortController;t.followers.set(r,{binding:o,tunnel:a,watch:p});try{t.worker.attach(s.port2,o)}catch{t.followers.delete(r),a.close();return}this.post({k:"joined",tab:r,binding:o,leader:this.tab}),t.faulted&&this.post({k:"fault",leader:this.tab}),this.hold(`${this.base}/tab/${r}`,!1,p.signal).then(l=>{l?.(),this.drop(t,r)},()=>{});return}case"leave":t&&this.drop(t,e.tab);return;case"joined":if(e.tab===this.tab&&this.joining){let o=this.joining;this.joining=null,o.resolve({binding:e.binding,leader:e.leader})}return;case"leader":this.joining&&this.post({k:"join",tab:this.tab});return;case"bye":i&&i.leader===e.leader&&this.departed(i,e.signedOut===!0);return;case"signedOut":i&&i.leader===e.leader&&(i.signedOut=!0);return;case"signedIn":!t&&!i&&!this.joining&&e.leader!==this.tab&&this.signedInElsewhere();return;case"fault":i&&!i.left&&i.leader===e.leader&&i.port.dispatchEvent(new MessageEvent("messageerror"));return;case"m":e.up&&t?t.followers.get(e.tab)?.tunnel.deliver(e.s,e.d):!e.up&&i&&e.tab===this.tab&&i.tunnel.deliver(e.s,e.d);return}}drop(e,t){let i=e.followers.get(t);if(i){e.followers.delete(t),i.watch.abort(),i.tunnel.close();try{e.worker.detach(i.binding)}catch{}}}};function Vi(n){try{return n()}catch{return}}function Uq(){let n=Vi(()=>globalThis.crypto?.subtle),e=Vi(()=>globalThis.navigator?.storage),t=Vi(()=>typeof e?.getDirectory=="function"?()=>e.getDirectory.call(e):void 0);return{subtle:n,abortSignalAny:Vi(()=>typeof AbortSignal=="function"&&typeof AbortSignal.any=="function")===!0,randomUUID:Vi(()=>typeof globalThis.crypto?.randomUUID=="function")===!0,worker:Vi(()=>typeof Worker=="function")===!0,messageChannel:Vi(()=>typeof MessageChannel=="function")===!0,locks:Vi(()=>typeof globalThis.navigator?.locks?.request=="function")===!0,broadcastChannel:Vi(()=>typeof BroadcastChannel=="function")===!0,indexedDB:Vi(()=>typeof globalThis.indexedDB<"u")===!0,getDirectory:t}}async function _x(n=Uq()){let e=[];if(n.subtle||e.push("web_crypto"),n.abortSignalAny||e.push("abort_signal_any"),n.randomUUID||e.push("random_uuid"),n.worker||e.push("worker"),n.messageChannel||e.push("message_channel"),n.locks||e.push("web_locks"),n.broadcastChannel||e.push("broadcast_channel"),n.indexedDB||e.push("indexed_db"),n.subtle)try{await n.subtle.generateKey({name:"X25519"},!1,["deriveBits"])}catch{e.push("x25519")}if(e.length)return{ok:!1,problem:"browser_unsupported",missing:Object.freeze(e)};if(typeof n.getDirectory!="function")return{ok:!1,problem:"application_storage_unavailable",missing:Object.freeze(["opfs"])};try{await n.getDirectory()}catch{return{ok:!1,problem:"application_storage_unavailable",missing:Object.freeze(["opfs"])}}return{ok:!0}}function rh(n,e,t={pendingForMs:0,connection:"online"}){if(!Number.isSafeInteger(n)||n<0)throw new RangeError("invalid unsynced count");return n===0?{kind:"no_pending_edits",unsynced:0,warning:null}:{kind:"not_yet_synced",unsynced:n,warning:!e.persistent&&(t.pendingForMs>=3e4||t.connection==="offline")?"storage_may_be_evicted":null}}function Ax(n){switch(n){case"pending":return"not_yet_synced";case"confirmed":return"saved";case"rejected":return"rejected";case"unknown":return"outcome_unknown";default:throw new RangeError("invalid receipt state")}}var kx="Some changes are only on this device. Stay online so they can sync.";async function oh(n,e,t=!1){let i=!1;try{i=await n?.persisted()===!0,!i&&t&&(i=await n?.persist?.()===!0)}catch{}return{persistent:i,installed:e}}ah();var xx=Object.freeze(new Set);function Cx(n,e){let t=`mdbase.${n}.forgotten-collections.v1.${encodeURIComponent(e)}`,i=()=>{try{return globalThis.localStorage??null}catch{return null}},o=null,s=()=>{let a=null;try{a=i()?.getItem(t)??null}catch{}if(o&&o.raw===a)return o;let p=null,l=xx;try{let c=a?JSON.parse(a):null;c?.v===1&&typeof c.account=="string"&&c.account.length<=64&&Array.isArray(c.ids)&&c.ids.length<=1024&&c.ids.every(d=>typeof d=="string"&&d.length>0&&d.length<=64)&&(p=c.account,l=Object.freeze(new Set(c.ids)))}catch{}return o={raw:a,account:p,ids:l},o},r=(a,p)=>{try{p.size?i()?.setItem(t,JSON.stringify({v:1,account:a,ids:[...p].slice(-1024)})):i()?.removeItem(t)}catch{}o=null};return Object.freeze({read(a){let p=s();return a&&p.account===a?p.ids:xx},add(a,p){let l=s(),c=new Set(l.account===a?l.ids:[]);c.has(p)||(c.add(p),r(a,c))},remove(a,p){let l=s();if(l.account!==a||!l.ids.has(p))return!1;let c=new Set(l.ids);return c.delete(p),r(a,c),!0},clear(){try{i()?.removeItem(t)}catch{}o=null}})}var Kq=new Set(["owner","editor","viewer"]),to=(n,e=512)=>typeof n=="string"&&n.length>0&&n.length<=e,Wq=new Set(["unselected","opening","setup_required","ready"]);function Ix(n){let e=n;return!e||typeof e!="object"||!to(e.collectionId,64)||typeof e.displayName!="string"||e.displayName.length>512||!Kq.has(e.role)?null:Object.freeze({collectionId:e.collectionId,displayName:e.displayName,role:e.role})}function Ox(n){let e=n;return!e||typeof e!="object"||e.state!=="paired"||!to(e.requestId,64)||!to(e.installationId,64)||!to(e.deviceId,64)||!to(e.appId,64)||e.kind!=="app-runtime"&&e.kind!=="mobile"||!to(e.verificationUri,2048)||!to(e.accountId,64)||!Array.isArray(e.collectionIds)||e.collectionIds.length>1024||!e.collectionIds.every(t=>to(t,64))?null:Object.freeze({requestId:e.requestId,installationId:e.installationId,deviceId:e.deviceId,appId:e.appId,kind:e.kind,verificationUri:e.verificationUri,state:"paired",accountId:e.accountId,...typeof e.accountEmail=="string"&&e.accountEmail.length<=320?{accountEmail:e.accountEmail}:{},collectionIds:Object.freeze([...e.collectionIds]),createCollections:e.createCollections===!0,requestedCreateCollections:e.requestedCreateCollections===!0})}function Rx(n,e){let t=`mdbase.${n}.session-hint.v1.${encodeURIComponent(e)}`,i=null,o=null,s=()=>{try{return globalThis.localStorage??null}catch{return null}},r=()=>{let p=null;try{p=s()?.getItem(t)??null}catch{return null}if(i&&i.raw===p)return i.value;let l=null;try{let c=p?JSON.parse(p):null,d=c?.v===1?Ox(c.signIn):null,u=Array.isArray(c?.collections)&&c.collections.length<=1024?c.collections.map(Ix):null;d&&u&&u.every(f=>f!==null)&&(l=Object.freeze({signIn:d,collections:Object.freeze(u)}))}catch{l=null}return i={raw:p,value:l},l},a=()=>{o=null;try{s()?.removeItem(t)}catch{}};return Object.freeze({read:r,clear:a,observe(p){if(p.status==="signed_out"&&p.signIn===null){o!==""&&(a(),o="");return}if(!Wq.has(p.status)||p.signIn?.state!=="paired")return;let l=Ox(p.signIn),c=p.collections.map(Ix);if(!l||!c.every(u=>u!==null))return;let d=JSON.stringify({v:1,signIn:l,collections:c});if(d!==o){o=d;try{s()?.setItem(t,d)}catch{}}}})}Dy();ie();function A2(n,e){return new Promise((t,i)=>{let o=()=>{clearTimeout(s),i(A("cancelled","The original collection closed."))};if(n.aborted){i(A("cancelled","The original collection closed."));return}let s=setTimeout(()=>{n.removeEventListener("abort",o),t()},e);n.addEventListener("abort",o,{once:!0})})}var k2=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,Ga=Object.freeze({checking:!1,assessment:null,problem:null}),S2=Object.freeze({capabilities:Ga,contracts:Ga,configuration:Ga,files:Ga,people:Ga,notifications:Ga}),oo=(n,e)=>{let t=e?Object.freeze({status:e,problem:e==="incompatible"?Object.freeze({code:"incompatible"}):null}):null;return Object.freeze({checking:n,assessment:t,problem:null,facets:Object.freeze({...S2,configuration:Object.freeze({checking:n,assessment:t,problem:null})})})},gh=n=>n==="approval_required"?"device_approval_required":n,P2=n=>n.state==="opening"||n.state==="unavailable"&&n.reason!=="sync_required"&&n.reason!=="access_removed"&&n.reason!=="collection_deleted",sC=n=>{if(oe(n)){let e=n.details instanceof Map?n.details.get("availability"):void 0;return typeof e=="string"?gh(e):n.reason??n.code}return"open_failed"},aC=n=>{if(!oe(n))return;let e=A0(n.details);return Object.freeze({name:"MdbaseError",code:n.code,...e?{relay:e}:{}})};function x2(n){let e=n.manifest?.redirect_uris;return(Array.isArray(e)?e.filter(i=>typeof i=="string"):[]).find(i=>{try{return new URL(i).origin===n.origin}catch{return!1}})??new URL("/",n.origin).href}function lC(n,e,t){if(n.signIn?.state!=="paired"||!e.length&&!t)return n;let i=new Set(n.collections.map(p=>p.collectionId)),o=e.filter(p=>!i.has(p.collectionId)),s=o.length?Object.freeze([...n.collections,...o]):n.collections;if(!t||n.status!=="unselected"||i.has(t.collectionId))return s===n.collections?n:Object.freeze({...n,collections:s});let{problemDetail:r,...a}=n;return Object.freeze({...a,collections:s,status:t.status,selectedCollectionId:t.collectionId,problem:t.problem,transport:null,live:null,...t.problemDetail?{problemDetail:t.problemDetail}:{},..."readiness"in n?{readiness:t.readiness}:{}})}var bh=class{options;loading=null;list=Object.freeze([]);open=null;listed=null;settled=null;refreshing=null;closed=!1;bindings=null;bindingsAccount=null;native=null;revision=0;constructor(e){this.options=e}grants(){let e=this.loading??=(this.options.grants??(async()=>{let{MdbaseAppGrants:t}=await Promise.resolve().then(()=>(oC(),rC));return new t({declaration:this.options.declaration,redirectUri:x2(this.options.declaration)})}))();return e.catch(()=>{this.loading===e&&(this.loading=null)}),e}changed(){if(!this.closed){this.revision++;try{this.options.onChange()}catch{}}}bind(e,t){let i=t.filter(o=>o.account_id===e);this.bindingsAccount===e&&JSON.stringify(i)===JSON.stringify(this.bindings)||(this.bindingsAccount=e,this.bindings=Object.freeze([...i]),this.settled=null,this.listed=null,this.setList([]))}async nativeAuthorization(e,t,i){if(e.action==="cancel")return this.native?.life.abort(),this.native?.prepared?.cancel(),this.native=null,null;if(this.closed||i.aborted)throw A("cancelled","Original Native authorization fenced");if(e.action==="prepare"){if(this.native||e.value.authorizationId)throw A("unauthenticated","Original Native preparation unavailable");let a={context:e.value,portal:t,prepared:null,life:new AbortController};this.native=a;let p=AbortSignal.any([i,a.life.signal]),l=await this.grants();if(!l.prepareAuthorization)throw A("unavailable","Native authorization unavailable");let c=btoa(String.fromCharCode(...Uint8Array.from(e.value.challenge.match(/../g),u=>parseInt(u,16)))).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,""),d=await l.prepareAuthorization({authorizationNonce:c,expectedAccountId:e.value.accountId,signal:p});if(a.prepared=d,this.native!==a||p.aborted||d.applicationId!==e.value.appId)throw d.cancel(),A("unauthenticated","Original application registration mismatch");return Object.freeze({authorizationId:d.authorizationId,applicationId:d.applicationId,manifestDigest:d.manifestDigest})}let o=this.native,s=o?.prepared;if(!o||!s||o.portal!==t||o.context.requestId!==e.value.requestId||s.authorizationId!==e.value.authorizationRequestId)throw A("unauthenticated","Original Native preparation unavailable");let r=await s.finish({popup:t,collection:e.value.collectionId,signal:AbortSignal.any([i,o.life.signal])});if(this.native!==o||i.aborted||!r.nativeCompletion)throw A("unauthenticated","Original Native completion unavailable");return r.nativeCompletion}entries(){return this.list}has(e){return this.list.some(t=>t.collectionId===e)||this.open?.id===e}state(){return this.open?.state??null}connection(e){let t=this.open;return t&&t.id===e&&t.state.status==="ready"?t.connection:null}listing(e){return!this.closed&&e!==null&&this.settled!==e}ensure(e){this.settled!==e&&!this.refreshing&&this.refresh(e).catch(()=>{})}refresh(e=this.listed){if(this.closed)return Promise.resolve();if(this.refreshing)return this.refreshing;let t=(async()=>{try{let i=await this.grants(),o=this.bindings,s=[];if(o)for(let a of o)a.account_id===e&&await i.verifiedStoredNativeGrant?.(a)&&s.push(a);let r=await i.collections(o===null?{}:{bindings:s});if(this.closed||o!==this.bindings)return;this.listed=e,this.setList(r)}finally{!this.closed&&e!==null&&this.settled!==e&&(this.settled=e,this.changed())}})().finally(()=>{this.refreshing===t&&(this.refreshing=null)});return this.refreshing=t,t}setList(e){let t=Object.freeze(e.filter(i=>k2.test(i.collectionId)).map(i=>Object.freeze({collectionId:i.collectionId,displayName:i.displayName,role:i.role??"editor",availability:i.availability,kind:"private"})));JSON.stringify(t)!==JSON.stringify(this.list)&&(this.list=t,this.changed())}setAvailability(e,t){this.list.some(i=>i.collectionId===e&&JSON.stringify(i.availability)!==JSON.stringify(t))&&(this.list=Object.freeze(this.list.map(i=>i.collectionId===e?Object.freeze({...i,availability:t}):i)),this.changed())}set(e,t){if(this.open!==e||e.life.signal.aborted)return;let{problemDetail:i,...o}=e.state,{problemDetail:s,...r}=t,a=r.problem===null?void 0:s??(r.problem===void 0?i:void 0);e.state=Object.freeze({...o,...r,...a?{problemDetail:a}:{}}),this.changed()}async openCollection(e,t){if(this.closed)throw A("cancelled","Private collections closed","application_entry_fenced");this.close(!1);let i={id:e,life:new AbortController,client:null,setup:null,connection:null,stopLink:null,state:Object.freeze({collectionId:e,status:"opening",problem:null,readiness:oo(!0,null)})};this.open=i,this.changed();let o=i.life.signal;try{let s=await this.grants(),r=this.bindings?.find(d=>d.account_id===t.account&&d.collection_id===e),a=async()=>{if(this.bindings!==null&&(!r||this.bindingsAccount!==t.account||!this.bindings.includes(r)||!await s.verifiedStoredNativeGrant?.(r)))throw A("unauthenticated","Original account-bound Native grant unavailable");if(o.aborted)throw A("cancelled","Original Native open fenced")};await a();let p=await s.availability(e,{signal:o});if(this.setAvailability(e,p),P2(p)&&(p.state==="unavailable"&&this.set(i,{status:"blocked",problem:gh(p.reason),readiness:oo(!1,null)}),p=await s.waitForAvailable(e,{signal:o,timeoutMs:this.options.waitMs??10*6e4,onAvailability:d=>{this.setAvailability(e,d),d.state==="unavailable"?this.set(i,{status:"blocked",problem:gh(d.reason)}):this.set(i,{status:"opening",problem:null,readiness:oo(!0,null)})}})),p.state!=="available"){if(p.state==="opening")throw A("unavailable","The collection is still getting ready","collection_unavailable");this.set(i,{status:"blocked",problem:gh(p.reason),readiness:oo(!1,null)});return}this.set(i,{status:"opening",problem:null}),await a();let l=await(this.options.connect??C2(this.options.declaration))(s,e,o);if(this.open!==i||o.aborted||l.collection!==e){if(l.close(),this.open===i&&!o.aborted)throw A("invalid_request","a different collection opened","collection_mismatch");return}i.client=l,i.setup=s.setup(l),i.connection=Object.freeze({id:e,displayName:this.list.find(d=>d.collectionId===e)?.displayName??"Collection",scope:Object.freeze({account:t.account,installation:t.installation,collection:e}),generation:crypto.randomUUID(),records:l,files:l.files,people:s.people(e,l),isCurrent:()=>this.open===i&&!o.aborted&&!this.closed}),await this.assessOpen(i);let c=0;i.stopLink=l.onLink((d,u)=>{u?this.set(i,{problem:sC(u),problemDetail:aC(u)}):d==="open"&&this.set(i,{problem:null});let f=++c;s.availability(e,{signal:o}).then(h=>{this.open===i&&!o.aborted&&f===c&&this.setAvailability(e,h)}).catch(()=>{})})}catch(s){throw this.open===i&&!o.aborted&&this.set(i,{status:"blocked",problem:sC(s),problemDetail:aC(s),readiness:oo(!1,null)}),s}}async assessOpen(e){this.set(e,{readiness:oo(!0,e.state.readiness.assessment?.status??null)});let t=1e3;for(;;){if(this.open!==e||e.life.signal.aborted)throw A("cancelled","The original collection closed.");let i;try{i=await e.setup.assess({signal:e.life.signal})}catch(o){if(!oe(o)||o.code!=="rate_limited")throw o;let s=o.retryAfterMs;await A2(e.life.signal,Math.min(2147483647,Math.max(t,typeof s=="number"&&Number.isFinite(s)?s:0))),t=Math.min(3e4,t*2);continue}if(this.open!==e||e.life.signal.aborted)throw A("cancelled","The original collection closed.");return this.set(e,{status:i==="ready"?"ready":"setup_required",problem:null,readiness:oo(!1,i)}),i}}current(){let e=this.open;if(!e?.setup||e.life.signal.aborted)throw A("invalid_request","No Private collection is open","application_connection_fenced");return e}isOpen(){return this.open!==null}async assess(){let e=this.current();return await this.assessOpen(e),e.state.readiness}plan(e){return this.current().setup.plan(e)}async apply(e,t={}){let i=this.current(),o=await i.setup.apply(e,t);this.set(i,{status:o==="ready"?"ready":"setup_required",problem:null,readiness:oo(!1,o)})}async configure(e={}){let i=await this.current().setup.plan(e.signal?{signal:e.signal}:{});await this.apply(i,e)}async add(e,t,i){let o;try{o=await this.grants()}catch(r){throw e.close(),r}let s=await o.authorize({popup:e,...t?{collection:t}:{},...i?{signal:i}:{}});return await this.refresh().catch(()=>{}),s.collectionId}async forget(e){this.open?.id===e&&this.close();let t=await this.grants(),i=this.bindings?.find(o=>o.collection_id===e&&o.account_id===this.bindingsAccount);(this.bindings===null||i&&await t.verifiedStoredNativeGrant?.(i))&&await(i?t.forget(e,{expectedNoisePublicKey:i.client_noise_public_key}):t.forget(e)),this.list.some(o=>o.collectionId===e)&&(this.list=Object.freeze(this.list.filter(o=>o.collectionId!==e)),this.changed())}async forgetAll(){this.native?.life.abort(),this.native?.prepared?.cancel(),this.native=null,this.close();try{await(await this.grants()).forgetAllGrants()}finally{this.list=Object.freeze([]),this.listed=null,this.settled=null,this.changed()}}close(e=!0){let t=this.open;if(t){this.open=null,t.life.abort(),t.stopLink?.();try{t.client?.close()}catch{}e&&this.changed()}}dispose(){this.native?.life.abort(),this.native?.prepared?.cancel(),this.native=null,this.close(!1),this.closed=!0}};function C2(n){return async(e,t,i)=>{let{connect:o}=await Promise.resolve().then(()=>(Ps(),xd));return o({connector:e.connector(t),app:{name:n.id,version:"1"},signal:i})}}var Nh={};function mT(n){let e=globalThis.document;return!e||typeof e.addEventListener!="function"||e.visibilityState!=="hidden"?Promise.resolve():new Promise((t,i)=>{let o=()=>{e.visibilityState!=="hidden"&&(e.removeEventListener("visibilitychange",o),n.removeEventListener("abort",s),t())},s=()=>{e.removeEventListener("visibilitychange",o),i(n.reason)};e.addEventListener("visibilitychange",o),n.addEventListener("abort",s,{once:!0})})}var yp=class extends Error{code="application_not_yet_available";constructor(){super("MdbaseConnect application runtime is not yet available"),this.name="MdbaseApplicationUnavailableError"}},Uw=Object.freeze({code:"application_not_yet_available"}),il=Object.freeze({checking:!1,assessment:null,problem:Uw}),yT=Object.freeze({checking:!1,assessment:null,problem:Uw,facets:Object.freeze({capabilities:il,contracts:il,configuration:il,files:il,people:il,notifications:il})}),rl=Object.freeze({checking:!1,assessment:null,problem:null}),jh=Object.freeze({checking:!1,assessment:null,problem:null,facets:Object.freeze({capabilities:rl,contracts:rl,configuration:rl,files:rl,people:rl,notifications:rl})}),Nw=()=>new yp,aI=Object.freeze({state:"none",problem:null,usable:null,requested:Object.freeze({collectionId:null,source:"none",displayName:null,approved:!1})});function gT(){let n={status:"blocked",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:Uw.code,timing:null,readiness:yT,selection:aI},e=Object.freeze({...n,phase:ic(n),sync:null,writes:null,links:null}),t=()=>Promise.reject(Nw());return Object.freeze({getSnapshot:()=>e,subscribe:()=>()=>{},start:t,authorize:t,select:t,approve:t,reauthorize:t,refreshCollectionList:t,requestAccess:t,chooseAnother:t,assess:t,configure:t,setup:Object.freeze({plan:t,apply:t}),clearSelection:t,forget:t,deleteCollection:t,setForeground(){throw Nw()},close:t,signOut:t})}var bT=n=>typeof Worker=="function"&&typeof MessageChannel=="function"&&Rt()!==null&&Lt(n,!0);function wT(n,e){if(n===void 0)return null;let t=()=>{throw A("invalid_request","Invalid sign-in opener","application_sign_in_opener")};if(!n||typeof n!="object"||typeof n.open!="function"||n.close!==void 0&&typeof n.close!="function")return t();let i=n.returnUrl;i!==void 0&&(PP(i,e.manifest,Qt(e.environment))||t());let o=n.open.bind(n),s=n.close?.bind(n);return Object.freeze({open:o,...s?{close:s}:{},...i!==void 0?{returnUrl:i}:{}})}async function vT(n){let e=!0;if(n.webPush){let t=globalThis.navigator?.serviceWorker,i;t&&typeof t.getRegistration=="function"&&(e=await Promise.race([(async()=>{let o=await(await t.getRegistration())?.pushManager?.getSubscription();return o?await o.unsubscribe():!0})().catch(()=>!1),new Promise(o=>{i=setTimeout(()=>o(!1),5e3)})]).finally(()=>clearTimeout(i)))}try{n.server==="incomplete"&&console.warn("mdbase: signed out on this device, but mdbase could not be reached to end the session. This device stays listed under the account until it is removed there."),(n.local==="incomplete"||!e)&&console.warn("mdbase: signed out, but some local data on this device could not be removed.")}catch{}}function _T(n){let e=`mdbase.${n}.selected-collection.v1`;return Object.freeze({read:()=>{try{return globalThis.localStorage?.getItem(e)??null}catch{return null}},write:t=>{try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}})}var ol=class{app;declaration;compiled;lifetime=new AbortController;listeners=new Set;nativeListeners=new Set;selection=null;memory=null;runtime=null;initialization=null;closing=null;closed=!1;foreground=!0;incarnation=0;hidden=null;tabs=null;election=null;signingOut=!1;snapshot=Object.freeze({status:"not_started",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:null,timing:null,readiness:jh});composed=null;hint=null;forgotten=null;handledApproval=null;refreshing=null;refreshedAt=0;approvalPortal=null;revision=0;links=null;cpOrigin=null;opening=null;syncing=null;storagePolicy=null;pendingSave=null;signIn;typeIssues;privates=null;overlaid=new WeakMap;constructor(e,t={}){this.declaration=yr(e),this.compiled=Zr(this.declaration);let i=t.readiness?.typeIssues??"block";if(i!=="block"&&i!=="degrade")throw new TypeError('readiness.typeIssues must be "block" or "degrade"');if(this.typeIssues=i,this.signIn=wT(t.signIn,this.declaration),!bT(this.declaration.origin)){this.app=gT();return}try{let s=this.environment().cpOrigin;this.cpOrigin=s,this.hint=Rx(this.declaration.storage.applicationNamespace,s),this.forgotten=Cx(this.declaration.storage.applicationNamespace,s),this.links=Object.freeze({account:`${s}/account`,manageAccess:`${s}/account/applications`})}catch{}t.followVisibility!==!1&&this.followVisibility(),this.followPageLifecycle(),this.followFocus(),this.followStoragePolicy(),this.memory=_T(this.declaration.storage.applicationNamespace),t.privateCollections!==!1&&(this.privates=new bh({declaration:this.declaration,onChange:()=>{this.revision++,this.notify()}})),this.selection=new jf({browser:new Lf(this.declaration.origin,{},MP()),session:this.selectionSession(),memory:this.memory}),this.selection.subscribe(()=>{this.unforgetApproved(),this.notify(!1)});let o=()=>this.getSnapshot();this.app=Object.freeze({getSnapshot:o,subscribe:s=>(this.listeners.add(s),()=>{this.listeners.delete(s)}),start:s=>this.track(()=>this.call(r=>this.started(r,s)).catch(r=>{let a=this.runtime?.getNativeSnapshot();if(!(r?.code==="open_in_another_tab"&&a?.status==="blocked"&&a.problem==="open_in_another_tab"))throw r})),authorize:s=>this.track(()=>this.approve(void 0,s)),approve:(s,r)=>this.track(()=>this.approve(s,r)),reauthorize:s=>this.track(()=>{let r=this.choose(),a=r.getSnapshot(),p=this.privates?.state()?.collectionId??a.usable?.collectionId??a.requested.collectionId;return p?this.approve(p,s):r.reauthorize(s)}),addPrivateCollection:s=>this.track(()=>this.approve(null,s)),refreshCollectionList:s=>this.track(()=>Promise.all([this.call(r=>r.queue(()=>r.refreshCollections(s))),this.privates?.refresh(this.account()).catch(()=>{})])),requestAccess:(s,r)=>this.requestAccess(s,r),select:(s,r)=>this.track(()=>this.choose().select(s,{...r,history:"push"})),clearSelection:s=>this.track(()=>this.choose().select(null,s)),chooseAnother:s=>this.track(()=>this.choose().chooseAnother(s)),forget:(s,r)=>this.track(async()=>{let a=this.choose(),p=this.account();if(this.privates?.has(s)){await this.privates.forget(s),a.getSnapshot().requested.collectionId===s&&await a.select(null,r);return}if(p&&this.forgotten){this.forgotten.add(p,s),this.revision++,(a.getSnapshot().requested.collectionId===s||(this.runtime?.getSnapshot()??this.snapshot).selectedCollectionId===s)&&await a.select(null,r),this.notify(!1);return}await this.call(l=>l.queue(()=>l.forget(s,r))),a.getSnapshot().requested.collectionId===s&&await a.select(null,r)}),deleteCollection:(s,r)=>this.track(async()=>{let a=this.choose(),{confirmName:p,...l}=r??{};await this.call(c=>c.queue(()=>c.deleteCollection(s,p,l))),a.getSnapshot().requested.collectionId===s&&await a.select(null,l)}),assess:s=>this.privates?.isOpen()?this.privates.assess():this.call(r=>r.queue(()=>r.assess(s))),configure:s=>this.track(()=>this.privates?.isOpen()?this.privates.configure(s):this.call(r=>r.queue(()=>r.configure(s)))),setup:Object.freeze({plan:s=>(this.privates?.isOpen()?this.privates.plan(s):this.call(r=>r.queue(()=>r.planSetup(s)))).then(r=>Px(r,this.getSnapshot().readiness)),apply:(s,r)=>this.track(()=>this.privates?.isOpen()?this.privates.apply(s,r):this.call(a=>a.queue(()=>a.applySetup(s,r))))}),setForeground:s=>this.setForeground(s),close:()=>this.close(),signOut:s=>this.signOut(s)})}withPrivate(e){let t=this.privates;if(!t)return e;let i=this.overlaid.get(e);if(i&&i.revision===t.revision)return i.value;let o=lC(e,t.entries(),t.state());return this.overlaid.set(e,{revision:t.revision,value:o}),o}getSnapshot(){let e=this.withPrivate(this.runtime?.getSnapshot()??this.snapshot),t=this.selection?.getSnapshot()??aI,i=this.composed,o=e.signIn===null&&(e.status==="starting"||e.status==="blocked"&&e.problem==="open_in_another_tab")?this.hint?.read()??null:null;if(i&&i.base===e&&i.selection===t&&i.revision===this.revision&&i.hint===o)return i.value;let s=o?Object.freeze({...e,signIn:o.signIn,collections:o.collections}):e,r=this.forgotten?.read(s.signIn?.accountId)??null,a=r?.size&&s.collections.some(m=>r.has(m.collectionId)&&m.collectionId!==s.selectedCollectionId)?Object.freeze({...s,collections:Object.freeze(s.collections.filter(m=>!r.has(m.collectionId)||m.collectionId===s.selectedCollectionId))}):s,p=a.selectedCollectionId,l=p&&!this.closed?this.privates?.connection(p)??this.runtime?.connection(p)??null:null,c=ic({...a,selection:t},{connection:l,previous:i?.value.phase??null,...this.cpOrigin?{cpOrigin:this.cpOrigin}:{}});c=this.trackOpening(c);let d=this.trackSync(c,a.problem,a.transport??null,a.live??null),u=this.syncing?.writes()??null,f=this.trackSaveWarning(),h=Object.freeze({...a,selection:t,phase:c,sync:d,writes:u,storage:this.storagePolicy,saveWarning:f,links:this.linksFor(p)});return this.composed={base:e,selection:t,revision:this.revision,hint:o,value:h},h}linksFor(e){return this.links&&e?Object.freeze({...this.links,manageAccess:`${this.cpOrigin}/access?collection=${encodeURIComponent(e)}`}):this.links}trackSaveWarning(){let e=this.syncing,t=e?.status,i=t?.pending??0;if(this.pendingSave&&(this.closed||this.hidden||!i||this.pendingSave.id!==e?.id)&&this.clearPendingSave(),this.closed||this.hidden||!e||!t||!i)return null;if(!this.pendingSave){let o={id:e.id,since:performance.now(),timer:null};o.timer=setTimeout(()=>{this.pendingSave===o&&(o.timer=null,this.revision++,this.notify(!1))},3e4),this.pendingSave=o}return rh(i,this.storagePolicy??{persistent:!1,installed:!1},{pendingForMs:performance.now()-this.pendingSave.since,connection:t.connection}).warning}clearPendingSave(){this.pendingSave?.timer!==null&&this.pendingSave?.timer!==void 0&&clearTimeout(this.pendingSave.timer),this.pendingSave=null}trackOpening(e){let t=e.kind==="opening"?e.collectionId:null;if(this.opening&&this.opening.id!==t&&(clearTimeout(this.opening.timer),this.opening=null),t===null||this.closed)return e;if(!this.opening){let i={id:t,slow:!1,timer:setTimeout(()=>{this.opening===i&&(i.slow=!0,this.revision++,this.notify(!1))},bu)};this.opening=i}return e.kind==="opening"&&this.opening.slow?{...e,slow:!0}:e}trackSync(e,t,i,o){let s=e.kind==="ready"?e.collectionId:null;if(this.syncing&&this.syncing.id!==s){try{this.syncing.stop()}catch{}this.syncing=null}if(e.kind!=="ready"||this.closed)return null;if(!this.syncing){let r=e.connection.records,a=null;try{a=r.status}catch{}let p={id:e.collectionId,stop:()=>{},status:a,writes:()=>null},l=()=>{this.syncing===p&&(this.revision++,this.getSnapshot(),this.notify(!1))},c=()=>{},d=()=>{};try{c=r.onStatus(u=>{p.status=u,l()})}catch{}try{let u=r.ledger;d=u.subscribe(l),p.writes=()=>{try{return u.getSnapshot()}catch{return null}}}catch{}p.stop=()=>{c(),d()},this.syncing=p}try{e.connection.records.setTransportDeferred(i!==null)}catch{}return this.syncing.status?eu(this.syncing.status,t,i,o):null}nativeAuthorization(e,t,i){return!this.privates||this.closed||this.hidden?Promise.reject(A("unavailable","Native authorization unavailable")):this.privates.nativeAuthorization(e,t,AbortSignal.any([i,this.lifetime.signal]))}account(){return(this.runtime?.getSnapshot()??this.snapshot).signIn?.accountId??null}unforgetApproved(){let e=this.selection?.getSnapshot().lastApproval??null,t=this.account();!e||e===this.handledApproval||(this.handledApproval=e,t&&e.collectionId&&(e.outcome==="added"||e.outcome==="unchanged")&&this.forgotten?.remove(t,e.collectionId)&&this.revision++)}followFocus(){let e=typeof window>"u"?void 0:window,t=globalThis.document;if(!e||typeof e.addEventListener!="function")return;let i=()=>{t?.visibilityState!=="hidden"&&this.refreshCollections()};e.addEventListener("focus",i,{signal:this.lifetime.signal}),t&&typeof t.addEventListener=="function"&&t.addEventListener("visibilitychange",i,{signal:this.lifetime.signal})}refreshCollections(){let e=this.runtime,t=Date.now();if(!e||this.closed||this.hidden||this.refreshing||t-this.refreshedAt<2e3)return;let i=e.getNativeSnapshot();i.signIn?.state!=="paired"||i.status!=="unselected"&&i.status!=="ready"&&i.status!=="setup_required"||(this.refreshedAt=t,this.privates?.refresh(i.signIn.accountId).catch(()=>{}),this.refreshing=e.queue(()=>e.refreshCollections()).catch(()=>{}).finally(()=>{this.refreshing=null}))}followStoragePolicy(){let e=globalThis.navigator?.storage;if(!e||typeof e.persisted!="function")return;let t=()=>{try{return globalThis.matchMedia?.("(display-mode: standalone)").matches===!0||globalThis.navigator?.standalone===!0}catch{return!1}},i=(s=!1)=>{this.closed||oh(e,t(),s).then(r=>{this.closed||this.storagePolicy?.persistent===r.persistent&&this.storagePolicy?.installed===r.installed||(this.storagePolicy=r,this.revision++,this.notify(!1))}).catch(()=>{})},o=globalThis.document;o&&typeof o.addEventListener=="function"&&o.addEventListener("visibilitychange",()=>{o.visibilityState!=="hidden"&&i()},{signal:this.lifetime.signal}),i(!0)}notify(e=!0){let t=this.runtime?.getSnapshot(),i=t?.signIn?.state==="paired"?t.signIn.accountId:null;if(i&&!this.closed&&!this.hidden&&(this.privates?.bind(i,t?.signIn?.nativeGrants??[]),this.privates?.ensure(i)),e)for(let o of[...this.nativeListeners])try{o()}catch{}for(let o of[...this.listeners])try{o()}catch{}}choose(){this.check();let e=this.selection;return e.start(),e}async track(e){return await e(),this.getSnapshot()}selectionSession(){return Object.freeze({getSnapshot:()=>this.withPrivate(this.runtime?.getNativeSnapshot()??this.snapshot),subscribe:e=>(this.nativeListeners.add(e),()=>{this.nativeListeners.delete(e)}),open:(e,t={})=>this.call(async i=>{let o=this.privates,s=i.getNativeSnapshot().collections.some(p=>p.collectionId===e);if(!o||s||!o.has(e))return o?.close(),i.queue(()=>i.select(e,t));i.getNativeSnapshot().selectedCollectionId!==null&&await i.queue(()=>i.clearSelection(t));let r=i.getNativeSnapshot().signIn?.accountId,a=i.getNativeSnapshot().signIn?.installationId;if(!r||!a)throw A("unauthenticated","Sign in before opening a collection");o.openCollection(e,{account:r,installation:a}).catch(()=>{})}),clear:(e={})=>(this.privates?.close(),this.call(t=>t.queue(()=>t.clearSelection(e)))),authorize:(e={})=>this.authorize(e,e.collectionHint??null),listing:()=>this.privates?.listing(this.account())??!1})}check(){if(this.closed||this.hidden||this.lifetime.signal.aborted)throw A("cancelled","Application entry fenced","application_entry_fenced")}environment(){return Xn({environment:this.declaration.environment,appOrigin:this.declaration.origin,platform:this.declaration.manifest.platform==="native"?"native":void 0,release:zo()})}initialize(){if(this.initialization)return this.initialization;let e=this.incarnation,t=Promise.resolve().then(async()=>{if(this.check(),typeof Nh.url!="string")throw Nw();let i=new URL(Nh.url);if(Cn(i)!==this.declaration.origin||Rt()!==this.declaration.origin)throw A("unavailable","Application module binding unavailable","application_worker_module_binding");let o=this.environment();qP(this.declaration.environment,this.declaration.origin,this.declaration.manifest.platform==="native"?"native":void 0);let s=await _x();if(this.check(),!s.ok)throw A("unavailable","This browser can't run mdbase",{reason:s.problem,details:new Map([["missing",s.missing.join(",")]])});let r=await qf({declaration:this.declaration,signal:this.lifetime.signal,isCurrent:()=>!this.closed});this.check();let{ApplicationRuntime:a}=await Promise.resolve().then(()=>(sI(),oI));if(this.check(),e!==this.incarnation)throw A("cancelled","Application entry fenced","application_entry_fenced");let p=SP(this.declaration,r);r.supersededDeclaredId&&console.info(`mdbase: ${hu("application_registration_id_superseded")}`);let l=wu(this.declaration),c=Object.freeze({cpOrigin:o.cpOrigin,appId:p.id,...l===null?{}:{storageNamespace:l}}),d=v=>(this.runtime=v,v.subscribe(()=>{this.hint?.observe(v.getNativeSnapshot()),this.observeSignOut(v),v.getNativeSnapshot().signIn?.state==="paired"&&this.tabs?.signedIn(),this.notify(),this.awaitOtherTab(v,c)}),v.setForeground(this.foreground),this.notify(),v),u=this.tabsFor(c),f=new AbortController;this.election?.abort(),this.election=f;let h=u?await u.elect(AbortSignal.any([this.lifetime.signal,f.signal])):{kind:"leader"};if(this.closed||this.hidden||e!==this.incarnation||f.signal.aborted)throw h.kind==="follower"?h.leave():u?.resign(),A("cancelled","Application entry fenced","application_entry_fenced");if(h.kind==="follower")return d(new a({declaration:p,compiledManifest:this.compiled,typeIssues:this.typeIssues,cpOrigin:o.cpOrigin,port:h.port,binding:h.binding,releaseWorker:()=>h.leave(),nativeAuthorization:(v,_,k)=>this.nativeAuthorization(v,_,k)}));let m=new MessageChannel,b=crypto.randomUUID(),w;try{w=new Worker(new URL("./worker.js",Nh.url),{type:"module"})}catch{throw u?.resign(),m.port1.close(),m.port2.close(),A("unavailable","Application Worker construction unavailable","application_worker_unavailable")}let g=v=>{v.preventDefault(),m.port1.dispatchEvent(new MessageEvent("messageerror")),u?.fault()};w.addEventListener("error",g);let y=new a({declaration:p,compiledManifest:this.compiled,typeIssues:this.typeIssues,cpOrigin:o.cpOrigin,port:m.port1,binding:b,releaseWorker:()=>{w.removeEventListener("error",g),w.terminate(),u?.resign()},nativeAuthorization:(v,_,k)=>this.nativeAuthorization(v,_,k)});try{w.postMessage([Qn,b,p,...l===null?[]:[l]],[m.port2])}catch{throw w.removeEventListener("error",g),w.terminate(),u?.resign(),m.port1.close(),m.port2.close(),A("unavailable","Application bootstrap unavailable","application_worker_binding")}return u?.lead({attach:(v,_)=>w.postMessage([Qn,b,"attach",_],[v]),detach:v=>w.postMessage([Qn,b,"detach",v])}),d(y)}).catch(i=>{let o=this.initialization===t;if(o&&(this.initialization=null),!this.closed&&o){let{problemDetail:s,...r}=this.snapshot,a=i instanceof se&&i.reason==="application_registration_refused"?Mo(i.details):null;this.snapshot=Object.freeze({...r,status:"blocked",problem:typeof i?.reason=="string"?i.reason:typeof i?.code=="string"?i.code:"application_entry_unavailable",...a?{problemDetail:Object.freeze({name:"MdbaseError",code:i.code,registration:a})}:{}}),this.notify()}throw i});this.initialization=t;{let{problemDetail:i,signOutResult:o,...s}=this.snapshot;this.snapshot=Object.freeze({...s,status:"starting",problem:null})}return this.notify(),t}async call(e){this.check();let t=await this.initialize();return this.check(),e(t)}started(e,t){this.choose();let i=e.getNativeSnapshot().status;return i==="not_started"||i==="starting"||i==="blocked"&&!e.getNativeSnapshot().signIn?e.queue(()=>e.start(t)):Promise.resolve()}reservePortal(e){this.check();let t=this.environment(),i=e.signal?AbortSignal.any([this.lifetime.signal,e.signal]):this.lifetime.signal,o=Qt(this.declaration.environment),s=()=>!this.closed,r=this.signIn?hx(t.cpOrigin,i,s,this.signIn,o):Xf(t.cpOrigin,i,s,o);return{portal:Jf(r),signal:i}}requestAccess(e,t){try{this.check();let i=this.runtime,o=i?.getNativeSnapshot(),s=o?.selectedCollectionId??null,r=Qf(this.compiled),a=()=>s&&i?eh(i.getNativeSnapshot(),s):[],p=gx(r,e,t,a()),l=s?i.connection(s):null;if(!i||!s||!l)throw A("invalid_request","requestAccess needs an open collection","access_no_collection");let c=()=>bx(l.files,r,a());if(!p.length)return Promise.resolve(c());let{portal:d,signal:u}=this.reservePortal(t);return wx({granted:c,native:()=>i.getNativeSnapshot(),start:()=>i.queue(()=>i.requestFileAccess(d,s,p,t.reason,{signal:u})),poll:f=>i.queue(()=>i.pollFileAccess(f))},d,u)}catch(i){return Promise.reject(i)}}approve(e,t={}){let i=this.choose(),o=i.getSnapshot(),s=this.approvalPortal;if(s&&o.approval){if((e===void 0?o.requested.collectionId:e)!==o.approval.collectionId)return Promise.reject(new Vt("application_selection_busy"));if(t.signal?.aborted)throw A("cancelled","Application entry fenced","application_entry_fenced");return s.closed||s.focus(),Promise.resolve()}return i.approve(e,t)}authorize(e={},t=null){let i;try{i=this.approvalPortal=this.reservePortal(e).portal}catch(o){return Promise.reject(o)}return this.call(async o=>(await this.started(o,e),o.queue(()=>o.authorizeReserved(i,e,t)))).catch(o=>{try{i.close()}catch{}throw o})}async signOut(e={}){let t=await this.call(async s=>(await this.started(s,e),s));this.signingOut=!0;try{await t.queue(()=>t.signOut(e))}finally{this.signingOut=!1}let i=t.getNativeSnapshot().signOutResult??null;await this.signedOut(t,i);let o=this.snapshot.signOutResult??i;return o&&await vT(o),this.getSnapshot()}async signedOut(e,t,i=!1){i||this.tabs?.signedOut(),this.clearPendingSave(),++this.incarnation,this.runtime===e&&(this.runtime=null),this.initialization=null,this.hint?.clear(),this.forgotten?.clear(),this.handledApproval=null;let o=null;if(this.privates)try{await this.privates.forgetAll(),o="erased"}catch{o="incomplete"}let s=t&&o?Object.freeze({...t,grants:o,...o==="incomplete"?{local:"incomplete"}:{}}):t;this.snapshot=Object.freeze({status:"signed_out",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:!s&&o==="incomplete"?"sign_out_failed":null,timing:null,readiness:jh,...s?{signOutResult:s}:{}});try{this.memory?.write(null)}catch{}if(this.selection&&!this.closed&&(this.selection.resync(),await this.selection.select(null,{history:"replace"}).catch(()=>{})),this.revision++,this.notify(),i){e.abandon();return}await e.close().catch(()=>{})}observeSignOut(e){let t=e.getNativeSnapshot().signOutResult;!t||this.signingOut||this.closed||this.runtime!==e||this.signedOut(e,t)}tabsFor(e){if(this.tabs)return this.tabs;let t=globalThis.navigator?.locks,i=globalThis.BroadcastChannel;return!t||typeof t.request!="function"||typeof i!="function"?null:(this.tabs=new ih({...e,build:Nh.url},{locks:t,BroadcastChannel:i},this.leaderLost,this.signedInElsewhere),this.tabs)}leaderLost=e=>{if(this.closed||this.hidden)return;let t=this.runtime,i=t!==null||this.initialization!==null;if(this.election?.abort(),this.election=null,e&&t&&!this.signingOut?this.signedOut(t,t.getNativeSnapshot().signOutResult??null,!0):e&&i&&(++this.incarnation,this.initialization=null),!i||e){this.tabs?.resign();return}++this.incarnation,this.initialization=null,this.runtime=null,t?.abandon();let{problemDetail:o,...s}=this.snapshot;this.snapshot=Object.freeze({...s,status:"starting",problem:null,selectedCollectionId:null,readiness:jh}),this.notify(),this.selection?.resync(),this.app.start().catch(()=>{})};signedInElsewhere=()=>{this.closed||this.hidden||this.signingOut||this.runtime!==null||this.initialization!==null||this.snapshot.status!=="signed_out"||(this.selection?.resync(),this.app.start().catch(()=>{}))};setForeground(e){this.foreground=e,this.runtime?.setForeground(e)}followVisibility(){let e=globalThis.document;if(!e||typeof e.addEventListener!="function")return;let t=()=>{this.closed||this.setForeground(e.visibilityState!=="hidden")},i=()=>{e.visibilityState!=="hidden"&&t()};e.addEventListener("visibilitychange",t,{signal:this.lifetime.signal});let o=typeof window>"u"?void 0:window;o&&typeof o.addEventListener=="function"&&(o.addEventListener("focus",i,{signal:this.lifetime.signal}),o.addEventListener("online",i,{signal:this.lifetime.signal})),t()}followPageLifecycle(){let e=typeof window>"u"?void 0:window;if(!e||typeof e.addEventListener!="function")return;e.addEventListener("pagehide",this.pageHidden,{signal:this.lifetime.signal}),e.addEventListener("pageshow",this.pageShown,{signal:this.lifetime.signal});let t=globalThis.document;t&&typeof t.addEventListener=="function"&&(t.addEventListener("freeze",()=>this.pageHidden(),{signal:this.lifetime.signal}),t.addEventListener("resume",()=>this.pageShown({persisted:!0}),{signal:this.lifetime.signal}))}pageHidden=()=>{if(this.closed||this.hidden)return;let e=this.runtime,t=e!==null||this.initialization!==null;++this.incarnation,this.hidden=Object.freeze({resume:t}),this.clearPendingSave(),this.initialization=null,this.runtime=null,this.election?.abort(),this.election=null,e?.abandon(),this.tabs?.release();let{problemDetail:i,...o}=this.snapshot;this.snapshot=Object.freeze({...o,status:t?"starting":this.snapshot.status,problem:null,selectedCollectionId:null,readiness:jh})};pageShown=e=>{let t=this.hidden;this.closed||!t||!e.persisted||(this.hidden=null,this.notify(),t.resume&&(this.selection?.resync(),this.app.start().catch(()=>{})))};awaitingOtherTab=!1;awaitOtherTab(e,t){let i=e.getNativeSnapshot(),o=globalThis.navigator?.locks;if(this.awaitingOtherTab||this.closed||i.status!=="blocked"||i.problem!=="open_in_another_tab"||!o)return;this.awaitingOtherTab=!0;let s=this.incarnation,r=this.lifetime.signal,a=()=>!this.closed&&!this.hidden&&s===this.incarnation&&this.runtime===e;VP(o,t,r).then(()=>mT(r)).then(()=>{this.awaitingOtherTab=!1,a()&&(this.selection?.resync(),this.app.start().catch(()=>{}))},()=>{this.awaitingOtherTab=!1})}close(){if(this.closing)return this.closing;if(this.closed=!0,this.lifetime.abort(),this.selection?.close(),this.election?.abort(),this.privates?.dispose(),this.opening&&(clearTimeout(this.opening.timer),this.opening=null),this.clearPendingSave(),this.syncing){try{this.syncing.stop()}catch{}this.syncing=null}return this.closing=Promise.resolve().then(async()=>{await this.initialization?.catch(()=>{}),await this.runtime?.close(),this.tabs?.release();{let{problemDetail:e,...t}=this.snapshot;this.snapshot=Object.freeze({...t,status:"closed",problem:null,selectedCollectionId:null})}this.runtime=null,this.notify(),this.listeners.clear(),this.nativeListeners.clear()}),this.closing}application(){return this.app}connection(e){return this.closed?null:this.privates?.connection(e)??this.runtime?.connection(e)??null}};ie();var bn=n=>n;function lI(n,e={}){return AT(new ol(n,e))}function AT(n){let e=n.application(),t=()=>bn(e.getSnapshot()),i=async o=>bn(await e.approve(null,o));return Object.freeze({getSnapshot:t,subscribe:o=>e.subscribe(o),start:async o=>bn(await e.start(o)),signIn:async o=>bn(await e.authorize(o)),addCollection:i,addPrivateCollection:i,approve:async(o,s)=>bn(await e.approve(o,s)),refreshCollectionList:async o=>{if(!e.refreshCollectionList)throw A("unavailable","Refreshing the collection list isn't available here.","application_not_yet_available");return bn(await e.refreshCollectionList(o))},reauthorize:async o=>bn(await e.reauthorize(o)),configure:async o=>bn(await e.configure(o)),select:async(o,s)=>bn(await e.select(o,s)),chooseAnother:async o=>bn(await e.chooseAnother(o)),forget:async(o,s)=>bn(await e.forget(o,s)),deleteCollection:async(o,s)=>bn(await e.deleteCollection(o,s)),requestAccess:(o,s)=>e.requestAccess(o,s),assess:o=>e.assess(o),setup:Object.freeze({plan:o=>e.setup.plan(o),async apply(o,s){try{return Object.freeze({outcome:"applied",snapshot:bn(await e.setup.apply(o,s))})}catch(r){if(oe(r,"conflict")&&r.reason==="setup_changed")return Object.freeze({outcome:"changed",snapshot:t()});if(oe(r,"outcome_unknown"))return Object.freeze({outcome:"unknown",snapshot:t()});throw r}}}),connection:o=>n.connection(o),setForeground:o=>e.setForeground(o),signOut:async o=>{if(!e.signOut)throw A("unavailable","Sign out isn't available here.","application_not_yet_available");return bn(await e.signOut(o))},close:()=>e.close(),application:e})}Ea();If();ie();function cI(n,e){let t=Zr(yr(n)).manifest.requirements.capabilities;if(t?.contract_version!==2)return null;if(!e.isCurrent())throw A("invalid_request","the application connection is not current","application_connection_fenced");let i=new Set(e.records.hello.grant.capabilities),o=new Set(t.required),s=Object.freeze([...new Set([...t.required,...t.optional??[]])].map(r=>Object.freeze({id:r,requirement:o.has(r)?"required":"optional",state:i.has(r)?"available":"missing"})));return Object.freeze({values:s,requiredAvailable:s.every(r=>r.requirement==="optional"||r.state==="available"),missing:Object.freeze(s.filter(r=>r.state==="missing").map(r=>r.id))})}Ps();var Zw={};ls(Zw,{APP_BASES_PROFILE:()=>Fm,APP_COLLECTION_SETUP_LIMITS:()=>wr,AppCloudCopyBootstrapError:()=>en,AppCloudCopyHostError:()=>co,AppCollectionControlError:()=>ti,AppCollectionJoinError:()=>lo,AppCollectionJoinLedger:()=>Xa,AppCollectionSetupError:()=>nn,AppCollectionSetupJournal:()=>Ba,AppCpAuthorityError:()=>Zn,AppCpCloudCopyBootstrap:()=>$a,AppCpDeviceRegistration:()=>sl,AppCpLogAuthority:()=>Da,AppCpPeopleAuthority:()=>ul,AppDeviceRegistrationError:()=>ts,AppHttpLogError:()=>mn,AppHttpLogTransport:()=>Ua,AppIndexedDbDeviceKeyProtectedStore:()=>cl,AppIndexedDbDeviceKeyProvider:()=>ll,AppIndexedDbNoiseProtectedStore:()=>dl,AppInstallationSignInError:()=>Xe,AppLogHostError:()=>pt,AppLogPump:()=>is,AppProtectedInstallationSignIn:()=>ja,AppReplicaOwnerError:()=>We,AppStrictDeviceApprovalError:()=>an,AppWasmRuntime:()=>fl,AppWebCloudCopyHost:()=>ml,AppWebCollectionError:()=>up,AppWebDeviceKeyCustody:()=>al,AppWebNoiseCustody:()=>pl,AppWebSignInSession:()=>Zh,UNSYNCED_STORAGE_WARNING:()=>kx,acquireAppInstallationLease:()=>Wc,acquireAppReplicaLease:()=>Kc,appBrowserDirectAccess:()=>Vh,appCollectionControlClient:()=>uh,appInstallationLockName:()=>Eb,appLocalConnector:()=>Ph,appLogHealth:()=>Bw,appModelPackPlan:()=>Ho,appModelResourcePlan:()=>xt,appMutationSaveState:()=>Ax,appReplicaLockName:()=>Uf,appSaveState:()=>rh,appStoragePolicy:()=>oh,attachAppLocalFacade:()=>Sh,createAppCollectionPeople:()=>ph,createAppWebCollectionAdapter:()=>TC,decodeAppBasesCell:()=>yo,decodeAppBasesDiscoveryResult:()=>td,decodeAppBasesResult:()=>Zp,decodeAppBasesSourceResult:()=>nd,decodeAppCollectionSetupIntent:()=>Et,encodeAppBasesDiscoveryRequest:()=>Qp,encodeAppBasesRequest:()=>Xp,encodeAppBasesSourceRequest:()=>ed,openAppWebCollectionClient:()=>Ch,openOwnedAppWorker:()=>KP,probeAppStorage:()=>AI,selectAppEnvironment:()=>Xn,verifyAppHandover:()=>dI});xh();Vm();function pI(n,e){return n.seq===e.seq&&n.chain===e.chain&&n.policyGeneration===e.policyGeneration&&n.catalogGeneration===e.catalogGeneration}async function dI(n,e){let t=null;try{let{runtime:i,localPort:o,localClient:s,hostedClient:r,source:a}=n,p=r.hello,l=s.hello,c=a.collection,d=a.deviceId,u=r.authenticatedDevice;if(!(P=>typeof P=="string"&&P.replace(/-/g,"").toLowerCase()===d.replace(/-/g,"").toLowerCase())(u))return null;let h=p.status.confirmedHead,m=h?Object.freeze({...h}):void 0;if(!m||!p.headWitness||p.headWitness.length>64*1024||m.seq===0||p.collection!==c||l.collection!==c)return null;t=new Uint8Array(p.headWitness);let b=t,w=()=>{try{return!e.aborted&&n.isCurrent()===!0&&a.isCurrent()===!0&&l.collection===c&&a.collection===c&&a.deviceId===d&&s.hello===l}catch{return!1}},g=()=>{try{let P=i.observations();return!P.requiresReopen&&!P.keyringRebuilding&&!P.keyringRebuildFailed&&P.status.mode==="synced"&&P.status.confirmedHead!==void 0&&P.status.confirmedHead.seq>=m.seq}catch{return!1}},y=()=>{if(!w()||!g())return!1;let P=i.verifyHandover(o,a,b);return P!==null&&pI(P,m)},v=()=>{try{return!e.aborted&&w()&&r.hello===p&&r.authenticatedDevice===u}catch{return!1}};if(!v()||!y())return null;let _=await s.appliedPrefix(m.seq,e);if(!v()||!y()||_.seq!==m.seq||_.appliedThrough<m.seq||_.chain!==m.chain)return null;let k=Object.freeze({...m}),S=!1,x={head:k,appliedThrough:_.appliedThrough,isCurrent:()=>{if(S)return!1;try{return y()&&pI(k,m)}catch{return!1}},dispose:()=>{S=!0,b.fill(0)}};return t=null,x}catch{return null}finally{t?.fill(0)}}bt();ge();var ts=class extends Error{constructor(t){super(`app device registration: ${t}`);this.reason=t;this.name="AppDeviceRegistrationError"}reason},wt=n=>new ts(n),Uh=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),sl=class{constructor(e,t,i,o,s={}){this.runtime=e;this.session=t;this.persistence=o;try{this.scope=Object.freeze({connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId,kind:t.kind});for(let a of[this.scope.connectorId,this.scope.deviceId,this.scope.installationId])if(U(a).every(p=>p===0))throw wt("binding");if(t.kind!=="mobile"&&t.kind!=="app-runtime")throw wt("binding");this.rawOrigin=t.cpOrigin;let r=new URL(this.rawOrigin);if(r.username||r.password||r.pathname!=="/"||r.search||r.hash||r.protocol!=="https:"&&!(s.allowLoopbackHttp===!0&&ot(this.rawOrigin))||(this.origin=r.origin,this.now=s.now??Date.now,this.fetchImpl=s.fetch??globalThis.fetch,!(i.envelope instanceof Uint8Array)||!i.envelope.length||i.envelope.length>1024)||!e.deviceCustodyCurrent(t,i)||(this.custody=Object.freeze({signPublicKey:new Uint8Array(i.signPublicKey),kemPublicKey:new Uint8Array(i.kemPublicKey),noisePublicKey:new Uint8Array(i.noisePublicKey),envelope:new Uint8Array(i.envelope)}),!this.current()))throw wt("binding")}catch{throw e.retireLog(),wt("binding")}}runtime;session;persistence;attempted=!1;lifetime=new AbortController;origin;rawOrigin;scope;custody;now;fetchImpl;current(){try{return!this.lifetime.signal.aborted&&this.runtime.deviceCustodyCurrent(this.session,this.custody)&&this.session.isCurrent()===!0&&this.session.cpOrigin===this.rawOrigin&&this.session.connectorId===this.scope.connectorId&&this.session.deviceId===this.scope.deviceId&&this.session.installationId===this.scope.installationId&&this.session.kind===this.scope.kind}catch{return!1}}check(e){if(!this.current()||e.aborted)throw this.close(),wt("fenced")}async json(e,t,i,o){this.check(o);let s=new AbortController,r=()=>s.abort(),a=setTimeout(r,15e3);a.unref?.(),o.addEventListener("abort",r,{once:!0}),this.lifetime.signal.addEventListener("abort",r,{once:!0});let p=new Uint8Array(32*1024),l=0,c=null,d=null;try{let u=this.fetchImpl;if(c=await u(`${this.origin}${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,...i===void 0?{}:{"content-type":"application/json"}},body:i,signal:s.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(o),s.signal.aborted||!c.ok)throw wt("unavailable");let f=c.headers.get("content-length");if(f!==null&&/^(0|[1-9][0-9]*)$/.test(f)&&Number(f)>p.length)throw s.abort(),wt("response");if(!c.body)throw wt("response");for(d=c.body.getReader();;){let{done:m,value:b}=await d.read();try{if(this.check(o),s.signal.aborted)throw wt("unavailable");if(m)break;if(l+b.length>p.length)throw s.abort(),wt("response");p.set(b,l),l+=b.length}finally{b?.fill(0)}}let h=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(p.subarray(0,l)));if(!h||typeof h!="object"||Array.isArray(h))throw wt("response");return h}catch(u){throw this.check(o),u instanceof ts?u:wt("unavailable")}finally{p.fill(0),(d?.cancel()??c?.body?.cancel())?.catch(()=>{}),d?.releaseLock(),clearTimeout(a),o.removeEventListener("abort",r),this.lifetime.signal.removeEventListener("abort",r)}}async register(e){let t=null,i=null;try{if(this.check(e.signal),this.attempted)throw wt("fenced");this.attempted=!0,await this.persistence.pending(new Uint8Array(this.custody.envelope),e),this.check(e.signal);let o=await this.session.connectorBearer(e);if(this.check(e.signal),typeof o!="string"||!o||o.length>16*1024||/[^\x21-\x7e]/.test(o))throw wt("binding");let s=await this.json("/v1/next/devices/challenge",o,void 0,e.signal);if(this.check(e.signal),typeof s.challenge!="string"||!/^[0-9a-f]{64}$/.test(s.challenge)||typeof s.expires_at!="number"||!Number.isSafeInteger(s.expires_at)||s.expires_at-this.now()<=5e3||s.expires_at-this.now()>16*6e4)throw wt("response");t=Uint8Array.from(s.challenge.match(/../g).map(l=>parseInt(l,16)));let r=this.runtime.signCpEnrol(t);this.check(e.signal),i=r.signature;let a=await this.json("/v1/next/devices",o,JSON.stringify({device_id:this.scope.deviceId,kind:this.scope.kind,capabilities:["collection_mode_switch_v1"],challenge:s.challenge,sign_pk:Uh(r.signPublicKey),kem_pk:Uh(r.kemPublicKey),noise_pk:Uh(r.noisePublicKey),sig:Uh(i)}),e.signal);if(this.check(e.signal),a.device_id!==this.scope.deviceId)throw wt("response");let p=Object.freeze({connectorId:this.scope.connectorId,deviceId:this.scope.deviceId,installationId:this.scope.installationId,signPublicKey:new Uint8Array(r.signPublicKey),kemPublicKey:new Uint8Array(r.kemPublicKey),noisePublicKey:new Uint8Array(r.noisePublicKey)});return await this.persistence.registered(p,e),this.check(e.signal),this.runtime.acknowledgeDeviceRegistration(p),p}catch(o){throw this.close(),o instanceof ts?o:wt("unavailable")}finally{t?.fill(0),i?.fill(0)}}close(){this.lifetime.signal.aborted||(this.lifetime.abort(),this.custody.envelope.fill(0),this.runtime.retireLog())}};Je();ge();var Wt=()=>new Error("app device key custody unavailable; preserve storage and reopen"),al=class{constructor(e,t,i){this.pin=e;this.key=t;this.store=i;try{this.scope=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId}),this.current=e.isCurrent,this.owned=e.installationOwned;let o=[this.scope.accountId,this.scope.connectorId,this.scope.deviceId,this.scope.installationId].map(U);if(o.some(s=>s.every(r=>r===0))||t.type!=="secret"||t.extractable||t.algorithm.name!=="AES-GCM"||t.algorithm.length!==256||!t.usages.includes("encrypt")||!t.usages.includes("decrypt"))throw Wt();this.namespace=`mdbase.app-device-keys.v1:${o.map(s=>Array.from(s,r=>r.toString(16).padStart(2,"0")).join("")).join(":")}`,this.aad=pe(["mdbase/v1/app-device-keys-platform",...o]),this.check(new AbortController().signal)}catch{throw Wt()}}pin;key;store;scope;namespace;aad;current;owned;attempted=!1;check(e){try{if(e.aborted||this.pin.isCurrent!==this.current||this.pin.installationOwned!==this.owned||this.current.call(this.pin)!==!0||this.owned.call(this.pin)!==!0||this.pin.accountId!==this.scope.accountId||this.pin.connectorId!==this.scope.connectorId||this.pin.deviceId!==this.scope.deviceId||this.pin.installationId!==this.scope.installationId)throw Wt()}catch{throw Wt()}}async openNativeDevice(e,t){let i=null,o=null,s=!1;try{if(this.attempted)throw Wt();this.attempted=!0;let r=t.signal,a=t.mode;if(this.check(r),!["fresh","existing"].includes(a)||t.noise.mode!==a||t.noise.mode==="existing"&&!(t.noise.envelope instanceof Uint8Array))throw Wt();let p=t.noise.mode==="fresh"?{mode:"fresh"}:{mode:"existing",envelope:new Uint8Array(t.noise.envelope)};if(p.mode==="existing"&&(!p.envelope.length||p.envelope.length>1024))throw Wt();let l=await this.store.read(this.namespace,{signal:r});if(this.check(r),a==="fresh"){if(l!==null)throw Wt();i=globalThis.crypto.getRandomValues(new Uint8Array(64));let u=globalThis.crypto.getRandomValues(new Uint8Array(12)),f=new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:u,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,i));if(this.check(r),o=pe(new Map([[0,1],[1,u],[2,f]])),await this.store.create(this.namespace,o,{signal:r})!==!0)throw Wt();this.check(r)}else{if(!(l instanceof Uint8Array)||l.length===0||l.length>256)throw Wt();o=new Uint8Array(l);let u=ue(o);if(!(u instanceof Map))throw Wt();let f=u;if(f.size!==3||f.get(0)!==1)throw Wt();let h=f.get(1),m=f.get(2);if(!(h instanceof Uint8Array)||h.length!==12||!(m instanceof Uint8Array)||m.length!==80||(i=new Uint8Array(await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(h),additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(m))),this.check(r),i.length!==64))throw Wt()}this.check(r);let c=Object.freeze({connectorId:this.scope.connectorId,deviceId:this.scope.deviceId,installationId:this.scope.installationId,isCurrent:()=>{try{return this.check(r),!0}catch{return!1}}});s=!0;let d=e.openDeviceConsuming({pin:c,signSecretKey:i.subarray(0,32),kemSecretKey:i.subarray(32),opened:p});return this.check(r),d}catch{if(s)try{e.retireLog()}catch{}throw Wt()}finally{i?.fill(0),o?.fill(0)}}};Jn();ge();var Dh="device-key-kek",uI="original-device-kek",vt=()=>new Error("app device key provider unavailable; preserve storage and reopen");function $h(n){if(typeof globalThis.CryptoKey!="function"||!(n instanceof CryptoKey)||n.type!=="secret"||n.extractable||n.algorithm.name!=="AES-GCM"||n.algorithm.length!==256||n.usages.length!==2||!n.usages.includes("encrypt")||!n.usages.includes("decrypt"))throw vt();return n}function kT(n){if(n===void 0)return null;if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).length!==2||!Object.hasOwn(n,"version")||!Object.hasOwn(n,"key")||n.version!==1)throw vt();return $h(n.key)}var ll=class n{constructor(e,t,i){this.source=e;this.origin=t;this.lifetime=i;this.scope=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId}),this.current=e.isCurrent,this.owned=e.installationOwned}source;origin;lifetime;db=null;value=null;closed=!1;loaned=!1;scope;current;owned;static async open(e){let t=null;try{let{source:i,origin:o,mode:s,signal:r}=e;t=new n(i,o,r);let a=Object.values(t.scope).map(u=>{let f=U(u);if(f.every(h=>h===0))throw vt();return Array.from(f,h=>h.toString(16).padStart(2,"0")).join("")});if(!Lt(o,e.allowLoopbackHttp===!0,e.allowNativeLoopbackHttp===!0?"native":void 0)||!["fresh","existing"].includes(s)||!globalThis.indexedDB||!globalThis.crypto?.subtle||typeof globalThis.CryptoKey!="function")throw vt();t.check(r);let p=crypto.subtle.generateKey.bind(crypto.subtle),l=`mdbase.app.device-key-kek.v1.${a.join(".")}`,c=await t.openDatabase(l,s);t.db=c,c.onversionchange=()=>t.close(),t.check(r);let d=await t.transaction("readonly",r,null);if(t.check(r),s==="existing"){if(d===null||typeof d=="boolean")throw vt();t.value=d}else{if(d!==null)throw vt();let u=$h(await p({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]));if(t.check(r),await t.transaction("readwrite",r,u)!==!0)throw vt();t.check(r),t.value=u}return t.check(r),t}catch{throw t?.close(),vt()}}check(e){try{if(this.closed||this.lifetime.aborted||e.aborted||Rt()!==this.origin||this.source.isCurrent!==this.current||this.source.installationOwned!==this.owned||this.current.call(this.source)!==!0||this.owned.call(this.source)!==!0||Object.entries(this.scope).some(([t,i])=>this.source[t]!==i))throw vt()}catch{throw vt()}}openDatabase(e,t){return new Promise((i,o)=>{this.check(this.lifetime);let s=indexedDB.open(e,1),r=!1,a=!1,p=()=>{r=!0,o(vt())};this.lifetime.addEventListener("abort",p,{once:!0});let l=()=>this.lifetime.removeEventListener("abort",p);s.onblocked=p,s.onupgradeneeded=()=>{try{if(this.check(this.lifetime),r||t!=="fresh"||s.result.objectStoreNames.length!==0)throw vt();s.result.createObjectStore(Dh),a=!0}catch{s.transaction?.abort()}},s.onerror=()=>{l(),o(vt())},s.onsuccess=()=>{l();try{if(this.check(this.lifetime),r||t==="fresh"&&!a||s.result.objectStoreNames.length!==1||!s.result.objectStoreNames.contains(Dh))throw vt();i(s.result)}catch{s.result.close(),o(vt())}}})}transaction(e,t,i){return new Promise((o,s)=>{if(this.check(t),!this.db)throw vt();let r=this.db.transaction(Dh,e,{durability:"strict"}),a=r.objectStore(Dh),p=null,l=!1,c=()=>{l=!0;try{r.abort()}catch{}};t.addEventListener("abort",c,{once:!0}),this.lifetime.addEventListener("abort",c,{once:!0});let d=()=>{t.removeEventListener("abort",c),this.lifetime.removeEventListener("abort",c)};r.onerror=r.onabort=()=>{d(),p=null,s(vt())},r.oncomplete=()=>{d();try{if(this.check(t),l)throw vt();o(p)}catch{p=null,s(vt())}};let u=a.get(uI);u.onsuccess=()=>{try{this.check(t);let f=kT(u.result);e==="readonly"?p=f:(p=f===null,p===!0&&i!==null&&a.add({version:1,key:$h(i)},uI))}catch{c()}}})}deviceCustodyKek(e){if(this.check(e.signal),this.loaned||!this.value)throw vt();return this.loaned=!0,$h(this.value)}close(){this.closed||(this.closed=!0,this.value=null,this.db?.close(),this.db=null)}};Jn();ge();var zh="original-device-keys",fI="custody",ST=256,sn=()=>new Error("app device key custody store unavailable");function hI(n){if(!(n instanceof Uint8Array)||!n.length||n.length>ST)throw sn();return new Uint8Array(n)}var cl=class n{constructor(e,t,i,o,s){this.db=e;this.source=t;this.scope=i;this.namespace=o;this.origin=s;this.current=t.isCurrent,this.owned=t.installationOwned,e.onversionchange=()=>this.close()}db;source;scope;namespace;origin;closed=!1;current;owned;static async open(e){try{return await this.openChecked(e)}catch{throw sn()}}static async openChecked(e){let{source:t,signal:i,mode:o,origin:s}=e,r=Object.freeze({accountId:t.accountId,connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId}),a=t.isCurrent,p=t.installationOwned,l=()=>{try{return!i.aborted&&t.isCurrent===a&&t.installationOwned===p&&a.call(t)===!0&&p.call(t)===!0&&Object.keys(r).every(m=>t[m]===r[m])}catch{return!1}},c=[r.accountId,r.connectorId,r.deviceId,r.installationId].map(m=>{let b=U(m);if(b.every(w=>w===0))throw sn();return Array.from(b,w=>w.toString(16).padStart(2,"0")).join("")});if(!Lt(s,e.allowLoopbackHttp===!0,e.allowNativeLoopbackHttp===!0?"native":void 0)||Rt()!==s||!["fresh","existing"].includes(o)||!l()||!globalThis.indexedDB)throw sn();let d=`mdbase.app-device-keys.v1:${c.join(":")}`,u=`mdbase.app.device-keys.v1.${c.join(".")}`,f=await new Promise((m,b)=>{let w=indexedDB.open(u,1),g=!1,y=()=>{g=!0,b(sn())};i.addEventListener("abort",y,{once:!0});let v=()=>i.removeEventListener("abort",y);w.onblocked=y,w.onupgradeneeded=()=>{if(g||o!=="fresh"||!l()||w.result.objectStoreNames.length!==0){w.transaction?.abort();return}w.result.createObjectStore(zh)},w.onerror=()=>{v(),b(sn())},w.onsuccess=()=>{if(v(),g||!l()||w.result.objectStoreNames.length!==1||!w.result.objectStoreNames.contains(zh)){w.result.close(),b(sn());return}m(w.result)}}),h=new n(f,t,r,d,s);try{h.check(i);let m=await h.read(d,{signal:i});try{if(o==="fresh"!=(m===null))throw sn();return h.check(i),h}finally{m?.fill(0)}}catch{throw h.close(),sn()}}check(e,t=this.namespace){try{if(this.closed||e.aborted||t!==this.namespace||Rt()!==this.origin||this.source.isCurrent!==this.current||this.source.installationOwned!==this.owned||this.current.call(this.source)!==!0||this.owned.call(this.source)!==!0||Object.keys(this.scope).some(i=>this.source[i]!==this.scope[i]))throw sn()}catch{throw sn()}}async read(e,t){let i=await this.transaction("readonly",e,t.signal,null);try{return this.check(t.signal,e),i}catch{throw i instanceof Uint8Array&&i.fill(0),sn()}}async create(e,t,i){this.check(i.signal,e);let o=hI(t);try{let s=await this.transaction("readwrite",e,i.signal,o);return this.check(i.signal,e),s===!0}finally{o.fill(0)}}transaction(e,t,i,o){return new Promise((s,r)=>{this.check(i,t);let a=this.db.transaction(zh,e,{durability:"strict"}),p=a.objectStore(zh),l=null,c=!1,d=()=>{c=!0;try{a.abort()}catch{}},u=()=>i.removeEventListener("abort",d);i.addEventListener("abort",d,{once:!0}),a.onabort=a.onerror=()=>{u(),l instanceof Uint8Array&&l.fill(0),r(sn())},a.oncomplete=()=>{u();try{if(this.check(i,t),c)throw sn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),r(sn())}};let f=p.get(fI);f.onsuccess=()=>{let h=null;try{this.check(i,t),h=f.result===void 0?null:hI(f.result),e==="readonly"?(l=h,h=null):(l=h===null,l===!0&&o!==null&&p.add(new Uint8Array(o),fI))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db.close())}};Je();ge();var Me=()=>new Error("app Noise custody unavailable; preserve storage and reopen"),gp=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),pl=class{constructor(e,t,i){this.pin=e;this.key=t;this.store=i;try{this.scope=Object.freeze({connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId});let o=[this.scope.connectorId,this.scope.deviceId,this.scope.installationId].map(U);if(o.some(s=>s.every(r=>r===0))||t.type!=="secret"||t.extractable||t.algorithm.name!=="AES-GCM"||t.algorithm.length!==256||!t.usages.includes("encrypt")||!t.usages.includes("decrypt"))throw Me();this.namespace=`mdbase.app-noise.v1:${this.scope.connectorId}:${this.scope.deviceId}:${this.scope.installationId}`,this.aad=pe(["mdbase/v1/app-noise-platform",...o]),this.check(new AbortController().signal)}catch{throw Me()}}pin;key;store;scope;namespace;aad;check(e){try{if(e.aborted||this.pin.isCurrent()!==!0||this.pin.connectorId!==this.scope.connectorId||this.pin.deviceId!==this.scope.deviceId||this.pin.installationId!==this.scope.installationId)throw Me()}catch{throw Me()}}receiptValue(e){if(e.connectorId!==this.scope.connectorId||e.deviceId!==this.scope.deviceId||e.installationId!==this.scope.installationId)throw Me();let t=[e.signPublicKey,e.kemPublicKey,e.noisePublicKey];if(t.some(i=>!(i instanceof Uint8Array)||i.length!==32||i.every(o=>o===0)))throw Me();return t.map(i=>new Uint8Array(i))}receipt(e){if(e===null)return null;if(!Array.isArray(e)||e.length!==3||e.some(t=>!(t instanceof Uint8Array)||t.length!==32||t.every(i=>i===0)))throw Me();return Object.freeze({...this.scope,signPublicKey:new Uint8Array(e[0]),kemPublicKey:new Uint8Array(e[1]),noisePublicKey:new Uint8Array(e[2])})}markerValue(e){let t=U(e.collection);if(t.every(i=>i===0)||typeof e.acknowledged!="boolean"||!(e.sasCommitment instanceof Uint8Array)||e.sasCommitment.length!==32||e.sasCommitment.every(i=>i===0))throw Me();return[t,...this.receiptValue(e),new Uint8Array(e.sasCommitment),e.acknowledged]}marker(e,t){if(e===null)return null;if(!t||!Array.isArray(e)||e.length!==6||!(e[0]instanceof Uint8Array)||e[0].length!==16||e[0].every(r=>r===0)||typeof e[5]!="boolean")throw Me();let i=this.receipt(e.slice(1,4));for(let r of["signPublicKey","kemPublicKey","noisePublicKey"])if(!gp(i[r],t[r]))throw Me();let o=e[4];if(!(o instanceof Uint8Array)||o.length!==32||o.every(r=>r===0))throw Me();let s=Array.from(e[0],r=>r.toString(16).padStart(2,"0")).join("");return Object.freeze({...i,collection:`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`,sasCommitment:new Uint8Array(o),acknowledged:e[5]})}async restore(e){let t=await this.read(e);return this.check(e.signal),t?.value??null}async read(e){let t=null,i=null;try{this.check(e.signal);let o=await this.store.read(this.namespace,e);if(this.check(e.signal),o===null)return null;if(!(o instanceof Uint8Array)||o.length===0||o.length>4096)throw Me();t=new Uint8Array(o);let s=ue(t);if(!(s instanceof Map))throw Me();let r=s,a=r.get(1),p=r.get(2);if(r.size!==3||r.get(0)!==1||!(a instanceof Uint8Array)||a.length!==12||!(p instanceof Uint8Array)||p.length<16||p.length>2064||(i=new Uint8Array(await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(a),additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(p))),this.check(e.signal),i.length>2048))throw Me();let l=ue(i);if(!(l instanceof Map))throw Me();let c=l,d=c.get(1);if(!(c.get(0)===1&&c.size===3||c.get(0)===2&&c.size===4&&c.has(3))||!(d instanceof Uint8Array)||d.length===0||d.length>1024||!c.has(2))throw Me();let u=this.receipt(c.get(2)),f=c.get(0)===2?this.marker(c.get(3),u):null;return{value:Object.freeze({envelope:new Uint8Array(d),receipt:u,privateEnrolMarker:f}),encrypted:new Uint8Array(t)}}catch{throw Me()}finally{t?.fill(0),i?.fill(0)}}async write(e,t,i,o,s=null){let r=null,a=null;try{if(this.check(o.signal),!(e instanceof Uint8Array)||!e.length||e.length>1024)throw Me();let p=new Map([[0,s===null?1:2],[1,new Uint8Array(e)],[2,t===null?null:this.receiptValue(t)]]);if(s!==null){let u=this.markerValue(s);this.marker(u,t),p.set(3,u)}if(r=pe(p),r.length>2048)throw Me();let l=globalThis.crypto.getRandomValues(new Uint8Array(12)),c=new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:l,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(r)));this.check(o.signal),a=pe(new Map([[0,1],[1,l],[2,c]]));let d=await this.store.compareAndSet(this.namespace,i,a,o);if(this.check(o.signal),d!==!0)throw Me()}catch{throw Me()}finally{r?.fill(0),a?.fill(0)}}async pending(e,t){let i=await this.read(t);if(this.check(t.signal),i){if(!gp(i.value.envelope,e))throw Me();return}await this.write(e,null,null,t),this.check(t.signal)}async privateEnrolPending(e,t){try{if(e.acknowledged!==!1)throw Me();await this.writePrivateMarker(e,!1,t)}catch{throw Me()}}async privateEnrolAcknowledged(e,t){try{await this.writePrivateMarker(e,!0,t)}catch{throw Me()}}async writePrivateMarker(e,t,i){this.check(i.signal);let o=this.marker(this.markerValue(e),e),s=await this.read(i);if(this.check(i.signal),!s?.value.receipt)throw Me();for(let a of["signPublicKey","kemPublicKey","noisePublicKey"])if(!gp(o[a],s.value.receipt[a]))throw Me();let r=s.value.privateEnrolMarker;if(r){if(r.collection!==o.collection||!gp(r.sasCommitment,o.sasCommitment))throw Me();if(r.acknowledged){if(!t)throw Me();return}if(!t)return}else if(t)throw Me();await this.write(s.value.envelope,s.value.receipt,s.encrypted,i,Object.freeze({...o,acknowledged:t})),this.check(i.signal)}async registered(e,t){let i=await this.read(t);if(this.check(t.signal),!i)throw Me();if(i.value.receipt){for(let o of["signPublicKey","kemPublicKey","noisePublicKey"])if(!gp(i.value.receipt[o],e[o]))throw Me();this.receiptValue(e);return}await this.write(i.value.envelope,e,i.encrypted,t),this.check(t.signal)}};Jn();ge();var Bh="opaque-noise",mI="custody",PT=4096,wn=()=>new Error("app noise custody store unavailable");function Dw(n){if(!(n instanceof Uint8Array)||n.byteLength<1||n.byteLength>PT)throw wn();return new Uint8Array(n)}function xT(n,e){return n===null||e===null?n===e:n.length===e.length&&n.every((t,i)=>t===e[i])}function $w(n){if(U(n).every(t=>t===0))throw wn();return n.toLowerCase()}function zw(n,e){try{return n.isCurrent()===!0&&n.connectorId===e[0]&&n.deviceId===e[1]&&n.installationId===e[2]}catch{return!1}}var dl=class n{constructor(e,t,i,o){this.db=e;this.source=t;this.pins=i;this.origin=o;e.onversionchange=()=>this.close()}db;source;pins;origin;closed=!1;static async open(e){try{return await this.openChecked(e)}catch{throw wn()}}static async openChecked(e){let{source:t,signal:i}=e,o=[t.connectorId,t.deviceId,t.installationId];if(!Lt(e.origin,e.allowLoopbackHttp===!0,e.allowNativeLoopbackHttp===!0?"native":void 0)||Rt()!==e.origin||!["fresh","existing"].includes(e.mode)||i.aborted||!zw(t,o)||typeof globalThis.indexedDB>"u")throw wn();let s=`mdbase.app.noise.v1.${$w(o[2])}.${$w(o[0])}.${$w(o[1])}`,r=await new Promise((p,l)=>{let c=indexedDB.open(s,1),d=!1,u=()=>{d=!0,l(wn())};i.addEventListener("abort",u,{once:!0});let f=()=>i.removeEventListener("abort",u);c.onblocked=u,c.onupgradeneeded=()=>{if(d||i.aborted||e.mode!=="fresh"||!zw(t,o)||c.result.objectStoreNames.length!==0){c.transaction?.abort();return}c.result.createObjectStore(Bh)},c.onerror=()=>{f(),l(wn())},c.onsuccess=()=>{if(f(),d||i.aborted||c.result.objectStoreNames.length!==1||!c.result.objectStoreNames.contains(Bh)){c.result.close(),l(wn());return}p(c.result)}}),a=new n(r,t,o,e.origin);try{let p=await a.read(a.namespace,{signal:i});if(e.mode==="fresh"!=(p===null))throw wn();return p?.fill(0),a.check(i),a}catch{throw a.close(),wn()}}get namespace(){return`mdbase.app-noise.v1:${this.pins[0]}:${this.pins[1]}:${this.pins[2]}`}check(e,t=this.namespace){if(this.closed||e.aborted||t!==this.namespace||Rt()!==this.origin||!zw(this.source,this.pins))throw wn()}async read(e,t){this.check(t.signal,e);let i=await this.transaction("readonly",t.signal,null,null);try{return this.check(t.signal),i}catch{throw i instanceof Uint8Array&&i.fill(0),wn()}}async compareAndSet(e,t,i,o){this.check(o.signal,e);let s=null,r=null;try{s=t===null?null:Dw(t),r=Dw(i);let a=await this.transaction("readwrite",o.signal,s,r);return this.check(o.signal),a===!0}finally{s?.fill(0),r?.fill(0)}}transaction(e,t,i,o){return new Promise((s,r)=>{this.check(t);let a=this.db.transaction(Bh,e,{durability:"strict"}),p=a.objectStore(Bh),l=null,c=!1,d=()=>{c=!0;try{a.abort()}catch{}},u=()=>t.removeEventListener("abort",d);t.addEventListener("abort",d,{once:!0}),a.onabort=a.onerror=()=>{u(),l instanceof Uint8Array&&l.fill(0),r(wn())},a.oncomplete=()=>{u();try{if(this.check(t),c)throw wn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),r(wn())}};let f=p.get(mI);f.onsuccess=()=>{let h=null;try{this.check(t),h=f.result===void 0?null:Dw(f.result),e==="readonly"?(l=h,h=null):(l=xT(h,i),l===!0&&o!==null&&p.put(new Uint8Array(o),mI))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db.close())}};Qc();Zc();bt();ge();ie();var ki=()=>A("unavailable","people metadata is unavailable","people_response");function yI(n){if(!n||typeof n!="object"||Array.isArray(n))throw ki();return n}function gI(n){if(typeof n=="number"&&!Number.isSafeInteger(n))throw ki();let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw ki();return e}var ul=class{constructor(e,t={}){this.session=e;this.rawOrigin=e.cpOrigin;let i=new URL(this.rawOrigin);if(i.username||i.password||i.pathname!=="/"||i.search||i.hash||i.protocol!=="https:"&&!(t.allowLoopbackHttp===!0&&ot(e.cpOrigin)))throw A("invalid_request","invalid people CP origin","people_binding");this.cpOrigin=i.origin,this.collection=e.collection,this.connector=e.connectorId,this.device=e.deviceId,this.ep=gI(e.endpoint);for(let o of[this.collection,this.connector,this.device])if(U(o).every(s=>s===0))throw A("invalid_request","nil people binding","people_binding");if(this.fetchImpl=t.fetch??globalThis.fetch,!this.isCurrent())throw A("unauthenticated","people scope is not current","people_fenced")}session;cpOrigin;rawOrigin;collection;connector;device;ep;fetchImpl;lifetime=new AbortController;isCurrent(){try{return!this.lifetime.signal.aborted&&this.session.isCurrent()===!0&&this.session.cpOrigin===this.rawOrigin&&this.session.collection===this.collection&&this.session.connectorId===this.connector&&this.session.deviceId===this.device&&gI(this.session.endpoint)===this.ep}catch{return!1}}check(e){if(e?.throwIfAborted(),!this.isCurrent())throw A("unauthenticated","people scope changed","people_fenced")}async request(e,t={}){if(e!=="identity"&&e!=="members")throw A("invalid_request","invalid people resource");this.check(t.signal);let i=new AbortController,o=()=>i.abort();t.signal?.addEventListener("abort",o,{once:!0}),this.lifetime.signal.addEventListener("abort",o,{once:!0});let s=setTimeout(o,15e3);s.unref?.();let r=new Uint8Array(1024*1024),a=0,p,l;try{let c=await this.session.connectorBearer({signal:i.signal});if(this.check(t.signal),i.signal.aborted)throw ki();if(typeof c!="string"||!/^(idev_|ct_)/.test(c)||c.length>16*1024||/[^\x21-\x7e]/.test(c))throw A("unauthenticated","invalid people credential","people_binding");let d=this.fetchImpl;if(p=await d(`${this.cpOrigin}/v1/authorities/${this.collection}/${e}?device_id=${this.device}`,{method:"GET",headers:{authorization:`Bearer ${c}`},signal:i.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(t.signal),i.signal.aborted)throw ki();let u=p.headers.get("content-length");if(u!==null&&/^(0|[1-9][0-9]*)$/.test(u)&&Number(u)>r.length||!p.body)throw ki();for(l=p.body.getReader();;){let{done:h,value:m}=await l.read();try{if(this.check(t.signal),i.signal.aborted)throw ki();if(h)break;if(a+m.length>r.length)throw ki();r.set(m,a),a+=m.length}finally{m?.fill(0)}}let f=yI(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r.subarray(0,a))));if(this.check(t.signal),p.status===401)throw A("unauthenticated","people credential is no longer current","people_fenced");if(p.status===403){let h=yI(f.error);throw A("forbidden","people access was refused",e==="members"&&h.code==="people_permission_declined"?"people_permission_declined":"people_access")}if(p.status===404)throw A("upgrade_required","people metadata is unsupported","people_unsupported");if(!p.ok)throw ki();return f}catch(c){throw this.check(t.signal),c instanceof se?c:ki()}finally{i.abort(),r.fill(0),(l?.cancel()??p?.body?.cancel())?.catch(()=>{}),l?.releaseLock(),clearTimeout(s),t.signal?.removeEventListener("abort",o),this.lifetime.signal.removeEventListener("abort",o)}}close(){this.lifetime.abort()}};Xc();Je();ge();ie();At();Cr();Je();ge();Fn();var bI=16*1024*1024,CT=9*1024*1024,IT=64,OT=64*1024*1024,RT=new Set(["append","read","head","subscribe","unsubscribe","put_object","get_object","has_objects","put_snapshot","get_snapshot","endorse_snapshot","stream_join","stream_leave","stream_send"]),pt=class extends Error{constructor(t){super(`app log host: ${t}`);this.reason=t;this.name="AppLogHostError"}reason};function ns(n){if((typeof n!="number"||!Number.isSafeInteger(n))&&typeof n!="bigint")throw new pt("invalid_call");let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw new pt("invalid_call");return e}function Fh(n,e){return n.length===e.length&&n.every((t,i)=>t===e[i])}var ET=new Set(["read","head","subscribe","get_object","has_objects","put_object","get_snapshot"]),qT=6;function wI(n){try{return n.server}catch{return null}}function TT(n){try{return n.reason}catch{return null}}function Bw(n,e=globalThis.navigator?.onLine){let t=wI(n);if(kn(t)){let i=t.retryAfterMs;return t.status===429?{kind:"rate_limited",retryAfterMs:i}:t.status>=500?{kind:"server_busy",retryAfterMs:i}:t.status===401||t.status===403?{kind:"auth"}:null}return TT(n)!=="unavailable"?null:e===!1?{kind:"offline"}:{kind:"unreachable"}}var is=class{constructor(e,t,i){this.runtime=e;this.transport=t;try{if(this.endpoint=ns(i.endpoint),this.collection=U(i.collection),ns(t.endpoint)!==this.endpoint||!Fh(U(t.collection),this.collection))throw new Error}catch{throw new pt("invalid_binding")}if(this.rounds=i.maxRounds??64,!Number.isSafeInteger(this.rounds)||this.rounds<1||this.rounds>64)throw new RangeError("invalid app log pump rounds")}runtime;transport;abort=new AbortController;endpoint;collection;rounds;work=null;closed=!1;failed=!1;retired=!1;problem=null;terminal=null;health=null;sent=0;readAfter=[-1n,-1n];readAdvances=0;get fenced(){return this.failed}get callsSent(){return this.sent}get readProgress(){return this.readAdvances}responseProgress(){return this.transport.responseProgress?.()??[]}get serverProblem(){return this.problem}get terminalProblem(){return this.terminal}get transportHealth(){return this.health}current(){if(this.closed||this.failed)return!1;if(ns(this.transport.endpoint)!==this.endpoint||!Fh(U(this.transport.collection),this.collection))throw new pt("invalid_binding");return this.transport.isCurrent()===!0?!0:(this.retire(),!1)}retire(){if(this.closed=!0,this.abort.abort(),!this.retired){this.retired=!0;try{this.runtime.retireLog()}catch{throw this.failed=!0,new pt("fenced")}}}capture(e){if(!Array.isArray(e)||e.length>IT)throw new pt("invalid_call");let t=0,i=new Set,o=[];try{for(let s of e){if(ns(s.endpoint)!==this.endpoint||!(s.frame instanceof Uint8Array)||s.frame.length>bI||s.sidecar!==void 0&&(!(s.sidecar instanceof Uint8Array)||s.sidecar.length>CT))throw new pt("invalid_call");if(t+=s.frame.length+(s.sidecar?.length??0),t>OT)throw new pt("invalid_call");let r=ue(s.frame);if(!(r instanceof Map))throw new pt("invalid_call");let a=r;if(a.size!==4||a.get(0)!==0||!RT.has(a.get(2)))throw new pt("invalid_call");let p=ns(a.get(1));if(i.has(p))throw new pt("invalid_call");i.add(p);let l=a.get(3),c=l instanceof Map?l.get(0):void 0;if(!(c instanceof Uint8Array)||!Fh(c,this.collection)||s.sidecar!==void 0&&a.get(2)!=="put_object")throw new pt("invalid_call");if(s.sidecar!==void 0){let u=l,f=u.get(4);if(s.sidecar.length<=1024*1024||ns(u.get(3))!==BigInt(s.sidecar.length)||u.has(5)||!(f instanceof Uint8Array)||!Fh(f,it(s.sidecar)))throw new pt("invalid_call")}let d=a.get(2)==="read"?{after:ns(l.get(1)),control:l.get(3)===1}:void 0;o.push({id:p,method:a.get(2),...d?{read:d}:{},call:{endpoint:this.endpoint,frame:s.frame.slice(),...s.sidecar?{sidecar:s.sidecar.slice()}:{}}})}return o}catch{for(let s of o)this.wipe(s);throw new pt("invalid_call")}}wipe(e){e.call.frame.fill(0),e.call.sidecar?.fill(0)}pump(){return this.work?this.work:this.failed?Promise.reject(new pt("fenced")):this.closed?Promise.resolve({quiet:!0}):(this.work=Promise.resolve().then(()=>this.drive()).finally(()=>{this.work=null}),this.work)}async drive(){try{for(let e=0;e<this.rounds;e++){if(!this.current())return{quiet:!0};let t=this.capture(this.runtime.takeLogCalls());if(!t.length)return{quiet:!0};this.sent+=t.length;let i=[];try{for(let o=0;o<t.length;){if(!this.current())return{quiet:!0};let s=o+1,r=l=>ET.has(t[l].method);if(r(o))for(;s<t.length&&s-o<qT&&r(s);)s++;let a=t.slice(o,s);o=s;let p=a.map(l=>this.transport.send(l.call,{signal:this.abort.signal}).then(c=>({reply:c,error:null}),c=>({reply:null,error:c})));i.push(...p);for(let[l,c]of a.entries()){let{reply:d,error:u}=await p[l];if(d===null){if(!this.current())return{quiet:!0};let f=wI(u);if(kn(f)){let m=St(f);m&&(this.problem=f),(m||f.status===403&&f.code==="forbidden")&&(this.terminal??=f)}let h=Bw(u);h&&(this.health=h),this.runtime.logNoResponse(c.id);continue}try{if(!this.current())return{quiet:!0};if(!(d instanceof Uint8Array)||d.length>bI){this.runtime.logNoResponse(c.id);continue}if(this.runtime.acceptLogReply(c.id,d)!==!0)this.runtime.logNoResponse(c.id);else if(this.problem=null,this.health=null,c.read){let f=c.read.control?1:0;c.read.after>this.readAfter[f]&&(this.readAfter[f]=c.read.after,this.readAdvances++)}}finally{d instanceof Uint8Array&&d.fill(0)}}}}finally{for(let o of await Promise.all(i))o.reply instanceof Uint8Array&&o.reply.fill(0);for(let o of t)this.wipe(o)}}return{quiet:!1}}catch{throw this.failed=!0,this.retire(),new pt("fenced")}}async drainForAuthenticatedReconnect(){if(this.closed||this.failed||this.retired)throw new pt("fenced");if(this.closed=!0,this.abort.abort(),this.retired=!0,await this.work?.catch(()=>{}),this.failed)throw new pt("fenced")}async close(){this.retire(),await this.work?.catch(()=>{})}};no();Go();function bp(n,e,t=0,i={nodes:0}){if(t>32||++i.nodes>65536)throw A("invalid_request","resource DATA exceeds bound");if(n===null||typeof n=="boolean"||typeof n=="string"||typeof n=="number"&&Number.isFinite(n))return n;if(Array.isArray(n))return n.map(r=>bp(r,e,t+1,i));let o=e?n!==null&&typeof n=="object"&&Object.getPrototypeOf(n)===Object.prototype?Object.entries(n):null:n instanceof Map?[...n]:null;if(!o)throw A("invalid_request","invalid resource DATA");let s=new Map;for(let[r,a]of o){if(typeof r!="string"||s.has(r))throw A("invalid_request","invalid resource DATA");s.set(r,bp(a,e,t+1,i))}return e?s:Object.fromEntries(s)}var an=class extends Error{reason="strict_device_approval";constructor(){super("this account uses strict device approval; add this device from your desktop"),this.name="AppStrictDeviceApprovalError"}},M=()=>A("unavailable","app runtime unavailable; reopen and reconcile");function vI(n){if(!(n instanceof Uint8Array)||n.length===0||n.length>64*1024)throw M();return new Uint8Array(n)}function vn(n){if((typeof n!="number"||!Number.isSafeInteger(n))&&typeof n!="bigint")throw M();let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw M();return e}var _I=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]);function Ht(n){if(!(n instanceof Uint8Array)||n.length!==32)throw M();return n}var fl=class n extends $s{constructor(t,i){super(t);this.sqlBinding=i}sqlBinding;attempted=!1;active=!1;retired=!1;collection=null;deviceId=null;connectorId=null;cpPin=null;deviceAttempted=!1;deviceActive=!1;deviceRegistered=!1;devicePin=null;installationId=null;publicIdentity=null;noiseEnvelope=null;cloudSource=null;cloudCallback=null;cloudCollection=null;cloudPurpose=null;cloudIssued=!1;privateAttempted=!1;privateSource=null;prospectiveCollection=null;privatePurpose=null;sasCommitment=null;privateEnrolAcknowledged=!1;endpoint=null;logGeneration=0n;pump=null;transport=null;get sql(){return this.sqlBinding.sql}get app(){return this.x}static async create(t,i){if(i.needsRecovery)throw M();return this.instantiateApp(t,i)}static async createDevice(t){return this.instantiateApp(t,null)}static async instantiateApp(t,i){let o={sql:i,exports:null,run:null},s=await this.load(t,a=>(o.exports=a,o.run=i?.import(a)??null,{host_app_sql:(p,l)=>o.run?.(p,l)??0n})),r=["rt_app_account_key_unlock","rt_app_account_key_status","rt_app_account_key_device_setup","rt_app_private_collection_pin","rt_app_private_enrol_restore","rt_app_private_enrol_commitment","rt_app_private_create_sign","rt_app_private_device_enrol_sign","rt_app_device_open","rt_app_device_registered","rt_app_device_adopt","rt_app_device_retire","rt_app_cp_enrol_sign","rt_app_verify_handover","rt_app_cp_bind_connector","rt_app_cp_log_token_sign","rt_app_open","rt_app_log_bind","rt_app_log_generation","rt_app_log_reconnect","rt_app_log_http_sign","rt_app_log_calls","rt_app_log_reply","rt_app_log_no_response","rt_app_log_retire","rt_app_log_push","rt_app_observations","rt_app_shutdown"];if(!(s.memory instanceof WebAssembly.Memory)||r.some(a=>typeof s[a]!="function"))throw M();return new n(s,o)}open(t){throw M()}fail(){try{(this.active||this.attempted)&&this.sql?.fence()}finally{this.active=!1,this.deviceActive=!1,this.discard()}}guard(t){try{return t()}catch{throw this.fail(),M()}}openAppConsuming(t){let i=null;try{if(this.attempted||this.deviceAttempted||!this.sql||this.sql.needsRecovery)throw M();this.attempted=!0;let o=vn(t.endpoint);if(!Array.isArray(t.trustedRoots)||t.trustedRoots.length<1||t.trustedRoots.length>64||!Array.isArray(t.trustedSigners)||t.trustedSigners.length>1024||!Number.isSafeInteger(t.sqliteVersion)||t.sqliteVersion<0||t.sqliteVersion>4294967295)throw M();let s=t.state==="e2e"?0:t.state==="cloud_copy"?1:-1,r=t.opened==="fresh"?0:t.opened==="existing"?1:t.opened==="unclean"?2:-1;if(s<0||r<0||typeof t.cloudCopyOptIn!="boolean"||s===1!==t.cloudCopyOptIn||(i=qn(new Map([[0,3],[1,U(t.collection)],[2,U(t.replicaId)],[3,U(t.deviceId)],[4,o],[5,t.trustedRoots.map(Ht)],[6,t.trustedSigners.map(U)],[7,Ap(t.expectedGenesis)],[8,s],[9,t.cloudCopyOptIn],[10,Ht(t.signSecretKey)],[11,Ht(t.kemSecretKey)],[12,r],[13,t.sqliteVersion],[16,vI(t.policyPins)]])),i.length>64*1024)||this.guard(()=>this.takeOut(this.app.rt_app_open(...this.put(i)))).length)throw M();this.collection=t.collection,this.deviceId=t.deviceId,this.endpoint=o,this.active=!0,this.markOpened()}catch{throw this.retireLog(),this.fail(),M()}finally{i?.fill(0),t.signSecretKey?.fill(0),t.kemSecretKey?.fill(0)}}tick(){this.active&&!this.retired&&this.guard(()=>super.tick())}connect(t={}){if(!this.active||this.retired||t.collection!==void 0&&(typeof t.collection!="string"||t.collection.toLowerCase()!==this.collection?.toLowerCase()))throw M();let i=super.connect(t),o=i.send.bind(i),s=i.close.bind(i);return i.send=r=>this.guard(()=>o(r)),i.close=()=>this.guard(()=>s()),i}executeBases(t,i){return this.readBases(t,i,"execute")}discoverBases(t,i,o){if(i!=="list-views"&&i!=="read-view-source")throw M();return this.readBases(t,o,i)}readBases(t,i,o){let s=this.sessionForPort(t),r=o==="execute"?this.app.rt_app_bases_execute:o==="list-views"?this.app.rt_app_bases_list_views:this.app.rt_app_bases_read_view_source;if(!this.active||this.retired||!this.sql||this.sql.needsRecovery||s===null||typeof r!="function")throw M();if(!(i instanceof Uint8Array)||!i.length||i.length>128*1024)throw A("invalid_request","Bases request bytes exceed bound");let a=new Uint8Array(i);try{let p=this.guard(()=>{let l=vn(r.call(this.app,s,...this.put(a))),c=Number(l&0xffffffffn);if(!c||c>(o==="execute"?16:1)*1024*1024)throw M();return this.takeOut(l)});if(!this.active||this.retired||this.sql.needsRecovery||this.sessionForPort(t)!==s)throw p.fill(0),M();return p}finally{a.fill(0)}}setupResources(t,i,o,s,r){let a=this.sessionForPort(t),p=this.app.rt_app_resources;if(!this.active||this.retired||!this.sql||this.sql.needsRecovery||a===null||typeof p!="function")throw A("unavailable","resource setup unsupported","resource_setup_unsupported");if(i!=="assess"&&i!=="apply"||i==="apply"&&(typeof s!="string"||!/^sha256:[0-9a-f]{64}$/.test(s)))throw M();let l=r!==void 0,c=[1,i==="apply"?1:0,bp(o,!0),s??null];l&&c.push(bp(ei(r),!0));let d=pe(c);if(!d.length||d.length>512*1024)throw d.fill(0),A("invalid_request","resource DATA exceeds bound");let u;try{if(u=this.guard(()=>{let m=vn(p.call(this.app,a,...this.put(d))),b=Number(m&0xffffffffn);if(!b||b>512*1024)throw M();return this.takeOut(m)}),!this.active||this.retired||this.sql.needsRecovery||this.sessionForPort(t)!==a)throw M();let f=this.guard(()=>ue(u));if(!Array.isArray(f)||f.length!==3||f[0]!==1||typeof f[1]!="boolean")throw M();if(f[1]===!1)throw A("unavailable","resource setup unavailable","resource_setup_unavailable");let h=bp(f[2],!1);return i==="assess"?Jo(h,l):xt(h)}finally{d.fill(0),u?.fill(0)}}resourceRejected(t,i){let o=null;try{let s=this.sessionForPort(t),r=this.app.rt_app_receipt_rejected;return!this.active||this.retired||s===null||typeof r!="function"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(i)?!1:(o=U(i),this.guard(()=>r.call(this.app,s,...this.put(o)))===1&&this.active&&!this.retired&&this.sessionForPort(t)===s)}catch{return!1}finally{o?.fill(0)}}verifyHandover(t,i,o){let s=null,r=null;try{let a=this.sessionForPort(t),p=i.collection,l=i.deviceId;if(!this.active||this.retired||a===null||p!==this.collection||i.isCurrent()!==!0||!(o instanceof Uint8Array)||o.length>64*1024)return null;s=new Uint8Array(o),r=U(l);let c=this.guard(()=>this.takeOut(this.app.rt_app_verify_handover(a,...this.put(r),...this.put(s))));if(c.length===0||this.sessionForPort(t)!==a||i.isCurrent()!==!0||i.collection!==p||i.deviceId!==l)return null;let d=this.guard(()=>Lp.dec(ue(c)));return d.seq===0||[d.chain,d.policyGeneration,d.catalogGeneration].some(u=>u===`sha256:${"00".repeat(32)}`)?null:d}catch{return null}finally{s?.fill(0),r?.fill(0)}}bindCpConnector(t){let i=null;try{if(!this.active||this.retired||this.pump||this.cpPin||t.isCurrent()!==!0||t.deviceId!==this.deviceId||t.collection!==this.collection)throw M();let o=t.connectorId;if(i=U(o),i.every(s=>s===0)||this.guard(()=>this.app.rt_app_cp_bind_connector(...this.put(i)))!==1)throw M();this.connectorId=o,this.cpPin=t}catch{throw M()}finally{i?.fill(0)}}deviceCurrent(){try{let t=this.devicePin;return this.deviceActive&&!this.retired&&t!==null&&t.isCurrent()===!0&&t.connectorId===this.connectorId&&t.deviceId===this.deviceId&&t.installationId===this.installationId}catch{return!1}}publicResult(t){if(t.length>1024)throw M();let i=ue(t);if(!(i instanceof Map))throw M();let o=i;if(o.size!==4||[0,1,2,3].some(r=>!o.has(r)))throw M();let s=r=>{let a=o.get(r);if(!(a instanceof Uint8Array)||a.length!==32||a.every(p=>p===0))throw M();return new Uint8Array(a)};return{m:o,identity:Object.freeze({signPublicKey:s(0),kemPublicKey:s(1),noisePublicKey:s(2)})}}openDeviceConsuming(t){let i=null;try{if(this.deviceAttempted||this.attempted||this.retired)throw M();this.deviceAttempted=!0;let o=t.pin;if(this.devicePin=o,this.connectorId=o.connectorId,this.deviceId=o.deviceId,this.installationId=o.installationId,this.deviceActive=!0,!this.deviceCurrent())throw M();let s=[this.connectorId,this.deviceId,this.installationId].map(U);if(s.some(l=>l.every(c=>c===0)))throw M();let r=t.opened;if(r.mode!=="fresh"&&r.mode!=="existing"||r.mode==="existing"&&(!(r.envelope instanceof Uint8Array)||!r.envelope.length||r.envelope.length>1024))throw M();i=qn(new Map([[0,1],[1,s[0]],[2,s[1]],[3,s[2]],[4,r.mode==="fresh"?0:1],[5,Ht(t.signSecretKey)],[6,Ht(t.kemSecretKey)],[7,r.mode==="fresh"?new Uint8Array:new Uint8Array(r.envelope)]]));let a=this.guard(()=>this.takeOut(this.app.rt_app_device_open(...this.put(i))));if(!a.length||!this.deviceCurrent())throw M();let p=this.guard(()=>{let{m:l,identity:c}=this.publicResult(a),d=l.get(3);if(!(d instanceof Uint8Array)||!d.length||d.length>1024)throw M();return{...c,envelope:new Uint8Array(d)}});return this.publicIdentity={signPublicKey:new Uint8Array(p.signPublicKey),kemPublicKey:new Uint8Array(p.kemPublicKey),noisePublicKey:new Uint8Array(p.noisePublicKey)},this.noiseEnvelope=new Uint8Array(p.envelope),Object.freeze(p)}catch{throw this.retireLog(),M()}finally{i?.fill(0),t.signSecretKey?.fill(0),t.kemSecretKey?.fill(0)}}deviceCustodyCurrent(t,i){try{return this.deviceCurrent()&&!this.active&&this.publicIdentity!==null&&this.noiseEnvelope!==null&&t.isCurrent()===!0&&t.connectorId===this.connectorId&&t.deviceId===this.deviceId&&t.installationId===this.installationId&&i.envelope instanceof Uint8Array&&i.envelope.length===this.noiseEnvelope.length&&i.envelope.every((o,s)=>o===this.noiseEnvelope[s])&&["signPublicKey","kemPublicKey","noisePublicKey"].every(o=>i[o]instanceof Uint8Array&&i[o].length===32&&i[o].every((s,r)=>s===this.publicIdentity[o][r]))}catch{return!1}}acknowledgeDeviceRegistration(t){let i=null;try{if(!this.deviceCurrent()||this.active||this.deviceRegistered||!this.publicIdentity||t.connectorId!==this.connectorId||t.deviceId!==this.deviceId||t.installationId!==this.installationId)throw M();for(let o of["signPublicKey","kemPublicKey","noisePublicKey"])if(Ht(t[o]).some((s,r)=>s!==this.publicIdentity[o][r]))throw M();if(i=qn(new Map([[0,U(t.connectorId)],[1,U(t.deviceId)],[2,U(t.installationId)],[3,new Uint8Array(t.signPublicKey)],[4,new Uint8Array(t.kemPublicKey)],[5,new Uint8Array(t.noisePublicKey)]])),this.guard(()=>this.app.rt_app_device_registered(...this.put(i)))!==1||!this.deviceCurrent())throw M();this.deviceRegistered=!0}catch{throw this.retireLog(),M()}finally{i?.fill(0)}}prepareCloudCopyCollection(t){let i=null;try{if(t.approvalMode==="strict")throw new an;if(this.cloudSource||this.privateAttempted||!this.deviceCurrent()||!this.deviceRegistered||this.active||t.approvalMode!=="password-ak1"||!["create","join"].includes(t.purpose)||(this.cloudSource=t,this.cloudCallback=t.isCurrent,this.cloudCollection=t.collection,this.cloudPurpose=t.purpose,!this.cloudCopyCollectionCurrent(t)))throw M();let o=U(t.collection);if(o.every(s=>s===0)||(i=qn(new Map([[0,o],[1,t.purpose==="create"?0:1]])),this.guard(()=>this.app.rt_app_cloud_copy_pin(...this.put(i)))!==1||!this.cloudCopyCollectionCurrent(t)))throw M()}catch(o){throw this.retireLog(),o instanceof an?o:M()}finally{i?.fill(0)}}cloudCopyCollectionCurrent(t){try{let i=this.cloudSource;return this.deviceCurrent()&&!this.active&&this.deviceRegistered&&i!==null&&(!t||t===i)&&i.isCurrent===this.cloudCallback&&i.isCurrent()===!0&&i.connectorId===this.connectorId&&i.deviceId===this.deviceId&&i.installationId===this.installationId&&i.collection===this.cloudCollection&&i.purpose===this.cloudPurpose&&i.approvalMode==="password-ak1"}catch{return!1}}signCloudCopyCreate(t){return this.signCloudCopy(t,"create")}signCloudCopyJoin(t){return this.signCloudCopy(t,"join")}signCloudCopy(t,i){let o=null,s=null;try{if(this.cloudIssued||!this.cloudCopyCollectionCurrent()||this.cloudPurpose!==i||(this.cloudIssued=!0,o=new Uint8Array(Ht(t)),s=this.guard(()=>this.takeOut(i==="create"?this.app.rt_app_cloud_copy_create_sign(...this.put(o)):this.app.rt_app_cloud_copy_join_sign(...this.put(o)))),s.length!==64||!this.cloudCopyCollectionCurrent()))throw M();return s}catch{throw s?.fill(0),this.retireLog(),M()}finally{o?.fill(0)}}preparePrivateCollection(t,i){let o=null,s=null;try{if(t.approvalMode==="strict")throw new an;if(this.cloudSource||this.privateAttempted||!this.deviceCurrent()||!this.deviceRegistered||this.active||t.approvalMode!=="password-ak1"||!["create","enrol"].includes(t.purpose)||(this.privateAttempted=!0,this.privateSource=t,this.prospectiveCollection=t.collection,this.privatePurpose=t.purpose,!this.privateCollectionCurrent()))throw M();let r=U(t.collection);if(r.every(a=>a===0))throw M();if(i.mode==="fresh"){if(o=qn(new Map([[0,r],[1,t.purpose==="create"?0:1]])),this.guard(()=>this.app.rt_app_private_collection_pin(...this.put(o)))!==1)throw M()}else if(i.mode==="existing"){let a=i.marker,p=this.publicIdentity;if(t.purpose!=="enrol"||!p||a.collection!==t.collection||a.connectorId!==this.connectorId||a.deviceId!==this.deviceId||a.installationId!==this.installationId||typeof a.acknowledged!="boolean")throw M();for(let c of["signPublicKey","kemPublicKey","noisePublicKey"])if(!_I(Ht(a[c]),p[c]))throw M();let l=new Uint8Array(Ht(a.sasCommitment));if(l.every(c=>c===0)||(s=l,o=qn(new Map([[0,1],[1,r],[2,U(a.connectorId)],[3,U(a.deviceId)],[4,U(a.installationId)],[5,new Uint8Array(a.signPublicKey)],[6,new Uint8Array(a.kemPublicKey)],[7,new Uint8Array(a.noisePublicKey)],[8,l],[9,a.acknowledged]])),this.privateEnrolAcknowledged=a.acknowledged,this.guard(()=>this.app.rt_app_private_enrol_restore(...this.put(o)))!==1))throw M()}else throw M();if(!this.privateCollectionCurrent())throw M();if(t.purpose==="enrol"){let a=this.guard(()=>this.takeOut(this.app.rt_app_private_enrol_commitment()));if(a.length!==32||a.every(p=>p===0)||s!==null&&!_I(a,s))throw M();this.sasCommitment=new Uint8Array(a)}}catch(r){throw this.retireLog(),r instanceof an?r:M()}finally{o?.fill(0)}}registeredDeviceReceipt(){if(!this.deviceCurrent()||!this.deviceRegistered||!this.publicIdentity)throw M();let t=this.publicIdentity;return Object.freeze({connectorId:this.connectorId,deviceId:this.deviceId,installationId:this.installationId,signPublicKey:new Uint8Array(t.signPublicKey),kemPublicKey:new Uint8Array(t.kemPublicKey),noisePublicKey:new Uint8Array(t.noisePublicKey)})}privateEnrolMarker(){if(!this.privateCollectionCurrent()||this.privatePurpose!=="enrol"||!this.sasCommitment||!this.publicIdentity)throw M();let t=this.publicIdentity;return Object.freeze({connectorId:this.connectorId,deviceId:this.deviceId,installationId:this.installationId,collection:this.prospectiveCollection,sasCommitment:new Uint8Array(this.sasCommitment),acknowledged:this.privateEnrolAcknowledged,signPublicKey:new Uint8Array(t.signPublicKey),kemPublicKey:new Uint8Array(t.kemPublicKey),noisePublicKey:new Uint8Array(t.noisePublicKey)})}privateCollectionCurrent(t){try{if(t&&(t.isCurrent()!==!0||t.connectorId!==this.connectorId||t.deviceId!==this.deviceId||t.installationId!==this.installationId||t.collection!==this.prospectiveCollection||t.purpose!==this.privatePurpose||t.approvalMode!=="password-ak1"))return!1;let i=this.privateSource;return this.deviceCurrent()&&!this.active&&this.deviceRegistered&&i!==null&&i.isCurrent()===!0&&i.connectorId===this.connectorId&&i.deviceId===this.deviceId&&i.installationId===this.installationId&&i.collection===this.prospectiveCollection&&i.purpose===this.privatePurpose&&i.approvalMode==="password-ak1"}catch{return!1}}signPrivateCreate(t){let i=null;try{if(!this.privateCollectionCurrent()||this.privatePurpose!=="create")throw M();i=new Uint8Array(Ht(t));let o=this.guard(()=>this.takeOut(this.app.rt_app_private_create_sign(...this.put(i))));if(o.length!==64||!this.privateCollectionCurrent())throw M();return o}catch{throw this.retireLog(),M()}finally{i?.fill(0)}}signPrivateDeviceEnrol(t){let i=null;try{if(!this.privateCollectionCurrent()||this.privatePurpose!=="enrol"||!this.sasCommitment||this.privateEnrolAcknowledged)throw M();i=new Uint8Array(Ht(t));let o=this.guard(()=>this.takeOut(this.app.rt_app_private_device_enrol_sign(...this.put(i))));if(o.length!==64||!this.privateCollectionCurrent())throw M();return Object.freeze({signature:o,sasCommitment:new Uint8Array(this.sasCommitment)})}catch{throw this.retireLog(),M()}finally{i?.fill(0)}}adoptDevice(t,i){let o=null;try{if(!this.deviceCurrent()||!this.deviceRegistered||this.attempted||this.active||t.deviceId!==this.deviceId||this.privateSource&&(!this.privateCollectionCurrent()||t.collection!==this.prospectiveCollection)||this.cloudSource&&(!this.cloudCopyCollectionCurrent()||t.collection!==this.cloudCollection||t.state!=="cloud_copy"||t.cloudCopyOptIn!==!0))throw M();let s=vI(t.policyPins);if(i){if(this.sql||i.needsRecovery||!this.sqlBinding.exports)throw M();this.sqlBinding.sql=i,this.sqlBinding.run=i.import(this.sqlBinding.exports)}if(!this.sql||this.sql.needsRecovery)throw M();this.attempted=!0;let r=vn(t.endpoint),a=t.state==="e2e"?0:t.state==="cloud_copy"?1:-1,p=t.opened==="fresh"?0:t.opened==="existing"?1:t.opened==="unclean"?2:-1;if(a<0||p<0||typeof t.cloudCopyOptIn!="boolean"||a===1!==t.cloudCopyOptIn||!Array.isArray(t.trustedRoots)||t.trustedRoots.length<1||t.trustedRoots.length>64||!Array.isArray(t.trustedSigners)||t.trustedSigners.length>1024||!Number.isSafeInteger(t.sqliteVersion)||t.sqliteVersion<0||t.sqliteVersion>4294967295||(o=qn(new Map([[0,4],[1,U(t.collection)],[2,U(t.replicaId)],[3,U(t.deviceId)],[4,r],[5,t.trustedRoots.map(Ht)],[6,t.trustedSigners.map(U)],[7,Ap(t.expectedGenesis)],[8,a],[9,t.cloudCopyOptIn],[10,null],[11,null],[12,p],[13,t.sqliteVersion],[14,U(this.connectorId)],[15,U(this.installationId)],[16,s]])),o.length>64*1024)||this.guard(()=>this.takeOut(this.app.rt_app_device_adopt(...this.put(o)))).length||!this.deviceCurrent())throw M();this.collection=t.collection,this.endpoint=r,this.active=!0,this.markOpened()}catch{throw this.retireLog(),this.fail(),M()}finally{o?.fill(0)}}signCpEnrol(t){let i=null;try{if(!this.deviceCurrent()||!this.publicIdentity||this.active||this.pump)throw this.retireLog(),M();i=new Uint8Array(Ht(t));let o=this.guard(()=>this.takeOut(this.app.rt_app_cp_enrol_sign(...this.put(i))));if(!this.deviceCurrent())throw this.retireLog(),M();if(!o.length)throw M();let{m:s,identity:r}=this.guard(()=>this.publicResult(o)),a=s.get(3);if(!(a instanceof Uint8Array)||a.length!==64||["signPublicKey","kemPublicKey","noisePublicKey"].some(p=>r[p].some((l,c)=>l!==this.publicIdentity[p][c])))throw M();return Object.freeze({...r,signature:new Uint8Array(a)})}catch{throw this.retireLog(),M()}finally{i?.fill(0)}}signCpLogToken(t){let i=null;try{if(!this.active||this.retired||!this.cpPin)throw M();let o=this.cpPin,s=!1;try{s=o.isCurrent()===!0&&o.connectorId===this.connectorId&&o.deviceId===this.deviceId&&o.collection===this.collection}catch{}if(!s)throw this.retireLog(),M();i=new Uint8Array(Ht(t));let r=this.guard(()=>this.takeOut(this.app.rt_app_cp_log_token_sign(...this.put(i))));if(r.length!==64)throw r.fill(0),M();return r}catch{throw M()}finally{i?.fill(0)}}bindLogTransport(t){try{if(!this.active||this.retired||this.pump||this.endpoint===null||this.collection===null||t.isCurrent()!==!0||vn(t.endpoint)!==this.endpoint||t.collection!==this.collection)throw M()}catch{throw M()}let i=U(this.collection);if(this.guard(()=>this.app.rt_app_log_bind(this.endpoint,...this.put(i)))!==1)throw M();if(this.logGeneration=this.guard(()=>vn(this.app.rt_app_log_generation())),this.logGeneration===0n)throw this.retireLog(),M();return this.pump=new is(this,t,{endpoint:this.endpoint,collection:this.collection}),this.transport=t,this.pump}requestLogHead(){return!this.active||this.retired||this.pump===null||typeof this.app.rt_app_log_head!="function"?!1:this.guard(()=>this.app.rt_app_log_head())===1}get supportsLogPush(){return typeof this.app.rt_app_log_hello_sign=="function"}signLogHello(t,i){let o=null;try{if(!this.supportsLogPush||!this.active||this.retired||!this.pump||!this.transport||this.logGeneration===0n||!this.transport.isCurrent()||!(t instanceof Uint8Array)||t.length!==32||typeof i!="string"||i.length===0||i.length>16*1024||/[^\x21-\x7e]/.test(i))return null;let s=new TextEncoder().encode(i);o=new Uint8Array(32+s.length),o.set(t,0),o.set(s,32),s.fill(0);let r=this.logGeneration,a=this.guard(()=>this.takeOut(this.app.rt_app_log_hello_sign(r,...this.put(o))));return a.length!==64?(a.fill(0),null):a}catch{return null}finally{o?.fill(0)}}async reconnectLogTransport(t){let i=this.pump,o=this.logGeneration,s=()=>this.active&&!this.retired&&this.pump===i&&i!==null&&this.transport===t&&t.isCurrent()===!0&&vn(t.endpoint)===this.endpoint&&t.collection===this.collection;try{if(!s()||(await i.drainForAuthenticatedReconnect(),!s()))throw M();this.pump=null,this.transport=null;let r=U(this.collection);try{if(this.guard(()=>this.app.rt_app_log_reconnect(this.endpoint,...this.put(r)))!==1)throw M()}finally{r.fill(0)}if(this.logGeneration=this.guard(()=>vn(this.app.rt_app_log_generation())),this.logGeneration<=o||!t.isCurrent()||this.retired||!this.active)throw M();return this.pump=new is(this,t,{endpoint:this.endpoint,collection:this.collection}),this.transport=t,this.pump}catch{throw this.retireLog(),M()}}signLogHttp(t){let i=null;try{if(!this.active||!this.pump||!this.transport||this.logGeneration===0n||this.endpoint===null||t.path!=="/v1/rpc"||t.collection!==this.collection||vn(t.endpoint)!==this.endpoint||!this.transport.isCurrent()||!(t.frame instanceof Uint8Array)||t.frame.length===0||t.frame.length>16*1024*1024||!(t.nonce instanceof Uint8Array)||t.nonce.length!==32||typeof t.token!="string"||t.token.length===0||t.token.length>16*1024||/[^\x21-\x7e]/.test(t.token))throw M();i=qn(new Map([[0,t.frame],[1,t.token],[2,t.nonce]]));let o=this.guard(()=>this.takeOut(this.app.rt_app_log_http_sign(this.endpoint,this.logGeneration,vn(t.originalCallId),...this.put(i))));if(o.length!==64)throw o.fill(0),M();return o}catch{throw M()}finally{i?.fill(0)}}takeLogCalls(){return!this.active||this.retired?[]:this.guard(()=>{let t=this.takeOut(this.app.rt_app_log_calls());if(!t.length)return[];let i=ue(t);if(!Array.isArray(i)||i.length>64)throw M();return i.map(o=>{if(!(o instanceof Map))throw M();let s=o,r=s.get(0),a=s.get(1),p=s.get(2);if(vn(r)!==this.endpoint||!(a instanceof Uint8Array)||p!==void 0&&!(p instanceof Uint8Array))throw M();return{endpoint:r,frame:a,...p!==void 0?{sidecar:p}:{}}})})}acceptLogReply(t,i){return!this.active||this.retired?!1:this.guard(()=>this.app.rt_app_log_reply(vn(t),...this.put(i))===1)}logNoResponse(t){this.active&&!this.retired&&this.guard(()=>this.app.rt_app_log_no_response(vn(t)))}retireLog(){this.logGeneration=0n,!this.retired&&(this.retired=!0,this.cpPin=null,this.connectorId=null,this.devicePin=null,this.installationId=null,this.privateSource=null,this.prospectiveCollection=null,this.privatePurpose=null,this.sasCommitment?.fill(0),this.sasCommitment=null,this.publicIdentity=null,this.noiseEnvelope?.fill(0),this.noiseEnvelope=null,this.deviceActive=!1,this.deviceRegistered=!1,this.active?this.guard(()=>{super.dispose(),this.app.rt_app_log_retire()}):this.deviceAttempted&&this.guard(()=>this.app.rt_app_device_retire()))}pushLog(t){return!this.active||this.retired||!this.pump||!this.transport?!1:this.guard(()=>{let i=this.transport;return i.isCurrent()!==!0||vn(i.endpoint)!==this.endpoint||i.collection!==this.collection?(this.retireLog(),!1):this.app.rt_app_log_push(...this.put(t))===1})}accountKeyCurrent(t){try{return this.active&&!this.retired&&t.isCurrent()===!0&&t.approvalMode==="password-ak1"&&t.collection===this.collection&&t.deviceId===this.deviceId&&t.connectorId===this.connectorId&&t.installationId===this.installationId&&this.devicePin!==null&&this.devicePin.isCurrent()===!0&&this.devicePin.connectorId===this.connectorId&&this.devicePin.deviceId===this.deviceId&&this.devicePin.installationId===this.installationId}catch{return!1}}accountKeyState(t){let i=ue(t);if(!(i instanceof Map))throw M();let o=i;if(o.size!==2||!o.has(0)||!o.has(1))throw M();let s=o.get(0),r=o.get(1);if(s===0||s===1){if(r!==null)throw M();return Object.freeze({state:s===0?"pending":"keyed"})}if(s!==2||typeof r!="string"||!["not_private","not_ready","not_enrolled","not_authorized","device_missing","enrolment_mismatch","not_keyed","no_wrap","inconsistent","failed","outcome_unknown"].includes(r))throw M();return Object.freeze({state:"refused",reason:r})}unlockAccountKeyConsuming(t,i){try{if(t.approvalMode==="strict")throw new an;if(!this.accountKeyCurrent(t))throw M();Ht(i);let o=this.guard(()=>this.accountKeyState(this.takeOut(this.app.rt_app_account_key_unlock(...this.put(i)))));if(!this.accountKeyCurrent(t))throw M();return o}catch(o){throw this.retireLog(),o instanceof an?o:M()}finally{i instanceof Uint8Array&&i.fill(0)}}setupAccountKeyDeviceConsuming(t,i){try{if(t.approvalMode==="strict")throw new an;if(!this.accountKeyCurrent(t))throw M();Ht(i);let o=this.guard(()=>this.accountKeyState(this.takeOut(this.app.rt_app_account_key_device_setup(...this.put(i)))));if(!this.accountKeyCurrent(t))throw M();return o.state==="refused"?o:Object.freeze({state:o.state==="keyed"?"recovery_keyed":"recovery_pending"})}catch(o){throw this.retireLog(),o instanceof an?o:M()}finally{i instanceof Uint8Array&&i.fill(0)}}accountKeyStatus(t){try{if(!this.accountKeyCurrent(t))throw M();let i=this.guard(()=>this.accountKeyState(this.takeOut(this.app.rt_app_account_key_status())));if(!this.accountKeyCurrent(t))throw M();return i}catch{throw this.retireLog(),M()}}observations(){if(!this.active||this.retired)throw M();return this.guard(()=>{let t=ue(this.takeOut(this.app.rt_app_observations()));if(!(t instanceof Map))throw M();let i=t;for(let o of[1,2,3,4])if(typeof i.get(o)!="boolean")throw M();return{status:er.dec(i.get(0)),keyringRebuilding:i.get(1),keyringRebuildFailed:i.get(2),snapshotInstallAvailable:i.get(3),requiresReopen:i.get(4)}})}async close(){return this.pump&&(await this.pump.close(),this.pump=null,this.transport=null),this.shutdown()}shutdown(){if(!this.active)return this.deviceAttempted&&!this.retired&&this.retireLog(),this.discard(),!1;if(this.pump)return this.pump.close().catch(()=>{}),this.fail(),!1;try{return this.retireLog(),super.dispose(),this.guard(()=>this.app.rt_app_shutdown()===1)&&this.sql!==null&&!this.sql.needsRecovery}finally{this.active=!1,this.discard()}}dispose(){this.shutdown()}};async function AI(n){if(!n.worker)return{supported:!1,reason:"worker_required"};if(!n.storage?.getDirectory)return{supported:!1,reason:"opfs_unavailable"};let e,t,i=!1,o,s={supported:!1,reason:"probe_failed"};try{let r=n.randomUUID();if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(r))return s;t=r.toLowerCase(),e=await(await n.storage.getDirectory()).getDirectoryHandle(".mdbase-app-probes",{create:!0});let a=await e.getFileHandle(t,{create:!0});if(i=!0,!a.createSyncAccessHandle)s={supported:!1,reason:"sync_handle_unavailable"};else{o=await a.createSyncAccessHandle();let p=new Uint8Array([109,100,98,110]),l=new Uint8Array(p.length);if(o.write(p,{at:0})!==p.length)throw new Error("short probe write");if(o.flush(),o.read(l,{at:0})!==p.length||l.some((c,d)=>c!==p[d]))throw new Error("probe readback failed");s={supported:!0,backend:"opfs_sahpool_candidate",crashDurability:"unqualified",eviction:"possible"}}}catch{s={supported:!1,reason:"probe_failed"}}finally{let r=!0;try{o?.close()}catch{r=!1,s={supported:!1,reason:"cleanup_failed"}}if(i&&r&&e&&t)try{await e.removeEntry(t)}catch{s={supported:!1,reason:"cleanup_failed"}}}return s}eo();Qr();vw();no();rp();Go();Jb();kh();Yc();var Fw=Object.freeze({status:"unsupported"}),Vh=Object.freeze({snapshot(){return Fw},async check(n={}){return n.signal?.throwIfAborted(),Fw},async request(n={}){return n.signal?.throwIfAborted(),Fw},disable(){}});Fn();Yc();var Kw="mdbase.app.log-token.v1",hl="tokens";function kI(){return new Promise(n=>{let e;try{e=indexedDB.open(Kw,1)}catch{n(null);return}e.onupgradeneeded=()=>{try{e.result.createObjectStore(hl)}catch{}},e.onsuccess=()=>{let t=e.result;t.onversionchange=()=>t.close(),n(t.objectStoreNames.contains(hl)?t:(t.close(),null))},e.onerror=e.onblocked=()=>n(null)})}function Vw(n,e){return kI().then(t=>new Promise(i=>{if(!t){i(null);return}let o=null;try{let s=t.transaction(hl,n),r=e(s.objectStore(hl));r&&(r.onsuccess=()=>{o=r.result??null}),s.oncomplete=()=>{t.close(),i(o)},s.onerror=s.onabort=()=>{t.close(),i(null)}}catch{t.close(),i(null)}}))}function SI(){return typeof indexedDB>"u"?null:Object.freeze({async read(n,e){let t=await Vw("readonly",i=>i.get(n)).catch(()=>null);return!t||typeof t.value!="string"||!t.value||t.value.length>16*1024||/[^\x21-\x7e]/.test(t.value)||typeof t.expires!="number"||!Number.isSafeInteger(t.expires)||t.expires-e<6e4||t.expires-e>16*6e4?null:Object.freeze({value:t.value,expires:t.expires})},async write(n,e){await Vw("readwrite",t=>t.put({value:e.value,expires:e.expires},n)).catch(()=>null)},async drop(n){await Vw("readwrite",e=>e.delete(n)).catch(()=>null)}})}async function PI(n){let{cpOrigin:e,connectorId:t,deviceId:i}=n;if(!t||!i)return!0;let o=await kI();return o?new Promise(s=>{try{let r=o.transaction(hl,"readwrite"),a=r.objectStore(hl).openCursor();a.onsuccess=()=>{let p=a.result;if(p){if(typeof p.key=="string"){let l=p.key.split(" ");l.length===5&&l[0]===e&&l[2]===t&&l[3]===i&&p.delete()}p.continue()}},r.oncomplete=()=>{o.close(),s(!0)},r.onerror=r.onabort=()=>{o.close(),s(!1)}}catch{o.close(),s(!1)}}):!1}cw();Jn();ge();Fc();Ps();ie();su();Zc();bt();Je();ge();var MT=4401,LT=4403,jT=4410,NT=3e4,UT=1e4,DT=6e4,$T=6e4,zT=15e3,BT=4,FT=64*1024,VT=1024*1024;function KT(n,e){let t=new URL(n);if(t.protocol==="https:")return`wss://${t.host}`;if(e&&ot(n))return`ws://${t.host}`;throw new Error("app log push: origin")}var WT=n=>[...n].map(e=>e.toString(16).padStart(2,"0")).join(""),xI=(n,e,t)=>pe(new Map([[0,0],[1,n],[2,e],[3,t]]));function HT(n){let e=n.get(3);if(!(e instanceof Map))return null;let t=e.get(0),i=e.get(1);return{code:typeof t=="string"?t:"unavailable",reason:typeof i=="string"?i:""}}var Kh=class{constructor(e,t,i={}){this.source=e;this.events=t;this.base=KT(e.origin,i.allowLoopbackHttp===!0),this.collectionBytes=U(e.collection);let o=i.WebSocket??globalThis.WebSocket;if(typeof o!="function")throw new Error("app log push: no WebSocket");this.Ws=o,this.random=i.random??Math.random,this.now=i.now??Date.now}source;events;base;collectionBytes;Ws;random;now;socket=null;connecting=!1;closed=!1;finished=null;unsupported=!1;paused=!1;isLive=!1;attempts=0;liveSince=0;retry=null;ping=null;pongDue=null;opening=null;unsigned=0;life=new AbortController;token=null;get live(){return this.isLive}get available(){return!this.unsupported&&this.finished===null&&!this.closed}get suspended(){return this.paused}start(){this.connect()}nudge(){this.unsupported=!1,this.unsigned=0,!(this.paused||this.socket||this.connecting||!this.available)&&(this.attempts=0,this.clearRetry(),this.connect())}suspend(){this.paused||!this.available||(this.paused=!0,this.clearRetry(),this.drop(1e3,"hidden"))}resume(){if(!this.paused){this.nudge();return}this.paused=!1,this.nudge()}close(){this.closed||(this.closed=!0,this.life.abort(),this.clearRetry(),this.drop(1e3,"closed"))}clearRetry(){this.retry!==null&&clearTimeout(this.retry),this.retry=null}clearPing(){this.ping!==null&&clearInterval(this.ping),this.ping=null,this.pongDue!==null&&clearTimeout(this.pongDue),this.pongDue=null,this.opening!==null&&clearTimeout(this.opening),this.opening=null}setLive(e){if(this.isLive!==e){this.isLive=e,e&&(this.liveSince=this.now());try{this.events.live(e)}catch{}}}end(e){if(!(this.finished||this.closed)){this.finished=e,this.clearRetry(),this.drop(1e3,e);try{this.events.ended(e)}catch{}}}drop(e,t){this.clearPing();let i=this.socket;if(this.socket=null,i){i.onopen=i.onmessage=i.onclose=i.onerror=null;try{i.close(e,t)}catch{}}this.setLive(!1)}schedule(e=!1){if(this.paused||!this.available||this.retry!==null)return;let t=e?0:Math.floor(this.random()*Math.min($T,1e3*2**Math.min(this.attempts,6)));this.attempts++,this.retry=setTimeout(()=>{this.retry=null,this.connect()},t)}async connect(){if(this.paused||this.socket||this.connecting||!this.available)return;if(!this.source.isCurrent()){this.close();return}this.connecting=!0;let e,t,i;try{let r=this.life.signal;if(e=await this.source.accessToken({signal:r}),t=await this.source.nonce({signal:r}),this.paused||!this.available||!this.source.isCurrent())return;if(i=this.source.signHello(t,e),!i){++this.unsigned>=BT?this.unsupported=!0:this.schedule();return}this.unsigned=0}catch{this.connecting=!1,this.schedule();return}finally{this.connecting=!1}this.token=e;let o;try{o=new this.Ws(`${this.base}/v1/ws?c=${this.source.collection}&n=${WT(t)}`)}catch{this.schedule();return}o.binaryType="arraybuffer",this.socket=o;let s=xI(1,"hello",new Map([[0,[1,0]],[1,e],[2,U(this.source.deviceId)],[3,i]]));i.fill(0),t.fill(0),o.onopen=()=>{try{o.send(s)}catch{this.lost(o,1006)}},o.onmessage=r=>this.message(o,r.data),o.onclose=r=>this.lost(o,r.code),o.onerror=()=>{},this.opening=setTimeout(()=>{this.opening=null,this.lost(o,1006)},zT)}message(e,t){if(e!==this.socket)return;if(typeof t=="string"){t==="pong"&&this.pongDue!==null&&(clearTimeout(this.pongDue),this.pongDue=null);return}if(!(t instanceof ArrayBuffer)||t.byteLength>VT){this.lost(e,1009);return}let i=new Uint8Array(t),o;try{let a=ue(i);if(!(a instanceof Map))throw new Error;o=a}catch{this.lost(e,1007);return}if(o.get(0)===2){if(!this.isLive)return;if(this.deliver(i),o.get(1)==="closed"){let a=o.get(2),p=a instanceof Map?a.get(1):null;this.end(p==="gone"?"gone":p==="revoked"?"revoked":"forbidden")}return}if(o.get(0)!==1)return;let s=o.get(1),r=HT(o);if(s===1){if(r){this.refused(e,r);return}try{e.send(xI(2,"subscribe",new Map([[0,this.collectionBytes],[1,0],[2,FT]])))}catch{this.lost(e,1006)}return}if(s===2){if(r){this.refused(e,r);return}let a=o.get(2);if(!(a instanceof Map)){this.lost(e,1007);return}let p=a.get(0),l=a.get(1);this.startPing(e),this.setLive(!0),(typeof p=="number"||typeof p=="bigint")&&l instanceof Uint8Array&&l.length===32&&this.deliver(pe(new Map([[0,2],[1,"head"],[2,new Map([[0,this.collectionBytes],[1,p],[2,l]])]])))}}deliver(e){try{this.events.push(e)}catch{}}refused(e,t){if(t.code==="forbidden"&&t.reason==="credentials_revoked"){this.end("revoked");return}if(t.code==="forbidden"||t.code==="not_found"){this.end(t.code==="not_found"?"gone":"forbidden");return}if(t.code==="gone"){this.end("gone");return}t.code==="unauthenticated"&&this.token&&(this.source.invalidateToken?.(this.token),this.token=null),this.lost(e,1008)}startPing(e){this.clearPing(),this.ping=setInterval(()=>{if(!(e!==this.socket||this.pongDue!==null)){try{e.send("ping")}catch{this.lost(e,1006);return}this.pongDue=setTimeout(()=>{this.pongDue=null,this.lost(e,1006)},UT)}},NT)}lost(e,t){if(e!==this.socket)return;let i=this.isLive&&this.now()-this.liveSince>=DT;if(this.drop(1e3,"lost"),t===LT){this.end("forbidden");return}if(t===jT){this.end("gone");return}if(i&&(this.attempts=0),t===MT){this.token&&this.source.invalidateToken?.(this.token),this.token=null,this.attempts=0,this.schedule(!0);return}this.schedule()}};uw();Fn();Xc();function Wh(n){return n.mode==="local_only"?null:n.incidents.some(e=>e.kind==="waiting_for_key")?"waiting_for_key":n.installing?"installing":n.resyncing?"resyncing":n.connection==="offline"?"offline":n.headKnown===0?"head_unknown":n.confirmedThrough<n.headKnown?"behind":null}function CI(n){let e=n.incidents.find(r=>r.kind==="waiting_for_key");if(!e)return null;let t={through:n.confirmedThrough,head:n.headKnown},i=e.details,o=r=>i instanceof Map?i.get(r):i&&typeof i=="object"?i[r]:void 0,s=o("reason");typeof s=="string"&&/^[a-z_]{1,32}$/.test(s)&&(t.key=s);for(let r of["position","at"]){let a=o(r);(typeof a=="number"||typeof a=="bigint")&&(t[r]=Number(a))}return t}xh();Qc();Je();ge();Fc();var Hh=264*1024+256,Ww=264*1024,De=()=>new Error("app cloud copy outcome unavailable; preserve storage and reopen"),Hw=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),GT=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),Gh=class{constructor(e,t,i,o,s){this.source=e;this.store=o;this.key=i;try{this.mode=s.mode,this.lifetime=s.signal,this.fields=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId,collection:e.collection,purpose:e.purpose,cpOrigin:e.cpOrigin,logOrigin:e.logOrigin,assetSha256:e.assetSha256});let r=e.displayName;if(this.displayName=r===void 0?void 0:br(r),this.displayName!==void 0&&e.purpose!=="create"||r!==this.displayName)throw De();this.current=e.isCurrent,this.owned=e.installationOwned,this.io=Object.freeze({read:o.read,cas:o.compareAndSet});let a=[e.accountId,e.connectorId,e.deviceId,e.installationId,e.collection].map(U);if(a.some(p=>p.every(l=>l===0))||!["create","join"].includes(e.purpose)||!["fresh","existing"].includes(this.mode)||!/^[0-9a-f]{64}$/.test(e.assetSha256)||(this.keys=Object.freeze([t.signPublicKey,t.kemPublicKey,t.noisePublicKey].map(p=>{if(!(p instanceof Uint8Array)||p.length!==32||p.every(l=>l===0))throw De();return new Uint8Array(p)})),t.connectorId!==e.connectorId||t.deviceId!==e.deviceId||t.installationId!==e.installationId)||typeof globalThis.CryptoKey!="function"||!(i instanceof CryptoKey)||i.type!=="secret"||i.extractable||i.algorithm.name!=="AES-GCM"||i.algorithm.length!==256||i.usages.length!==2||!i.usages.includes("encrypt")||!i.usages.includes("decrypt"))throw De();this.aad=pe(["mdbase/v1/app-cloud-copy-outcome-platform",...a,e.purpose,e.cpOrigin,e.logOrigin,e.assetSha256,...this.keys]),this.check(this.lifetime)}catch{throw De()}}source;store;closed=!1;key;fields;displayName;current;owned;io;keys;aad;mode;lifetime;check(e){try{if(this.closed||!this.key||e!==this.lifetime||e.aborted||this.source.displayName!==this.displayName||this.source.isCurrent!==this.current||this.source.installationOwned!==this.owned||this.current.call(this.source)!==!0||this.owned.call(this.source)!==!0||this.store.read!==this.io.read||this.store.compareAndSet!==this.io.cas||Object.entries(this.fields).some(([t,i])=>this.source[t]!==i))throw De()}catch{throw De()}}operation(e){if(e){if(e.displayName!==this.displayName)throw De();for(let t of Object.keys(this.fields))if(e[t]!==this.fields[t])throw De();for(let[t,i]of["signPublicKey","kemPublicKey","noisePublicKey"].entries())if(!(e[i]instanceof Uint8Array)||!Hw(e[i],this.keys[t]))throw De()}return Object.freeze({...this.fields,...this.displayName===void 0?{}:{displayName:this.displayName},signPublicKey:new Uint8Array(this.keys[0]),kemPublicKey:new Uint8Array(this.keys[1]),noisePublicKey:new Uint8Array(this.keys[2])})}metadata(e){let t=this.operation(e.operation);if(!(e.genesisItem instanceof Uint8Array)||!e.genesisItem.length||e.genesisItem.length>256*1024||typeof e.expectedGenesis!="string"||!/^sha256:[0-9a-f]{64}$/.test(e.expectedGenesis))throw De();return Object.freeze({operation:t,genesisItem:new Uint8Array(e.genesisItem),expectedGenesis:e.expectedGenesis})}async hashChecked(e,t){let i=new TextEncoder().encode("mdbase/v1/chain"),o=new Uint8Array(1+i.length+e.genesisItem.length);o[0]=i.length,o.set(i,1),o.set(e.genesisItem,1+i.length);let s=new Uint8Array(await crypto.subtle.digest("SHA-256",o));if(this.check(t),e.expectedGenesis!==`sha256:${GT(s)}`)throw De()}async read(e){let t=null;try{this.check(e);let i=await this.io.read.call(this.store,Object.freeze({signal:e}));if(this.check(e),i===null){if(this.mode!=="fresh")throw De();return null}if(!(i instanceof Uint8Array)||!i.length||i.length>Hh)throw De();let o=new Uint8Array(i),s=ue(o);if(!(s instanceof Map))throw De();let r=s;if(r.size!==3||r.get(0)!==1)throw De();let a=r.get(1),p=r.get(2);if(!(a instanceof Uint8Array)||a.length!==12||!(p instanceof Uint8Array)||p.length<16||p.length>Ww+16||(t=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(a),additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(p))),this.check(e),t.length>Ww))throw De();let l=ue(t);if(!(l instanceof Map))throw De();let c=l,d=c.get(0)===1&&c.size===3;if(!d&&!(c.get(0)===2&&c.size===4)||(d?null:c.get(3))!==(this.displayName??null))throw De();let u=c.get(1);if(!Array.isArray(u)||u.length!==3||u.some((m,b)=>!(m instanceof Uint8Array)||!Hw(m,this.keys[b])))throw De();let f=c.get(2),h=null;if(f!==null){if(!Array.isArray(f)||f.length!==2||!(f[0]instanceof Uint8Array)||typeof f[1]!="string")throw De();h=this.metadata({operation:this.operation(),genesisItem:f[0],expectedGenesis:f[1]}),await this.hashChecked(h,e)}return{encrypted:o,metadata:h}}catch{throw De()}finally{t?.fill(0)}}async write(e,t,i){let o=null,s=null;try{if(this.check(i),o=pe(new Map([[0,2],[1,this.keys.map(l=>new Uint8Array(l))],[2,e===null?null:[e.genesisItem,e.expectedGenesis]],[3,this.displayName??null]])),o.length>Ww)throw De();let r=crypto.getRandomValues(new Uint8Array(12)),a=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:r,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(o)));if(this.check(i),s=pe(new Map([[0,1],[1,r],[2,a]])),s.length>Hh)throw De();let p=await this.io.cas.call(this.store,t,s,Object.freeze({signal:i}));if(this.check(i),p!==!0)throw De()}catch{throw De()}finally{o?.fill(0),s?.fill(0)}}async restore(e){let{signal:t}=e,i=await this.read(t);return this.check(t),i===null?Object.freeze({state:"none"}):i.metadata===null?Object.freeze({state:"pending",operation:this.operation()}):Object.freeze({state:"completed",metadata:this.metadata(i.metadata)})}async pending(e,t){let{signal:i}=t;this.check(i),this.operation(e);let o=await this.read(i);this.check(i),!o&&await this.write(null,null,i)}async completed(e,t){let{signal:i}=t;this.check(i);let o=this.metadata(e);await this.hashChecked(o,i);let s=await this.read(i);if(this.check(i),!s)throw De();if(s.metadata){if(!Hw(s.metadata.genesisItem,o.genesisItem)||s.metadata.expectedGenesis!==o.expectedGenesis)throw De();return}await this.write(o,s.encrypted,i)}close(){this.closed=!0,this.key=null}};Jn();ge();var Yh="public-outcome",Gw="operation",Gt=()=>new Error("app cloud copy outcome store unavailable; preserve storage and reopen"),YT=(n,e)=>n===null||e===null?n===e:n.length===e.length&&n.every((t,i)=>t===e[i]);function Yw(n){if(!(n instanceof Uint8Array)||!n.length||n.length>Hh)throw Gt();return new Uint8Array(n)}var Jh=class n{constructor(e,t,i){this.source=e;this.origin=t;this.lifetime=i;this.fields=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId,collection:e.collection,purpose:e.purpose,cpOrigin:e.cpOrigin,logOrigin:e.logOrigin,assetSha256:e.assetSha256}),this.current=e.isCurrent,this.owned=e.installationOwned}source;origin;lifetime;db=null;closed=!1;fields;current;owned;get fenced(){return this.closed||this.lifetime.aborted}check(e){try{if(this.fenced||e!==this.lifetime||e.aborted||Rt()!==this.origin||this.source.isCurrent!==this.current||this.source.installationOwned!==this.owned||this.current.call(this.source)!==!0||this.owned.call(this.source)!==!0||Object.entries(this.fields).some(([t,i])=>this.source[t]!==i))throw Gt()}catch{throw Gt()}}static async open(e){let{source:t,origin:i,mode:o,signal:s,allowLoopbackHttp:r}=e,a=null;try{a=new n(t,i,s);let p=[a.fields.accountId,a.fields.connectorId,a.fields.deviceId,a.fields.installationId,a.fields.collection].map(c=>{if(U(c).every(d=>d===0))throw Gt();return c.toLowerCase()});if(!Lt(i,r===!0,e.allowNativeLoopbackHttp===!0?"native":void 0)||!["fresh","existing"].includes(o)||!["create","join"].includes(a.fields.purpose)||!/^[0-9a-f]{64}$/.test(a.fields.assetSha256)||!globalThis.indexedDB)throw Gt();a.check(s),a.db=await a.openDatabase(`mdbase.app.cloud-copy-outcome.v1.${p.join(".")}.${a.fields.purpose}`,o),a.db.onversionchange=()=>a.close(),a.check(s);let l=await a.read(Object.freeze({signal:s}));try{if(o==="fresh"!=(l===null))throw Gt();a.check(s)}finally{l?.fill(0)}return a}catch{throw a?.close(),Gt()}}openDatabase(e,t){return new Promise((i,o)=>{this.check(this.lifetime);let s=indexedDB.open(e,1),r=!1,a=!1,p=()=>{r=!0,o(Gt())},l=()=>this.lifetime.removeEventListener("abort",p);this.lifetime.addEventListener("abort",p,{once:!0}),s.onblocked=p,s.onupgradeneeded=()=>{try{if(this.check(this.lifetime),r||t!=="fresh"||s.result.objectStoreNames.length!==0)throw Gt();s.result.createObjectStore(Yh),a=!0}catch{s.transaction?.abort()}},s.onerror=()=>{l(),o(Gt())},s.onsuccess=()=>{l();try{if(this.check(this.lifetime),r||t==="fresh"&&!a||s.result.objectStoreNames.length!==1||!s.result.objectStoreNames.contains(Yh))throw Gt();i(s.result)}catch{s.result.close(),o(Gt())}}})}async read(e){let{signal:t}=e;this.check(t);let i=await this.transaction("readonly",t,null,null);return this.check(t),i}async compareAndSet(e,t,i){let{signal:o}=i;this.check(o);let s=e===null?null:Yw(e),r=Yw(t);try{let a=await this.transaction("readwrite",o,s,r);return this.check(o),a===!0}finally{s?.fill(0),r.fill(0)}}transaction(e,t,i,o){return new Promise((s,r)=>{if(this.check(t),!this.db)throw Gt();let a=this.db.transaction(Yh,e,{durability:"strict"}),p=a.objectStore(Yh),l=null,c=!1,d=()=>{c=!0;try{a.abort()}catch{}},u=()=>t.removeEventListener("abort",d);t.addEventListener("abort",d,{once:!0}),a.onabort=a.onerror=()=>{u(),l instanceof Uint8Array&&l.fill(0),r(Gt())},a.oncomplete=()=>{u();try{if(this.check(t),c)throw Gt();s(l)}catch{l instanceof Uint8Array&&l.fill(0),r(Gt())}};let f=p.get(Gw);f.onsuccess=()=>{let h=null;try{this.check(t),h=f.result===void 0?null:Yw(f.result),e==="readonly"?(l=h,h=null):(l=YT(h,i),l===!0&&o!==null&&(i===null?p.add(new Uint8Array(o),Gw):p.put(new Uint8Array(o),Gw)))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db?.close(),this.db=null)}};var co=class extends Error{constructor(t){super(`app cloud copy host: ${t}`);this.reason=t;this.name="AppCloudCopyHostError"}reason},JT=32,XT=8,Ae=n=>new co(n),II=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),ml=class n{constructor(e,t,i,o,s){this.source=e;this.installation=t;this.originalRelease=i;this.origin=o;this.lifetime=s;this.selected=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId,kind:e.kind,cpOrigin:e.cpOrigin,logOrigin:e.logOrigin,approvalMode:e.approvalMode}),this.currentCallback=e.isCurrent,this.bearerCallback=e.connectorBearer,this.ownershipCallback=t.isCurrent;for(let r of[e.accountId,e.connectorId,e.deviceId,e.installationId])if(U(r).every(a=>a===0))throw Ae("binding");if(e.kind!=="app-runtime"&&e.kind!=="mobile"||i.schema!=="mdbn-app-trust/release/1"||i.cpOrigin!==e.cpOrigin||i.logOrigin!==e.logOrigin||!/^[0-9a-f]{64}$/.test(i.assetSha256)||!i.trustedRoots.length||i.trustedRoots.length>64||!i.policyPins.length||i.policyPins.length>65536)throw Ae("binding");if(this.trust=Object.freeze({...i,source:Object.freeze({...i.source}),trustedRoots:Object.freeze(i.trustedRoots.map(r=>{if(!(r instanceof Uint8Array)||r.length!==32||r.every(a=>a===0))throw Ae("binding");return new Uint8Array(r)})),policyPins:new Uint8Array(i.policyPins)}),this.pin=Object.freeze({...this.selected,isCurrent:()=>this.current(),installationOwned:()=>this.current(),connectorBearer:async({signal:r})=>{this.check(r);let a=await this.bearerCallback.call(this.source,Object.freeze({signal:r}));return this.check(r),a}}),e.approvalMode==="strict")throw new an;this.check(s)}source;installation;originalRelease;origin;lifetime;closing=!1;closeResult=null;provider=null;keys=null;noiseStore=null;key=null;noise=null;native=null;publicReceipt=null;signIn=null;originalCustody=null;collectionAttempted=!1;collectionSignal=null;collectionCurrent=null;outcomeStore=null;outcome=null;bootstrap=null;bootstrapConfirmed=!1;collectionScope=null;collectionSession=null;adoptedEndpoint=null;sqlAttempted=!1;sqlClose=null;collectionSql=null;logRequest=null;logLoopback=!1;logWork=null;authority=null;peopleMetadata=null;pump=null;timerPorts=new Set;readWork=null;readAbort=null;readClient=null;readVerified=!1;facades=new Map;logWorkListener=null;selected;currentCallback;bearerCallback;ownershipCallback;trust;pin;current(){try{let e=this.originalRelease,t=this.trust;return!this.closing&&!this.lifetime.aborted&&Rt()===this.origin&&this.source.isCurrent===this.currentCallback&&this.source.connectorBearer===this.bearerCallback&&this.installation.isCurrent===this.ownershipCallback&&this.currentCallback.call(this.source)===!0&&this.ownershipCallback.call(this.installation)===!0&&this.installation.scope.account===this.selected.accountId&&this.installation.scope.installation===this.selected.installationId&&Object.entries(this.selected).every(([i,o])=>this.source[i]===o)&&e.schema===t.schema&&e.environment===t.environment&&e.cpOrigin===t.cpOrigin&&e.logOrigin===t.logOrigin&&e.assetSha256===t.assetSha256&&e.source.repository===t.source.repository&&e.source.commit===t.source.commit&&e.source.version===t.source.version&&e.trustedRoots.length===t.trustedRoots.length&&e.trustedRoots.every((i,o)=>II(i,t.trustedRoots[o]))&&II(e.policyPins,t.policyPins)}catch{return!1}}check(e){if(e.aborted||!this.current())throw Ae("fenced")}operationSignal(e){let t=AbortSignal.any([this.lifetime,...this.collectionSignal?[this.collectionSignal]:[],e]);return this.check(t),t}static async openOriginalDevice(e){let{session:t,installation:i,release:o,origin:s,mode:r,signal:a,loadRuntime:p,fetch:l,allowLoopbackHttp:c,allowNativeLoopbackHttp:d}=e,u=null;try{if(!["fresh","existing"].includes(r))throw Ae("binding");u=new n(t,i,o,s,a);let{custody:f,restored:h}=await u.openOwnedDevice({mode:r,signal:a,loadRuntime:p,allowLoopbackHttp:c,allowNativeLoopbackHttp:d,requireReceipt:!0});if(r==="existing")u.native.acknowledgeDeviceRegistration(h.receipt),u.check(a),u.publicReceipt=u.native.registeredDeviceReceipt();else{let m=await new sl(u.native,u.pin,f,u.noise,{fetch:l,allowLoopbackHttp:c}).register(Object.freeze({signal:a}));u.check(a),u.publicReceipt=m}return u}catch(f){throw await u?.close(),f instanceof co||f instanceof an?f:Ae("unavailable")}}static async openInstallationDevice(e){let{signIn:t,installation:i,release:o,origin:s,signal:r,loadRuntime:a,allowLoopbackHttp:p,allowNativeLoopbackHttp:l}=e,c=null;try{let d=t.confirmedHostSession(o.logOrigin,o.environment);c=new n(d,i,o,s,r),c.signIn=t;let u=await t.prepareOriginalDevice(i);c.check(r);let{custody:f,restored:h}=await c.openOwnedDevice({mode:u.mode,signal:r,loadRuntime:a,allowLoopbackHttp:p,allowNativeLoopbackHttp:l,requireReceipt:!1});if(c.originalCustody=f,h?.receipt&&t.view().state!=="paired")throw Ae("recovery_required");return await c.noise.pending(new Uint8Array(f.envelope),{signal:r}),c.check(r),t.view().state==="paired"&&await c.completeInstallationSignIn(),c}catch(d){throw await c?.close(),d}}async attestInstallation(){if(this.check(this.lifetime),!this.signIn||!this.native||!this.originalCustody||!this.noise)throw Ae("binding");let e=await this.signIn.attest({runtime:this.native,custody:this.originalCustody,persistence:this.noise,installation:this.installation});return this.check(this.lifetime),e}async completeInstallationSignIn(){if(this.check(this.lifetime),!this.signIn||!this.native||!this.originalCustody||!this.noise)throw Ae("binding");return await this.signIn.acknowledge({runtime:this.native,custody:this.originalCustody,persistence:this.noise,installation:this.installation}),this.check(this.lifetime),this.publicReceipt=this.native.registeredDeviceReceipt(),this.registeredReceipt()}async openOwnedDevice(e){let{mode:t,signal:i,loadRuntime:o,allowLoopbackHttp:s,allowNativeLoopbackHttp:r,requireReceipt:a}=e;this.check(i),this.provider=await ll.open({source:this.pin,origin:this.origin,mode:t,signal:i,allowLoopbackHttp:s,allowNativeLoopbackHttp:r}),this.check(i),this.key=this.provider.deviceCustodyKek({signal:i}),this.check(i),this.keys=await cl.open({source:this.pin,origin:this.origin,mode:t,signal:i,allowLoopbackHttp:s,allowNativeLoopbackHttp:r}),this.check(i),this.noiseStore=await dl.open({source:this.pin,origin:this.origin,mode:t,signal:i,allowLoopbackHttp:s,allowNativeLoopbackHttp:r}),this.check(i),this.noise=new pl(this.pin,this.key,this.noiseStore);let p=await this.noise.restore({signal:i});if(this.check(i),t==="existing"?!p||a&&!p.receipt:p!==null)throw Ae("recovery_required");let l=await o(Object.freeze({signal:i}));if(this.check(i),!(l instanceof Uint8Array)||!l.length)throw Ae("binding");this.native=await fl.createDevice(new Uint8Array(l)),this.check(i);let c=await new al(this.pin,this.key,this.keys).openNativeDevice(this.native,{signal:i,mode:t,noise:t==="fresh"?{mode:"fresh"}:{mode:"existing",envelope:p.envelope}});return this.check(i),{custody:c,restored:p}}async bootstrapCloudCopy(e){let{scope:t,collectionCurrent:i,purpose:o,outcomeMode:s,signal:r,reconcile:a,fetch:p,allowLoopbackHttp:l,allowNativeLoopbackHttp:c}=e,d=this.operationSignal(r),u=e.displayName,f=u===void 0?void 0:br(u);if(f!==void 0&&o!=="create"||(this.check(d),this.collectionAttempted||!this.native||!this.key||!this.publicReceipt||t.account!==this.selected.accountId||t.installation!==this.selected.installationId||!["create","join"].includes(o)||!["fresh","existing"].includes(s)||U(t.collection).every(w=>w===0)))throw Ae("binding");let h=Object.freeze({account:t.account,installation:t.installation,collection:t.collection}),m=()=>{try{return this.current()&&!d.aborted&&e.scope===t&&e.collectionCurrent===i&&Object.entries(h).every(([w,g])=>t[w]===g)&&i.call(e)===!0&&this.outcomeStore?.fenced!==!0}catch{return!1}};if(!m())throw Ae("fenced");this.collectionAttempted=!0,this.collectionSignal=d,this.collectionCurrent=m,this.collectionScope=h;let b=Object.freeze({...this.pin,collection:h.collection,purpose:o,assetSha256:this.trust.assetSha256,...f===void 0?{}:{displayName:f},isCurrent:m});this.collectionSession=b;try{this.outcomeStore=await Jh.open({source:b,origin:this.origin,mode:s,signal:d,allowLoopbackHttp:l,allowNativeLoopbackHttp:c}),this.checkCollection(d),this.outcome=new Gh(b,this.publicReceipt,this.key,this.outcomeStore,{mode:s,signal:d}),this.native.prepareCloudCopyCollection(b),this.checkCollection(d),this.bootstrap=new $a(this.native,b,this.trust,this.outcome,{fetch:p,allowLoopbackHttp:l,...f===void 0?{}:{displayName:f}});let w=await this.bootstrap.bootstrap(Object.freeze({signal:d,...a?{reconcile:a}:{}}));return this.checkCollection(d),this.bootstrapConfirmed=!0,w}catch(w){throw await this.close(),w}}checkCollection(e){if(this.check(e),this.collectionCurrent?.()!==!0)throw Ae("fenced")}adoptCloudCopy(e,t){let i=this.operationSignal(e.signal);if(this.checkCollection(i),!this.bootstrap||!this.bootstrapConfirmed||this.adoptedEndpoint!==null)throw Ae("fenced");let o=e.endpoint;this.bootstrap.adoptCollection({...e,signal:this.collectionSignal},t),this.checkCollection(i),this.adoptedEndpoint=o}async openCollectionSql(e){let{replicaId:t,endpoint:i,openSql:o}=e,s=this.operationSignal(e.signal);if(this.checkCollection(s),!this.bootstrapConfirmed||!this.collectionScope||this.sqlAttempted||this.adoptedEndpoint!==null||U(t).every(r=>r===0)||typeof i!="bigint"&&!Number.isSafeInteger(i)||BigInt(i)<0n||BigInt(i)>(1n<<64n)-1n)throw Ae("binding");this.sqlAttempted=!0;try{let r=await o.call(e,Object.freeze({scope:this.collectionScope,signal:s})),a=r.close;if(this.sqlClose=async()=>{await a.call(r)},this.collectionSql=r.sql,this.checkCollection(s),e.openSql!==o)throw Ae("fenced");this.adoptCloudCopy({signal:s,replicaId:t,endpoint:i,opened:r.opened,sqliteVersion:r.sqliteVersion,cloudCopyOptIn:!0},r.sql)}catch(r){throw await this.close(),r}}async startCollectionLog(e){let{fetch:t,allowLoopbackHttp:i}=e,o=this.operationSignal(e.signal);if(this.checkCollection(o),!this.native||!this.collectionSession||this.adoptedEndpoint===null)throw Ae("binding");let s=t??globalThis.fetch,r=i===!0;if(this.authority&&(s!==this.logRequest||r!==this.logLoopback))throw Ae("fenced");if(this.pump)return;if(this.logWork){await this.logWork,this.checkCollection(o);return}this.authority||(this.logRequest=s,this.logLoopback=r,this.authority=new Da(this.native,Object.freeze({...this.collectionSession,endpoint:this.adoptedEndpoint,directOrigins:Object.freeze([])}),{fetch:s,allowLoopbackHttp:i,tokenCache:SI()}));let a=this.authority,p=(async()=>{await a.accessToken(Object.freeze({signal:o})),this.checkCollection(o),this.pump=this.native.bindLogTransport(a.logTransport())})();this.logWork=p;try{await p}finally{this.logWork===p&&(this.logWork=null)}}peopleAuthority(){if(this.checkCollection(this.lifetime),!this.collectionSession||this.adoptedEndpoint===null||!this.logRequest)throw Ae("binding");if(!this.peopleMetadata){let e=this.adoptedEndpoint,t=this.collectionSession,i=new ul(Object.freeze({...t,endpoint:e,directOrigins:Object.freeze([]),isCurrent:()=>this.collectionCurrent?.()===!0&&this.adoptedEndpoint===e,connectorBearer:async({signal:s})=>{s.throwIfAborted(),this.checkCollection(this.lifetime);let r=await t.connectorBearer({signal:this.lifetime});return this.checkCollection(this.lifetime),s.throwIfAborted(),r}}),{fetch:this.logRequest,allowLoopbackHttp:this.logLoopback}),o=Object.freeze({collection:i.collection,isCurrent:()=>i.isCurrent(),request:(s,r)=>i.request(s,r)});this.peopleMetadata={authority:i,view:o}}return this.peopleMetadata.view}openTimersPort(e){if(this.checkCollection(this.lifetime),!this.readVerified||!this.logRequest||!this.collectionScope||e.signal.aborted)throw Ae("binding");let{scope:t,generation:i,signal:o}=e,s=this.collectionScope;if(t.account!==s.account||t.installation!==s.installation||t.collection!==s.collection||U(i).every(h=>h===0))throw Ae("binding");let r=this.source.timerConsent,a=r?.call(this.source);if(!a?.approved)return null;let p=a.grants.find(h=>h.collectionId===t.collection);if(!p)return null;let l=globalThis.WorkerGlobalScope;if(typeof l!="function"||!(globalThis instanceof l)||U(p.grantId).every(h=>h===0)||!/^[0-9a-f]{64}$/.test(p.declarationDigest))throw Ae("binding");let c=JSON.stringify(a),d=new MessageChannel,u=()=>{try{return!o.aborted&&e.signal===o&&e.scope===t&&e.generation===i&&this.collectionCurrent?.()===!0&&this.current()&&t.account===s.account&&t.installation===s.installation&&t.collection===s.collection&&this.source.timerConsent===r&&JSON.stringify(r?.call(this.source))===c}catch{return!1}},f=hC(d.port1,{scope:s,generation:i,grantId:p.grantId,cpOrigin:new URL(this.selected.cpOrigin).origin,signal:o,isCurrent:u,fetch:this.logRequest,...this.signIn?{journal:{read:()=>this.signIn.originalTimerChannel(p.grantId),write:h=>this.signIn.retainTimerChannel(p.grantId,h)}}:{},bearer:async()=>{if(!u())throw Ae("fenced");let h=await this.bearerCallback.call(this.source,{signal:this.lifetime});if(!u())throw Ae("fenced");return h}});return this.timerPorts.add(f),Object.freeze({port:d.port2,close:async()=>{await f.close(),d.port2.close(),this.timerPorts.delete(f)}})}serverProblem(){return this.pump?.serverProblem??null}transportHealth(){return this.pump?.transportHealth??null}initialSync(){try{return this.native?Wh(this.native.observations().status):"unavailable"}catch{return"unavailable"}}keyWaitDetail(){try{return this.native?CI(this.native.observations().status):null}catch{return null}}pendingWrites(){try{return this.native?.observations().status.pending??0}catch{return 0}}pushLog(e){try{return this.native?.pushLog(e)===!0}catch{return!1}}openLogPush(e){this.checkCollection(this.lifetime);let t=this.native,i=this.authority,o=this.collectionSession,s=this.logRequest;if(!t||!this.pump||!i||!o||!s)throw Ae("binding");if(!t.supportsLogPush||typeof WebSocket!="function")return null;let r=this.logLoopback,a=i.origin,p=()=>{try{return this.collectionCurrent?.()===!0&&this.current()&&this.authority===i&&i.isCurrent()}catch{return!1}};return new Kh({origin:a,collection:i.collection,deviceId:o.deviceId,isCurrent:p,accessToken:l=>i.accessToken(l),invalidateToken:l=>i.invalidateToken(l),nonce:async({signal:l})=>{let c=await s(`${a}/v1/nonce`,{signal:l,cache:"no-store",credentials:"omit",redirect:"error",referrerPolicy:"no-referrer"}),d=(await c.text()).trim();if(!c.ok||!/^[0-9a-f]{64}$/.test(d))throw Ae("unavailable");return Uint8Array.from(d.match(/../g).map(u=>parseInt(u,16)))},signHello:(l,c)=>p()?t.signLogHello(l,c):null},e,{allowLoopbackHttp:r})}async driveCollection(e){let t=this.operationSignal(e.signal);if(this.checkCollection(t),!this.native||!this.pump||this.adoptedEndpoint===null)throw Ae("binding");for(let i=0;i<XT;i++){let o=this.pump.callsSent;if(this.native.tick(),await this.pump.pump(),this.checkCollection(t),this.pump?.callsSent===o)break}}async wakeCollectionLog(e){let t=this.operationSignal(e.signal);if(this.checkCollection(t),!this.native||!this.pump||this.adoptedEndpoint===null)throw Ae("binding");this.native.tick(),(await this.pump.pump()).quiet&&(this.checkCollection(t),this.native.requestLogHead()&&(await this.pump.pump(),this.checkCollection(t),this.native.tick()))}waitForVerifiedRead(e){let{timeoutMs:t=15e3,cold:i=!1}=e,o=this.operationSignal(e.signal);if(this.checkCollection(o),!this.native||!this.collectionScope||this.adoptedEndpoint===null||!Number.isSafeInteger(t)||t<1||t>15e3||typeof i!="boolean"||i&&!this.pump)throw Ae("binding");if(this.readWork)return this.readWork.then(()=>{this.checkCollection(o)});let s=this.verifyRead(o,t,i,e.onProgress);return this.readWork=s,s.finally(()=>{this.readWork===s&&(this.readWork=null)}).catch(()=>{}),s}async verifyRead(e,t,i,o){let s=new AbortController,r=()=>s.abort();this.readAbort=s,e.addEventListener("abort",r,{once:!0});let a=null,p=Ae(i?"sync_stalled":"unavailable"),l,c=new Promise((h,m)=>{l=()=>m(p),s.signal.addEventListener("abort",l,{once:!0})});c.catch(()=>{});let d=null,u=h=>{if(h!==d){d=h;try{o?.(h)}catch{}}},f=()=>{this.checkCollection(e);let h=i?this.pump.terminalProblem:null;if(kn(h))throw new mn(St(h)??"unavailable",h);let m=this.native.observations();if(m.requiresReopen||m.keyringRebuildFailed)throw Ae("recovery_required");let b=Wh(m.status);return u(b==="installing"?"loading_snapshot":b==="waiting_for_key"?"waiting_for_key":b==="behind"?"replaying":b===null?"verifying_read":"syncing"),m};this.readVerified=!1;try{if(this.pump){let m=()=>{let _=f();return[_.status.confirmedThrough,_.status.installing?.done??0,_.status.installing?.total??0,this.pump.readProgress]},b=m(),w=Date.now(),g=new Map,y=null,v=()=>{try{let _=Date.now(),k=m();k.some((C,E)=>C>b[E])&&(w=_,y=null),b=k.map((C,E)=>Math.max(C,b[E]));let S=this.pump.responseProgress(),x=new Set(S.map(C=>C.id));for(let C of g.keys())x.has(C)||g.delete(C);for(let C of S){let E=g.get(C.id);C.bytes>(E?.bytes??0)&&g.set(C.id,{bytes:C.bytes,at:_})}let P=t-(_-w);P<=0&&(y??=new Set(g.keys()),P=Math.max(0,...[...y].map(C=>{let E=g.get(C);return E?t-(_-E.at):0}))),P<=0?r():a=setTimeout(v,Math.min(250,P))}catch(_){p=_,r()}};a=setTimeout(v,Math.min(250,t))}else a=setTimeout(r,t);this.readClient=await Promise.race([Ei.connect({app:{name:"app-local-read-gate",version:"1"},connector:Ds(this.native,{collection:this.collectionScope.collection}),reconnect:!1,signal:s.signal}).then(m=>{if(s.signal.aborted)throw m.close(),Ae("unavailable");return m}),c]),this.checkCollection(e);let h=250;for(;!s.signal.aborted;){this.native.tick(),this.pump&&await Promise.race([this.pump.pump(),c]),this.checkCollection(e);let m=f();if(i&&Wh(m.status)!==null){await pp(h,s.signal),h=Math.min(1e3,h*2);continue}try{if(await Promise.race([this.readClient.query({limit:1},void 0,s.signal),c]),this.checkCollection(e),s.signal.aborted)throw Ae("unavailable");this.readVerified=!0;return}catch(b){if(this.checkCollection(e),!(b instanceof se)||b.code!=="unavailable"||!this.pump||s.signal.aborted)throw b}await pp(h,s.signal),h=Math.min(1e3,h*2)}throw Ae("unavailable")}catch(h){throw this.checkCollection(e),s.signal.aborted?p:h}finally{a!==null&&clearTimeout(a),e.removeEventListener("abort",r),s.signal.removeEventListener("abort",l),this.readClient?.close(),this.readClient=null,this.readAbort=null}}onLogWork(e){this.logWorkListener=e}attachDataFacade(e){if(this.checkCollection(this.lifetime),!this.native||!this.collectionScope||!this.readVerified||this.facades.size>=JT||this.facades.has(e))throw Ae("fenced");let t=Object.freeze({...this.collectionScope,isCurrent:()=>{try{return this.checkCollection(this.lifetime),!0}catch{return!1}}}),i=Sh(this.native,e,t,()=>this.logWorkListener?.());return this.facades.set(e,i),i.resourceSetup}detachDataFacade(e){let t=this.facades.get(e);t&&(this.facades.delete(e),t.close())}registeredReceipt(){this.check(this.lifetime);let e=this.publicReceipt;if(!e)throw Ae("fenced");return Object.freeze({...e,signPublicKey:new Uint8Array(e.signPublicKey),kemPublicKey:new Uint8Array(e.kemPublicKey),noisePublicKey:new Uint8Array(e.noisePublicKey)})}close(){if(this.closing=!0,this.readVerified=!1,this.readAbort?.abort(),this.closeResult)return this.closeResult;let e=!1;for(let t of[()=>this.readClient?.close(),()=>{for(let i of this.facades.values())i.close();this.facades.clear()},()=>this.peopleMetadata?.authority.close(),()=>this.bootstrap?.close(),()=>this.outcome?.close()])try{t()}catch{e=!0}return this.closeResult??=(async()=>{try{await Promise.all([...this.timerPorts].map(async i=>{try{await i.close()}catch{e=!0}})),this.timerPorts.clear();let t=await this.native?.close();if(this.collectionSql&&t!==!0&&this.collectionSql.fence(),this.authority?.close(),await this.sqlClose?.(),e)throw Ae("unavailable")}finally{this.key=null,this.noise=null,this.originalCustody?.envelope.fill(0),this.originalCustody=null,this.signIn=null,this.publicReceipt=null,this.outcomeStore?.close(),this.noiseStore?.close(),this.keys?.close(),this.provider?.close()}})()}};lx();ie();Yc();Qc();Go();no();kh();Zc();Xc();eo();Fn();var ZT=new Set(["binding","fenced","busy","open_in_another_tab","account_confirmation_required","recovery_account_mismatch","outcome_unknown","response","refused","expired","recovery_required","unavailable","collection_migrating","collection_not_yet_migrated","account_suspended","update_required"]),QT=new Set(["AbortError","ConstraintError","DataCloneError","InvalidStateError","NotAllowedError","NotFoundError","NotReadableError","OperationError","QuotaExceededError","SecurityError","TimeoutError","TransactionInactiveError","UnknownError","VersionError"]),po=(n,e,t,i)=>Object.freeze({problem:n,detail:Object.freeze({name:e,code:t,...i?{server:i}:{}})});function Jw(n){try{for(let[e,t]of[[Xe,"AppInstallationSignInError"],[co,"AppCloudCopyHostError"],[en,"AppCloudCopyBootstrapError"],[nn,"AppCollectionSetupError"],[ti,"AppCollectionControlError"],[lo,"AppCollectionJoinError"],[Zn,"AppCpAuthorityError"],[mn,"AppHttpLogError"]])if(n instanceof e){let i=n.reason,o=("server"in n?Ur(n.server):null)??void 0;return i==="sync_stalled"?po("unavailable",t,i,o):ZT.has(i)?po(i,t,i,o):po("open_failed",t,null,o)}if(n instanceof We&&n.reason==="busy")return po("open_in_another_tab","AppReplicaOwnerError","busy");if(n instanceof se){let e=Sr(n.code)?n.code:null;return po(e==="outcome_unknown"?e:"open_failed","MdbaseError",e)}if(typeof DOMException<"u"&&n instanceof DOMException){let e=QT.has(n.name)?n.name:null;return po("open_failed","DOMException",e)}for(let[e,t]of[[TypeError,"TypeError"],[RangeError,"RangeError"],[SyntaxError,"SyntaxError"],[ReferenceError,"ReferenceError"],[URIError,"URIError"],[EvalError,"EvalError"],[Error,"Error"]])if(n instanceof e)return po("open_failed",t,null)}catch{}return po("open_failed","UnknownError",null)}Qc();Qr();eo();ge();var eM=5e3,tM=n=>Array.from(U(n),e=>e.toString(16).padStart(2,"0")).join(""),Si=n=>(U(n),n.toLowerCase());function Xh(n,e,t=eM){let i;return Promise.race([n.catch(()=>e),new Promise(o=>{i=setTimeout(()=>o(e),t)})]).finally(()=>clearTimeout(i))}function Xw(n){return Xh(new Promise(e=>{let t=indexedDB.deleteDatabase(n);t.onsuccess=()=>e(!0),t.onerror=()=>e(!1)}),!1)}function nM(n){let e=encodeURIComponent(n.cpOrigin),t=`mdbase.app.installation.v1.${e}.${n.appId}`;return[n.owner===void 0?t:`mdbase.app.installation.v2.${e}.${encodeURIComponent(n.owner)}.${n.appId}`,t]}async function iM(n,e,t){let i=new Set(n.isolated?[]:n.databases);!n.isolated&&n.storageNamespace===void 0&&i.add(t);let{accountId:o,connectorId:s,deviceId:r,installationId:a}=n;if(o&&s&&r&&a){let p=[o,s,r,a].map(tM).join(".");i.add(`mdbase.app.device-key-kek.v1.${p}`),i.add(`mdbase.app.device-keys.v1.${p}`),i.add(`mdbase.app.noise.v1.${Si(a)}.${Si(s)}.${Si(r)}`);let l=[o,s,r,a].map(Si).join("."),c=[`mdbase.app.cloud-copy-outcome.v1.${l}.`,`mdbase.app.private-bootstrap.v1.${l}.`];for(let u of n.collectionIds){let f=Si(u);for(let h of["create","join"])i.add(`${c[0]}${f}.${h}`);for(let h of["create","enrol"])i.add(`${c[1]}${f}.${h}`)}let d=indexedDB.databases;if(typeof d=="function"){let u=await Xh(d.call(indexedDB),[]);for(let{name:f}of u)f&&c.some(h=>f.startsWith(h))&&i.add(f)}}return i.delete(e),[...i]}async function rM(n,e){let t=globalThis.navigator?.storage;return typeof t?.getDirectory!="function"?!0:Xh((async()=>{let i=await t.getDirectory(),o=`.mdbase-app-${Si(n)}-${Si(e)}-`,s=[];for await(let a of i.keys())a.startsWith(o)&&s.push(a);let r=!0;for(let a of s)try{await i.removeEntry(a,{recursive:!0})}catch{r=!1}return r})(),!1)}async function OI(n,e){try{if(!globalThis.indexedDB||!n.accountId||!n.connectorId||!n.deviceId||!n.installationId)return!1;let t=Si(e),i=[n.accountId,n.connectorId,n.deviceId,n.installationId].map(Si).join("."),o=["create","join"].map(a=>`mdbase.app.cloud-copy-outcome.v1.${i}.${t}.${a}`);o.push(...["create","enrol"].map(a=>`mdbase.app.private-bootstrap.v1.${i}.${t}.${a}`));let s=await Promise.all(o.map(Xw)),r=globalThis.navigator?.storage;if(typeof r?.getDirectory=="function"){let a=await r.getDirectory();try{await a.removeEntry(`.mdbase-app-${Si(n.accountId)}-${Si(n.installationId)}-${t}`,{recursive:!0})}catch(p){if(!(p instanceof DOMException&&p.name==="NotFoundError"))return!1}}return s.every(Boolean)}catch{return!1}}async function RI(n){if(!globalThis.indexedDB)return Object.freeze({ledger:!1,complete:!1});let[e,t]=nM(n),i=await Xw(e),o=null;try{o=await iM(n,e,t)}catch{}let s=o?await Promise.all([...o,...n.isolated||n.storageNamespace!==void 0?[]:[Kw]].map(Xw)):[!1],r=n.storageNamespace===void 0?!0:await Xh(PI(n),!1),a=n.accountId&&n.installationId?await rM(n.accountId,n.installationId).catch(()=>!1):!0;return Object.freeze({ledger:i,complete:i&&r&&a&&s.every(Boolean)})}ie();var oM=Object.freeze({status:"unselected",problem:null,transport:null,live:null}),_t=n=>new Xe(n),sM=new Set(["collection_not_yet_migrated","collection_migrating","account_suspended","update_required"]),Zh=class{lifetime=new AbortController;flowLifetime=new AbortController;options;environment;listeners=new Set;flow=null;host=null;installation=null;installationLease=null;slots=new Map;focus=null;openingSlot=null;abortCollections=()=>{for(let e of this.slots.values())e.lifetime?.abort()};base=Object.freeze({status:"not_started",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:null,timing:null});snapshotValue=this.base;authorizationStartedAt=null;authorizationRetryAt=0;authorizationRateLimit=null;pending=null;polling=null;timer=null;closing=null;foreground=!0;receiptRead=null;foregroundRead=null;attested=!1;acknowledged=!1;consentPending=!1;fileAccess=null;freshApproval=!1;approvalWindow=null;nativePending=null;forgotten=new Set;removedScopes=new Set;onAbort=()=>{this.close().catch(()=>{})};constructor(e){this.options=Object.freeze({...e}),this.environment=Xn({environment:e.environment,appOrigin:e.origin,platform:e.allowNativeLoopbackHttp?"native":void 0,release:e.release}),e.signal.addEventListener("abort",this.onAbort,{once:!0}),this.lifetime.signal.addEventListener("abort",this.abortCollections,{once:!0})}getSnapshot(){return this.snapshotValue}snapshot(){return this.getSnapshot()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}viewFor(e,t={}){return t.bystander&&this.base.status==="authorizing"&&this.consentPending&&e!==null&&this.slots.has(e)?this.compose(e,!0):e===this.focus?this.snapshotValue:this.compose(e)}collectionView(e){return this.slots.get(e)?.view??null}heldCollections(){return[...this.slots.keys()]}compose(e,t=!1){let i=this.base,o=e===null?void 0:this.slots.get(e);if(!o)return i;if(i.status!=="unselected"&&!t)return Object.freeze({...i,selectedCollectionId:o.id,transport:o.view.transport,live:o.view.live});let{problemDetail:s,...r}=i,{problemDetail:a,...p}=o.view;return Object.freeze({...r,...t?{status:"unselected",problem:null,approval:null}:{},...p,selectedCollectionId:o.id,...a?{problemDetail:a}:{}})}connection(e=this.focus){let t=e===null?void 0:this.slots.get(e),i=this.base.status==="unselected"||this.base.status==="authorizing"&&this.consentPending;return!t||this.closing||this.options.signal.aborted||!t.usable||t.lifetime?.signal.aborted||!this.installation?.isCurrent()||!i||!["ready","setup_required"].includes(t.view.status)||!this.sameScope(t.scope,t.leaseScope)||t.scope?.collection!==t.id?null:t.selected?.connection??null}sameScope(e,t){return e!==null&&t!==null&&e.account===t.account&&e.installation===t.installation&&e.collection===t.collection&&e.account===this.installation?.scope.account&&e.installation===this.installation?.scope.installation}directAccess=Vh;checkDirectAccess(e){return this.check(),this.directAccess.check(e)}requestDirectAccess(e){return this.check(),this.directAccess.request(e)}check(){if(this.closing||this.options.signal.aborted||this.lifetime.signal.aborted)throw _t("fenced")}publish(e){this.check(),this.setBase(e),this.changed()}setBase(e){let{problemDetail:t,...i}=this.base,o=e.problem===null?void 0:e.problemDetail??t;this.base=Object.freeze({...i,...e,selectedCollectionId:null,signIn:this.flow?.view()??null,...o?{problemDetail:o}:{}})}publishSlot(e,t){if(this.check(),this.slots.get(e.id)!==e)return;let i=this.base.timing;if(this.authorizationStartedAt!==null&&(t.status==="ready"||t.status==="setup_required")){let p=Math.max(0,performance.now()-this.authorizationStartedAt);i=Object.freeze({firstScreenMs:i?.firstScreenMs??p,readyMs:t.status==="ready"?i?.readyMs??p:i?.readyMs??null})}this.setBase({timing:i});let{problemDetail:o,...s}=e.view,r=t.problem===null?void 0:t.problemDetail??o,a=(t.status??s.status)==="opening"?"openingProgress"in t?t.openingProgress??null:s.openingProgress??null:null;e.view=Object.freeze({...s,...t,openingProgress:a,...r?{problemDetail:r}:{}}),this.changed()}changed(){this.snapshotValue=this.compose(this.focus);for(let e of[...this.listeners])try{e()}catch{}}poll(e){this.pending||(this.operation(e).catch(()=>{}),this.polling=this.pending)}stopPolling(){this.timer!==null&&clearTimeout(this.timer),this.timer=null}operation(e,t=!1){if(this.check(),this.pending)return Promise.reject(_t("busy"));this.foregroundRead=null,this.stopPolling();let o=Promise.resolve().then(()=>(this.check(),e())).catch(async s=>{if(!t&&!this.closing&&!this.options.signal.aborted){let{problem:r,detail:a}=Jw(s);if(r==="open_failed")try{console.error("mdbase web sign-in open failed",a.name,a.code)}catch{}let p=this.openingSlot;if(this.openingSlot=null,p&&this.slots.get(p.id)===p){let l=!1;try{l=s instanceof en&&s.reason==="unavailable"&&s.retryable===!0&&p.view.status==="opening"&&this.base.collections.some(c=>c.collectionId===p.id)&&this.flow?.view().state==="paired"&&this.installation?.isCurrent()===!0}catch{}if(l){try{await this.closeSlot(p),this.check()}catch(c){throw!this.closing&&!this.options.signal.aborted&&this.publishSlot(p,{status:"blocked",problem:"recovery_required",problemDetail:Jw(c).detail}),c}this.publishSlot(p,{status:"unselected",problem:r,problemDetail:a})}else this.publishSlot(p,{status:"blocked",problem:r,problemDetail:a})}else this.publish({status:"blocked",problem:r,problemDetail:a})}throw s});return this.pending=o,o.finally(()=>{this.pending===o&&(this.pending=null),this.schedulePoll()})}start(){return this.operation(async()=>{if(this.flow)return this.getSnapshot();this.publish({status:"starting",problem:null,signOutResult:null});let e=this.options;this.flow=await ja.open({...e,mode:e.storeMode??"open",signal:this.flowLifetime.signal,environmentSelection:this.environment}),this.check();let t=this.flow.view();if(t.state==="paired"){if(this.flow.pendingNativeSelection?.()&&!t.nativeSelection)throw _t("recovery_required");await this.openDevice(!1,this.options.recoveryFor!==void 0),this.flow.collectionConsentView()?.state==="pending"?(this.consentPending=!0,this.publish({status:"authorizing"})):await this.refreshCollections()}else this.publish({status:t.state==="pending"?"signed_out":"authorizing"});return this.getSnapshot()})}authorize(e={}){if(this.check(),this.authorizationRateLimit&&Date.now()<this.authorizationRetryAt)return Promise.reject(this.authorizationRateLimit);let t=this.pending!==null&&this.pending===this.polling?this.pending:null;if(!this.flow||this.pending&&!t)return Promise.reject(_t("busy"));let i=this.options.openPortal();return t?t.catch(()=>{}).then(()=>{try{this.check()}catch(s){throw i.close(),s}if(this.pending)throw i.close(),_t("busy");let o=this.base.status;return o!=="authorizing"&&o!=="signed_out"?(i.close(),this.getSnapshot()):this.beginAuthorization(i,e)}):this.beginAuthorization(i,e)}beginAuthorization(e,t){let i={collectionHint:t.collectionHint??null},o=this.flow.view();return this.authorizationStartedAt=performance.now(),this.publish({timing:Object.freeze({firstScreenMs:null,readyMs:null}),approval:null}),this.operation(async()=>{try{if(o.state==="paired"){if(this.flow.pendingNativeSelection?.()&&!o.nativeSelection)throw _t("recovery_required");await this.openDevice(),this.check();let s=await this.flow.startCollectionConsent(this.installation,this.options.requestedCreateCollections??this.options.freshRequestedCreateCollections??!1,i);this.check(),this.consentPending=!0,e.navigate(s.verificationUri)}else{let s=await this.flow.start(i).catch(r=>this.renewFromGesture(r));this.check(),e.navigate(s.verificationUri)}return this.holdApprovalWindow(e),this.publish({status:"authorizing",problem:null}),await this.advance(),this.getSnapshot()}catch(s){throw s instanceof Xe&&s.server?.status===429&&(this.authorizationRateLimit=s,this.authorizationRetryAt=Date.now()+Math.min(Fs,Math.max(Bs,s.server.retryAfterMs??3e4))),e.close(),s}})}requestFileAccess(e,t,i){if(this.check(),!this.flow||this.pending)return Promise.reject(_t("busy"));let o=this.options.openPortal();return this.operation(async()=>{try{if(this.flow.view().state!=="paired"||!this.installation||!this.base.collections.some(r=>r.collectionId===e))throw _t("refused");let s=await this.flow.startFileAccess(this.installation,e,t,i);return this.check(),this.fileAccess=s,o.navigate(s.verificationUri),this.holdApprovalWindow(o),this.publish({fileAccess:Object.freeze({requestId:s.requestId,collectionId:e,actions:s.actions,state:"pending"})}),this.getSnapshot()}catch(s){throw o.close(),s}},!0)}pollFileAccess(e){let t=this.fileAccess;return!t||t.requestId!==e||this.pending||!this.flow||!this.installation?Promise.resolve(this.getSnapshot()):this.operation(async()=>{let i={state:"pending"};try{i=await this.flow.exchangeFileAccess(this.installation,t)}catch{}if(this.check(),this.fileAccess!==t||i.state==="pending"&&Date.now()<t.expiresAt)return this.getSnapshot();this.fileAccess=null,this.closeApprovalWindow();let o=i.state==="granted"?i.actions:null,s=o?Object.freeze(this.base.collections.map(r=>r.collectionId!==t.collectionId?r:Object.freeze({...r,fileActions:Object.freeze([...new Set([...r.fileActions??[],...o])])}))):this.base.collections;return this.publish({collections:s,fileAccess:Object.freeze({requestId:e,collectionId:t.collectionId,actions:o??t.actions,state:i.state==="pending"?"expired":i.state})}),this.getSnapshot()},!0)}async renewFromGesture(e){if(!(e instanceof Xe)||e.reason!=="expired"&&e.reason!=="refused")throw e;try{return await this.flow.renewExpiredPairing()}catch(t){throw t instanceof Xe&&t.reason==="recovery_required"?e:t}}renewExpiredPairing(){return this.operation(async()=>{if(!this.flow)throw _t("binding");return await this.flow.renewExpiredPairing(),this.check(),this.publish({status:"signed_out",problem:null}),this.getSnapshot()})}receiptGeneration(e){try{if(!e.isCurrent())return null;let t=e.view(),i=this.consentPending?e.collectionConsentView():null;return(this.consentPending?i?.state!=="pending":!["pending","awaiting_approval"].includes(t.state))?null:JSON.stringify([t.requestId,t.installationId,t.deviceId,t.accountId,t.state,this.consentPending,i?.requestId,i?.state])}catch{return null}}currentReceipt(e){try{return!this.closing&&!this.lifetime.signal.aborted&&!this.flowLifetime.signal.aborted&&!e.caller.aborted&&this.options.signal===e.caller&&this.flow===e.flow&&this.installation===e.installation&&(e.installation===null||e.installation.isCurrent()===!0)&&this.attested===e.attested&&this.acknowledged===e.acknowledged&&this.receiptGeneration(e.flow)===e.generation}catch{return!1}}async exchangeReceipt(e){let t=this.flow,i=this.pending,o=t?this.receiptGeneration(t):null,s=t&&i&&o!==null?Object.freeze({flow:t,operation:i,generation:o,caller:this.options.signal,installation:this.installation,attested:this.attested,acknowledged:this.acknowledged}):null;this.receiptRead=s;let r=!1;try{let a=await e();return r=a!=null,a}catch(a){if(a instanceof Xe&&a.reason==="outcome_unknown"&&this.flow?.isCurrent())return this.publish({status:"authorizing",problem:"outcome_unknown"}),null;throw a}finally{this.receiptRead===s&&(this.receiptRead=null),this.foregroundRead===s&&(!r||!s||!this.currentReceipt(s))&&(this.foregroundRead=null)}}async advance(){if(this.consentPending){let t;try{t=await this.exchangeReceipt(()=>this.flow.exchangeCollectionConsent(this.installation))}catch(i){if(!(i instanceof Xe)||i.reason!=="refused"&&i.reason!=="expired")throw i;this.check(),this.consentPending=!1,this.closeApprovalWindow(),this.publish({status:"unselected",problem:null,approval:Object.freeze({outcome:"cancelled"})}),await this.refreshCollections();return}if(this.check(),!t)return;if(t.state==="scope_updated"){if(t.accountSelectionConfirmed!==!0)throw _t("account_confirmation_required");let i=this.flow.pendingNativeSelection?.();if(i?.requestId===t.requestId)await this.finishNativeChoice(i);else if(this.flow.view().collectionSelection?.requestId!==t.requestId)throw _t("response");this.consentPending=!1,this.freshApproval=!0,this.closeApprovalWindow(),await this.refreshCollections()}else await this.prepareNativeChoice(),this.publish({status:"authorizing",problem:null});return}let e=await this.exchangeReceipt(()=>this.flow.exchange());if(this.check(),!!e)if(e.state==="account_selected"&&(e=await this.flow.confirmPortalSelectedAccount(),this.check()),(e.state==="account_confirmed"||e.state==="awaiting_approval")&&(await this.openDevice(),this.check(),this.attested||(await this.host.attestInstallation(),this.check(),this.attested=!0),await this.prepareNativeChoice()),e.state==="paired"){let t=this.flow.pendingNativeSelection?.();if(t?.requestId===e.requestId)await this.finishNativeChoice(t);else if(e.collectionSelection?.requestId!==e.requestId)throw _t("response");this.freshApproval=!0,this.closeApprovalWindow(),await this.openDevice(),this.check(),await this.refreshCollections()}else this.publish({status:"authorizing",problem:null})}async prepareNativeChoice(){let e=this.approvalWindow?.nativeAuthorization;if(!e||!this.installation)return;let t=this.flow.nativeAuthorizationContext(this.installation);if(!t)return;let i=this.nativePending;if(!i){if(i={context:t,port:e,life:new AbortController,prepared:null,failed:!1,attempted:!1},this.nativePending=i,t.authorizationId){i.failed=!0;return}let o=i,s=AbortSignal.any([this.lifetime.signal,this.flowLifetime.signal,i.life.signal]);e.prepare(t,s).then(r=>{this.nativePending!==o||s.aborted||(o.prepared=Object.freeze({...r}))},()=>{o.failed=!0})}if(i.context.requestId!==t.requestId||i.context.accountId!==t.accountId||i.context.challenge!==t.challenge)throw _t("fenced");if(i.prepared&&!i.attempted){i.attempted=!0;try{await this.flow.attachNativeAuthorization(this.installation,i.context,i.prepared),this.check()}catch{i.failed=!0}}}async finishNativeChoice(e){let t=this.nativePending;if(!t||!t.prepared||!t.attempted||t.context.requestId!==e.requestId||t.prepared.authorizationId!==e.authorizationRequestId)throw _t("recovery_required");await this.openDevice(),this.check();let i=await t.port.finish(e,AbortSignal.any([this.lifetime.signal,this.flowLifetime.signal,t.life.signal]));if(this.check(),this.nativePending!==t||!this.acknowledged||!this.installation)throw _t("fenced");await this.flow.completeNativeAuthorization(this.installation,i),this.check()}holdApprovalWindow(e){this.approvalWindow!==e&&this.closeApprovalWindow(),this.approvalWindow=e}closeApprovalWindow(){let e=this.approvalWindow;this.approvalWindow=null;let t=this.nativePending;this.nativePending=null,t?.life.abort();try{t?.port.cancel()}catch{}if(e)try{e.close()}catch{}}async openDevice(e=!1,t=!1){if(!this.installation){let i=this.flow.confirmedSelection(),o=Object.freeze({account:i.accountId,installation:i.installationId});this.installationLease=await Wc(this.options.locks,o,this.lifetime.signal),this.check(),this.installation=Object.freeze({scope:o,isCurrent:()=>!this.closing&&!this.options.signal.aborted&&!this.lifetime.signal.aborted&&this.installationLease!==null})}t||!this.host&&!e&&this.acknowledged&&this.flow.view().state==="paired"&&[...this.slots.values()].some(i=>i.host!==null)||(this.host?!this.acknowledged&&this.flow.view().state==="paired"&&(await this.host.completeInstallationSignIn(),this.check(),this.acknowledged=!0):(this.host=await ml.openInstallationDevice({signIn:this.flow,installation:this.installation,release:this.options.release,origin:this.options.origin,signal:this.lifetime.signal,loadRuntime:this.options.loadRuntime,allowLoopbackHttp:this.environment.allowLoopbackHttp,allowNativeLoopbackHttp:this.environment.allowNativeLoopbackHttp}),this.check(),this.acknowledged=this.flow.view().state==="paired"))}async refreshCollections(){let e=await this.flow.listApprovedCollections(this.installation);this.check();for(let o of this.flow.view().collectionIds)e.some(s=>s.collectionId===o)||this.removedScopes.add(o);let t=Object.freeze(e.filter(o=>!this.forgotten.has(o.collectionId)));for(let o of this.slots.values()){if(o.usable&&o.selected&&!t.some(p=>p.collectionId===o.id)){o.usable=!1,o.lifetime?.abort(),await this.closeSlot(o),this.check(),this.deleteSlot(o);continue}let s=o.usable&&o.selected!==null&&t.some(p=>p.collectionId===o.id),{problemDetail:r,...a}=o.view;o.view=Object.freeze({...a,status:s?o.selected.state:"unselected",problem:null})}this.publish({status:"unselected",collections:t,problem:null});let i=this.flow.view().collectionSelection?.selectedCollectionId;(this.options.autoSelect??"only")==="only"&&(this.freshApproval&&i&&t.some(o=>o.collectionId===i)?await this.openSlot(i,!0):t.length===1&&await this.openSlot(t[0].collectionId,!0))}schedulePoll(){if(this.pending&&!this.closing&&!this.options.signal.aborted)return;let e=this.foregroundRead;this.foregroundRead=null;for(let i of this.closing||this.options.signal.aborted?[]:this.slots.values()){let o=this.retryAfterMs(i);o===null||i.timer!==null||i.view.status!=="blocked"||(i.timer=setTimeout(()=>{i.timer=null,!(this.slots.get(i.id)!==i||i.view.status!=="blocked"||i.view.problem!=="collection_migrating"||this.flow?.view().state!=="paired")&&this.operation(()=>this.openSlot(i.id)).catch(()=>{})},o))}if(this.closing||this.options.signal.aborted||this.timer!==null||this.base.status!=="authorizing")return;let t=this.foreground&&e&&this.currentReceipt(e)?e:null;this.timer=setTimeout(()=>{this.timer=null,this.poll(async()=>{t&&(!this.foreground||!this.currentReceipt(t))||await this.advanceApproval()})},t?0:this.foreground?this.base.problem==="outcome_unknown"?5e3:1e3:1e4)}retryAfterMs(e){let t=e.view;if(t.problem!=="collection_migrating")return null;let i=null;try{i=Ur(t.problemDetail?.server)?.retryAfterMs??null}catch{i=null}return Math.min(Fs,Math.max(Bs,i??3e4))}setForeground(e){this.check();let t=e&&!this.foreground;this.foreground=e,this.stopPolling(),e?t&&this.receiptRead?.operation===this.pending&&(this.foregroundRead=this.receiptRead):this.foregroundRead=null,e&&this.base.status==="authorizing"&&!this.pending?this.poll(()=>this.advanceApproval()):this.schedulePoll()}approvalWindowClosed(){this.check(),!(this.pending||this.base.status!=="authorizing"||!this.approvalWindowGone())&&(this.stopPolling(),this.poll(()=>this.advanceApproval()))}approvalWindowGone(){let e=this.approvalWindow;try{return e?.closed===!0}catch{return!1}}async advanceApproval(){let e=this.approvalWindowGone()?this.approvalWindow:null;if(await this.advance(),this.check(),!(!e||this.approvalWindow!==e||this.base.status!=="authorizing")&&this.base.problem!=="outcome_unknown"){if(this.closeApprovalWindow(),this.consentPending){this.consentPending=!1,this.publish({status:"unselected",problem:null,approval:Object.freeze({outcome:"closed"})}),await this.refreshCollections();return}this.publish({status:"signed_out",problem:"approval_window_closed",approval:Object.freeze({outcome:"closed"})})}}select(e){return this.operation(async()=>(await this.openSlot(e,!0),this.getSnapshot()))}openCollection(e){return this.operation(async()=>(await this.openSlot(e),this.viewFor(e)))}releaseCollection(e){return this.slots.has(e)?this.operation(async()=>{let t=this.slots.get(e);return t&&(await this.closeSlot(t),this.check(),this.deleteSlot(t),this.changed()),this.getSnapshot()}):Promise.resolve(this.getSnapshot())}async openSlot(e,t=!1){this.check();let i=this.base.collections.find(d=>d.collectionId===e);if(!i||this.flow?.view().state!=="paired"||!this.installation)throw _t("refused");let o=t?[...this.slots.values()].filter(d=>d.id!==e):[],s=this.slots.get(e);if(s&&s.usable&&s.selected&&!s.lifetime?.signal.aborted&&this.sameScope(s.scope,s.leaseScope)&&s.scope?.collection===e){for(let d of o)d.usable=!1,d.lifetime?.abort();this.focus=e,this.settleBase(),this.publishSlot(s,{status:s.selected.state,problem:null});for(let d of o)await this.closeSlot(d),this.check(),this.deleteSlot(d),this.changed();return}for(let d of o)d.usable=!1,d.lifetime?.abort();let r=s??{id:e,host:null,lease:null,leaseScope:null,selected:null,scope:null,lifetime:null,usable:!1,stopAssessment:null,timer:null,view:oM};r.usable=!1,r.lifetime?.abort(),this.slots.set(e,r),this.focus=e,this.openingSlot=r,this.settleBase(),this.publishSlot(r,{status:"opening",problem:null,openingProgress:null});for(let d of o)await this.closeSlot(d),this.check(),this.deleteSlot(d),this.changed();(r.lease||r.selected||r.host)&&await this.closeSlot(r),this.check(),await this.openDevice(!0),this.check(),r.host=this.host,this.host=null;let a=Object.freeze({...this.installation.scope,collection:e});r.lease=await Kc(this.options.locks,a,this.lifetime.signal),r.leaseScope=a,this.check(),r.lifetime=new AbortController;let p=this.freshApproval&&this.flow.view().collectionSelection?.createdCollectionIds.includes(e)===!0,l=r.lifetime,c=await this.options.openCollection({host:r.host,installation:this.installation,scope:a,collection:i,setupPolicy:p?"approved-new-collection":"explicit",signal:l.signal,onProgress:d=>{this.closing||this.slots.get(r.id)!==r||r.lifetime!==l||l.signal.aborted||r.view.status!=="opening"||r.view.openingProgress!==d&&this.publishSlot(r,{openingProgress:d})}});if(r.selected=c,r.scope=a,this.check(),c.state!=="ready"&&c.state!=="setup_required")throw _t("response");r.usable=!0,this.openingSlot===r&&(this.openingSlot=null),r.stopAssessment=c.subscribe?.(()=>{if(this.closing||this.slots.get(r.id)!==r||!r.usable||r.selected!==c||r.lifetime?.signal.aborted||!this.sameScope(r.scope,r.leaseScope)||r.scope?.collection!==r.id)return;let d=null;try{d=c.ended??null}catch{d=null}if(d){this.accessEnded(r,c,d);return}(c.state==="ready"||c.state==="setup_required")&&this.publishSlot(r,{status:c.state,...this.liveProblem(r,c)})})??null,this.publishSlot(r,{status:c.state,transport:null,live:null,openingProgress:null})}settleBase(){(this.base.status==="blocked"||this.base.status==="unselected")&&this.setBase({status:"unselected",problem:null})}deleteSlot(e){e.timer!==null&&clearTimeout(e.timer),e.timer=null,this.slots.get(e.id)===e&&this.slots.delete(e.id),this.focus===e.id&&(this.focus=null),this.openingSlot===e&&(this.openingSlot=null)}accessEnded(e,t,i){if(e.selected!==t||!e.usable)return;let o=i==="gone"?"collection_deleted":i==="revoked"?"unauthenticated":"access_removed";i!=="gone"&&this.removedScopes.add(e.id),e.usable=!1,this.publishSlot(e,{status:"blocked",problem:o,transport:null,live:null});let s=()=>{if(!(this.closing||this.options.signal.aborted||e.selected!==t||this.slots.get(e.id)!==e)){if(this.pending){this.pending.catch(()=>{}).then(s);return}this.operation(async()=>{if(await this.closeSlot(e),this.publishSlot(e,{status:"blocked",problem:o}),!(!this.flow||!this.installation||this.flow.view().state!=="paired"))try{let r=await this.flow.listApprovedCollections(this.installation);this.check(),this.publish({collections:Object.freeze(r.filter(a=>!this.forgotten.has(a.collectionId)))})}catch{}}).catch(()=>{})}};s()}liveProblem(e,t){let i=null;try{i=t.problem??null}catch{i=null}let o=null;try{o=t.health??null}catch{o=null}let s=o?Object.freeze({...o}):null,r=null;try{let p=t.live;r=typeof p=="boolean"?p:null}catch{r=null}let a=kn(i)?St(i):null;return a&&i?{problem:a,problemDetail:Object.freeze({name:"AppHttpLogError",code:a,server:i}),transport:s,live:r}:{...sM.has(e.view.problem??"")?{problem:null}:{},transport:s,live:r}}async closeSlot(e){e.usable=!1,e.timer!==null&&clearTimeout(e.timer),e.timer=null;let t=e.stopAssessment;e.stopAssessment=null;try{t?.()}catch{}e.lifetime?.abort(),await e.selected?.close(),e.selected=null,e.scope=null,e.lifetime=null,await e.host?.close(),e.host=null,await e.lease?.release(),e.lease=null,e.leaseScope=null}async closeSlots(){for(let t of[...this.slots.values()])await this.closeSlot(t),this.deleteSlot(t);let e=this.host;this.host=null,await e?.close()}clearSelection(){return this.operation(async()=>(await this.closeSlots(),this.focus=null,this.publish({status:"unselected",problem:null}),this.getSnapshot()))}refreshCollectionList(){return this.pending||!this.flow||!this.installation||this.consentPending||this.flow.view().state!=="paired"||this.base.status!=="unselected"?Promise.resolve(this.getSnapshot()):this.operation(async()=>(await this.refreshCollections(),this.getSnapshot()),!0)}scopeWasRemoved(e){return this.removedScopes.has(e)}removedScopeIds(){return Object.freeze([...this.removedScopes])}canAbandonWrongAccount(){return!this.closing&&!this.options.signal.aborted&&this.pending===null&&this.flow?.canAbandonWrongAccount()===!0&&this.installation===null&&this.host===null&&this.slots.size===0&&!this.attested&&!this.acknowledged}scopeRecoveryContext(){if(!this.flow||!this.installation||this.flow.view().state!=="paired")return null;let e=this.flow.view();return Object.freeze({accountId:this.installation.scope.account,accountLabel:e.accountEmail??(e.accountLogin?`@${e.accountLogin}`:null),references:this.flow.collectionRecoveries()})}prepareScopedRecovery(e,t){return this.check(),this.pending?this.pending.catch(()=>{}).then(()=>this.prepareScopedRecovery(e,t)):this.operation(async()=>{if(!this.flow||!this.installation||this.consentPending||this.flow.view().state!=="paired"||!this.flow.view().collectionIds.includes(e))throw _t("binding");let i=this.flow.collectionRecoveries(),o=this.slots.get(e);if(t===void 0&&!Object.hasOwn(i,e)&&!this.scopeWasRemoved(e))throw _t("binding");o&&(await this.closeSlot(o),this.check(),this.deleteSlot(o)),await this.flow.retireCollectionScope(this.installation,e,t??null),this.check();let s=this.flow.confirmedSelection(),r=this.options;if(!await OI({cpOrigin:r.cpOrigin,appId:r.appId,accountId:s.accountId,connectorId:s.connectorId,installationId:s.installationId,deviceId:s.deviceId,collectionIds:[e],databases:[]},e))throw _t("recovery_required");this.check();let a=await this.flow.freshCollectionInstallation(this.installation,e);return this.check(),Object.freeze({accountId:s.accountId,reference:a})},!0)}forget(e){return this.operation(async()=>{let t=this.slots.get(e);return t&&(await this.closeSlot(t),this.check(),this.deleteSlot(t)),this.forgotten.add(e),this.publish({collections:Object.freeze(this.base.collections.filter(i=>i.collectionId!==e))}),this.getSnapshot()})}deleteCollection(e,t){let i=null;return this.operation(async()=>{let o=this.base.collections.find(s=>s.collectionId===e);if(!this.flow||!this.installation||!o)i=new vi("collection_delete_not_found");else if(o.role!=="owner")i=new vi("collection_delete_not_owner");else{try{await this.flow.deleteApprovedCollection(this.installation,e,t)}catch(s){i=ax(s)}this.check()}return this.getSnapshot()}).then(o=>{if(i)throw i;return o})}signOut(){this.check();let e=this.pending!==null&&this.pending===this.polling?this.pending:null;return Promise.resolve(e?.catch(()=>{})).then(()=>this.operation(async()=>{let t=this.flow,i=null,o=null,s=!1;try{i=t?.view()??null}catch{i=null}try{o=t?.confirmedSelection().connectorId??null}catch{o=null}try{s=t?.hasWebPushChannel()===!0}catch{s=!1}let r=[...new Set([...i?.collectionIds??[],...this.base.collections.map(c=>c.collectionId)])];this.closeApprovalWindow(),this.fileAccess=null,this.consentPending=!1;try{await this.closeSlots()}catch(c){throw this.failSignOut(),c}this.check();let a="not_paired";if(t&&i?.state==="paired"){try{a=await t.signOutInstallation()}catch{a="incomplete"}this.check()}this.flow=null,this.installation=null;try{await t?.close()}catch{}this.flowLifetime.abort(),this.flowLifetime=new AbortController,await this.installationLease?.release(),this.installationLease=null,this.attested=!1,this.acknowledged=!1,this.freshApproval=!1,this.authorizationStartedAt=null,this.receiptRead=null,this.foregroundRead=null,this.forgotten.clear(),this.removedScopes.clear();let p=this.options,l=await RI({cpOrigin:p.cpOrigin,appId:p.appId,...p.owner===void 0?{}:{owner:p.owner},...p.storageNamespace===void 0?{}:{storageNamespace:p.storageNamespace},accountId:i?.accountId??null,connectorId:o,installationId:i?.installationId??null,deviceId:i?.deviceId??null,collectionIds:r,databases:p.localDatabases??[],...p.recoveryFor?{isolated:!0}:{}});if(this.check(),!l.ledger)throw this.failSignOut(),A("unavailable","This device couldn't remove its sign-in data.","sign_out_failed");return this.emit(Object.freeze({status:"signed_out",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:null,timing:null,signOutResult:Object.freeze({server:a,local:l.complete?"erased":"incomplete",webPush:s})})),this.getSnapshot()},!0))}failSignOut(){if(this.closing||this.options.signal.aborted)return;let e=null;try{e=this.flow?.view()??null}catch{e=null}let{problemDetail:t,...i}=this.base;this.focus=null,this.emit(Object.freeze({...i,status:"blocked",signIn:e,selectedCollectionId:null,problem:"sign_out_failed"}))}emit(e){if(this.check(),this.base=e,e.status==="signed_out"){for(let t of[...this.slots.values()])this.deleteSlot(t);this.focus=null}this.changed()}close(){if(this.closing)return this.closing;let e=this.pending;return this.foregroundRead=null,this.stopPolling(),this.options.signal.removeEventListener("abort",this.onAbort),this.closing=Promise.resolve().then(async()=>{await e?.catch(()=>{}),await this.closeSlots(),this.focus=null,await this.flow?.close(),this.flowLifetime.abort(),this.flow=null,this.installation=null,await this.installationLease?.release(),this.installationLease=null,this.base=Object.freeze({status:"closed",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:null,timing:this.base.timing}),this.snapshotValue=this.base;for(let t of[...this.listeners])try{t()}catch{}this.listeners.clear()}),this.lifetime.abort(),this.closing}};return UI(aM);})();
|
|
130
|
+
`);return{[Lc.version]:String(wb),[Lc.timestamp]:String(o),[Lc.nonce]:s,[Lc.signature]:rn(await aw(n,new TextEncoder().encode(r)))}}async function ow(n,e){let t=await crypto.subtle.generateKey({name:e,namedCurve:"P-256"},!1,n);return{privateKey:t.privateKey,publicKey:rn(new Uint8Array(await crypto.subtle.exportKey("raw",t.publicKey)))}}async function b2(){let n;try{n=await crypto.subtle.generateKey({name:"X25519"},!1,["deriveBits"])}catch{throw A("unavailable","this browser cannot keep a non-extractable X25519 key","browser_unsupported")}if(n.privateKey.extractable)throw A("unavailable","the Noise key must be non-extractable","browser_unsupported");return{privateKey:n.privateKey,publicKey:new Uint8Array(await crypto.subtle.exportKey("raw",n.publicKey))}}function w2(n){return{publicKey:n.noisePublicKey.slice(),dh:async e=>{let t=await crypto.subtle.importKey("raw",e,{name:"X25519"},!1,[]);return new Uint8Array(await crypto.subtle.deriveBits({name:"X25519",public:t},n.noisePrivateKey,256))}}}function v2(n,e){let t=new AbortController,i=()=>t.abort(),o=setTimeout(i,e);return o.unref?.(),n?.addEventListener("abort",i,{once:!0}),n?.aborted&&t.abort(),{signal:t.signal,done:()=>{clearTimeout(o),n?.removeEventListener("abort",i)}}}async function _2(n,e){let t=globalThis.navigator?.locks;if(t)return t.request(n,{mode:"exclusive"},e);let i=mh.get(n)??Promise.resolve(),o,s=new Promise(r=>{o=r});mh.set(n,s),await i;try{return await e()}finally{o(),mh.get(n)===s&&mh.delete(n)}}var p2,iC,ro,d2,Qx,f2,rn,hh,eC,tC,nC,yh,Ha,sw,Gi,mh,lw,oC=I(()=>{"use strict";jc();Qr();Ea();vu();If();qx();Tf();ge();Lr();ie();Fy();qo();Ts();bd();Yl();iu();Mx();Hx();Jx();Wm();Zx();Ob();p2=new Set(["owner","editor","viewer"]),iC="mdbase.app-grant.v1",ro=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,d2=15e3;Qx=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),f2=new TextEncoder().encode("mdbase-next client noise key v1\0");rn=n=>{let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")},hh=n=>crypto.getRandomValues(new Uint8Array(n)),eC=n=>{let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n),e},tC=(...n)=>{let e=new Uint8Array(n.reduce((i,o)=>i+o.length,0)),t=0;for(let i of n)e.set(i,t),t+=i.length;return e};nC=async n=>rn(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n))));yh=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),Ha=(n,e)=>!!e&&n.collection===e.collection&&n.owner===e.owner&&yh(n.noisePublicKey,e.noisePublicKey),sw=(n,e)=>Ha(n,e)&&yh(n.refresh,e.refresh),Gi=()=>A("cancelled","the stored grant changed during this operation"),mh=new Map;lw=class{constructor(e){this.options=e;this.declaration=yr(e.declaration),this.cpOrigin=Xn({environment:this.declaration.environment,appOrigin:this.declaration.origin,release:Ex()}).cpOrigin;try{this.redirect=new URL(e.redirectUri)}catch{throw A("invalid_request","redirectUri must be an absolute URL","redirect_uri")}if(this.redirect.origin!==this.declaration.origin||this.redirect.hash)throw A("invalid_request","redirectUri must be on the app's origin, without a fragment","redirect_uri");this.fetcher=e.fetch??globalThis.fetch.bind(globalThis),this.callbacks=e.callbacks??m2(),this.storeValue=e.store??null}options;declaration;cpOrigin;redirect;fetcher;callbacks;storeValue;registration=null;tokens=new Map;refreshing=new Map;forgotten=new Set;epoch=0;register(){let e=this.registration??=qf({declaration:this.options.declaration,signal:new AbortController().signal,isCurrent:()=>!0,fetch:this.fetcher});return e.catch(()=>{this.registration===e&&(this.registration=null)}),e}ownerValue=null;owner(){return this.ownerValue??=mk(Zr(this.declaration).manifest.id,wu(this.declaration))}async store(){if(this.storeValue)return this.storeValue;let e=this.owner();return this.storeValue=Xx(this.cpOrigin,(await this.register()).id,{owner:e})}async identity(){let e=await this.store(),t=await e.getIdentity();if(t)return t;let i=await ow(["sign"],"ECDSA");return e.putIdentityIfAbsent({version:1,privateKey:i.privateKey,publicKey:i.publicKey})}async request(e,t,i){let o=v2(i,d2);try{let s;try{s=await this.fetcher(`${this.cpOrigin}${e}`,{...t,redirect:"error",signal:o.signal})}catch{throw i?.aborted?A("cancelled","request cancelled"):A("unavailable","cannot reach the control plane","control_unreachable")}let r=null;try{let a=await s.json();a&&typeof a=="object"&&!Array.isArray(a)&&(r=a)}catch{r=null}return{status:s.status,body:r}}finally{o.done()}}async authorize(e){e=Object.freeze({...e});let t=await this.prepareAuthorization(e).catch(i=>{throw e.popup.close(),i});try{e.popup.navigate(t.authorizationUri);let{collectionId:i}=await t.finish(e);return{collectionId:i}}finally{t.cancel();try{e.popup.close()}catch{}}}async prepareAuthorization(e={}){if(e=Object.freeze({...e}),e.collection!==void 0&&!ro.test(e.collection))throw A("invalid_request","collection must be a UUID");if(e.expectedAccountId!==void 0&&(!ro.test(e.expectedAccountId)||!e.authorizationNonce))throw A("invalid_request","original account and challenge required","authorization_binding");if(e.authorizationNonce!==void 0&&(!/^[A-Za-z0-9_-]{43}$/.test(e.authorizationNonce)||!u2(e.authorizationNonce)))throw A("invalid_request","invalid original challenge","authorization_binding");let t=new AbortController,i=e.signal?AbortSignal.any([e.signal,t.signal]):t.signal,o=this.epoch,s=()=>{if(i.aborted)throw A("cancelled","authorization fenced","authorization_cancelled");if(o!==this.epoch)throw Gi()};s();let r=await this.register(),a=Zr(this.declaration),p=await this.identity(),l=await ow(["deriveBits"],"ECDH"),c=await ow(["sign"],"ECDSA"),d=await b2(),u=rn(hh(32)),f=rn(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(u)))),h=rn(hh(24)),m=crypto.randomUUID(),b=new Date,w={protocol_version:hr,authorization_id:m,application_id:r.id,application_declaration_id:String(a.manifest.id),application_manifest_digest:r.manifestDigest,application_installation_id:await lP(p.publicKey),installation_signing_public_key:p.publicKey,grant_agreement_public_key:l.publicKey,grant_signing_public_key:c.publicKey,flow:"authorization_code",authorization_nonce:e.authorizationNonce??rn(hh(32)),issued_at:b.toISOString(),expires_at:new Date(b.getTime()+10*6e4).toISOString(),redirect_uri:this.redirect.href,state:h,code_challenge:f,contracts:a.contracts,requested_operations:[...a.operations],...a.files?{requested_files:a.files}:{},...e.collection?{collection_id:e.collection}:{}},g={binding:w,signature:rn(await aw(p.privateKey,cP(w)))},y=tC(f2,eC(16),U(m),eC(32),d.publicKey),v={public_key:rn(d.publicKey),signature:rn(await aw(c.privateKey,y))};s();let _=await this.request("/oauth/authorization_request",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:r.id,redirect_uri:this.redirect.href,code_challenge:f,code_challenge_method:"S256",state:h,operations:a.operations.join(","),...e.collection?{collection_id:e.collection}:{},application_authorization:JSON.stringify(g),client_noise_key:JSON.stringify(v)})},i);s();let k=_.body?.authorization_uri;if(_.status!==200||_.body?.authorization_id!==m||typeof k!="string"||!k.startsWith(`${this.cpOrigin}/oauth/authorize?`))throw A("unavailable",`authorization could not be started (${_.status})`,"authorization_start");let S=null,x=this.awaitCallback(h,{navigate(){},close(){},get closed(){return S?.closed===!0}},{popup:{navigate(){},close(){}},signal:i,timeoutMs:e.timeoutMs});x.catch(()=>{});let P=!1;return Object.freeze({applicationId:r.id,manifestDigest:r.manifestDigest,authorizationId:m,authorizationUri:k,cancel:()=>t.abort(),finish:async C=>{if(C=Object.freeze({...C}),P)throw A("invalid_request","original authorization already consumed","authorization_binding");P=!0,S=C.popup;let E=()=>t.abort();C.signal?.addEventListener("abort",E,{once:!0}),C.signal?.aborted&&t.abort();try{s();let O=C.collection??e.collection;if(O!==void 0&&!ro.test(O))throw A("invalid_request","invalid approved collection","authorization_binding");if(e.collection&&O!==e.collection)throw A("forbidden","a different collection was approved","collection_mismatch");if(e.expectedAccountId&&!O)throw A("invalid_request","original Private choice required","authorization_binding");let L=await x;s();let z=await this.request("/oauth/token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:L,client_id:r.id,redirect_uri:this.redirect.href,code_verifier:u})},i);s();let Q=e.expectedAccountId?Nf(z.body,{accountId:e.expectedAccountId,authorizationRequestId:m,applicationId:r.id,declarationId:w.application_declaration_id,manifestDigest:r.manifestDigest,applicationInstallationId:w.application_installation_id,applicationOrigin:this.redirect.origin,collectionId:O,grantSigningPublicKey:c.publicKey,clientNoisePublicKey:rn(d.publicKey)}):void 0,V=await this.saveTokens(z,{noise:d,signing:c.privateKey,collection:O,check:s});return s(),{collectionId:V,...Q?{nativeCompletion:Q}:{}}}finally{C.signal?.removeEventListener("abort",E),t.abort()}}})}awaitCallback(e,t,i){let o=Math.min(Math.max(i.timeoutMs??6e5,1e3),18e5);return new Promise((s,r)=>{let a=null,p=f=>{c(),clearTimeout(d),clearInterval(u),i.signal?.removeEventListener("abort",l),f()},l=()=>p(()=>r(A("cancelled","authorization cancelled","authorization_cancelled"))),c=this.callbacks.subscribe(f=>{let h;try{h=new URL(f)}catch{return}if(h.origin!==this.redirect.origin||h.pathname!==this.redirect.pathname||h.searchParams.get("state")!==e)return;if(h.searchParams.get("error"))return p(()=>r(A("forbidden","access was not approved","authorization_denied")));let b=h.searchParams.get("code");if(!b)return p(()=>r(A("unavailable","the authorization callback has no code","authorization_callback")));p(()=>s(b))}),d=setTimeout(()=>p(()=>r(A("cancelled","authorization timed out","authorization_timed_out"))),o),u=setInterval(()=>{let f=!1;try{f=t.closed===!0}catch{f=!1}if(!f){a=null;return}a??=Date.now(),Date.now()-a>=3e3&&p(()=>r(A("cancelled","the authorization window was closed","authorization_cancelled")))},500);i.signal?.addEventListener("abort",l,{once:!0}),i.signal?.aborted&&l()})}async saveTokens(e,t){let i=e.body;if(e.status!==200||!i)throw e.status===400&&i&&typeof i.error=="string"&&i.error==="invalid_grant"?A("unauthenticated","the grant is no longer valid","grant_invalid"):e.status===400?un("sync_required"):A("unavailable",`token request failed (${e.status})`,"token_error");let o=i.access_token,s=i.refresh_token,r=i.collection_id,a=i.expires_in,p=i.refresh_expires_in;if(typeof o!="string"||typeof s!="string"||typeof r!="string"||!ro.test(r)||typeof a!="number"||!(a>0)||typeof p!="number"||!(p>0))throw A("unavailable","invalid token response","token_response");let l=r.toLowerCase();if(t.collection&&t.collection.toLowerCase()!==l)throw A("forbidden","a different collection was approved","collection_mismatch");if(t.previous&&t.previous.collection!==l)throw A("unavailable","the token names another collection","token_response");let c=t.previous?.refreshKey??await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),d=hh(12),u=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:d,additionalData:this.aad(l)},c,new TextEncoder().encode(s))),f=t.noise??{privateKey:t.previous.noisePrivateKey,publicKey:t.previous.noisePublicKey},h=t.signing??t.previous?.signingPrivateKey,m={version:1,collection:l,noisePrivateKey:f.privateKey,noisePublicKey:f.publicKey,refreshKey:c,refresh:tC(d,u),refreshExpiresAt:Date.now()+p*1e3,...h?{signingPrivateKey:h}:{},...t.previous?.owner?{owner:t.previous.owner}:{}},b=this.epoch;return await this.withLock(l,"commit",async()=>{let w=await this.store();if(b!==this.epoch||t.previous&&!sw(t.previous,await w.getGrant(l)))throw Gi();t.check?.(),await w.putGrant(m);let g=await w.getGrant(l);if(!g||!yh(m.noisePublicKey,g.noisePublicKey)||!yh(m.refresh,g.refresh))throw Gi();t.check?.(),this.tokens.set(l,{access:o,expiresAt:Date.now()+a*1e3,collection:l,owner:g.owner,noisePublicKey:g.noisePublicKey.slice()}),this.forgotten.delete(l)}),l}aad(e){return new TextEncoder().encode(`mdbase.app-grant.v2\0${this.cpOrigin}\0${this.owner()}\0${e}`)}async accessToken(e,t=!1){let i=await this.heldGrant(e),o=this.tokens.get(e);if(!t&&o&&Ha(i,o)&&o.expiresAt-Date.now()>6e4)return o.access;let s=this.refreshing.get(e);if(s&&sw(i,s.grant)){let p=await s.work;return await this.assertCurrent(i),p}let r=this.withLock(e,"refresh",async()=>{let p=await this.assertCurrent(i);return this.refresh(e,p)}),a={grant:i,work:r};this.refreshing.set(e,a);try{let p=await r;return await this.assertCurrent(i),p}finally{this.refreshing.get(e)===a&&this.refreshing.delete(e)}}withLock(e,t,i){return _2(`mdbase.app-grant.${t}:${JSON.stringify([this.cpOrigin,this.owner(),e])}`,i)}async heldGrant(e){let t=await(await this.store()).getGrant(e);if(!t)throw un("sync_required");return{...t,noisePublicKey:t.noisePublicKey.slice(),refresh:t.refresh.slice()}}async assertCurrent(e){let t=await(await this.store()).getGrant(e.collection);if(!Ha(e,t))throw Gi();return t}async refresh(e,t){if(t.refreshExpiresAt<=Date.now())throw un("sync_required");let i;try{let p=await crypto.subtle.decrypt({name:"AES-GCM",iv:t.refresh.slice(0,12),additionalData:this.aad(e)},t.refreshKey,t.refresh.slice(12));i=new TextDecoder().decode(p)}catch{throw A("unauthenticated","the stored grant could not be read","grant_storage")}let o=await this.register(),s=new URLSearchParams({grant_type:"refresh_token",refresh_token:i,client_id:o.id}),r=t.signingPrivateKey?await g2(t.signingPrivateKey,"/oauth/token",s.toString(),i):{},a=await this.request("/oauth/token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...r},body:s});try{await this.saveTokens(a,{previous:t})}catch(p){throw oe(p,"unauthenticated")&&p.reason==="grant_invalid"&&await this.withLock(e,"commit",async()=>{let l=await this.store();if(!sw(t,await l.getGrant(e)))throw Gi();await l.deleteGrant(e),this.forgotten.add(e);let c=this.tokens.get(e);c&&Ha(t,c)&&this.tokens.delete(e)}),p}return a.body.access_token}async route(e,t){for(let i=0;;i++){let o=await this.accessToken(e,i>0),s=await this.request(`/v1/next/collections/${encodeURIComponent(e)}/route`,{headers:{authorization:`Bearer ${o}`}},t);if(s.status===401&&i===0)continue;if(s.status===401)throw A("unauthenticated","the control plane refused the access token");if(s.status===409)throw A("unauthenticated","this app's key is not registered with its grant","client_key_required");if(s.status!==200||!s.body)throw A("unavailable",`control plane answered ${s.status}`,"control_error");let r=s.body;if(typeof r.collection!="string"||r.collection.toLowerCase()!==e||!Array.isArray(r.targets))throw A("unauthenticated","the route does not match this collection's grant","route_mismatch");let p=zn(r.availability)??(js(r,null).length?{state:"available"}:{state:"unavailable",reason:r.reason==="no_device_registered"?"no_device_registered":"device_offline"});return{token:o,route:r,availability:p}}}async verifiedStoredNativeGrant(e){let t=await this.register(),i=await(await this.store()).getGrant(e.collection_id);return!!i&&e.application_id===t.id&&e.application_origin===this.declaration.origin&&i.owner===this.owner()&&rn(i.noisePublicKey)===e.client_noise_public_key}async collections(e={}){let t=await(await this.store()).listGrants(),i=[];for(let s of t)(e.bindings===void 0||e.bindings.some(r=>r.collection_id===s.collection&&r.application_origin===this.declaration.origin&&rn(s.noisePublicKey)===r.client_noise_public_key))&&i.push(s);let o=new Set(i.map(s=>s.collection));for(let s of i){let r;try{r=await this.accessToken(s.collection)}catch(l){if(oe(l)&&(l.code==="unauthenticated"&&l.reason==="grant_invalid"||l.code==="forbidden"&&l.reason==="sync_required"))continue;throw l}await this.assertCurrent(s);let a=await this.request("/v1/next/apps/collections",{headers:{authorization:`Bearer ${r}`}},e.signal);if(await this.assertCurrent(s),a.status===401)throw await this.withLock(s.collection,"commit",async()=>{await this.assertCurrent(s);let l=this.tokens.get(s.collection);if(l?.access!==r||!Ha(s,l))throw Gi();this.tokens.delete(s.collection)}),A("unauthenticated","the control plane refused the collection listing token");if(a.status!==200||!Array.isArray(a.body?.collections))throw A("unavailable",`control plane answered ${a.status}`,"control_error");let p=[];for(let l of a.body.collections){let c=typeof l.collection=="string"?l.collection.toLowerCase():"";if(!ro.test(c)||p.some(f=>f.collectionId===c))continue;let d=zn(l.availability);if(l.state!=="synced_e2e"&&!d)continue;let u=o.has(c)?d??{state:"opening"}:{state:"unavailable",reason:"sync_required"};p.push(Object.freeze({collectionId:c,displayName:typeof l.name=="string"?l.name:"Collection",operations:Object.freeze(Array.isArray(l.operations)?l.operations.filter(f=>typeof f=="string"):[]),availability:Object.freeze(u),role:p2.has(l.role)?l.role:null}))}return p}return[]}async availability(e,t={}){let i=e.toLowerCase();try{return(await this.route(i,t.signal)).availability}catch(o){if(oe(o)&&o.details instanceof Map&&typeof o.details.get("availability")=="string")return zn({state:"unavailable",reason:o.details.get("availability")});throw o}}async waitForAvailable(e,t={}){let i=Date.now()+Math.min(Math.max(t.timeoutMs??6e4,0),6e5),o=Math.max(t.intervalMs??3e3,1e3),s=null;for(;;){if(t.signal?.aborted)throw A("cancelled","wait cancelled");let r=await this.availability(e,t.signal?{signal:t.signal}:{});if((!s||r.state!==s.state||r.state==="unavailable"&&s.state==="unavailable"&&r.reason!==s.reason)&&t.onAvailability?.(r),s=r,r.state==="available"||r.state==="unavailable"&&(r.reason==="sync_required"||r.reason==="access_removed"))return r;let a=i-Date.now();if(a<=0)return r;await new Promise(p=>{let l=setTimeout(c,Math.min(o,a));function c(){clearTimeout(l),t.signal?.removeEventListener("abort",c),p()}t.signal?.addEventListener("abort",c,{once:!0})})}}connector(e){let t=e.toLowerCase();if(!ro.test(t))throw A("invalid_request","collection must be a UUID");let i=null,o=this.options.webSocket,s;return gd({description:`app-grant:${t}`,open:async(r,a)=>{let p=await(s??=this.heldGrant(t));await this.assertCurrent(p);let c=await Mi({description:`app-grant:${t}`,staticKey:w2(p),target:async d=>{await this.assertCurrent(p);let{token:u,route:f,availability:h}=await this.route(t,d);if(await this.assertCurrent(p),h.state==="unavailable")throw un(h.reason);if(!ro.test(f.grant))throw A("unauthenticated","the route names no grant","route_mismatch");let m=js(f,i)[0];if(!m)throw un("device_offline");let b=new Uint8Array(32);for(let w=0;w<32;w++)b[w]=parseInt(m.noise_pk.slice(2*w,2*w+2),16);return{prologue:Ti(U(m.relay_collection),U(f.grant),U(m.device)),remoteStatic:b,device:m.device,openCarrier:async w=>{await this.assertCurrent(p);let g=await Ms(m.url,{accessToken:u,collection:m.relay_collection,grant:f.grant,device:m.device,devicePublicKey:b},o,w);try{return await this.assertCurrent(p),g}catch(y){throw g.close(),y}}}}}).open(r,a);try{await this.assertCurrent(p)}catch(d){throw c.port.close(),d}return w_(c.port,p),i=c.device??null,c},get target(){return i}})}people(e,t){let i=e.toLowerCase();if(!ro.test(i))throw A("invalid_request","collection must be a UUID");return new jr(t,Tx(i,{cpOrigin:this.cpOrigin,fetch:this.fetcher,accessToken:(o,s)=>this.accessToken(o,s),holds:o=>!this.forgotten.has(o)}))}setup(e){let t=Zr(this.declaration),i,o=async()=>{let r=e.currentSession(),a=r&&__(r);if(!a||a.collection!==e.collection||(i??=a,!Ha(i,a)))throw Gi();return i};return Wx({assertCurrent:async()=>this.assertCurrent(await o()),journal:Yx({store:()=>this.store(),grant:o,assertCurrent:r=>this.assertCurrent(r),aad:this.aad(e.collection)}),client:e,manifest:t.manifest,operations:t.operations})}async forget(e,t={}){let i=e.toLowerCase(),o=t.expectedNoisePublicKey;await this.withLock(i,"commit",async()=>{let s=await this.store(),r=await s.getGrant(i);if(o!==void 0&&r&&rn(r.noisePublicKey)!==o)throw Gi();await s.deleteGrant(i),this.forgotten.add(i),this.tokens.delete(i)})}async forgetAllGrants(){this.epoch++;let e=await this.store(),t=[];try{t=(await e.listGrants()).map(o=>o.collection).sort()}catch{}for(let o of t)this.forgotten.add(o);let i=async(o,s)=>o.length?this.withLock(o[0],"commit",()=>i(o.slice(1),s)):s();await i(t,async()=>{if(this.tokens.clear(),typeof e.clearGrants=="function"){await e.clearGrants();return}for(let o of await e.listGrants())await e.deleteGrant(o.collection),this.forgotten.add(o.collection);if((await e.listGrants()).length)throw A("unavailable","grant storage could not be cleared","grant_storage")}),this.tokens.clear()}}});function cC(n){let e=0,t=0;try{let i=n?.records.status.pending;e=typeof i=="number"&&i>0?i:0}catch{e=0}try{t=n?.records.ledger?.getSnapshot().pending.length??0}catch{t=0}return Math.max(e,t)}function pC(n=0){let e=n===1?"1 change hasn't":n>1?`${n} changes haven't`:"Some changes haven't";return A("conflict",`${e} reached mdbase yet. Wait for them to finish, or sign out anyway and lose them on this device.`,{reason:"sign_out_pending_writes",details:n})}var dC=I(()=>{"use strict";ie()});function pp(n,e){return new Promise((t,i)=>{if(e.aborted){i(e.reason);return}let o=()=>{clearTimeout(s),i(e.reason)},s=setTimeout(()=>{e.removeEventListener("abort",o),t()},n);e.addEventListener("abort",o,{once:!0})})}var cw=I(()=>{"use strict"});function wh(n,e){if(typeof n!="string"||!e.test(n))throw de("invalid_request","timer_input");return encodeURIComponent(n)}function so(n,e){if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!==e.split(",").sort().join())throw de("invalid_request","timer_input");return n}function uC(n){let e=so(n,"id,fire_at");if(wh(e.id,pw),typeof e.fire_at!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(e.fire_at)||!Number.isFinite(Date.parse(e.fire_at)))throw de("invalid_request","timer_input");return{id:e.id,fire_at:e.fire_at}}function dw(n){if(typeof n!="string"||!n.length||n.length>100)throw de("invalid_request","timer_input")}function O2(n,e,t){let i=`${n}/${wh(t[0],I2)}`;if(e==="list"&&t.length===1)return{path:i,method:"GET",write:!1};if(e==="put"&&t.length===3){let o=so(t[2],"criterion_id,fire_at");return dw(o.criterion_id),uC({id:t[1],fire_at:o.fire_at}),{path:`${i}/${wh(t[1],pw)}`,method:"PUT",body:o,write:!0}}if(e==="cancel"&&t.length===3){let o=t[2];if(o!==void 0&&(!Number.isSafeInteger(o)||o<1))throw de("invalid_request","timer_input");return{path:`${i}/${wh(t[1],pw)}${o===void 0?"":`?generation=${o}`}`,method:"DELETE",write:!0}}if((e==="reconcile"||e==="reconcileWithReceipt")&&t.length===2){let o=so(t[1],`criterion_id,timers${e==="reconcileWithReceipt"?",recovery":""}`);if(dw(o.criterion_id),!Array.isArray(o.timers)||o.timers.length>1e4)throw de("invalid_request","timer_input");let s=o.timers.map(uC);if(new Set(s.map(r=>r.id)).size!==s.length)throw de("invalid_request","timer_input");if(e==="reconcileWithReceipt"){let r=so(o.recovery,"protocol_version,operation_id,expected_revision");if(r.protocol_version!==1||typeof r.operation_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(r.operation_id)||!Number.isSafeInteger(r.expected_revision)||r.expected_revision<0||r.expected_revision>=Number.MAX_SAFE_INTEGER)throw de("invalid_request","timer_input")}return{path:`${i}/reconcile`,method:"POST",body:{...o,timers:s},write:!0}}if(e==="lookupOperation"&&t.length===2&&typeof t[1]=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(t[1]))return{path:`${i}/operations/${t[1]}`,method:"GET",write:!1};throw de("invalid_request","timer_input")}function hC(n,e){let t=fC(e.scope),i=e.generation,o=`/v1/next/collections/${e.scope.collection}/background-grants/${e.grantId}/timers`,s=!1,r=0,a=null,p=null,l=()=>{if(s||e.signal.aborted||!e.isCurrent())throw de("unauthenticated","timer_fenced")},c=()=>{if(p)return p;s=!0,e.signal.removeEventListener("abort",d),a?.ctrl.abort();try{n.postMessage([1,t,i,"close"])}finally{n.removeEventListener("message",u),n.close()}return p=Promise.resolve().then(async()=>{await a?.work})},d=()=>{c()},u=f=>{let h=f.data;if(!Array.isArray(h)||h[0]!==1||h[1]!==t||h[2]!==i){c();return}if(h.length===4&&h[3]==="close"){c();return}if(h.length===5&&h[4]==="cancel"&&Number.isSafeInteger(h[3])&&h[3]>0){a&&a.id===h[3]&&a.ctrl.abort();return}if(h.length!==6||!Number.isSafeInteger(h[3])||h[3]<=r||a||typeof h[4]!="string"||!Array.isArray(h[5])){c();return}let m=h[3],b=h[4],w=h[5],g=new AbortController;r=m;let y=!1,v=b!=="list"&&b!=="lookupOperation",_=Promise.resolve().then(async()=>{let k=setTimeout(()=>g.abort(),1e4),S,x,P=new Uint8Array(dp),C=0,E=()=>{x?.cancel().catch(()=>{})};g.signal.addEventListener("abort",E,{once:!0});try{l(),g.signal.throwIfAborted();let O=o.slice(0,-7)+"/notifications/channels",L,z,Q=null;if(b==="vapid"&&w.length===0){if(!e.journal)throw de("upgrade_required","native_timer_channel_journal_unavailable");e.journal.read(),L={path:"/v1/notifications/vapid-public-key",method:"GET",write:!1}}else if(b==="registerChannel"&&w.length===1){if(!e.journal)throw de("upgrade_required","native_timer_channel_journal_unavailable");let Y=w[0],ee=so(Y,`kind,criteria,${Y?.kind==="web_push"?"subscription":"token"}`);if(!["web_push","fcm"].includes(ee.kind)||!Array.isArray(ee.criteria)||!ee.criteria.length||ee.criteria.length>100||(ee.criteria.forEach(dw),new Set(ee.criteria).size!==ee.criteria.length))throw de("invalid_request","timer_input");let $e;if(ee.kind==="fcm"){if(typeof ee.token!="string"||ee.token.length<16||ee.token.length>4096||/[\s\u0000-\u001f\u007f]/.test(ee.token))throw de("invalid_request","timer_input");$e={transport:"fcm",token:ee.token}}else{let $=so(ee.subscription,"endpoint,expirationTime,keys"),J=so($.keys,"p256dh,auth");if(typeof $.endpoint!="string"||$.endpoint.length>2048||typeof J.p256dh!="string"||typeof J.auth!="string"||!/^[A-Za-z0-9_-]{87}$/.test(J.p256dh)||!/^[A-Za-z0-9_-]{22}$/.test(J.auth))throw de("invalid_request","timer_input");let be;try{be=new URL($.endpoint)}catch{throw de("invalid_request","timer_input")}if(be.protocol!=="https:"||be.username||be.password||be.hash||be.href!==$.endpoint||$.expirationTime!==null&&(!Number.isFinite($.expirationTime)||$.expirationTime<0))throw de("invalid_request","timer_input");$e={subscription:$}}L={path:O,method:"POST",write:!0,body:{installation_id:e.scope.installation,criteria:[...ee.criteria].sort(),...$e}};let mt=new TextEncoder().encode(JSON.stringify(L.body)),j;try{j=[...new Uint8Array(await crypto.subtle.digest("SHA-256",mt))].map($=>$.toString(16).padStart(2,"0")).join("")}finally{mt.fill(0)}l(),g.signal.throwIfAborted();let W=e.journal.read();if(Q=W,W?.pending)throw de("outcome_unknown","timer_channel_reapproval_required");z={grantId:e.grantId,kind:ee.kind,targetDigest:j,channelId:W?.channelId??null,pending:"register"}}else if(b==="unregisterChannel"&&w.length===1&&["web_push","fcm"].includes(w[0])){if(!e.journal)throw de("upgrade_required","native_timer_channel_journal_unavailable");let Y=e.journal.read();if(Q=Y,!Y){n.postMessage([1,t,i,m,!0,void 0]);return}if(Y.pending==="register")throw de("outcome_unknown","timer_channel_reapproval_required");if(Y.kind!==w[0]||!Y.channelId)throw de("invalid_request","timer_channel_kind");z={...Y,pending:"delete"},L={path:`${O}/${Y.channelId}`,method:"DELETE",write:!0}}else L=O2(o,b,w);v=L.write;let V=L.body===void 0?void 0:JSON.stringify(L.body);if(V&&new TextEncoder().encode(V).length>dp)throw de("invalid_request","timer_input");let te=await e.bearer();if(l(),g.signal.throwIfAborted(),typeof te!="string"||!/^(idev_|ct_)[A-Za-z0-9_-]{43}$/.test(te))throw de("unauthenticated","timer_credential");z&&(await e.journal.write(z),l(),g.signal.throwIfAborted()),y=v;let G=e.fetch;if(S=await G(`${e.cpOrigin}${L.path}`,{method:L.method,body:V,headers:{authorization:`Bearer ${te}`,...V===void 0?{}:{"content-type":"application/json"}},credentials:"omit",redirect:"error",cache:L.method==="GET"?"no-store":"default",referrerPolicy:"no-referrer",signal:g.signal}),l(),g.signal.throwIfAborted(),S.redirected)throw de("unavailable","timer_response");if(b==="unregisterChannel"&&S.status===204){await e.journal.write(null),l(),g.signal.throwIfAborted(),n.postMessage([1,t,i,m,!0,void 0]);return}if(S.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json"||!S.body)throw de("unavailable","timer_response");let K=S.headers.get("content-length");if(K&&/^\d+$/.test(K)&&Number(K)>dp)throw de("unavailable","timer_response");for(x=S.body.getReader();;){let Y=await x.read();try{if(l(),g.signal.throwIfAborted(),Y.done)break;if(C+Y.value.length>dp)throw de("unavailable","timer_response");P.set(Y.value,C),C+=Y.value.length}finally{Y.value?.fill(0)}}let X=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(P.subarray(0,C)));if(b==="unregisterChannel"&&S.status===404&&X?.error?.code==="channel_not_found"){await e.journal.write(null),l(),g.signal.throwIfAborted(),n.postMessage([1,t,i,m,!0,void 0]);return}if(!S.ok)throw S.status>=500?de("unavailable","timer_http"):X?.error?.operation_outcome==="unknown"?de("outcome_unknown","timer_write_unknown"):(z&&(await e.journal.write(Q),l(),g.signal.throwIfAborted()),y=!1,A(S.status===401||S.status===403?"unauthenticated":S.status===409?"conflict":S.status===404?"upgrade_required":S.status===429?"rate_limited":"invalid_request","Native timer request was refused.","timer_refused"));if(l(),g.signal.throwIfAborted(),b==="registerChannel"){if(typeof X?.channel_id!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(X.channel_id))throw de("unavailable","timer_channel_response");await e.journal.write({...z,channelId:X.channel_id,pending:null}),l(),g.signal.throwIfAborted(),n.postMessage([1,t,i,m,!0,{channelId:X.channel_id,installationId:e.scope.installation,criteria:L.body.criteria}])}else n.postMessage([1,t,i,m,!0,X])}catch(O){let L=y?de("outcome_unknown","timer_write_unknown"):O instanceof se?O:de(g.signal.aborted?"cancelled":"unavailable","timer_request");s||n.postMessage([1,t,i,m,!1,L.code,L.reason])}finally{clearTimeout(k),g.signal.removeEventListener("abort",E),P.fill(0),(x?.cancel()??S?.body?.cancel())?.catch(()=>{}),x?.releaseLock(),a?.id===m&&(a=null)}});a={id:m,ctrl:g,work:_}};n.addEventListener("message",u),n.start(),e.signal.addEventListener("abort",d,{once:!0});try{l()}catch(f){throw c(),f}return Object.freeze({close:c})}function mC(n,e,t){let i=fC(e.scope),o=e.generation,s=!1,r=0,a=null,p=()=>{if(s)return;s=!0,t.signal.removeEventListener("abort",p);let y=a;a=null,y?.signal?.removeEventListener("abort",y.abort),y?.reject(de(y.write?"outcome_unknown":"cancelled","timer_port_closed"));try{n.postMessage([1,i,o,"close"])}finally{n.removeEventListener("message",l),n.close(),t.onClose()}},l=y=>{let v=y.data;if(!Array.isArray(v)||v[0]!==1||v[1]!==i||v[2]!==o){p();return}if(v.length===4&&v[3]==="close"){p();return}let _=a;if(!_||v[3]!==_.id||!(v.length===6&&v[4]===!0||v.length===7&&v[4]===!1&&typeof v[5]=="string"&&Sr(v[5]))){p();return}a=null,_.signal?.removeEventListener("abort",_.abort),v[4]?_.resolve(v[5]):_.reject(A(v[5],"Native timer request could not complete.",typeof v[6]=="string"?v[6]:void 0))},c=(y,v,_,k=!1)=>{if(s||t.signal.aborted||_.signal?.aborted)return Promise.reject(de("cancelled","timer_port_closed"));if(a||d&&!k)return Promise.reject(de("unavailable","timer_port_busy"));if(r>=Number.MAX_SAFE_INTEGER)return p(),Promise.reject(de("unavailable","timer_port_closed"));let S=++r,x=y!=="list"&&y!=="lookupOperation"&&y!=="vapid";return new Promise((P,C)=>{let E=()=>{try{n.postMessage([1,i,o,S,"cancel"])}catch{p()}C(de(x?"outcome_unknown":"cancelled","timer_request_cancelled"))};a={id:S,write:x,resolve:P,reject:C,abort:E,signal:_.signal},_.signal?.addEventListener("abort",E,{once:!0});try{if(new TextEncoder().encode(JSON.stringify(v)).length>dp)throw de("invalid_request","timer_input");n.postMessage([1,i,o,S,y,v])}catch(O){a=null,_.signal?.removeEventListener("abort",E),C(O)}})},d=!1,u=()=>{if(s||t.signal.aborted)throw de("cancelled","timer_port_closed")},f=y=>{if(!y?.length||y.length>100||y.some(v=>typeof v!="string"||!v.length||v.length>100)||new Set(y).size!==y.length)throw de("invalid_request","timer_channel_criteria_required");return[...y].sort()},h=(y,v)=>{let _=so(y,"channelId,installationId,criteria");if(typeof _.channelId!="string"||_.installationId!==e.scope.installation||JSON.stringify(_.criteria)!==JSON.stringify(v))throw de("outcome_unknown","timer_channel_response");return{channelId:_.channelId,installationId:e.scope.installation,criteria:[...v]}},m=async(y,v)=>{if(u(),y.signal?.throwIfAborted(),d||a)throw de("unavailable","timer_port_busy");d=!0;try{return await v()}finally{d=!1}},b=y=>m(y,async()=>{let v=f(y.criteria);if(y.installationId!==void 0&&y.installationId!==e.scope.installation)throw de("invalid_request","timer_channel_installation");let _=y.serviceWorker;if(!_?.pushManager||typeof _.pushManager.getSubscription!="function"||typeof _.pushManager.subscribe!="function")throw de("invalid_request","timer_push_platform");let k=await c("vapid",[],y,!0);if(u(),y.signal?.throwIfAborted(),typeof k.public_key!="string"||!/^[A-Za-z0-9_-]{87}$/.test(k.public_key))throw de("unavailable","timer_vapid_response");let S=atob(k.public_key.replace(/-/g,"+").replace(/_/g,"/")),x=Uint8Array.from(S,E=>E.charCodeAt(0));if(x.length!==65||x[0]!==4||btoa(S).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")!==k.public_key)throw de("unavailable","timer_vapid_response");let P=await _.pushManager.getSubscription();if(u(),y.signal?.throwIfAborted(),P){let E=P.options.applicationServerKey;if(!E||E.byteLength!==x.length||new Uint8Array(E).some((O,L)=>O!==x[L]))throw de("invalid_request","timer_push_key_changed")}if(!P&&(P=await _.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:x}),s||t.signal.aborted||y.signal?.aborted))throw await P.unsubscribe(),de("cancelled","timer_port_closed");let C=P.toJSON();return h(await c("registerChannel",[{kind:"web_push",criteria:v,subscription:{endpoint:C.endpoint,expirationTime:C.expirationTime??null,keys:C.keys}}],y,!0),v)}),w=y=>m(y,async()=>{let v=f(y.criteria);if(y.installationId!==void 0&&y.installationId!==e.scope.installation)throw de("invalid_request","timer_channel_installation");return{...h(await c("registerChannel",[{kind:"fcm",criteria:v,token:y.token}],y,!0),v),transport:"fcm"}}),g=(y,v)=>m(v,async()=>{if(await c("unregisterChannel",["web_push"],v,!0),u(),v.signal?.throwIfAborted(),y){let _=await y.pushManager.getSubscription();u(),v.signal?.throwIfAborted(),_&&await _.unsubscribe(),u(),v.signal?.throwIfAborted()}});return n.addEventListener("message",l),n.start(),t.signal.addEventListener("abort",p,{once:!0}),t.signal.aborted&&p(),Object.freeze({list:(y,v)=>c("list",[y],v),put:(y,v,_,k)=>c("put",[y,v,_],k),cancel:(y,v,_,k)=>c("cancel",[y,v,_],k),reconcile:(y,v,_)=>c("reconcile",[y,v],_),reconcileWithReceipt:(y,v,_)=>c("reconcileWithReceipt",[y,v],_),lookupOperation:(y,v,_)=>c("lookupOperation",[y,v],_),registerWebPush:b,unregisterWebPush:g,registerFcm:w,unregisterFcm:y=>m(y,async()=>{await c("unregisterChannel",["fcm"],y,!0)}),close:p})}var I2,pw,dp,de,fC,uw=I(()=>{"use strict";ie();I2=/^[A-Za-z0-9._-]{1,64}$/,pw=/^[A-Za-z0-9._:-]{1,128}$/,dp=2*1024*1024,de=(n,e)=>A(n,"Native timer request could not complete.",e),fC=n=>JSON.stringify([n.account,n.installation,n.collection])});function Qo(n,e=null){if(n instanceof Ue)return n;let t=n?.name??"",i=n instanceof Error?n.message:String(n),o=n?.resultCode,s=typeof o=="number"?o&255:null;return t==="QuotaExceededError"||/quota/i.test(i)||s===13?new Ue("Full",i,e):s===11||s===26||/malformed|not a database|SQLITE_CORRUPT|SQLITE_NOTADB/i.test(i)?new Ue("Corrupt",i,e):t==="NoModificationAllowedError"||s===5||s===6||/SQLITE_BUSY|SQLITE_LOCKED|NoModificationAllowed/i.test(i)?new Ue("Busy",i,e):s===1||s===19||s===20||s===25||/SQLITE_ERROR|SQLITE_CONSTRAINT|syntax/i.test(i)?new Ue("Sql",i,e):new Ue("Other",i,e)}function fw(n){if(typeof n=="bigint")return n;if(typeof n=="number"&&Number.isSafeInteger(n))return BigInt(n);throw new Ue("Other","SQLite integer is not losslessly represented")}var Ue,yC,gC,bC,wC,vC,R2,vh,hw=I(()=>{"use strict";Ue=class extends Error{constructor(t,i,o=null){super(`${t}${o===null?"":`@${o}`}(${i})`);this.kind=t;this.detail=i;this.stmt=o;this.name="IndexError"}kind;detail;stmt},yC=1,gC=2,bC=3,wC=4,vC=5;R2="CREATE TABLE IF NOT EXISTS _mdbn_host(k TEXT PRIMARY KEY, v) WITHOUT ROWID",vh=class n{constructor(e,t,i){this.sqlite3=e;this.db=t;this.info=i}sqlite3;db;info;cache=new Map;closed=!1;static open(e,t,i={}){try{let o=i.synchronous??"NORMAL";if(o!=="NORMAL"&&o!=="FULL")throw new Ue("Other","unsupported synchronous profile");if(i.pragmas!==!1&&(t.exec("PRAGMA locking_mode=EXCLUSIVE"),t.exec("PRAGMA journal_mode=WAL"),t.exec(`PRAGMA synchronous=${o}`)),i.verifyPragmas&&(String(t.selectValue("PRAGMA locking_mode")).toLowerCase()!=="exclusive"||String(t.selectValue("PRAGMA journal_mode")).toLowerCase()!=="wal"||t.selectValue("PRAGMA synchronous")!==(o==="FULL"?2:1)))throw new Ue("Other","SQLite did not apply the requested storage profile");let s=t.selectValue("SELECT count(*) FROM sqlite_master WHERE name='_mdbn_host'")>0,r=t.selectValue("SELECT count(*) FROM sqlite_master");t.exec(R2);let a="Fresh";return s?a=t.selectValue("SELECT v FROM _mdbn_host WHERE k='clean'")===1?"Existing":"Unclean":r>0&&(a="Unclean"),t.exec("INSERT OR REPLACE INTO _mdbn_host(k, v) VALUES ('clean', 0)"),new n(e,t,{durability:"Disposable",opened:a,sqliteVersion:e.capi.sqlite3_libversion_number(),quotaSuspect:i.quotaSuspect??!1})}catch(o){throw Qo(o)}}prepare(e){let t=this.cache.get(e);return t||(t=this.db.prepare(e),this.cache.set(e,t)),t}bind(e,t){e.clearBindings(),t.forEach((i,o)=>{let s=o+1;switch(i.kind){case"Null":e.bind(s,null);break;case"Integer":e.bind(s,i.value);break;case"Real":e.bind(s,i.value);break;case"Text":e.bind(s,i.value);break;case"Blob":e.bindAsBlob(s,i.value);break}})}column(e,t){let i=this.sqlite3.capi;switch(i.sqlite3_column_type(e.pointer,t)){case vC:return{kind:"Null"};case yC:{let o=i.sqlite3_column_int64(e.pointer,t);return{kind:"Integer",value:fw(o)}}case gC:return{kind:"Real",value:i.sqlite3_column_double(e.pointer,t)};case bC:return{kind:"Text",value:e.getString(t)};case wC:return{kind:"Blob",value:e.getBlob(t)??new Uint8Array(0)};default:return{kind:"Null"}}}run(e,t){if(this.closed)throw new Ue("Other","index closed");let i=this.sqlite3.capi,o=e.mode==="Transaction",s=[],r=0,a=0,p=13,l=c=>{if(t){if(!Number.isSafeInteger(c)||c<0||c>t.maxBytes-p)throw new Ue("Full","index reply byte budget exceeded");p+=c}};if(t&&([t.maxBytes,t.maxRows,t.maxValues,t.maxColumns].some(c=>!Number.isSafeInteger(c)||c<0)||t.maxBytes<p))throw new Ue("Full","invalid index reply budget");if(o)try{this.db.exec("BEGIN IMMEDIATE")}catch(c){throw Qo(c)}for(let c=0;c<e.stmts.length;c++){let d=e.stmts[c];try{let u=this.prepare(d.sql);try{this.bind(u,d.params);let f=u.columnCount;if(t&&(!Number.isSafeInteger(f)||f<0||f>t.maxColumns))throw new Ue("Full","index reply column budget exceeded");l(24);let h=[];for(;u.step();){if(t&&++r>t.maxRows)throw new Ue("Full","index reply row budget exceeded");for(let m=0;m<f;m++){if(t){if(++a>t.maxValues)throw new Ue("Full","index reply value budget exceeded");let b=i.sqlite3_column_type(u.pointer,m);if(b===bC||b===wC)l(5),l(i.sqlite3_column_bytes(u.pointer,m));else if(b===yC||b===gC)l(9);else if(b===vC)l(1);else throw new Ue("Other","unknown SQLite value type")}h.push(this.column(u,m))}}s.push({columns:f,values:h,changes:fw(i.sqlite3_changes(this.db.pointer)),lastInsertRowid:fw(i.sqlite3_last_insert_rowid(this.db.pointer))})}finally{u.reset()}}catch(u){if(o)try{this.db.exec("ROLLBACK")}catch{}throw Qo(u,c)}}if(o)try{this.db.exec("COMMIT")}catch(c){try{this.db.exec("ROLLBACK")}catch{}throw Qo(c)}return s}close(e={}){if(!this.closed){this.closed=!0;for(let t of this.cache.values())try{t.finalize()}catch{}if(this.cache.clear(),e.markClean!==!1)try{this.db.exec("INSERT OR REPLACE INTO _mdbn_host(k, v) VALUES ('clean', 1)")}catch{}this.db.close()}}}});function L2(n){let e=new mw(n);if(!e.take(8).every((r,a)=>r===AC[a]))throw qt();let t=e.byte();if(t===1)throw e.done(),new Ue("Other","app database reset requires explicit recovery; automatic wipe refused");if(t!==0)throw qt();let i=e.byte();if(i>1)throw qt();let o=e.count(gn.maxStatements,8),s=[];for(let r=0;r<o;r++){let a=e.text(gn.maxSqlBytes),p=e.count(gn.maxParameters,1),l=[];for(let c=0;c<p;c++)l.push(e.value());s.push({sql:a,params:l})}return e.done(),{mode:i===0?"Transaction":"Autocommit",stmts:s}}function j2(n,e){if(!Array.isArray(n)||n.length!==e)throw qt();let t=new _h(2);t.u32(n.length);let i=0;for(let o of n){if(!Number.isSafeInteger(o.columns)||o.columns<0||o.columns>gn.maxColumns)throw ao();if(!Array.isArray(o.values)||(o.columns===0?o.values.length!==0:o.values.length%o.columns!==0))throw qt();if(i+=o.columns===0?0:o.values.length/o.columns,i>gn.maxRows||o.values.length>gn.maxValues)throw ao();t.u32(o.columns),t.int(o.changes,!1),t.int(o.lastInsertRowid,!0),t.u32(o.values.length);for(let s of o.values)t.value(s)}return t.done()}function N2(n,e){let t=n instanceof Ue?n.kind:"Other",i={Sql:0,Corrupt:1,Full:2,Busy:3,Other:4},o=new _h(3);o.byte(i[t]);let s=n instanceof Ue?n.stmt:null;return e!==null&&s!==null&&Number.isSafeInteger(s)&&s>=0&&s<e?(o.byte(1),o.u32(s)):o.byte(0),o.data(kC.encode("app index operation failed; reopen and reconcile")),o.done()}function _C(n,e,t){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t)||e<0||t<0||e>4294967295||t>4294967295||e>n.buffer.byteLength||t>n.buffer.byteLength-e)throw qt()}function SC(n,e){let t=!1,i=!1;return(o,s)=>{if(t)throw i=!0,n.fence(),qt();t=!0,i=!1;try{let r=e();if(_C(r.memory,o,s),s>gn.maxBytes)throw n.fence(),ao();let a=n.run(new Uint8Array(r.memory.buffer,o,s).slice()),p=r.alloc(a.length);if(_C(r.memory,p,a.length),i||p===0||p<o+s&&o<p+a.length)throw qt();return new Uint8Array(r.memory.buffer,p,a.length).set(a),BigInt(p)<<32n|BigInt(a.length)}catch(r){throw n.fence(),r}finally{t=!1}}}var AC,gn,E2,q2,T2,qt,ao,M2,kC,mw,_h,Ah,PC=I(()=>{"use strict";hw();AC=Uint8Array.of(77,68,66,73,68,88,0,1),gn=Object.freeze({maxBytes:4*1024*1024,maxStatements:16384,maxValues:131072,maxRows:4096,maxColumns:100,maxSqlBytes:100*1024,maxParameters:100}),E2=-(1n<<63n),q2=(1n<<63n)-1n,T2=(1n<<64n)-1n,qt=()=>new Ue("Other","invalid app index ABI"),ao=()=>new Ue("Full","app index ABI budget exceeded"),M2=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),kC=new TextEncoder,mw=class{constructor(e){this.bytes=e;if(e.length>gn.maxBytes)throw ao();this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}bytes;pos=0;values=0;view;take(e){if(!Number.isSafeInteger(e)||e<0||e>this.bytes.length-this.pos)throw qt();let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}byte(){return this.take(1)[0]}u32(){let e=this.pos;return this.take(4),this.view.getUint32(e,!0)}count(e,t){let i=this.u32();if(i>e)throw ao();if(i>Math.floor((this.bytes.length-this.pos)/t))throw qt();return i}data(e){return this.take(this.count(e,1))}text(e){return M2.decode(this.data(e))}value(){if(++this.values>gn.maxValues)throw ao();switch(this.byte()){case 0:return{kind:"Null"};case 1:{let e=this.pos;return this.take(8),{kind:"Integer",value:this.view.getBigInt64(e,!0)}}case 2:{let e=this.pos;this.take(8);let t=this.view.getFloat64(e,!0);if(!Number.isFinite(t))throw qt();return{kind:"Real",value:t}}case 3:return{kind:"Text",value:this.text(gn.maxBytes)};case 4:return{kind:"Blob",value:this.data(gn.maxBytes).slice()};default:throw qt()}}done(){if(this.pos!==this.bytes.length)throw qt()}};_h=class{parts=[];length=0;values=0;constructor(e){this.put(AC),this.byte(e)}put(e){if(e.length>gn.maxBytes-this.length)throw ao();this.length+=e.length,this.parts.push(e)}byte(e){this.put(Uint8Array.of(e))}u32(e){if(!Number.isSafeInteger(e)||e<0||e>4294967295)throw qt();let t=new Uint8Array(4);new DataView(t.buffer).setUint32(0,e,!0),this.put(t)}int(e,t){if(typeof e!="bigint"||e<(t?E2:0n)||e>(t?q2:T2))throw qt();let i=new Uint8Array(8),o=new DataView(i.buffer);t?o.setBigInt64(0,e,!0):o.setBigUint64(0,e,!0),this.put(i)}data(e){this.u32(e.length),this.put(e)}value(e){if(++this.values>gn.maxValues)throw ao();switch(e.kind){case"Null":this.byte(0);return;case"Integer":this.byte(1),this.int(e.value,!0);return;case"Real":{if(!Number.isFinite(e.value))throw qt();this.byte(2);let t=new Uint8Array(8);new DataView(t.buffer).setFloat64(0,e.value,!0),this.put(t);return}case"Text":this.byte(3),this.data(kC.encode(e.value));return;case"Blob":this.byte(4),this.data(e.value);return;default:throw qt()}}done(){let e=new Uint8Array(this.length),t=0;for(let i of this.parts)e.set(i,t),t+=i.length;return e}};Ah=class{constructor(e){this.index=e}index;fenced=!1;get needsRecovery(){return this.fenced||this.index.needsRecovery}fence(){this.fenced=!0,this.index.fence()}run(e){let t=null;try{if(this.needsRecovery)throw qt();let i=L2(e);t=i.stmts.length;let o=gn;return j2(this.index.run(i,o),t)}catch(i){return this.fence(),N2(i,t)}}}});function gw(n){let e=[n.account,n.installation,n.collection];if(e.some(i=>!U2.test(i)))throw new Ue("Other","invalid app storage scope");let t=`mdbase-app-${e.map(i=>i.toLowerCase()).join("-")}`;return{vfs:t,directory:`.${t}`}}async function xC(n,e){let t=gw(e),i,o,s;try{i=await n.installOpfsSAHPoolVfs({name:t.vfs,directory:t.directory,initialCapacity:6}),i.isPaused?.()&&await i.unpauseVfs(),o=new i.OpfsSAHPoolDb("/app.db");let r=vh.open(n,o,{synchronous:"FULL",verifyPragmas:!0});if(s=new yw(r),r.info.opened==="Unclean"){let a=s.run({mode:"Autocommit",stmts:[{sql:"PRAGMA quick_check",params:[]}]}),p=a[0]?.values;if(a.length!==1||p?.length!==1||p[0]?.kind!=="Text"||p[0].value!=="ok")throw s=void 0,r.close({markClean:!1}),o=void 0,new Ue("Corrupt","app database integrity check failed; recovery required")}return{index:s,pool:i}}catch(r){let a=!1;try{s?s.close():o?.close()}catch{a=!0}try{i?.pauseVfs?.()}catch{a=!0}let p=Qo(r);throw new Ue(a?"Other":p.kind,"app SQLite open failed; recovery required",p.stmt)}}var U2,yw,CC=I(()=>{"use strict";hw();U2=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;yw=class{constructor(e){this.inner=e}inner;fenced=!1;closed=!1;get info(){return this.inner.info}get needsRecovery(){return this.fenced}fence(){this.fenced=!0}run(e,t){if(this.closed||this.fenced)throw new Ue("Other","app database fenced or closed; reopen and reconcile");try{return t?this.inner.run(e,t):this.inner.run(e)}catch(i){this.fenced=!0;let o=Qo(i);throw new Ue(o.kind,"app SQLite operation failed; reopen and reconcile",o.stmt)}}reset(){throw new Ue("Other","app database reset requires explicit recovery; automatic wipe refused")}close(){this.closed||(this.closed=!0,this.inner.close({markClean:!this.fenced}))}}});function IC(n){let e=Object.freeze({...n});if(!/^[0-9a-f]{64}$/.test(e.wasmSha256)||!Number.isSafeInteger(e.maxWasmBytes)||e.maxWasmBytes<1||e.maxWasmBytes>4*1024*1024||typeof e.loadWasm!="function"||typeof e.initialize!="function")throw Ya("binding");return async({scope:t,signal:i})=>{let o=Object.freeze({account:t.account,installation:t.installation,collection:t.collection});gw(o);let s=()=>{if(i.aborted||Object.entries(o).some(([y,v])=>t[y]!==v))throw Ya("fenced")};s();let r=globalThis.WorkerGlobalScope;if(typeof r!="function"||!(globalThis instanceof r))throw Ya("unsupported");let a=await e.loadWasm({signal:i});if(s(),!(a instanceof Uint8Array)||a.byteLength<1||a.byteLength>e.maxWasmBytes)throw Ya("binding");let p=new Uint8Array(a),l=new Uint8Array(await crypto.subtle.digest("SHA-256",p));if(s(),Array.from(l,y=>y.toString(16).padStart(2,"0")).join("")!==e.wasmSha256)throw Ya("binding");let c=await e.initialize({wasmBinary:p,print(){},printErr(){}});s();let d=await xC(c,o),u=d.index,f=new Ah(u),h={import:y=>SC(f,y),fence:()=>f.fence(),get needsRecovery(){return f.needsRecovery}},m=y=>({kind:"Text",value:y}),b=Object.freeze({list(y){let[v]=u.run({mode:"Autocommit",stmts:[{sql:"SELECT v FROM _mdbn_host WHERE k >= 'w:' AND k < 'w;' ORDER BY k LIMIT 1024",params:[]}]}),_=[],k=0;for(let S of v?.values??[])if(S.kind==="Text"){if(k+=S.value.length,k>y)break;_.push(S.value)}return _},put(y,v){u.run({mode:"Autocommit",stmts:[{sql:"INSERT OR REPLACE INTO _mdbn_host(k, v) VALUES (?, ?)",params:[m(`w:${y}`),m(v)]}]})},remove(y){u.run({mode:"Autocommit",stmts:[{sql:"DELETE FROM _mdbn_host WHERE k = ?",params:[m(`w:${y}`)]}]})}}),w=null,g=()=>w??=Promise.resolve().then(async()=>{try{u.close(),await d.pool.pauseVfs()}catch{throw f.fence(),Ya("unavailable")}});return(i.aborted||Object.entries(o).some(([y,v])=>t[y]!==v))&&f.fence(),Object.freeze({sql:h,opened:{Fresh:"fresh",Existing:"existing",Unclean:"unclean"}[u.info.opened],sqliteVersion:u.info.sqliteVersion,ledger:b,close:g})}}var bw,Ya,OC=I(()=>{"use strict";CC();PC();bw=class extends Error{constructor(t){super(`app collection SQL: ${t}`);this.reason=t;this.name="AppCollectionSqlError"}reason},Ya=n=>new bw(n)});var Ja,D2,$2,lo,on,Xa,kh=I(()=>{"use strict";Ja="original-join",D2=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,$2="00000000-0000-0000-0000-000000000000",lo=class extends Error{constructor(t){super(`app collection join: ${t}`);this.reason=t;this.name="AppCollectionJoinError"}reason},on=(n="recovery_required")=>new lo(n),Xa=class{options;key;busy=!1;constructor(e){let t=Object.freeze({account:e.scope.account,installation:e.scope.installation,collection:e.scope.collection});if(Object.values(t).some(i=>typeof i!="string"||!D2.test(i)||i===$2)||typeof e.databaseName!="string"||!e.databaseName.length||e.databaseName.length>256||/[\u0000-\u001f\u007f]/.test(e.databaseName)||typeof e.isCurrent!="function")throw on("binding");this.options=Object.freeze({databaseName:e.databaseName,scope:t,isCurrent:e.isCurrent}),this.key=JSON.stringify([t.account,t.installation,t.collection])}check(e){if(e.aborted||this.options.isCurrent()!==!0)throw on("fenced")}marker(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).sort().join()!=="account,collection,installation,phase,version")throw on();let t=e;if(t.version!==1||t.phase!=="attempted"&&t.phase!=="completed"||Object.entries(this.options.scope).some(([i,o])=>t[i]!==o))throw on();return t}open(e){if(this.check(e),!globalThis.indexedDB)throw on();return new Promise((t,i)=>{let o=indexedDB.open(this.options.databaseName,1),s=!1,r=()=>e.removeEventListener("abort",a),a=()=>{s=!0,r();try{o.transaction?.abort()}catch{}i(on())};e.addEventListener("abort",a,{once:!0}),o.onblocked=o.onerror=a,o.onupgradeneeded=()=>{try{if(this.check(e),s||o.result.objectStoreNames.length)throw on();o.result.createObjectStore(Ja)}catch{try{o.transaction?.abort()}catch{}}},o.onsuccess=()=>{r();try{if(this.check(e),s||o.result.objectStoreNames.length!==1||!o.result.objectStoreNames.contains(Ja))throw on();t(o.result)}catch{o.result.close(),i(on())}}})}async change(e,t){if(this.check(t),this.busy)throw on("busy");this.busy=!0;let i=null;try{return i=await this.open(t),this.check(t),await new Promise((o,s)=>{this.check(t);let r=i.transaction(Ja,"readwrite",{durability:"strict"}),a=null,p,l=()=>{try{r.abort()}catch{}},c=()=>t.removeEventListener("abort",l);t.addEventListener("abort",l,{once:!0}),r.onabort=r.onerror=()=>{c(),s(p??on())},r.oncomplete=()=>{c();try{if(this.check(t),!a)throw on();o(Object.freeze(a))}catch{s(on())}};let d=r.objectStore(Ja),u=d.get(this.key);u.onsuccess=()=>{try{this.check(t);let f=u.result;if(f===void 0){if(e!=="prepare")throw on();d.add({version:1,...this.options.scope,phase:"attempted"},this.key),a={outcomeMode:"fresh",phase:"attempted"}}else{let h=this.marker(f);e==="complete"&&h.phase!=="completed"&&d.put({...h,phase:"completed"},this.key),a={outcomeMode:"existing",phase:e==="complete"?"completed":h.phase}}}catch(f){p=f,l()}}})}catch(o){throw o instanceof lo?o:on()}finally{i?.close(),this.busy=!1}}prepare(e){return this.change("prepare",e.signal)}async syncedBefore(e){return await this.synced("read",e.signal)===!0}async markSynced(e){await this.synced("mark",e.signal)}async synced(e,t){let i=null;try{i=await this.open(t),this.check(t);let o=JSON.stringify([this.options.scope.account,this.options.scope.installation,this.options.scope.collection,"synced"]);return await new Promise(s=>{let r=i.transaction(Ja,e==="mark"?"readwrite":"readonly"),a=!1;r.onabort=r.onerror=()=>s(!1),r.oncomplete=()=>s(e==="mark"||a);let p=r.objectStore(Ja);if(e==="mark")p.put({version:1,synced:!0},o);else{let l=p.get(o);l.onsuccess=()=>{let c=l.result;a=!!c&&c.version===1&&c.synced===!0}}})}catch{return!1}finally{i?.close()}}async complete(e){await this.change("complete",e.signal)}}});function ww(n){let e=[n.account,n.installation,n.collection];if(e.some(o=>typeof o!="string"||!z2.test(o))||typeof n.isCurrent!="function")throw ct();let t=JSON.stringify(e.map(o=>o.toLowerCase())),i=n.isCurrent.bind(n);return{binding:t,current:()=>{try{return i()===!0&&JSON.stringify([n.account,n.installation,n.collection].map(o=>o.toLowerCase()))===t}catch{return!1}}}}function qC(n,e,t,i,o){let s=ww(e),r=!1,a=()=>{if(!r){r=!0,n.onmessage=null,n.onmessageerror=null;try{n.postMessage([1,s.binding,"close"])}catch{}n.close(),i()}},p=()=>{if(r||!s.current())throw a(),ct()};return n.onmessageerror=a,n.onmessage=l=>{try{p();let c=l.data;if(!Array.isArray(c)||c[0]!==1||c[1]!==s.binding)throw ct();if(c.length===3&&c[2]==="close"){a();return}if(c.length===5&&B2.includes(c[2])){let u=c[2],f=c[3],h=c[4],m=RC(u);if(!o||!Number.isInteger(f)||f<1||f>4294967295||!(h instanceof Uint8Array)||!h.length||h.length>m)throw ct();p(),o(u,f,h);return}if(c.length!==4||c[2]!=="frame"||!(c[3]instanceof Uint8Array)||c[3].length===0||c[3].length>Rr)throw ct();let d=ue(new Uint8Array(c[3]));p(),t(d)}catch{a()}},n.start(),{close:a,send(l){try{p();let c=pe(l);if(!c.length||c.length>Rr)throw ct();p(),n.postMessage([1,s.binding,"frame",c],[c.buffer])}catch{throw a(),ct()}},control(l,c,d){try{p();let u=RC(l);if(!Number.isInteger(c)||c<1||c>4294967295||!(d instanceof Uint8Array)||!d.length||d.length>u||!(d.buffer instanceof ArrayBuffer)||d.byteOffset!==0||d.byteLength!==d.buffer.byteLength)throw ct();p(),n.postMessage([1,s.binding,l,c,d],[d.buffer])}catch{throw a(),ct()}},current:p}}function V2(n){if(!(n instanceof Map))return!1;let e=n;return e.get(0)===0&&F2.has(e.get(2))}function Sh(n,e,t,i){if(!ww(t).current())throw ct();let s;try{s=n.connect({collection:t.collection})}catch{throw e.close(),ct()}let r;try{r=qC(e,t,p=>{if(s.send(p),i&&V2(p))try{i()}catch{}},()=>s.close(),(p,l,c)=>{let d;try{if(p==="bases-request"&&typeof n.executeBases=="function")d=n.executeBases(s,c);else if((p==="bases-list-views-request"||p==="bases-read-view-source-request")&&typeof n.discoverBases=="function")d=n.discoverBases(s,p==="bases-list-views-request"?"list-views":"read-view-source",c);else throw ct()}finally{c.fill(0)}try{r.current(),r.control(EC(p),l,d)}catch(u){throw d.byteLength&&d.fill(0),u}}),s.onframe=p=>{try{r.send(p)}catch{}},s.onclose=()=>r.close()}catch{throw s.close(),e.close(),ct()}let a=Object.freeze({async assess(p,l,c){if(l.throwIfAborted(),r.current(),!n.setupResources)throw ct();let d=c===void 0?n.setupResources(s,"assess",p):n.setupResources(s,"assess",p,void 0,c);return r.current(),l.throwIfAborted(),d},async apply(p,l,c,d){if(c.throwIfAborted(),r.current(),!n.setupResources)throw ct();let u=d===void 0?n.setupResources(s,"apply",p,l):n.setupResources(s,"apply",p,l,d);return r.current(),c.throwIfAborted(),u},async rejected(p,l){if(l.throwIfAborted(),r.current(),!n.resourceRejected)return!1;let c=n.resourceRejected(s,p);return r.current(),l.throwIfAborted(),c}});return{close:()=>r.close(),resourceSetup:a}}function Ph(n,e){let t=ww(e),i=!1,o=!1,s,r=null,a=[],p=()=>A("cancelled","Bases read cancelled"),l=1;return{description:"app-local",close(){o=!0,s?s.close():n.close()},async open(c,d){if(i)throw ct();if(!t.current()||d?.aborted||o)throw n.close(),ct();i=!0;let u,f=s=qC(n,e,b=>u?.onframe?.(b),()=>{let b=r;r=null;let w=a.splice(0);b?.finish(void 0,p());for(let g of w)g.finish(void 0,p());u?.onclose?.(ct())},(b,w,g)=>{if(!r||b!==r.response||w!==r.id)throw g.fill(0),ct();let y=r;r=null,y.finish(g),h()});function h(){if(r||a.length===0)return;let b=a.shift();r=b;try{if(f.current(),r!==b){h();return}if(l>4294967295)throw f.close(),ct();b.id=l++,f.control(b.kind,b.id,b.request)}catch(w){r===b&&(r=null),b.finish(void 0,w),h()}}let m=(b,w,g)=>{try{if(f.current(),g?.aborted)throw p();if(!(w instanceof Uint8Array)||!w.length||w.length>128*1024)throw A("invalid_request","Bases request bytes exceed bound");if(a.length>=32)throw A("unavailable","Bases read queue is full","bases_read_backpressure")}catch(v){return Promise.reject(v)}let y=new Uint8Array(w);return new Promise((v,_)=>{let k=!1,S=(C,E)=>{if(r!==x&&y.byteLength&&y.fill(0),k){C?.byteLength&&C.fill(0);return}k=!0,g?.removeEventListener("abort",P),E!==void 0?_(E):v(C)},x={kind:b,request:y,response:EC(b),finish:S},P=()=>{let C=a.indexOf(x);C!==-1&&a.splice(C,1),r===x&&x.id===void 0&&(r=null),S(void 0,p())};a.push(x),g?.addEventListener("abort",P,{once:!0}),h()})};u={onframe:null,onclose:null,send:b=>f.send(b),close:()=>f.close(),readAppBases:(b,w)=>m("bases-request",b,w),readAppBasesDiscovery(b,w,g){return b!=="list-views"&&b!=="read-view-source"?Promise.reject(A("invalid_request","unknown native Bases read")):m(b==="list-views"?"bases-list-views-request":"bases-read-view-source-request",w,g)}};try{if(d?.aborted||o)throw ct();return await Ds({connect:()=>u}).open(c,d)}catch{throw f.close(),ct()}}}}var z2,ct,B2,EC,RC,F2,xh=I(()=>{"use strict";Je();ie();su();Ol();z2=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/iu,ct=()=>A("unavailable","app local facade unavailable; reopen and reconcile");B2=["bases-request","bases-response","bases-list-views-request","bases-list-views-response","bases-read-view-source-request","bases-read-view-source-response"],EC=n=>n==="bases-request"?"bases-response":n==="bases-list-views-request"?"bases-list-views-response":"bases-read-view-source-response",RC=n=>n.endsWith("request")?128*1024:n==="bases-response"?Rr:1024*1024;F2=new Set(["submit","resolve_hold","open_upload","upload_chunk","commit_upload","abort_upload","fetch_file","read_file","ack_chunks"])});function TC(n){let e=Object.freeze({...n,setupJournal:Object.freeze({...n.setupJournal})}),t=IC(e.sql);if(typeof e.handoff!="function")throw Yi("binding");let i=new Set;return async o=>{let s=JSON.stringify([o.scope.account,o.scope.installation,o.scope.collection]);if(i.has(s))throw Yi("fenced");i.add(s);let{host:r,installation:a,signal:p,collection:l,setupPolicy:c}=o,d=a.isCurrent,u=l.displayName,f=he=>{if(X())try{o.onProgress?.(he)}catch{}},h=Object.freeze({account:o.scope.account,installation:o.scope.installation,collection:o.scope.collection}),m=JSON.stringify([h.account,h.installation,h.collection]),b=new AbortController,w=!1,g=!0,y=null,v=null,_=null,k=null,S=null,x=null,P=null,C=null,E="setup_required",O=null,L=!1,z=null,Q=!1,V=null,te=new Map,G=null,K=new Set,X=()=>{try{return!w&&!b.signal.aborted&&!p.aborted&&o.signal===p&&o.host===r&&o.installation===a&&a.isCurrent===d&&d.call(a)===!0&&o.collection===l&&o.setupPolicy===c&&a.scope.account===h.account&&a.scope.installation===h.installation&&JSON.stringify([o.scope.account,o.scope.installation,o.scope.collection])===m&&l.collectionId===h.collection}catch{return!1}},Y=()=>{if(!X())throw Yi("fenced")},ee=()=>{for(let he of[...K])try{he()}catch{}},$e=()=>{if(_)return _;w=!0,E="setup_required",y!==null&&clearTimeout(y),y=null,z!==null&&clearTimeout(z),z=null;try{O?.close()}catch{}O=null;try{r.onLogWork?.(null)}catch{}p.removeEventListener("abort",mt);let he=[...te.values()];return te.clear(),_=Promise.resolve().then(async()=>{let me=!1;try{await S?.close()}catch{me=!0}try{await k?.close()}catch{me=!0}for(let Fe of he){try{await Fe.timers?.close()}catch{me=!0}try{await Fe.control.close()}catch{me=!0}try{Fe.data.port1.postMessage([1,JSON.stringify([h.account,h.installation,h.collection]),"close"])}catch{me=!0}for(let Rn of[Fe.data.port1,Fe.data.port2,Fe.command.port1,Fe.command.port2])try{Rn.close()}catch{me=!0}}try{P?.port1.postMessage([1,JSON.stringify([h.account,h.installation,h.collection]),"close"])}catch{me=!0}for(let Fe of[P?.port1,P?.port2,C?.port1,C?.port2])try{Fe?.close()}catch{me=!0}await v?.catch(()=>{});try{x?.close()}catch{me=!0}if(me)throw Yi("unavailable");K.clear(),i.delete(s)}),b.abort(),ee(),_},mt=()=>{$e().catch(()=>{})},j=null,W=0,$=()=>{let he=St(G);if(he!==null)return he==="collection_migrating"?Math.min(6e5,Math.max(5e3,G?.retryAfterMs??3e4)):3e5;let me=Math.min(6e4,1e3*2**Math.min(Math.max(W,ye),6));return j?.kind==="offline"?qe?me:null:j?.kind==="server_busy"||j?.kind==="rate_limited"?j.retryAfterMs??me:ye||j?me:250},J=()=>{let he=null;try{he=r.serverProblem()}catch{he=null}let me=null;try{me=r.transportHealth()}catch{me=null}W=me?W+1:0;let Fe=JSON.stringify(me)===JSON.stringify(j);(he!==G||!Fe)&&(G=he,j=me,ee())},be=Number.POSITIVE_INFINITY,ye=0,we=0,et=!1,qe=null,Dt=he=>{let me=he&&typeof he=="object"&&typeof he.code=="string"?he.code:null;try{console.debug("mdbase: sync turn failed",{reason:j?.kind??St(G)??me??"unknown",failures:ye})}catch{}},tt=()=>{if(g||Date.now()-we>=W2)return!1;try{return r.pendingWrites()>0}catch{return!1}},Ve=()=>{if(!X())return;if(!g&&!tt()&&!Q){v||O?.suspend();return}if(y!==null||v)return;let he=Q?0:$();Q=!1,he!==null&&(y=setTimeout(()=>{if(y=null,!X())return;let me=g&&Date.now()>=be;me&&(be=Number.POSITIVE_INFINITY);let Fe=v=me?r.wakeCollectionLog({signal:b.signal}):r.driveCollection({signal:b.signal});Fe.then(()=>{v===Fe&&(v=null),ye=0,et=!0,X()&&J(),qe?.(),Ve()},Rn=>{v===Fe&&(v=null),ye++,X()&&J(),Dt(Rn),qe?.(),Ve()})},he))},On=()=>{X()&&(Q=!0,y!==null&&clearTimeout(y),y=null,Ve())},Ar=he=>{L!==he&&(L=he,ee())},Pi=he=>{if(z!==null&&clearTimeout(z),z=null,he){Ar(!1);return}if(!O?.available){Ar(V===null);return}O.suspended||(z=setTimeout(()=>{z=null,X()&&!O?.live&&Ar(!0)},K2))},rs=he=>{if(Y(),he){(!O?.live||j?.kind==="offline")&&(be=0),ye=0,W=0,j?.kind==="offline"&&(Q=!0);try{O?.resume(),O&&!O.live&&Pi(!1)}catch{}}else g&&(we=Date.now());g=he,y!==null&&clearTimeout(y),y=null,Ve()},os=()=>new Promise((he,me)=>{let Fe,Rn=null,En=nt=>{qe=null,Rn!==null&&clearTimeout(Rn),b.signal.removeEventListener("abort",xi),nt?me(nt):he()},xi=()=>En(Yi("fenced"));b.signal.addEventListener("abort",xi,{once:!0}),qe=()=>{if(!X()){En(Yi("fenced"));return}if(V!==null){En();return}let nt="first_turn";if(et)try{nt=typeof r.initialSync=="function"?r.initialSync():null}catch{nt="unavailable"}if(nt===null||nt==="offline"||j?.kind==="offline"){En();return}let ii=null;if(nt==="waiting_for_key"&&typeof r.keyWaitDetail=="function")try{ii=r.keyWaitDetail()}catch{ii=null}let ss=nt+(ii?JSON.stringify(ii):"");if(ss!==Fe){Fe=ss;try{console.debug("mdbase: waiting for the first sync",{...ii,reason:nt})}catch{}}},Rn=setTimeout(()=>En(),H2),qe()});p.addEventListener("abort",mt,{once:!0});try{Y(),x=new Ba({...e.setupJournal,scope:h,isCurrent:X});let he=new Xa({databaseName:e.joinDatabaseName,scope:h,isCurrent:X}),me=await he.prepare({signal:b.signal});Y(),f("joining"),await r.bootstrapCloudCopy({scope:h,collectionCurrent:X,purpose:"join",outcomeMode:me.outcomeMode,signal:b.signal,...me.outcomeMode==="existing"?{reconcile:"explicit-unknown-outcome"}:{},fetch:e.fetch,allowLoopbackHttp:e.allowLoopbackHttp,allowNativeLoopbackHttp:e.allowNativeLoopbackHttp}),Y(),await he.complete({signal:b.signal}),Y();let Fe=r.registeredReceipt();if(Fe.installationId!==h.installation)throw Yi("binding");let Rn=null,En=async He=>{let Ze=await t(He);return Rn=Ze.ledger??null,Ze};f("opening_store"),await r.openCollectionSql({signal:b.signal,replicaId:Fe.deviceId,endpoint:0,openSql:En}),Y(),f("connecting_log");let xi=Date.now()+G2;for(let He=0;;He++)try{await r.startCollectionLog({signal:b.signal,fetch:e.fetch,allowLoopbackHttp:e.allowLoopbackHttp}),Y();break}catch(Ze){Y();let dt=Ze instanceof Zn&&Ze.reason==="unavailable"?Ze.server:null;if(!kn(dt)||dt.status!==503||dt.code!=="busy"||St(dt)!==null||He+1>=Y2)throw Ze;let Ci=dt.retryAfterMs??1e3*2**He;if(Date.now()+Ci>=xi||(await pp(Ci,b.signal),Y(),Date.now()>=xi))throw Ze}let nt=await he.syncedBefore({signal:b.signal});Y(),f("syncing"),await r.waitForVerifiedRead({signal:b.signal,cold:!nt,onProgress:f}),Y(),r.onLogWork?.(On),Ve();try{O=typeof r.openLogPush=="function"?r.openLogPush({push:He=>{X()&&(r.pushLog(He),On())},live:Pi,ended:He=>{V=He,On(),Pi(!1),qe?.(),ee()}}):null}catch{O=null}O?(O.start(),Pi(!1)):L=!0,nt&&(f("syncing"),await os()),Y(),f("checking_setup"),he.markSynced({signal:b.signal}).catch(()=>{});let ii=await x.load(b.signal);Y();let ss=ii&&ii.version!==1&&(ii.phase==="attempted"||ii.phase==="confirmed")?"reconcile-original":ii===null&&c==="approved-new-collection"?"approved-new":"inspect",as=crypto.randomUUID(),Qw=e.people===!0?{people:!0}:{},EI={owner:null},ev=(He,Ze,dt,Ci)=>Fx(Ze,{scope:h,generation:as},{journal:x,resourceSetup:r.attachDataFacade(He),signal:b.signal,isCurrent:X,ledger:()=>X()?Rn:null,setupTurn:EI,assess(kr){Y(),E=kr,ee()},foreground:dt,onProtocolFailure:Ci,...e.people===!0?{peopleAuthority:r.peopleAuthority()}:{}});S=r.openTimersPort({scope:h,generation:as,signal:b.signal}),Y(),P=new MessageChannel,C=new MessageChannel,k=ev(P.port1,C.port1,rs,mt),Y();let tv=He=>{if(P&&C&&He.dataPort===P.port2){let dt={data:P,command:C,control:k,timers:S};P=null,C=null,k=null,S=null;try{r.detachDataFacade(dt.data.port1)}catch{}dt.timers?.close().catch(()=>{}),dt.control?.close().catch(()=>{});for(let Ci of[dt.data.port1,dt.command.port1])try{Ci.close()}catch{}return}let Ze=te.get(He.dataPort);if(Ze){te.delete(He.dataPort);try{r.detachDataFacade(Ze.data.port1)}catch{}Ze.timers?.close().catch(()=>{}),Ze.control.close().catch(()=>{});for(let dt of[Ze.data.port1,Ze.command.port1])try{dt.close()}catch{}}},qI=Object.freeze({scope:h,generation:as,isCurrent:X,setForeground:rs,attach:()=>{if(!X()||V!==null)return null;let He=new MessageChannel,Ze=new MessageChannel,dt=null,Ci=null;try{dt=r.openTimersPort({scope:h,generation:as,signal:b.signal});let kr=null;return Ci=ev(He.port1,Ze.port1,()=>{},()=>{kr&&tv(kr)}),kr=Object.freeze({schema:"mdbn-app-collection/1",scope:h,generation:as,displayName:u,setupMode:ss==="reconcile-original"?ss:"inspect",dataPort:He.port2,controlPort:Ze.port2,...Qw,...dt?{timerPort:dt.port}:{}}),te.set(He.port2,{data:He,command:Ze,control:Ci,timers:dt}),kr}catch{try{r.detachDataFacade(He.port1)}catch{}dt?.close().catch(()=>{}),Ci?.close().catch(()=>{});for(let kr of[He.port1,He.port2,Ze.port1,Ze.port2])kr.close();return null}},detach:tv}),TI={get state(){return X()?E:"setup_required"},get problem(){return X()?G:null},get health(){return X()?j:null},get live(){return X()?!L:null},get ended(){return X()?V:null},connection:qI,close:$e,subscribe(He){return Y(),K.add(He),()=>{K.delete(He)}}};return e.handoff(Object.freeze({schema:"mdbn-app-collection/1",scope:h,generation:as,displayName:u,setupMode:ss,dataPort:P.port2,controlPort:C.port2,...Qw,...S?{timerPort:S.port}:{}})),Y(),Ve(),Object.freeze(TI)}catch(he){throw await $e(),he}}}async function Ch(n,e){if(n.schema!=="mdbn-app-collection/1"||Za.has(n.dataPort)||Za.has(n.controlPort)||n.dataPort===n.controlPort||!["inspect","approved-new","reconcile-original"].includes(n.setupMode)||n.people!==void 0&&n.people!==!0||e.signal.aborted||n.timerPort&&(Za.has(n.timerPort)||n.timerPort===n.dataPort||n.timerPort===n.controlPort))throw Yi("binding");Za.add(n.dataPort),Za.add(n.controlPort),n.timerPort&&Za.add(n.timerPort);let t=Object.freeze({...n.scope}),i=n.generation,o=n.setupMode,s=n.people===!0,r=n.dataPort,a=n.controlPort,p=e.signal,l=!1,c=null,d=null,u=null,f,h=()=>{if(!l){l=!0,p.removeEventListener("abort",h);for(let m of[()=>f?.close(),()=>d?.close(),()=>c?.close(),()=>u?.close(),()=>r.close(),()=>a.close()])try{m()}catch{}}};p.addEventListener("abort",h,{once:!0});try{if(u=Ph(r,{...t,isCurrent:()=>!l&&!p.aborted}),d=uh(a,{scope:t,generation:i},{signal:p,isCurrent:()=>!l,onClose:h,...s?{people:!0}:{}}),n.timerPort&&(f=new Ns(mC(n.timerPort,{scope:t,generation:i},{signal:p,onClose:()=>{}}),{criteria:e.timerCriteria??[]})),c=await Ei.connect({app:e.app,connector:u,reconnect:!1,signal:p,ledger:d.ledger}),l||p.aborted)throw c.close(),Yi("fenced");let m=s?ph(c,d):void 0;return Object.freeze({client:c,resourceSetup:d.resourceSetup,...m?{people:m}:{},journal:d.journal,scope:t,setupMode:o,close:h,...f?{timers:f}:{},assess:(b,w)=>d.assess(b,w),setForeground:(b,w)=>d.setForeground(b,w)})}catch(m){throw h(),m}}var K2,W2,H2,G2,Y2,up,Yi,Za,vw=I(()=>{"use strict";Fn();Zc();cw();Ps();Zy();uw();OC();kh();Go();no();xh();rp();K2=1e4,W2=12e4,H2=2e3,G2=15e3,Y2=3,up=class extends Error{constructor(t){super(`app web collection: ${t}`);this.reason=t;this.name="AppWebCollectionError"}reason},Yi=n=>new up(n);Za=new WeakSet});var Ut,Ih,J2,Oh,MC=I(()=>{"use strict";vw();Ut=class extends Error{constructor(t){super("SDK application connection unavailable");this.code=t;this.name="ApplicationUiConnectionError"}code},Ih=new WeakSet,J2=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,Oh=class{app;signal;current=null;pending=null;opening=null;retiring=null;closing=null;epoch=0;timerCriteria;constructor(e,t,i=[]){this.app=Object.freeze({...e}),this.signal=t,this.timerCriteria=Object.freeze([...i]),t.addEventListener("abort",this.abort,{once:!0})}abort=()=>{this.close().catch(()=>{})};connection(e){let t=this.current?.public;return t?.id===e&&t.isCurrent()?t:null}owned(){return this.current?.public.isCurrent()?this.current.ui:null}adopt(e,t){let i=t.caller,o=t.isCurrent,s=[e.dataPort,e.controlPort,...e.timerPort?[e.timerPort]:[]];if(s.some(g=>!(g instanceof MessagePort))||new Set(s).size!==s.length||s.some(g=>Ih.has(g))){for(let g of new Set(s))g instanceof MessagePort&&!Ih.has(g)&&(Ih.add(g),g.close());return Promise.reject(new Ut("application_connection_binding"))}for(let g of s)Ih.add(g);let r=g=>{for(let y of s)y.close();return Promise.reject(new Ut(g))};if(this.pending||this.current||this.retiring)return r("application_connection_busy");if(this.closing||this.signal.aborted||i.aborted||!o())return r("application_connection_fenced");let a=Object.freeze({...e.scope}),p=e.generation,l=e.displayName;if(e.schema!=="mdbn-app-collection/1"||Object.keys(a).sort().join()!=="account,collection,installation"||Object.values(a).some(g=>!J2.test(g)||g==="00000000-0000-0000-0000-000000000000")||typeof p!="string"||!p||p.length>256||typeof l!="string"||!l.trim()||new TextEncoder().encode(l).length>4096||!["inspect","approved-new","reconcile-original"].includes(e.setupMode))return r("application_connection_binding");if(e.people!==!0)return r("application_connection_people_unavailable");let c=Object.freeze({...e,scope:a,generation:p,displayName:l}),d=new AbortController,u=this.epoch;this.opening=d;let f=()=>d.abort();i.addEventListener("abort",f,{once:!0});let h=AbortSignal.any([this.signal,d.signal]),m=()=>!h.aborted&&!this.closing&&!this.retiring&&this.epoch===u&&o(),b=null,w=Promise.resolve().then(async()=>{if(!m()||i.aborted)throw new Ut("application_connection_fenced");if(b=await Ch(c,{app:this.app,signal:h,timerCriteria:this.timerCriteria}),!m()||i.aborted)throw new Ut("application_connection_fenced");if(b.client.collection!==a.collection||b.client.link!=="open")throw new Ut("application_connection_binding");if(!b.people)throw new Ut("application_connection_people_unavailable");let g=b,y=b.people,v=Object.freeze({id:a.collection,scope:a,generation:p,displayName:l,records:g.client,files:g.client.files,people:y,...g.timers?{timers:g.timers}:{},isCurrent:()=>m()&&this.current?.ui===g&&g.client.link==="open"});return this.current={public:v,ui:g,lifetime:d},v}).catch(g=>{d.abort(),b?.close();for(let y of s)y.close();throw g}).finally(()=>{i.removeEventListener("abort",f),this.pending===w&&(this.pending=null,this.opening=null)});return this.pending=w,w}retire(){if(this.retiring)return this.retiring;++this.epoch;let e=this.current,t=this.pending;this.opening?.abort(),e?.lifetime.abort();let i=Promise.resolve().then(async()=>{await t?.catch(()=>{}),e?.ui.close(),this.current===e&&(this.current=null)});return this.retiring=i,i.then(()=>{this.retiring===i&&(this.retiring=null)},()=>{}),i}close(){return this.closing?this.closing:(this.closing=Promise.resolve().then(()=>this.retire()),this.signal.removeEventListener("abort",this.abort),++this.epoch,this.opening?.abort(),this.current?.lifetime.abort(),this.closing)}}});function nT(n){if(n.capabilityContractVersion!==2)throw A("upgrade_required","unsupported readiness capability projection","readiness_capability_version");if(!Array.isArray(n.contracts)||n.contracts.length>128||!Array.isArray(n.requiredNativeCapabilities)||n.requiredNativeCapabilities.length>64)throw Ct("unsupported");let e=n.contracts.map(i=>{if(!i||!el(i.id,256)||!el(i.version,128)||!tT.test(i.digest))throw Ct("unsupported");return Object.freeze({id:i.id,version:i.version,digest:i.digest})}),t=n.requiredNativeCapabilities.map(i=>{if(!el(i,128))throw Ct("unsupported");return i});if(new Set(e.map(i=>JSON.stringify([i.id,i.version]))).size!==e.length||new Set(t).size!==t.length||n.typeIssues!==void 0&&n.typeIssues!=="block"&&n.typeIssues!=="degrade")throw Ct("unsupported");return Object.freeze({capabilityContractVersion:2,typeIssues:n.typeIssues??"block",contracts:Object.freeze(e),requiredNativeCapabilities:Object.freeze(t)})}function iT(n){let e=n instanceof Map?n.get("path"):null;return typeof e=="string"&&e?e:null}function Qa(n,e){return Object.freeze({reason:n,...n==="fenced"&&e?{detail:e}:{}})}function _w(n){if(!oe(n))return;let e=n.details instanceof Map?n.details.get("condition"):void 0,t=X2.find(i=>i===e);if(t)return t;if(n.code==="unauthenticated")return"read_unauthenticated";if(n.code==="cancelled")return"read_cancelled"}function Aw(n){try{if(oe(n)){if(n.code==="unauthenticated"||n.code==="cancelled")return"fenced";if(n.code==="too_large")return"budget";if(n.code==="upgrade_required"||n.code==="forbidden")return"unsupported";if(n.reason==="readiness_changed"||n.reason==="cursor_stale"||n.reason==="cursor_expired")return"changed";if(n.reason==="readiness_busy")return"busy";if(n.reason==="readiness_catalog_response")return"catalog_response"}}catch{}return"unavailable"}function Sw(n){let e=n.status;return JSON.stringify([e.mode,e.confirmedThrough,e.headKnown,e.pending,e.holds,e.unresolved,e.connection,e.installing,e.resyncing,e.incidents.map(t=>t.kind),e.confirmedHead])}function tl(n){return JSON.stringify(n,(e,t)=>typeof t=="bigint"?`${t}n`:t instanceof Map?[...t.entries()]:t instanceof Uint8Array?[...t]:t)}function jC(n,e,t){return new kw(n,e,t)}var X2,Z2,Q2,eT,LC,tT,el,Ct,kw,Pw=I(()=>{"use strict";ie();X2=["binding_invalid","binding_aborted","binding_not_current","readiness_closed","read_aborted","session_closed","session_replaced","session_collection_mismatch","read_unauthenticated","read_cancelled"],Z2=4096,Q2=2*1024*1024,eT=64,LC=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,tT=/^sha256:[0-9a-f]{64}$/,el=(n,e=4096)=>typeof n=="string"&&!!n.trim()&&new TextEncoder().encode(n).length<=e,Ct=(n,e)=>A(n==="fenced"?"unauthenticated":n==="budget"?"too_large":"unavailable","collection readiness unavailable",{reason:`readiness_${n}`,...e?{details:new Map([["condition",e]])}:{}});kw=class{constructor(e,t,i){this.client=e;if(this.declared=nT(t),!LC.test(i.collection)||i.collection==="00000000-0000-0000-0000-000000000000"||!LC.test(i.generation))throw Ct("fenced","binding_invalid");this.binding=Object.freeze({collection:i.collection,generation:i.generation,signal:i.signal,isCurrent:i.isCurrent.bind(i)}),this.readSignal=AbortSignal.any([this.binding.signal,this.lifetime.signal]),this.check(),this.binding.signal.addEventListener("abort",this.abort,{once:!0})}client;declared;binding;lifetime=new AbortController;readSignal;listeners=new Set;snapshotValue=Object.freeze({checking:!1,assessment:null,problem:null});watch=null;stops=[];pending=null;epoch=0;dirty=!1;scheduled=!1;retries=0;failures=0;closed=!1;lastStatus=null;assessedSession;assessedEpoch;assessedCatalog=null;probing=null;probeAgain=!1;abort=()=>{this.close()};getSnapshot(){if(this.snapshotValue.assessment)try{this.check(void 0,this.assessedSession,this.assessedEpoch)}catch(e){let t=Aw(e);t==="fenced"&&!this.closed&&!this.binding.signal.aborted&&this.binding.isCurrent()===!0&&(t="changed"),this.retryLater(t)||this.publish({checking:!1,assessment:null,problem:Qa(t,_w(e))})}return this.snapshotValue}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}publish(e){this.snapshotValue=Object.freeze(e);for(let t of this.listeners)try{t()}catch{}}check(e,t,i){e?.throwIfAborted();let o=this.fenceDetail(e);if(o)throw Ct("fenced",o);if(t?.closed)throw Ct("fenced","session_closed");if(t&&t!==this.client.currentSession())throw Ct("fenced","session_replaced");if(t&&t.hello.collection!==this.binding.collection)throw Ct("fenced","session_collection_mismatch");if(i!==void 0&&(i!==this.epoch||this.watch?.state!=="active"))throw Ct("changed")}fenceDetail(e){if(this.binding.signal.aborted)return"binding_aborted";if(this.closed)return"readiness_closed";if(e?.aborted)return"read_aborted";if(this.binding.isCurrent()!==!0)return"binding_not_current"}invalidate=()=>{if(this.closed)return;if(this.pending||!this.snapshotValue.assessment||this.assessedCatalog===null||this.client.link!=="open"){this.recheck();return}if(this.probing){this.probeAgain=!0;return}let e=this.snapshotValue.assessment,t=this.assessedCatalog,i=this.client.describe(this.readSignal).then(o=>{this.closed||this.snapshotValue.assessment!==e||tl(o)!==t&&this.recheck()},()=>{this.closed||this.recheck()});this.probing=i.finally(()=>{this.probing=null,this.probeAgain&&!this.closed&&(this.probeAgain=!1,this.invalidate())})};recheck(){this.closed||(this.epoch++,this.dirty=!0,this.publish({checking:!0,assessment:null,problem:null}),this.schedule())}schedule(){if(this.closed||this.pending||this.scheduled||!this.dirty||this.watch?.state!=="active"||this.client.link!=="open")return;this.scheduled=!0;let e=()=>{this.scheduled=!1,!this.closed&&this.dirty&&!this.pending&&this.watch?.state==="active"&&this.client.link==="open"&&this.refresh(void 0,!0).catch(()=>{})};this.retries?setTimeout(e,Math.min(5e3,100*2**this.retries,this.retrySince===null?5e3:Math.max(0,15e3-(Date.now()-this.retrySince)))):queueMicrotask(e)}retrySince=null;retryLater(e,t=!1){if(this.closed)return!1;if((e==="busy"||e==="changed")&&(this.retrySince??=Date.now(),Date.now()-this.retrySince>=15e3))return this.dirty=!1,this.publish({checking:!1,assessment:null,problem:Qa("busy_timeout")}),!0;if(e==="unavailable"&&t&&this.failures<5)this.failures++;else if(e!=="changed"&&e!=="busy")return!1;return this.dirty=!0,this.retries=Math.min(this.retries+1,6),this.publish({checking:!0,assessment:null,problem:null}),this.schedule(),!0}attach(){this.watch||(this.watch=this.client.watchChanges(void 0,this.invalidate),this.stops.push(this.watch.subscribe(this.invalidate),this.client.onLink(this.invalidate),this.client.onStatus(()=>{let e=Sw(this.client);e!==this.lastStatus&&(this.lastStatus=e,this.invalidate())})))}start(e){return this.refresh(e)}refresh(e,t=!1){try{if(this.check(e),this.pending)throw Ct("busy")}catch(a){return Promise.reject(a)}t||(this.retrySince=null);let i=AbortSignal.any([this.binding.signal,this.lifetime.signal,...e?[e]:[]]),o,s,r=Promise.resolve().then(async()=>{this.check(i),this.attach();let a=await this.client.readyForRead(i);this.check(i,a),await this.watch.ready,this.check(i,a);let p=this.epoch;this.dirty=!1,this.check(i,a,p);let l=await this.inventory(i,a,p),c=await this.client.describe(this.readSignal);this.check(i,a,p);let d=this.evaluate(c,a),u=tl(c);for(let b of d.paths){let w=l.find(y=>y.path===b);if(!w)throw Ct("changed");let g=await this.client.resources.get(b,this.readSignal);if(this.check(i,a,p),g.path!==w.path||g.revision!==w.revision||g.size!==w.size||g.state!=="confirmed")throw Ct("changed")}let f=await this.inventory(i,a,p);if(JSON.stringify(l)!==JSON.stringify(f))throw Ct("changed");this.check(i,a,p);let h=Object.freeze({collection:this.binding.collection,generation:this.binding.generation,resources:Object.freeze(f)}),m=Object.freeze({status:d.status,problem:d.reason?Qa(d.reason):null,witness:h,...d.unavailable.length?{unavailableTypes:Object.freeze(d.unavailable)}:{}});return o=a,s=p,this.retries=0,this.failures=0,this.retrySince=null,this.assessedSession=a,this.assessedEpoch=p,this.assessedCatalog=u,this.publish({checking:!1,assessment:m,problem:m.problem}),this.check(i,a,p),m}).catch(a=>{let p=i.aborted||this.closed?"fenced":Aw(a);throw this.retryLater(p,t)||this.publish({checking:!1,assessment:null,problem:Qa(p,this.fenceDetail(i)??_w(a))}),a});return this.pending=r,this.publish({checking:!0,assessment:null,problem:null}),r.finally(()=>{this.pending===r&&(this.pending=null),this.schedule()}).catch(()=>{}),r.then(a=>{try{if(this.check(i,o,s),this.snapshotValue.assessment!==a)throw Ct("changed");return a}catch(p){let l=i.aborted?"fenced":Aw(p);throw this.snapshotValue.assessment===a&&!this.retryLater(l)&&this.publish({checking:!1,assessment:null,problem:Qa(l,this.fenceDetail(i)??_w(p))}),p}})}async inventory(e,t,i){let o=[],s=new Set,r,a="",p=0;for(let l=0;l<eT;l++){this.check(e,t,i);let c=await this.client.resources.list({text:!1,limit:128,...r?{cursor:r}:{},signal:this.readSignal});this.check(e,t,i);for(let d of c.resources){if(!el(d.path)||d.path<=a||!el(d.revision,128)||!Number.isSafeInteger(d.size)||d.size<0||d.state!=="confirmed")throw Ct("catalog_response");a=d.path;let u=Object.freeze({path:d.path,revision:d.revision,size:d.size,state:d.state});if(p+=new TextEncoder().encode(JSON.stringify(u)).length,o.length>=Z2||p>Q2)throw Ct("budget");o.push(u)}if(c.complete===!0&&c.cursor===void 0)return o;if(c.complete!==!1||!el(c.cursor)||s.has(c.cursor))throw Ct("catalog_response");s.add(c.cursor),r=c.cursor}throw Ct("budget")}evaluate(e,t){let i=e.issues.filter(d=>d.severity==="error"),o=new Set;for(let d of i){let u=iT(d.details);if(!u)return{status:"incompatible",reason:"catalog_invalid",paths:[],unavailable:[]};o.add(u)}let s={status:"incompatible",reason:"catalog_invalid",paths:[],unavailable:[]};if(this.declared.requiredNativeCapabilities.some(d=>!t.hello.grant.capabilities.includes(d)))return{status:"incompatible",reason:"capability_missing",paths:[],unavailable:[]};let r=new Set,a=new Set,p=new Set;for(let d of e.contracts){let u=JSON.stringify([d.id,d.version]);if(a.has(u))return{status:"incompatible",reason:"catalog_response",paths:[],unavailable:[]};a.add(u)}for(let d of e.types){if(p.has(d.name))return{status:"incompatible",reason:"catalog_response",paths:[],unavailable:[]};p.add(d.name)}let l,c=[];for(let d of this.declared.contracts){let u=e.contracts.find(f=>f.id===d.id&&f.version===d.version);if(!u){l??="contract_missing";continue}if(u.digest!==d.digest)return{status:"incompatible",reason:"contract_mismatch",paths:[],unavailable:[]};if(r.add(u.path),o.has(u.path))return s;if(!u.implementedBy.length){l??="implementation_missing";continue}for(let f of u.implementedBy){let h=e.types.find(m=>m.name===f);if(!h||!h.implements.some(m=>m.contract===d.id&&m.version===d.version))return{status:"incompatible",reason:"catalog_response",paths:[],unavailable:[]};if(r.add(h.path),o.has(h.path)){if(this.declared.typeIssues!=="degrade")return s;c.some(m=>m.name===h.name)||c.push(Object.freeze({name:h.name,path:h.path,contract:Object.freeze({id:d.id,version:d.version}),problem:Object.freeze({code:"readiness_type_invalid"})}))}}}return{status:l?"setup_required":"ready",...l?{reason:l}:{},paths:[...r].sort(),unavailable:c}}async close(){if(!this.closed){this.closed=!0,this.dirty=!1,this.lifetime.abort(),this.binding.signal.removeEventListener("abort",this.abort);for(let e of this.stops.splice(0))e();this.watch?.(),this.watch=null,this.publish({checking:!1,assessment:null,problem:Qa("fenced",this.fenceDetail())})}await this.pending?.catch(()=>{})}}});function oT(n){let e=o=>o?Object.freeze({code:`readiness_${o.reason}`,...o.detail?{detail:o.detail}:{}}):null,t=e(n.problem),i=n.assessment?.unavailableTypes;return Object.freeze({checking:n.checking,assessment:n.assessment?Object.freeze({status:n.assessment.status,problem:e(n.assessment.problem),...i?.length?{unavailableTypes:i}:{}}):null,problem:t})}var NC,rT,fp,Ji,Rh,UC=I(()=>{"use strict";nc();ie();Pw();NC=["configuration","files"],rT=["people","notifications"],fp=class extends Error{constructor(t,i){super("SDK application readiness unavailable");this.code=t;this.detail=i;this.name="ApplicationReadinessError"}code;detail},Ji=(n,e=!1,t)=>Object.freeze({checking:e,assessment:null,problem:n?Object.freeze({code:n,...t?{detail:t}:{}}):null});Rh=class{connection;signal;observed;native;sources;listeners=new Set;stops=[];pending=null;closing=null;checking=!1;closed=!1;advisory=Promise.resolve();lastReady=null;constructor(e){this.connection=e.connection,this.signal=e.signal,this.observed=e.isCurrent,this.sources=Object.freeze({configuration:e.configuration,files:e.files,people:e.people,notifications:e.notifications}),this.native=e.nativeRequirements?jC(this.connection.records,e.nativeRequirements,{collection:this.connection.id,generation:this.connection.generation,signal:this.signal,isCurrent:()=>this.current()}):null,this.native&&this.stops.push(this.native.subscribe(this.changed));for(let t of Object.values(this.sources))t&&this.stops.push(t.subscribe(this.changed));this.signal.addEventListener("abort",this.abort,{once:!0})}fenceDetail(){try{return this.signal.aborted?"scope_aborted":this.closed?"scope_closed":this.observed()!==!0?"observer_not_current":this.connection.isCurrent()?this.connection.records.collection!==this.connection.id?"collection_mismatch":null:"connection_not_current"}catch{return"currentness_check_failed"}}current(){return this.fenceDetail()===null}connectionProblem(){if(!this.closed&&!this.signal.aborted&&this.connection.records.collection===this.connection.id&&this.connection.records.link==="closed"){let e=this.connection.records.linkProblem;if(oe(e)){let t=Lo(e);return t&&t.key!=="unknown"?t.key:e.code}}return"readiness_fenced"}changed=()=>{for(let e of[...this.listeners])try{e()}catch{}};abort=()=>{this.close().catch(()=>{})};subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getSnapshot(){let e=this.current(),t=Ji(e?"readiness_unsupported":"readiness_fenced"),i=t;if(e&&this.native){let u=this.native.getSnapshot(),f=u.assessment?.witness,h=f&&f.collection!==this.connection.id?"native_witness_collection_mismatch":f&&f.generation!==this.connection.generation?"native_witness_generation_mismatch":null;i=h?Ji("readiness_fenced",!1,h):oT(u)}let o=u=>{if(!e)return t;let f=this.sources[u];if(!f)return Ji(`${u}_unsupported`);try{let h=f.getSnapshot();return Object.freeze({checking:h.checking,assessment:h.assessment?Object.freeze({...h.assessment,problem:h.assessment.problem?Object.freeze({...h.assessment.problem}):null}):null,problem:h.problem?Object.freeze({...h.problem}):null})}catch{return Ji(`${u}_unavailable`)}},s=Object.freeze({capabilities:i,contracts:i,configuration:o("configuration"),files:o("files"),people:o("people"),notifications:o("notifications")}),r=[s.capabilities,s.contracts,s.configuration,s.files],a=e&&(this.checking||r.some(u=>u.checking)),p=null,l=null;if(!e)l=Object.freeze({code:"readiness_fenced"});else if(!a){let u=["capabilities","contracts",...NC].find(f=>s[f].problem);if(l=u?s[u].problem:null,u&&l?.code==="readiness_fenced"&&!l.detail&&(l=Object.freeze({...l,detail:`${u}_facet`})),r.every(f=>f.assessment!==null)){let f=r.find(w=>w.assessment?.status==="incompatible"),h=r.find(w=>w.assessment?.status==="setup_required"),m=f??h,b=i.assessment?.unavailableTypes;p=Object.freeze({status:f?"incompatible":h?"setup_required":"ready",problem:m?.assessment?.problem??null,...b?.length?{unavailableTypes:b}:{}})}}let c=this.fenceDetail();if(c)return this.lastReady=null,Object.freeze({checking:!1,assessment:null,problem:Object.freeze({code:this.connectionProblem(),detail:c}),facets:Object.freeze({capabilities:Ji("readiness_fenced",!1,c),contracts:Ji("readiness_fenced",!1,c),configuration:Ji("readiness_fenced",!1,c),files:Ji("readiness_fenced",!1,c),people:Ji("readiness_fenced",!1,c),notifications:Ji("readiness_fenced",!1,c)})});let d=!l||/_(changed|busy)$/.test(l.code);if(l===null&&p!==null&&!a)this.lastReady=Object.freeze({checking:a,assessment:p,problem:l,facets:s});else{if(this.lastReady&&d&&(a||p===null)&&(this.lastReady.assessment?.status==="ready"||!this.checking))return Object.freeze({...this.lastReady,facets:s});this.lastReady=null}return Object.freeze({checking:a,assessment:p,problem:l,facets:s})}refresh(e={}){let t=e.signal,i=this.fenceDetail()??(t?.aborted?"caller_aborted":null);if(i)return Promise.reject(new fp("application_readiness_fenced",i));if(this.pending)return Promise.reject(new fp("application_readiness_busy"));this.checking=!0;let o=Promise.resolve().then(async()=>{if(!this.current())return this.getSnapshot();await this.advisory,this.native&&await this.native.start();for(let s of NC){let r=this.sources[s];if(!this.current())break;r&&await r.refresh()}return this.getSnapshot()}).finally(()=>{if(this.pending!==o)return;this.pending=null,this.checking=!1;let s=(async()=>{for(let r of rT){let a=this.sources[r];if(!this.current())break;a&&await a.refresh().catch(()=>{})}})();this.advisory=s,this.changed()}).then(()=>this.getSnapshot());return this.pending=o,this.changed(),o.then(s=>{let r=this.fenceDetail()??(t?.aborted?"caller_aborted":null);if(r)throw new fp("application_readiness_fenced",r);return s})}close(){return this.closing?this.closing:(this.closed=!0,this.checking=!1,this.signal.removeEventListener("abort",this.abort),this.closing=Promise.resolve().then(async()=>{for(let e of this.stops.splice(0))e();for(let e of Object.values(this.sources))await e?.close();await this.native?.close(),await this.pending?.catch(()=>{}),await this.advisory,this.listeners.clear()}),this.changed(),this.closing)}}});function sT(n){let e=new Set,t=[],i=[];for(let o of n.review?.packs??[]){if(o.status!=="conflict"&&o.status!=="downgrade")continue;let s=o.installedVersion?jo(o.installedVersion,o.version):"unknown";s==="installed_newer"&&!o.resources.some(r=>r.action==="conflict")?(e.add(o.id),i.push(Object.freeze({id:o.id,version:o.version,installedVersion:o.installedVersion}))):s==="installed_newer_major"&&t.push(o.id)}return Object.freeze({kept:Object.freeze(i),compatible:e,major:Object.freeze(t)})}function aT(n,e){let t=n,i=t.provisions?.type_packs;return!e.size||!Array.isArray(i)?n:{...t,provisions:{...t.provisions,type_packs:i.filter(o=>!(typeof o?.manifest?.id=="string"&&e.has(o.manifest.id)))}}}function $C(n){return new Proxy({},{get(e,t){let i=Reflect.get(n,t,n);return typeof i!="function"?i:async(...o)=>{let s=o.find(a=>a instanceof AbortSignal),r=Date.now()+lT;for(let a=25;;a=Math.min(a*2,500))try{return await i.apply(n,o)}catch(p){if(!(p instanceof ti&&p.reason==="busy")||!s)throw p;if(Date.now()+a>r)throw ze("busy_timeout");await cT(a,s)}}}})}function BC(n,e){let t=Object.freeze({...n,scope:Object.freeze({...n.scope}),journal:$C(n.journal)});if(e&&(e=$C(e)),Object.values(t.scope).some(j=>!DC.test(j)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/.test(j))||!DC.test(t.generation)||!["inspect","approved-new","reconcile-original"].includes(t.setupMode))throw ze("binding");let i=JSON.stringify([t.scope.account,t.scope.installation,t.scope.collection]),o=new AbortController,s=AbortSignal.any([t.signal,o.signal]),r=new Set,a=vr(),p=null,l=null,c=!1,d,u=null,f=!1,h=!1,m=0,b=!1,w=!1,g=null,y=null,v=()=>{try{return JSON.stringify([t.client.link,Sw(t.client)])}catch{return null}},_=[],k=new WeakMap;function S(j,W){if(j?.throwIfAborted(),c||s.aborted||t.isCurrent()!==!0||JSON.stringify([t.journal.scope.account,t.journal.scope.installation,t.journal.scope.collection])!==i||W&&(W.closed||t.client.currentSession()!==W||W.hello.collection!==t.scope.collection))throw ze("fenced")}function x(j){a=Object.freeze(j);for(let W of r)try{W()}catch{}}function P(){if(c)return;let j=v();if(j!==null&&j===y)return;if(y=j,p||!a.assessment||u===null||t.client.link!=="open"){C();return}if(f){h=!0;return}f=!0;let W=a,$=u;t.client.describe(s).then(J=>{!c&&a===W&&tl(J)!==$&&C()},()=>{c||C()}).finally(()=>{f=!1,h&&!c&&(h=!1,y=null,P())})}function C(){c||(b=!0,p||x(vr(null,!0)),E())}function E(){c||p||w||!b||(w=!0,setTimeout(()=>{if(w=!1,c||p||!b)return;let j=ee(!1,{},void 0,!0);g=p,j.catch(()=>{})},m?Math.min(5e3,250*2**m):50))}function O(){if(a.assessment)try{S(void 0,d)}catch{c||s.aborted||t.isCurrent()!==!0?x(vr("configuration_fenced")):(b=!0,y=null,x(vr(null,!0)),E())}return a}async function L(j,W,$){let J=await t.client.awaitReceipt(j.mutationId,12e4,s);if(S(W,$),J.mutation!==j.mutationId||J.state!=="confirmed"||J.status!=="applied"||(J.conflicts?.length??0)!==0||J.published==="publishing"||J.published==="not_published")throw ze("recovery_required");return J}async function z(j,W,$){let J,be=0,ye=0,we=new Set,et=new Set,qe=new TextEncoder;for(let Dt=0;Dt<64;Dt++){S(W,$);let tt=await t.client.resources.list({text:!1,limit:128,...J===void 0?{}:{cursor:J},signal:s});if(S(W,$),tt.resources.length>128)throw ze("recovery_required");for(let Ve of tt.resources){let On=qe.encode(Ve.path).length;if(be++,ye+=On+128,!Ve.path||On>4096||et.has(Ve.path)||Ve.state!=="confirmed"||!xw.test(Ve.revision)||!Number.isSafeInteger(Ve.size)||Ve.size<0||be>4096||ye>2*1024*1024||j.has(Ve.path))throw ze("recovery_required");et.add(Ve.path)}if(tt.complete===!0&&tt.cursor===void 0)return;if(tt.complete!==!1||!tt.resources.length||typeof tt.cursor!="string"||!tt.cursor||qe.encode(tt.cursor).length>4096||we.has(tt.cursor))throw ze("recovery_required");we.add(tt.cursor),J=tt.cursor}throw ze("recovery_required")}async function Q(j,W,$){let J=j.version===2?j.plan.readback:j.plan.resourceReadback,be=new Set(J.filter(ye=>ye.doc===null).map(ye=>ye.path));be.size&&await z(be,W,$);for(let ye of J){if(ye.doc===null)continue;let we=await t.client.resources.get(ye.path,s);if(S(W,$),we.path!==ye.path||we.text!==ye.doc||we.state!=="confirmed")throw ze("recovery_required")}if(j.version!==2)for(let ye of j.plan.sources){let we=await t.client.get(ye.id,void 0,s);if(S(W,$),we.id!==ye.id||we.path!==ye.path||we.state.state!=="confirmed"||we.state.hold||we.state.unresolved)throw ze("recovery_required")}}async function V(j,W,$){return await L(j,W,$),j.phase==="attempted"&&(j=j.version===2?await t.journal.recordConfirmed(j.mutationId,s):await t.journal.recordResourceConfirmed(j.mutationId,s),S(W,$)),j.phase==="verified"||(await Q(j,W,$),j.phase==="confirmed"&&(j=j.version===2?await t.journal.recordVerified(j.mutationId,s):await t.journal.recordResourceVerified(j.mutationId,s),S(W,$))),j}async function te(j,W){let $=await t.journal.load(s);if(S(j,W),!$)return{journaled:!1,previous:null};if($=Et($,t.scope),$.version===1||$.phase==="prepared")throw ze("recovery_required");if($.phase==="attempted"&&($.version===3||$.version===4)&&t.journal.recordResourceRejected){let J=await t.client.awaitReceipt($.mutationId,12e4,s);S(j,W),J.mutation===$.mutationId&&J.state==="rejected"&&($=Et(await t.journal.recordResourceRejected($.mutationId,s),t.scope),S(j,W))}if($.version===1)throw ze("recovery_required");return $.phase==="rejected"?{journaled:!0,previous:$.version===4?$.previous:null}:{journaled:!0,previous:await V($,j,W)}}async function G(j,W){let $=t.compiledManifest.manifest,J=await Cw(e.assess($,s,j),j),be=J;J.status==="conflict"&&!J.review&&(be=await e.assess($,s,ei({})));let ye=sT(be);if(!ye.compatible.size)return{assessed:J,manifest:$,newer:ye};let we=aT($,ye.compatible),et=W?j??ei({}):j;return J=await Cw(e.assess(we,s,et),et),{assessed:J,manifest:we,newer:ye}}async function K(j,W,$={}){S(W);let J=await t.client.readyForRead(s);S(W,J),_.length||(y=v(),_.push(t.client.onStatus(P),t.client.onLink(P))),b=!1;let{journaled:be,previous:ye}=await te(W,J);if(!e)throw ze("unsupported");let we=null;try{we=tl(await t.client.describe(s))}catch{}S(W,J);let et=await G($.decisions,!1),qe=et.assessed,Dt=et.manifest;if(S(W,J),!xw.test(qe.assessmentDigest)||!["current","provision","conflict"].includes(qe.status))throw ze("response");if($.expected!==void 0&&qe.assessmentDigest!==$.expected)throw Iw();let tt=!be&&t.setupMode==="approved-new";if(qe.status==="provision"&&(j||tt)){if(t.setupMode==="reconcile-original")throw ze("recovery_required");if(!(t.compiledManifest.operations.includes("apply_collection_setup")||t.compiledManifest.operations.includes("apply_type_pack"))||!J.hello.grant.capabilities.includes("definitions.manage"))throw ze("not_authorized");let rs=$.records??[];if(rs.length&&!J.hello.grant.capabilities.includes("records.create"))throw ze("not_authorized");let os=xt(await Cw(e.apply(Dt,qe.assessmentDigest,s,$.decisions),$.decisions));if(S(W,J),os.assessmentDigest!==qe.assessmentDigest)throw ze("response");if(os.sources.length)throw ze("unsupported_source_provision");let he=rs.length?xt({...os,sources:rs.map(nt=>({id:crypto.randomUUID(),path:nt.path,document:nt.document}))}):os,me;if(ye){if(!t.journal.prepareResourceRound)throw ze("recovery_required");me=await t.journal.prepareResourceRound(he,ye.mutationId,s)}else me=await t.journal.prepareResources(he,s);if(S(W,J),me=Et(me,t.scope),me.version!==3&&me.version!==4||me.phase!=="prepared"||JSON.stringify(me.plan)!==JSON.stringify(he))throw ze("recovery_required");let Fe=Et(await t.journal.recordResourceAttempt(me.mutationId,s),t.scope);if(S(W,J),Fe.version!==3&&Fe.version!==4||Fe.mutationId!==me.mutationId||Fe.phase!=="attempted"||JSON.stringify(Fe.plan)!==JSON.stringify(he))throw ze("recovery_required");let Rn=[...he.resourceOps,...he.sources.map(nt=>({kind:"create",id:nt.id,path:nt.path,document:nt.document}))],En=await t.client.submit(Rn,{mutationId:me.mutationId,wait:"confirmed",signal:s});if(S(W,J),En.length!==1||En[0].mutationId!==me.mutationId)throw ze("recovery_required");let xi;try{xi=await En[0].confirmed}catch(nt){throw S(W,J),En[0].receipt.state!=="rejected"||!t.journal.recordResourceRejected?nt:(await t.journal.recordResourceRejected(me.mutationId,s),S(W,J),Iw(me.mutationId,nt))}if(S(W,J),xi.state!=="confirmed"||xi.status!=="applied"||(xi.conflicts?.length??0)!==0)throw ze("recovery_required");await V(Fe,W,J),b=!1,y=v();try{we=tl(await t.client.describe(s))}catch{we=null}if(qe=await e.assess(Dt,s),S(W,J),qe.status!=="current"||!xw.test(qe.assessmentDigest))throw ze("recovery_required")}let Ve=qe.status==="conflict"?et.newer.major.length?"installed_newer":"configuration_conflict":null,On=Ve?Object.freeze({code:Ve}):null,Ar=Object.freeze({status:qe.status==="current"?"ready":qe.status==="conflict"?"incompatible":"setup_required",problem:On});d=J,u=we;let Pi=Object.freeze({checking:!1,assessment:Ar,problem:On});return m=0,x(b?vr(null,!0):Pi),S(W,J),Pi}function X(j={}){try{S(j.signal)}catch(J){return Promise.reject(J)}let W=p,$=(W?W.then(()=>{},()=>{}):Promise.resolve()).then(()=>Y(j));return p=$,$.finally(()=>{p===$&&(p=null)}).catch(()=>{}),$}async function Y(j){let W=sh(j.records),$=ei(j.adopt===void 0?{}:{adopt:j.adopt}),J=AbortSignal.any([s,...j.signal?[j.signal]:[]]),be=await t.client.readyForRead(s);if(S(J,be),await te(J,be),!e)throw ze("unsupported");let{assessed:ye,newer:we}=await G($,!0);if(S(J,be),!ye.review)throw ze("response");let et=[];if(ye.status!=="current")for(let tt of W){let Ve=await t.client.find({path:tt.path},void 0,s);S(J,be),et.push({path:tt.path,free:Ve===null})}let qe=be.hello.grant.capabilities,Dt=tp(ye,{records:et,canManage:qe.includes("definitions.manage")&&(t.compiledManifest.operations.includes("apply_collection_setup")||t.compiledManifest.operations.includes("apply_type_pack")),canCreateRecords:qe.includes("records.create"),newer:we});return k.set(Dt,Object.freeze({decisions:$,records:W.filter(tt=>et.some(Ve=>Ve.path===tt.path&&Ve.free))})),Dt}function ee(j,W={},$,J=!1){try{S(W.signal)}catch(we){return Promise.reject(we)}if(p&&p===g){let we=p;return we.then(()=>{},()=>{}).then(()=>p&&p!==we?Promise.reject(ze("busy")):ee(j,W,$))}if(p)return Promise.reject(ze("busy"));let be=AbortSignal.any([s,...W.signal?[W.signal]:[]]),ye=Promise.resolve().then(()=>K(j,be,$)).catch(we=>{let et=s.aborted||be.aborted,qe=oe(we)&&we.reason==="configuration_busy_timeout";qe&&(b=!1);let Dt=!et&&!qe&&(b||zC(we));throw Dt&&zC(we)&&(b=!0,m=Math.min(m+1,4)),!et&&!qe&&!b&&J&&m<5&&!c&&t.isCurrent()===!0&&(m++,b=!0,Dt=!0),x(Dt?vr(null,!0):vr(et?"configuration_fenced":qe?"configuration_busy_timeout":"configuration_unavailable")),we});return p=ye,x(vr(null,!0)),ye.finally(()=>{p===ye&&(p=null),g===ye&&(g=null),E()}).catch(()=>{}),ye.then(we=>(S(be,d),we))}let $e=()=>{if(!l){c=!0,t.signal.removeEventListener("abort",mt),o.abort();for(let W of _.splice(0))W();x(vr("configuration_fenced"));let j=p;l=Promise.resolve().then(async()=>{await j})}return l},mt=()=>{$e().catch(()=>{})};return t.signal.addEventListener("abort",mt,{once:!0}),Object.freeze({getSnapshot:O,subscribe(j){return r.add(j),()=>{r.delete(j)}},assess:j=>ee(!1,j),configure:j=>ee(!0,j),plan:X,async apply(j,W={}){let $=k.get(j);if(!$)throw new TypeError("setup.apply needs a plan returned by setup.plan");if(j.refusal)throw A(j.refusal.code==="setup_conflict"?"conflict":j.refusal.code==="installed_newer"?"upgrade_required":"forbidden",j.refusal.message,j.refusal.code);if(j.status==="current"){await ee(!1,W,{decisions:$.decisions,expected:j.digest});return}await ee(!0,W,{decisions:$.decisions,expected:j.digest,records:$.records})},close:$e})}var DC,xw,ze,Iw,Cw,lT,cT,zC,vr,FC=I(()=>{"use strict";ie();Go();Pw();no();yu();ah();DC=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,xw=/^sha256:[0-9a-f]{64}$/,ze=n=>A("unavailable","application configuration unavailable",`configuration_${n}`),Iw=(n,e)=>new se(A("conflict","This collection changed since the setup was reviewed. Review it again.","setup_changed").toProblem(),{...n?{mutationId:n}:{},...e===void 0?{}:{cause:e}}),Cw=async(n,e)=>{try{return await n}catch(t){throw e?.adopt&&Object.keys(e.adopt).length&&oe(t,"unavailable")&&t.reason==="resource_setup_unavailable"?Iw(void 0,t):t}};lT=15e3,cT=(n,e)=>new Promise((t,i)=>{if(e.aborted){i(e.reason);return}let o=()=>{clearTimeout(s),i(e.reason)},s=setTimeout(()=>{e.removeEventListener("abort",o),t()},n);e.addEventListener("abort",o,{once:!0})});zC=n=>oe(n)&&n.reason==="configuration_busy",vr=(n=null,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n?Object.freeze({code:n}):null})});function VC(n){return{issuer:n.issuer,subject:n.subject,name:n.name,...n.accountId===void 0?{}:{account_id:n.accountId}}}function KC(n){let e=n.scope,t=e.account,i=e.installation,o=e.collection,s=n.generation,r=n.signal,a=n.people,p=n.isCurrent.bind(n),l=typeof a?.current=="function"?a.current.bind(a):void 0,c=typeof a?.members=="function"?a.members.bind(a):void 0,d=new Set,u=es(null),f=!1,h=!1,m=null;function b(){try{return f||r.aborted||p()!==!0?!1:!f&&!r.aborted&&n.scope===e&&n.generation===s&&n.signal===r&&n.people===a&&!!s&&s.length<=256&&[t,i,o].every(k=>typeof k=="string"&&!!k&&k.length<=128)&&e.account===t&&e.installation===i&&e.collection===o}catch{return!1}}function w(k){u=b()?k:_r;for(let S of[...d])try{S()}catch{}b()||(u=_r)}function g(){return b()||(u=_r),u}function y(){if(!f){f=!0,r.removeEventListener("abort",y),u=_r;for(let k of[...d])try{k()}catch{}d.clear()}}r.addEventListener("abort",y,{once:!0}),r.aborted&&y();function v(k,S){return!b()||S?.aborted?Promise.reject(hp()):new Promise((x,P)=>{let C=!1,E=(z,Q)=>{C||(C=!0,S?.removeEventListener("abort",O),r.removeEventListener("abort",O),d.delete(L),Q!==void 0?P(Q):x(z))},O=()=>E(void 0,hp()),L=()=>{b()||O()};d.add(L),S?.addEventListener("abort",O,{once:!0}),r.addEventListener("abort",O,{once:!0}),k.then(()=>{!b()||S?.aborted?O():E(g())},()=>E(void 0,hp())),(!b()||S?.aborted)&&O()})}function _(k={}){let S=k.signal;if(!b()||S?.aborted)return Promise.reject(hp());if(m)return Promise.reject(A("unavailable","People readiness READ is occupied","people_readiness_busy"));let x=Promise.resolve().then(async()=>{if(!b())return _r;if(!l||!c)return es("people_unsupported");try{let C=await l({signal:r});if(!b()||(Fa("identity",{...VC(C),...C.personSettingsUrl===void 0?{}:{person_settings_url:C.personSettingsUrl}}),!b()))return _r;let E=await c({signal:r});return b()?!Array.isArray(E)||E.length>1e3?es("people_response"):(Fa("members",{members:Array.from(E,O=>({...VC(O),role:O.role}))}),b()?pT:_r):_r}catch{return es(b()?"people_unavailable":"people_fenced")}});m=x,w(es(null,!0));let P=x.then(C=>(w(C),g()),()=>(w(es("people_unavailable")),g())).finally(()=>{m===x&&(m=null)});return v(P,S)}return Object.freeze({getSnapshot:g,subscribe(k){return f?()=>{}:(d.add(k),()=>{d.delete(k)})},start(k={}){return h?v(m??Promise.resolve(g()),k.signal):!b()||k.signal?.aborted?Promise.reject(hp()):(h=!0,_(k))},refresh:_,close:y})}var es,_r,pT,hp,WC=I(()=>{"use strict";rp();ie();es=(n,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n===null?null:Object.freeze({code:n})}),_r=es("people_fenced"),pT=Object.freeze({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null}),hp=()=>A("cancelled","People readiness ended","people_readiness_fenced")});function Eh(n){if(!n||!Array.isArray(n.criteria))return Object.freeze([]);let e=n.criteria.filter(t=>t?.event?.id===kf.id&&t.event.version===kf.version&&t.event.digest===kf.digest).map(t=>t.id);return Object.freeze([...new Set(e)])}var Ow=I(()=>{"use strict";jc()});function HC(n){let e=n.scope,t=e.account,i=e.installation,o=e.collection,s=n.generation,r=n.signal,a=n.isCurrent.bind(n),p=n.notifications,l=p?.declaration,c=p?.timerNamespace,d=n.timers,u=typeof d?.list=="function"?d.list.bind(d):void 0,f=new Set,h=Ai(null),m=!1,b=!1,w=null;function g(){try{return m||r.aborted||a()!==!0?!1:!m&&!r.aborted&&n.signal===r&&n.scope===e&&n.generation===s&&!!s&&s.length<=256&&[t,i,o].every(x=>typeof x=="string"&&!!x&&x.length<=128)&&e.account===t&&e.installation===i&&e.collection===o&&n.notifications===p&&p?.declaration===l&&p?.timerNamespace===c&&n.timers===d}catch{return!1}}function y(x){h=g()?x:qh;for(let P of[...f])try{P()}catch{}g()||(h=qh)}function v(){return g()||(h=qh),h}function _(){if(!m){m=!0,r.removeEventListener("abort",_),h=qh;for(let x of[...f])try{x()}catch{}f.clear()}}r.addEventListener("abort",_,{once:!0}),r.aborted&&_();function k(x,P){return!g()||P?.aborted?Promise.reject(mp()):new Promise((C,E)=>{let O=!1,L=(V,te)=>{O||(O=!0,P?.removeEventListener("abort",z),r.removeEventListener("abort",z),f.delete(Q),te!==void 0?E(te):C(V))},z=()=>L(void 0,mp()),Q=()=>{g()||z()};f.add(Q),P?.addEventListener("abort",z,{once:!0}),r.addEventListener("abort",z,{once:!0}),x.then(()=>{!g()||P?.aborted?z():L(v())},()=>L(void 0,mp())),(!g()||P?.aborted)&&z()})}function S(x={}){let P=x.signal;if(!g()||P?.aborted)return Promise.reject(mp());if(w)return Promise.reject(A("unavailable","Notification readiness READ is occupied","notification_readiness_busy"));let C=Promise.resolve().then(async()=>{if(!g())return Ai("notifications_fenced");if(l===null&&p&&Object.hasOwn(p,"declaration"))return Object.freeze({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null});if(!u&&Eh(l).length)return Ai("notifications_consent_required");if(!l||typeof l!="object"||!u||typeof c!="string"||!/^[A-Za-z0-9._-]{1,64}$/.test(c))return Ai("notifications_unsupported");try{let O=await u(c,{signal:r});return g()?!O||O.namespace!==c||!Array.isArray(O.timers)||O.timers.length>1e4?Ai("notifications_response"):Ai("notifications_unsupported"):Ai("notifications_fenced")}catch{return Ai(g()?"notifications_unavailable":"notifications_fenced")}});w=C,y(Ai(null,!0));let E=C.then(O=>(y(O),v()),()=>(y(Ai("notifications_unavailable")),v())).finally(()=>{w===C&&(w=null)});return k(E,P)}return Object.freeze({getSnapshot:v,subscribe(x){return m?()=>{}:(f.add(x),()=>{f.delete(x)})},start(x={}){return b?k(w??Promise.resolve(v()),x.signal):!g()||x.signal?.aborted?Promise.reject(mp()):(b=!0,S(x))},refresh:S,close:_})}var dT,Ai,qh,mp,GC=I(()=>{"use strict";ie();Ow();dT=n=>Object.freeze({code:n}),Ai=(n,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n===null?null:dT(n)}),qh=Ai("notifications_fenced"),mp=()=>A("cancelled","Notification readiness ended","notification_readiness_fenced")});function XC(n){let e=new Set,t=!1,i=()=>{if(t||!n.isCurrent())return YC;let s=n.declaration;if(!s)return Rw;let r;try{r=n.grant()}catch{return uT}return r?s.required.some(a=>!r.actions.includes(a))?JC("files_access_missing"):n.scope==="collection"&&r.scope.kind!=="collection"?JC("files_scope_missing"):Rw:Rw},o=i();return Object.freeze({getSnapshot:()=>t||!n.isCurrent()?YC:o,subscribe(s){return t?()=>{}:(e.add(s),()=>{e.delete(s)})},async refresh(){let s=i();if(s!==o){o=s;for(let r of[...e])try{r()}catch{}}return o},close(){t=!0,e.clear()}})}var Th,Rw,YC,uT,JC,ZC=I(()=>{"use strict";Th=n=>Object.freeze(n),Rw=Th({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null}),YC=Th({checking:!1,assessment:null,problem:Object.freeze({code:"files_fenced"})}),uT=Th({checking:!1,assessment:null,problem:Object.freeze({code:"files_unavailable"})}),JC=n=>Th({checking:!1,assessment:Object.freeze({status:"incompatible",problem:Object.freeze({code:n})}),problem:null})});var Mh,QC=I(()=>{"use strict";MC();UC();FC();WC();GC();Ow();ql();th();ZC();Mh=class{constructor(e,t,i,o="block",s=()=>[]){this.typeIssues=o;this.consented=s;this.compiled=e,this.signal=i,this.ui=new Oh(t,i,Eh(this.compiled.manifest.notifications)),i.addEventListener("abort",this.abort,{once:!0})}typeIssues;consented;ui;signal;compiled;listeners=new Set;selected=null;epoch=0;opening=null;retiring=null;closing=null;changed=()=>{for(let e of[...this.listeners])try{e()}catch{}};abort=()=>{this.close().catch(()=>{})};subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}connection(e){return this.ui.connection(e)}getReadiness(){return this.selected?.readiness.getSnapshot()??null}selectedId(){return this.selected?.connection.id??null}adopt(e,t,i){let o=this.epoch,s=()=>!this.signal.aborted&&!this.closing&&!this.retiring&&this.epoch===o&&i(),r=!!this.opening||!!this.selected||!!this.retiring||!!this.closing,a=this.ui.adopt(e,{caller:t,isCurrent:s});if(r)return a;let p=null,l=[],c=a.then(d=>{if(!s()||t.aborted)throw new Ut("application_connection_fenced");let u=this.ui.owned();if(!u)throw new Ut("application_connection_binding");let f=Qf(this.compiled);f&&I_(d.files,yx(f,()=>this.consented(d.id)));let h=new AbortController,m=AbortSignal.any([this.signal,h.signal]);p=h;let b=()=>s()&&d.isCurrent(),w={scope:d.scope,generation:d.generation,signal:m,isCurrent:b},g=BC({client:d.records,compiledManifest:this.compiled,journal:u.journal,...w,setupMode:u.setupMode},u.resourceSetup);l.push(()=>g.close());let y={getSnapshot:g.getSnapshot,subscribe:g.subscribe,refresh:g.assess,close:g.close},v=KC({people:d.people,...w});l.push(()=>v.close());let _=this.compiled.manifest.notifications,k=HC({notifications:{declaration:_?.criteria?.length?_:null},timers:d.timers,...w});l.push(()=>k.close());let S=this.compiled.manifest.requirements.files?.scope?.kind,x=XC({declaration:f,scope:typeof S=="string"?S:null,grant:()=>d.files.grant,isCurrent:b});l.push(()=>x.close());let P=this.compiled.nativeCapabilities?{...this.compiled.nativeCapabilities,contracts:this.compiled.manifest.requirements.contracts,typeIssues:this.typeIssues}:null,C=new Rh({connection:d,nativeRequirements:P,signal:m,isCurrent:b,configuration:y,files:x,people:v,notifications:k}),E=C.subscribe(this.changed);return this.selected={connection:d,lifetime:h,readiness:C,configuration:g,unsubscribe:E},p=null,l.length=0,this.changed(),d}).catch(async d=>{p?.abort();let f=(await Promise.allSettled([this.ui.retire(),...l.map(h=>Promise.resolve().then(h))])).find(h=>h.status==="rejected");throw f?.status==="rejected"?f.reason:d}).finally(()=>{this.opening===c&&(this.opening=null)});return this.opening=c,c}assess(e={}){return!this.selected||!this.selected.connection.isCurrent()||this.retiring||this.closing?Promise.reject(new Ut("application_connection_fenced")):this.selected.readiness.refresh(e)}async configure(e={}){let t=this.selected,i=this.epoch;if(!t||!t.connection.isCurrent()||this.retiring||this.closing)throw new Ut("application_connection_fenced");if(await t.configuration.configure(e),e.signal?.aborted||this.epoch!==i||this.selected!==t||!t.connection.isCurrent())throw new Ut("application_connection_fenced");return t.readiness.refresh(e)}planSetup(e={}){let t=this.selected;return!t||!t.connection.isCurrent()||this.retiring||this.closing?Promise.reject(new Ut("application_connection_fenced")):t.configuration.plan(e)}async applySetup(e,t={}){let i=this.selected,o=this.epoch;if(!i||!i.connection.isCurrent()||this.retiring||this.closing)throw new Ut("application_connection_fenced");if(await i.configuration.apply(e,t),t.signal?.aborted||this.epoch!==o||this.selected!==i||!i.connection.isCurrent())throw new Ut("application_connection_fenced");return i.readiness.refresh(t)}retire(){if(this.retiring)return this.retiring;++this.epoch;let e=this.selected,t=this.opening;e?.lifetime.abort(),e?.unsubscribe();let i=this.ui.retire(),o=Promise.resolve().then(async()=>{let r=(await Promise.allSettled([i,t?.catch(()=>{}),e?.readiness.close()])).find(a=>a.status==="rejected");if(r?.status==="rejected")throw r.reason;this.selected===e&&(this.selected=null)});return this.retiring=o,this.changed(),o.then(()=>{this.retiring===o&&(this.retiring=null),this.changed()},()=>{}),o}close(){return this.closing?this.closing:(this.signal.removeEventListener("abort",this.abort),this.closing=Promise.resolve().then(async()=>{await this.retire(),await this.ui.close(),this.listeners.clear()}),this.closing)}}});function eI(n){return typeof n=="string"&&fT.includes(n)}var fT,tI=I(()=>{"use strict";fT=["joining","opening_store","connecting_log","syncing","loading_snapshot","replaying","waiting_for_key","verifying_read","checking_setup"]});function Ew(n,e){return!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!==e.split(",").sort().join()?nl():n}function qw(n){(typeof n!="string"||!hT.test(n)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/.test(n))&&nl()}function nI(n){let e=Ew(n,"rpc,action,value");if((!Number.isSafeInteger(e.rpc)||e.rpc<1||e.rpc>4294967295)&&nl(),e.action==="cancel")e.value!==null&&nl();else if(e.action==="prepare"){let t=Ew(e.value,`requestId,accountId,appId,challenge${Object.hasOwn(e.value,"authorizationId")?",authorizationId":""}`);for(let i of["requestId","accountId","appId"])qw(t[i]);t.authorizationId!==void 0&&qw(t.authorizationId),(typeof t.challenge!="string"||!/^[0-9a-f]{64}$/.test(t.challenge))&&nl()}else if(e.action==="finish"){let t=Ew(e.value,"requestId,authorizationRequestId,collectionId");for(let i of Object.keys(t))qw(t[i])}else nl();return Object.freeze({...e,value:e.value===null?null:Object.freeze({...e.value})})}var hT,nl,iI=I(()=>{"use strict";Yf();hT=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,nl=()=>{throw new Se("application_worker_binding")}});function Tw(n){if(!n||typeof n!="object"||Array.isArray(n))throw new Se("application_worker_binding");let e=n;if(!["not_started","starting","signed_out","authorizing","unselected","opening","setup_required","ready","blocked","closed"].includes(e.status)||!(e.openingProgress==null||typeof e.openingProgress=="string")||!Array.isArray(e.collections)||e.collections.length>1024||!(e.selectedCollectionId===null||typeof e.selectedCollectionId=="string")||!(e.problem===null||typeof e.problem=="string"&&/^[a-z0-9_-]{1,128}$/.test(e.problem)))throw new Se("application_worker_binding");return Object.freeze({...e,openingProgress:eI(e.openingProgress)?e.openingProgress:null})}var Mw,Lh,rI=I(()=>{"use strict";tI();iI();Yf();Mw=class extends Error{constructor(t){super("SDK application operation unavailable");this.code=t;this.name="ApplicationWorkerReplyError"}code};Lh=class{port;binding;owner;nextId=0;active=null;portal=null;fault=null;stopping=null;stopReply=null;watch=null;abandoned=!1;constructor(e,t,i){if(!cx(t))throw new Se("application_worker_binding");this.port=e,this.binding=t,this.owner=Object.freeze({...i}),e.addEventListener("message",this.message),e.addEventListener("messageerror",this.messageError),e.start()}id(){if(this.nextId===Gf)throw new Se("application_worker_stop_failed");return++this.nextId}send(e,t,i){let o=Fb([Qn,this.binding,e,t,i],this.binding);try{this.port.postMessage(o)}catch{throw this.quarantine("application_worker_unavailable"),this.fault}}request(e,t,i,o){if(this.fault||this.stopping||i.aborted)return Promise.reject(this.fault??new Se("application_worker_fenced"));if(this.active)return Promise.reject(new Se("application_worker_busy"));let s;try{s=this.id(),Fb([Qn,this.binding,s,e,t],this.binding)}catch(p){return Promise.reject(p)}if(o){if(!["authorize","renewExpiredPairing","requestFileAccess"].includes(e))return Promise.reject(new Se("application_worker_binding"));this.portal?.life.abort();try{this.portal?.value.close()}catch{return this.quarantine("application_worker_stop_failed"),Promise.reject(this.fault)}this.portal={id:s,value:o,caller:i,life:new AbortController,lastRpc:0,busy:!1},this.watchPortal()}let r,a=new Promise(p=>{r=p});return new Promise((p,l)=>{let c={id:s,caller:i,done:a,finish:r,resolve:p,reject:l,fenced:!1,reply:!1,handoff:null,cancel:()=>{c.fenced=!0,l(new Se("application_worker_fenced"))}};this.active=c,i.addEventListener("abort",c.cancel,{once:!0});try{this.send(s,e,t)}catch(d){l(d)}i.aborted&&c.cancel()})}drain(){return this.fault?Promise.reject(this.fault):this.active?.done??Promise.resolve()}setForeground(e){!this.stopping&&!this.fault&&this.send(0,"foreground",e)}watchPortal(){this.watch!==null&&clearInterval(this.watch),this.watch=null;let e=this.portal;!e||!("closed"in e.value)||(this.watch=setInterval(()=>{if(this.portal!==e||this.stopping||this.fault){clearInterval(this.watch),this.watch=null;return}let t=!1;try{t=e.value.closed===!0}catch{}if(t){clearInterval(this.watch),this.watch=null,e.lastRpc===0&&(this.portal=null);try{this.send(0,"approvalClosed",!0)}catch{}}},500))}messageError=()=>this.quarantine("application_worker_unavailable");quarantine(e){if(!this.fault){this.fault=new Se(e),this.active&&(this.active.fenced=!0,this.active.reject(this.fault)),this.stopReply?.reject(this.fault);try{this.owner.failed?.(this.fault)}catch{}}}message=e=>{try{let t=e.data;if(!Array.isArray(t)||t.length!==5||t[0]!==Qn||t[1]!==this.binding||!Number.isInteger(t[3])||t[3]<0||t[3]>Gf)throw new Se("application_worker_binding");if(this.fault)return;let[,,i,o,s]=t;if(i==="nativeSnapshot"){if(o!==0)throw new Se("application_worker_binding");let l=Tw(s);this.stopping||this.owner.snapshot(l);return}if(i==="fatal"){if(o!==0)throw new Se("application_worker_binding");this.quarantine("application_worker_stop_failed");return}if(i==="nativeAuthorization"){let l=nI(s),c=this.portal;if(!c||c.id!==o||this.stopping||c.caller.aborted||l.rpc<=c.lastRpc)throw new Se("application_worker_fenced");if(c.lastRpc=l.rpc,l.action==="cancel")c.life.abort();else if(c.busy)throw new Se("application_worker_binding");l.action!=="cancel"&&(c.busy=!0);let d=AbortSignal.any([c.caller,c.life.signal]);Promise.resolve().then(()=>{if(!this.owner.nativeAuthorization)throw new Se("application_worker_unavailable");return this.owner.nativeAuthorization(l,c.value,d)}).then(u=>{if(d.aborted||this.portal!==c||this.stopping)throw new Se("application_worker_fenced");this.port.postMessage([Qn,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!0,value:u}])},()=>{this.port.postMessage([Qn,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!1}])}).catch(()=>{try{this.port.postMessage([Qn,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!1}])}catch{}}).finally(()=>{c.busy=!1});return}if(i==="portal"){if(!s||!["navigate","close"].includes(s.action))throw new Se("application_worker_binding");let l=this.portal;if(!l||l.id!==o)return;if(s.action==="close")l.life.abort(),l.value.close(),this.portal=null;else{if(this.stopping||typeof s.uri!="string"||s.uri.length>8192)throw new Se("application_worker_binding");l.value.navigate(s.uri)}return}if(i==="handoff"&&o===0){if(!s||s.schema!=="mdbn-app-collection/1")throw new Se("application_worker_binding");let l=[s.dataPort,s.controlPort,...s.timerPort?[s.timerPort]:[]];if(l.some(c=>!(c instanceof MessagePort)))throw new Se("application_worker_binding");if(this.stopping||!this.owner.attached){for(let c of l)c.close();return}this.owner.attached(s);return}if(i==="handoff"){let l=this.active;if(!l||l.id!==o||l.reply||l.handoff)throw new Se("application_worker_binding");if(this.stopping){if(!s||s.schema!=="mdbn-app-collection/1")throw new Se("application_worker_binding");for(let c of[s.dataPort,s.controlPort,...s.timerPort?[s.timerPort]:[]]){if(!(c instanceof MessagePort))throw new Se("application_worker_binding");c.close()}l.handoff=Promise.resolve();return}l.handoff=Promise.resolve().then(()=>this.owner.handoff(s,l.caller)),l.handoff.catch(()=>{});return}if(i!=="reply"||!s||typeof s.ok!="boolean"||!s.ok&&(!s.problem||typeof s.problem.code!="string"||s.problem.code.length>128))throw new Se("application_worker_binding");let r=this.stopReply;if(r&&r.id===o){if(s.ok){let l=Tw(s.snapshot);if(l.status!=="closed"||l.selectedCollectionId!==null)throw new Se("application_worker_stop_failed");r.resolve()}else r.reject(new Se("application_worker_stop_failed"));return}let a=this.active;if(!a||a.id!==o||a.reply)throw new Se("application_worker_binding");a.reply=!0;let p=s.ok?Tw(s.snapshot):null;this.settle(a,p,s.ok?null:Object.freeze({code:s.problem.code}))}catch{this.quarantine("application_worker_binding")}};async settle(e,t,i){try{if(await e.handoff,e.fenced||e.caller.aborted||this.stopping||this.fault)throw this.fault??new Se("application_worker_fenced");if(i)throw new Mw(i.code);t&&e.resolve(t)}catch(o){e.reject(o)}finally{e.caller.removeEventListener("abort",e.cancel),this.active===e&&(this.active=null),e.finish()}}abandon(){if(this.abandoned)return;this.abandoned=!0,this.fault||(this.fault=new Se("application_worker_fenced")),this.watch!==null&&(clearInterval(this.watch),this.watch=null);let e=this.active;e&&(e.fenced=!0,e.reject(this.fault),e.finish(),this.active=null),this.stopReply?.reject(this.fault),this.stopReply=null,this.portal?.life.abort();try{this.portal?.value.close()}catch{}this.portal=null;try{this.owner.releaseWorker()}catch{}this.port.removeEventListener("message",this.message),this.port.removeEventListener("messageerror",this.messageError),this.port.close()}close(){if(this.stopping)return this.stopping;let e=this.active;return e&&(e.fenced=!0,e.reject(new Se("application_worker_fenced"))),this.stopping=Promise.resolve().then(async()=>{if(this.fault)throw new Se("application_worker_stop_failed");this.portal?.life.abort(),this.portal?.value.close(),this.portal=null;let t=this.id();if(await new Promise((i,o)=>{this.stopReply={id:t,resolve:i,reject:o};try{this.send(t,"close",null)}catch(s){o(s)}}),await e?.done,this.fault)throw new Se("application_worker_stop_failed");this.owner.releaseWorker(),this.port.removeEventListener("message",this.message),this.port.removeEventListener("messageerror",this.messageError),this.port.close()}).catch(t=>{throw this.quarantine("application_worker_stop_failed"),t}),this.stopping}}});var oI={};ls(oI,{ApplicationRuntime:()=>jw,ApplicationRuntimeError:()=>ni});var ni,Lw,jw,sI=I(()=>{"use strict";dC();QC();bt();th();rI();Vb();ni=class extends Error{constructor(t){super("SDK application runtime unavailable");this.code=t;this.name="ApplicationRuntimeError"}code},Lw=()=>{let n=Object.freeze({checking:!1,assessment:null,problem:null});return Object.freeze({checking:!1,assessment:null,problem:null,facets:Object.freeze({capabilities:n,contracts:n,configuration:n,files:n,people:n,notifications:n})})},jw=class{lifetime=new AbortController;scope;worker;cpOrigin;lab;listeners=new Set;unsubscribe;raw=Object.freeze({status:"not_started",collections:Object.freeze([]),selectedCollectionId:null,signIn:null,problem:null,timing:null});snapshot=Object.freeze({...this.raw,readiness:Lw()});pending=null;closing=null;epoch=0;loggedProblem=null;assessing=!1;retiring=!1;closed=!1;stopped=!1;stopFailed=!1;constructor(e){this.cpOrigin=e.cpOrigin,this.lab=Qt(e.declaration.environment),this.scope=new Mh(e.compiledManifest,{name:e.declaration.name,version:"1"},this.lifetime.signal,e.typeIssues,t=>eh(this.raw,t)),this.worker=new Lh(e.port,e.binding,{snapshot:t=>{this.closed||(this.raw=t,this.followSession(),this.publish())},handoff:(t,i)=>{let o=this.epoch;return this.scope.adopt(t,i,()=>!this.closed&&this.epoch===o).then(()=>{this.portsFailed=null},s=>{throw this.portsFailed=t.scope.collection,s})},attached:t=>this.attached(t),releaseWorker:e.releaseWorker,...e.nativeAuthorization?{nativeAuthorization:e.nativeAuthorization}:{},failed:t=>{this.closed||(this.raw=Object.freeze({...this.raw,status:"blocked",problem:t.code}),this.publish())}}),this.unsubscribe=this.scope.subscribe(()=>this.publish())}portsFailed=null;attached(e){let t=()=>{for(let o of[e.dataPort,e.controlPort,...e.timerPort?[e.timerPort]:[]])try{o.close()}catch{}};if(this.closed){t();return}let i=this.lifetime.signal;this.queue(()=>this.action(async()=>{if(this.raw.selectedCollectionId!==e.scope.collection)return t(),this.snapshot;this.scope.selectedId()!==null&&(++this.epoch,await this.retireOwn());let o=this.epoch;return await this.scope.adopt(e,i,()=>!this.closed&&this.epoch===o).catch(s=>{throw this.portsFailed=e.scope.collection,s}),this.portsFailed=null,this.complete(this.raw,i)},i)).catch(()=>{this.closed||this.publish()})}followSession(){if(this.pending)return;let e=this.raw.status==="ready"||this.raw.status==="setup_required",t=this.raw.selectedCollectionId,i=this.scope.selectedId();if(i!==null&&(i!==t||!e&&this.raw.status!=="opening"&&this.raw.status!=="authorizing")){let o=this.lifetime.signal;this.queue(()=>this.action(async()=>(this.scope.selectedId()===i&&(++this.epoch,await this.retireOwn()),this.publish(),this.snapshot),o)).catch(()=>{})}}connection(e){return this.closed?null:this.scope.connection(e)}getSnapshot(){return this.snapshot}getNativeSnapshot(){return this.raw}async queue(e){for(;this.pending&&!this.closed;)await this.pending.catch(()=>{});return e()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}publish(){if(this.closed)this.snapshot=Object.freeze({...this.raw,status:this.stopped?"closed":"blocked",problem:this.stopped?null:this.stopFailed?"application_stop_failed":"application_closing",selectedCollectionId:null,readiness:Lw()});else{let e=this.scope.getReadiness()??Lw(),t=this.raw.status,i=this.raw.problem,o,s=this.raw.selectedCollectionId,r=this.retiring&&e.problem?.code==="readiness_fenced",a=s!==null&&(this.scope.getReadiness()===null||r)&&this.portsFailed!==s;if((t==="ready"||t==="setup_required")&&a)t="opening";else if(t==="ready"||t==="setup_required"){let l=this.assessing&&!e.assessment&&e.problem?.code!=="readiness_fenced";if(t=e.checking||l?"opening":e.assessment?.status==="ready"?"ready":e.assessment?.status==="setup_required"?"setup_required":"blocked",t==="blocked"){let c=e.problem??e.assessment?.problem;i=c?.code??"application_readiness_unavailable",o=c?.detail}}let p=`${i}:${o??""}`;if(t==="blocked"&&i&&p!==this.loggedProblem){this.loggedProblem=p;try{o?console.error("mdbase application blocked:",i,o):console.error("mdbase application blocked:",i)}catch{}}else t!=="blocked"&&(this.loggedProblem=null);this.snapshot=Object.freeze({...this.raw,status:t,problem:i,openingProgress:t==="opening"?e.checking?"checking_setup":this.raw.openingProgress??null:null,collections:Object.freeze(this.raw.collections.map(l=>Object.freeze({...l}))),readiness:e})}for(let e of[...this.listeners])try{e()}catch{}}retireOwn(){return this.retiring=!0,this.scope.retire()}settled(){return this.assessing=!1,this.publish(),this.snapshot}signal(e){return e.signal?AbortSignal.any([this.lifetime.signal,e.signal]):this.lifetime.signal}action(e,t){if(this.closed||t.aborted)return Promise.reject(new ni("application_fenced"));if(this.pending)return Promise.reject(new ni("application_busy"));this.assessing=!0;let i=Promise.resolve().then(async()=>{if(this.closed||t.aborted)throw new ni("application_fenced");let o=await e();if(this.closed||t.aborted)throw new ni("application_fenced");return o}).finally(async()=>{(this.assessing||this.retiring)&&(this.assessing=!1,this.retiring=!1,this.publish()),await this.worker.drain(),this.pending===i&&(this.pending=null)});return this.pending=i,i}async complete(e,t){if(this.closed||t.aborted)throw new ni("application_fenced");let i=!!(e.selectedCollectionId&&this.scope.connection(e.selectedCollectionId));if(this.raw=e,this.assessing=i,this.publish(),i){try{await this.scope.assess({signal:t}).catch(()=>{})}finally{this.assessing=!1}this.publish()}if(this.closed||t.aborted)throw new ni("application_fenced");return this.snapshot}start(e={}){let t=this.signal(e);return this.action(async()=>this.complete(await this.worker.request("start",null,t),t),t)}authorizeReserved(e,t={},i=null){let o=this.signal(t);return this.action(async()=>this.complete(await this.worker.request("authorize",i,o,e),o),o).catch(s=>{throw e.close(),s})}authorize(e={}){let t=this.signal(e),i;try{i=Jf(Xf(this.cpOrigin,t,()=>!this.closed,this.lab))}catch(o){return Promise.reject(o)}return this.authorizeReserved(i,e)}select(e,t={}){let i=this.signal(t);return this.action(async()=>{if(this.raw.selectedCollectionId===e&&(this.raw.status==="ready"||this.raw.status==="setup_required")&&this.scope.connection(e)?.isCurrent())return this.snapshot.status==="blocked"?this.complete(this.raw,i):this.snapshot;++this.epoch;let o=this.retireOwn();if(this.publish(),await o,this.closed||i.aborted)throw new ni("application_fenced");return this.complete(await this.worker.request("select",e,i),i)},i)}assess(e={}){let t=this.signal(e);return this.action(async()=>(await this.scope.assess({signal:t}),this.settled()),t).then(i=>i.readiness)}configure(e={}){let t=this.signal(e);return this.action(async()=>(await this.scope.configure({signal:t}),this.settled()),t)}planSetup(e={}){let t=this.signal(e);return this.closed||t.aborted?Promise.reject(new ni("application_fenced")):this.scope.planSetup({...e,signal:t})}applySetup(e,t={}){let i=this.signal(t);return this.action(async()=>(await this.scope.applySetup(e,{signal:i}),this.settled()),i)}clearSelection(e={}){let t=this.signal(e);return this.action(async()=>(++this.epoch,await this.retireOwn(),this.complete(await this.worker.request("clearSelection",null,t),t)),t)}forget(e,t={}){let i=this.signal(t);return this.action(async()=>(this.raw.selectedCollectionId===e&&(++this.epoch,await this.retireOwn()),this.complete(await this.worker.request("forget",e,i),i)),i)}refreshCollections(e={}){let t=this.signal(e);return this.action(async()=>(this.raw=await this.worker.request("refreshCollections",null,t),this.publish(),this.snapshot),t)}signOut(e={}){let t=this.signal(e),i=this.raw.selectedCollectionId,o=e.discard!==!0&&i?cC(this.scope.connection(i)):0;return o>0?Promise.reject(pC(o)):this.action(async()=>(++this.epoch,await this.retireOwn(),this.complete(await this.worker.request("signOut",null,t),t)),t)}deleteCollection(e,t,i={}){let o=this.signal(i);return this.action(async()=>(await this.worker.request("deleteCollection",[e,t],o),this.raw.selectedCollectionId===e&&(++this.epoch,await this.retireOwn()),this.complete(await this.worker.request("forget",e,o),o)),o)}requestFileAccess(e,t,i,o,s={}){let r=this.signal(s);return this.action(async()=>(this.raw=await this.worker.request("requestFileAccess",[t,i,o],r,e),this.publish(),this.snapshot),r).catch(a=>{throw e.close(),a})}pollFileAccess(e){let t=this.lifetime.signal;return this.action(async()=>(this.raw=await this.worker.request("pollFileAccess",e,t),this.publish(),this.snapshot),t)}setForeground(e){this.closed||this.worker.setForeground(e)}abandon(){this.closed||(this.closed=!0,this.stopped=!0,++this.epoch,this.unsubscribe(),this.listeners.clear(),this.closing=Promise.resolve(),this.worker.abandon(),this.lifetime.abort())}close(){return this.closing?this.closing:(this.closed=!0,++this.epoch,this.lifetime.abort(),this.unsubscribe(),this.closing=Promise.resolve().then(async()=>{await Promise.all([this.scope.close(),this.worker.close()]),await this.pending?.catch(()=>{}),this.stopped=!0,this.publish(),this.listeners.clear()}).catch(()=>{throw this.stopFailed=!0,this.publish(),new ni("application_stop_failed")}),this.publish(),this.closing)}}});var aM={};ls(aM,{ACCOUNT_KEY_STATES:()=>cy,API_VERSIONS:()=>sd,AppHost:()=>Zw,COLLECTION_UNAVAILABLE_REASONS:()=>$y,CborError:()=>Ie,Client:()=>xd,DESCRIBE_TYPING_MAX_PATHS:()=>Pl,DESCRIBE_TYPING_MAX_TYPES:()=>Sl,DEVICE_KINDS:()=>ly,ERROR_CODES:()=>Pp,FilesApi:()=>_s,Float64:()=>yt,HOLD_COMPARE_SCHEME:()=>tc,HOLD_TITLE:()=>ec,IkInitiator:()=>Rs,IkResponder:()=>Xd,LiveQuery:()=>Ss,MAX_CONVENIENCE_BYTES:()=>ad,MAX_DEPTH:()=>tm,MDBASE_NOTIFICATION_CLICK:()=>eg,MDBASE_NOTIFICATION_TYPE:()=>Ql,MdbaseApplicationUnavailableError:()=>yp,MdbaseClient:()=>Ei,MdbaseConnect:()=>ol,MdbaseError:()=>se,MdbasePeopleClient:()=>jr,NoiseError:()=>rt,PERSON_CONTRACT:()=>Gy,PROBLEM_CODES:()=>sk,PresenceApi:()=>ks,READ_MANY_MAX_CONCURRENCY:()=>Xm,READ_MANY_MAX_REFS:()=>Jm,RecordReader:()=>Il,SESSION_LIFETIME_MS:()=>Ly,SLOW_OPENING_MS:()=>bu,SchemaError:()=>ne,Session:()=>go,TEMPORAL_HINTS:()=>Vp,TimersApi:()=>Ns,WasmRuntime:()=>$s,Write:()=>_o,applicationPhase:()=>ic,approvalReadiness:()=>pA,bytesEqual:()=>HI,clientPrologue:()=>Ti,collectionUnavailableError:()=>un,compareVersions:()=>lg,connect:()=>my,controlRouteResolver:()=>L0,createMdbase:()=>lI,createViewSource:()=>hd,decode:()=>ue,describeDiagnostic:()=>hu,describeError:()=>Lo,describeHold:()=>J0,diffEdits:()=>Jp,duplexCarrier:()=>By,effectiveCapabilities:()=>cI,encode:()=>pe,encodeSecret:()=>qn,fileGrant:()=>Ym,formatSas:()=>fA,framedPort:()=>id,fromHex:()=>cs,generateKeyPair:()=>Es,handleMdbaseNotificationClick:()=>G0,handleMdbasePush:()=>H0,holdCompareLink:()=>rg,holdNotice:()=>X0,inProcessConnector:()=>Ds,indexedDbKeyStorage:()=>Wy,isCollectionUnavailableReason:()=>Ls,isConfirmed:()=>M0,isErrorCode:()=>Sr,isMdbaseError:()=>oe,isReadyPhase:()=>hk,isValid:()=>KI,keyPairFromSecret:()=>w0,loadOrCreateClientKey:()=>E0,localLinkConnector:()=>C0,localLinkFirstPayload:()=>Vy,mdbaseError:()=>A,memoryKeyStorage:()=>Ky,memoryWriteLedgerStore:()=>vd,nextRelayConnector:()=>x0,noiseChannel:()=>jy,noiseConnector:()=>Mi,orderTargets:()=>js,parseCollectionAvailability:()=>zn,parseHoldCompareLink:()=>Y0,parseMdbaseNativeNotification:()=>tg,parseMdbasePush:()=>ou,parseVersion:()=>Ks,pipeCloseError:()=>To,portPair:()=>g_,problemCodeOf:()=>sg,queryPages:()=>cd,readMany:()=>ld,readMdbaseNotificationData:()=>ng,readViewSourceRecord:()=>fd,recoveryFor:()=>JI,relayConnector:()=>k0,relayPipeCarrier:()=>Ms,resolveRecordLinks:()=>O_,revisionOf:()=>si,routeFromControl:()=>Hy,sameIdentity:()=>nu,showMdbaseNotification:()=>ig,staticKeyOf:()=>Yd,streamCarrier:()=>_0,structMap:()=>WI,summarizeStatus:()=>eu,syncStatusText:()=>Z0,toHex:()=>ri,toPlain:()=>bs,toValue:()=>ut,updateViewSource:()=>md,uuidv7:()=>Ln,valueEquals:()=>Ir,versionRelation:()=>jo,webSocketCarrier:()=>qs,wire:()=>Nm});Je();ge();ie();At();At();Ps();Zm();iy();ql();ql();ry();Rl();Ol();Oi();ge();ie();qo();Ts();Yl();function k0(n){let e=U(n.collection),t=n.grant?U(n.grant):null;return Mi({description:`relay:${n.collection}`,staticKey:n.staticKey,target:async()=>{let i=await n.resolveRoute();if(!i)throw A("unavailable","no device of this collection is online","no_device_online");return{prologue:Ti(e,t,U(i.targetDevice)),remoteStatic:i.noisePublicKey,device:i.targetDevice,openCarrier:o=>i.pipe?Ms(i.url,{accessToken:i.pipe.accessToken,collection:i.pipe.collection,grant:n.grant??"",device:i.targetDevice,devicePublicKey:i.noisePublicKey},n.webSocket,o):qs(i.url,n.webSocket,o)}}})}Fy();Ts();qo();Je();ge();ie();At();qo();Ts();var G1=new Uint8Array(16);function Vy(n,e){if(n.length!==32)throw A("invalid_request","the link token is 32 bytes");let t=Qi.dec(e);if(t.kind!=="request"||t.method!=="hello")throw A("internal","expected the hello request");return pe(new Map([[0,n],[1,t.params]]))}function C0(n){let e=U(n.collection),t=n.staticKey??Es(),i=null;return Mi({description:"localhost-link",staticKey:t,firstPayload:o=>Vy(i.token,o),target:async()=>{i=typeof n.link=="function"?await n.link():n.link;let o=i;if(!Number.isInteger(o.port)||o.port<=0||o.port>65535)throw A("unavailable","invalid local link port","daemon_not_running");let s=Ti(e,null,n.localOnly?G1:U(o.device));return{prologue:s,preamble:s,remoteStatic:o.noisePublicKey,openCarrier:r=>qs(`ws://127.0.0.1:${o.port}/v1/plugin`,n.webSocket,r)}}})}Ty();ie();function Ky(){let n=new Map;return{get:async e=>n.get(e),put:async(e,t)=>{n.set(e,t)},putIfAbsent:async(e,t)=>{let i=n.get(e);return i||(n.set(e,t),t)},delete:async e=>{n.delete(e)}}}function Wy(n="mdbase-keys",e="keys"){let t=globalThis.indexedDB;if(!t)throw A("invalid_request","IndexedDB is not available here; pass another KeyStorage");let i=()=>new Promise((r,a)=>{let p=t.open(n,1);p.onupgradeneeded=()=>p.result.createObjectStore(e),p.onsuccess=()=>r(p.result),p.onerror=()=>a(p.error)}),o=async(r,a)=>{let p=await i();try{return await new Promise((l,c)=>{let d=p.transaction(e,r),u,f=!1;d.oncomplete=()=>f?l(u):c(A("unavailable","key storage transaction completed without a result","key_storage")),d.onabort=()=>c(d.error??A("unavailable","key storage transaction aborted","key_storage")),d.onerror=()=>c(d.error??A("unavailable","key storage transaction failed","key_storage"));try{a(d.objectStore(e),h=>{u=h,f=!0})}catch(h){d.abort(),c(h)}})}finally{p.close()}},s=(r,a)=>o(r,(p,l)=>{let c=a(p);c.onsuccess=()=>l(c.result)});return{get:r=>s("readonly",a=>a.get(r)),put:(r,a)=>s("readwrite",p=>p.put(a,r)).then(()=>{}),putIfAbsent:(r,a)=>o("readwrite",(p,l)=>{let c=p.get(r);c.onsuccess=()=>{if(c.result!==void 0){l(c.result);return}try{let d=p.add(a,r);d.onsuccess=()=>l(a)}catch{p.transaction.abort()}}}),delete:r=>s("readwrite",a=>a.delete(r)).then(()=>{})}}function R0(){return globalThis.crypto?.subtle}async function Y1(){let n=R0();if(!n)return null;try{let e=await n.generateKey({name:"X25519"},!1,["deriveBits"]),t=new Uint8Array(await n.exportKey("raw",e.publicKey));return{kind:"webcrypto",privateKey:e.privateKey,publicKey:t}}catch{return null}}function J1(n){return n.kind==="raw"?{publicKey:n.publicKey,nonExtractable:!1,dh:e=>sr.getSharedSecret(n.secretKey,e)}:{publicKey:n.publicKey,nonExtractable:!n.privateKey.extractable,dh:async e=>{let t=R0(),i=await t.importKey("raw",e,{name:"X25519"},!1,[]),o=await t.deriveBits({name:"X25519",public:i},n.privateKey,256);return new Uint8Array(o)}}}var X1=Ky(),I0=new WeakMap;function O0(n,e){if(e&&(n.kind!=="webcrypto"||n.privateKey.extractable!==!1||n.privateKey.type!=="private"||n.privateKey.algorithm.name!=="X25519"||!n.privateKey.usages.includes("deriveBits")))throw A("invalid_request","a non-extractable X25519 key is required; explicitly reauthorize incompatible stored identities","key_storage")}async function E0(n,e={}){let t=e.storage??(globalThis.indexedDB?Wy():X1),i=e.requireNonExtractable,o=I0.get(t);o||(o=new Map,I0.set(t,o));let s=o.get(n);s||(s=(async()=>{let r=await t.get(n);if(r)return r;let a=await Y1();if(!a){if(i)throw A("invalid_request","this platform cannot keep a non-extractable X25519 key","key_storage");let p=sr.utils.randomSecretKey();a={kind:"raw",secretKey:p,publicKey:sr.getPublicKey(p)}}return O0(a,i),t.putIfAbsent?t.putIfAbsent(n,a):(await t.put(n,a),a)})(),o.set(n,s));try{let r=await s;return O0(r,i),J1(r)}finally{o.get(n)===s&&o.delete(n)}}py();var q0={collection_not_yet_migrated:"Your collection needs an upgrade on your computer; your changes are safe",collection_migrating:"Your collection is being upgraded; changes will sync when it's done",update_required:"Update the app to keep syncing",account_suspended:"Syncing is paused: your account is suspended"},T0={offline:"You're offline",unreachable:"Can't reach the sync service",server_busy:"The sync service is busy; trying again shortly",rate_limited:"Syncing is paused for a moment",auth:"Sign in again to keep syncing"};function eu(n,e,t,i){let o=n.mode!=="local_only"&&t&&Object.hasOwn(T0,t.kind)?t.kind:null,s={pending:n.pending,holds:n.holds,conflicts:n.unresolved,confirmedThrough:n.mode==="local_only"?null:n.confirmedThrough,health:o,live:n.mode==="local_only"||typeof i!="boolean"?null:i},r=n.pending>0?`, ${n.pending} change${n.pending===1?"":"s"} waiting`:"";if(n.mode==="local_only")return{...s,kind:"local",text:n.pending?`Saving${r}`:"Saved on this device"};if(e&&Object.hasOwn(q0,e))return{...s,kind:e,text:`${q0[e]}${r}`};if(n.installing)return{...s,kind:"installing",text:`Loading the collection (${n.installing.done}/${n.installing.total})`};if(o){let p=n.pending?`. ${n.pending} change${n.pending===1?" is":"s are"} saved on this device and will sync later`:"";return{...s,kind:o==="offline"||o==="unreachable"?"offline":n.confirmedThrough<n.headKnown?"catching_up":"synced",text:`${T0[o]}${p}`}}if(n.connection!=="online")return{...s,kind:"offline",text:`Offline; synced through ${n.confirmedThrough}${r}`};if(n.confirmedThrough<n.headKnown)return{...s,kind:"catching_up",text:`Catching up (${n.confirmedThrough}/${n.headKnown})${r}`};let a=s.live===!1?". Live updates are paused; changes from other devices appear when you come back to this app":"";return{...s,kind:"synced",text:`Synced through ${n.confirmedThrough}${r}${a}`}}function M0(n){return n.state==="confirmed"}uy();Yl();Zd();Je();Lr();ie();function Hy(n,e){for(let t of n.targets??[]){if(!/^[0-9a-f]{64}$/i.test(t.noise_pk)||!t.url||!t.device)continue;let i={url:t.url,targetDevice:t.device,noisePublicKey:cs(t.noise_pk)};return t.relay_collection&&(i.pipe={collection:t.relay_collection,accessToken:e}),i}return null}function L0(n){let e;try{e=new URL(n.server)}catch{throw A("invalid_request","The control plane requires an HTTPS origin")}if(e.protocol!=="https:"&&!!1||e.username||e.password||e.pathname!=="/"||e.search||e.hash)throw A("invalid_request","The control plane requires an HTTPS origin without credentials, path, query or fragment");let t=`${e.origin}/v1/next/collections/${encodeURIComponent(n.collection)}/route`,i=n.fetch??globalThis.fetch.bind(globalThis);return async()=>{let o=await n.accessToken(),s;try{s=await i(t,{headers:{authorization:`Bearer ${o}`},redirect:"error"})}catch{throw A("unavailable","cannot reach the control plane","control_unreachable")}if(s.status===401)throw A("unauthenticated","the control plane refused the access token");if(s.status===409)throw A("unauthenticated","this app's key is not registered with its grant","client_key_required");if(!s.ok)throw A("unavailable",`control plane answered ${s.status}`,"control_error");let r=await s.json(),a=zn(r.availability);if(a?.state==="unavailable")throw un(a.reason);let p=Hy(r,o);if(!p&&r.reason==="no_device_registered")throw A("unavailable","this collection has no device set up to serve it","no_device_registered");return p}}Lr();iu();Zy();ie();var Ql="mdbase.notification",eg="mdbase.notification.click",B0=/^[\x21-\x7e]{1,256}$/,oR=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Nr=n=>A("invalid_request",n,"invalid_push_payload"),sR=()=>A("upgrade_required","The push uses an envelope version this SDK does not support.","unsupported_push_version");function V0(n){if(typeof n=="string")try{n=JSON.parse(n)}catch{throw Nr("The push payload is not JSON.")}else if(n&&typeof n=="object"&&typeof n.json=="function")try{n=n.json()}catch{throw Nr("The push payload is not JSON.")}if(!n||typeof n!="object"||Array.isArray(n))throw Nr("The push payload is not an object.");return n}function Us(n,e,t){return typeof n=="string"&&n.length>=e&&n.length<=t}function K0(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n;return!Us(e.title,1,80)||e.body!==void 0&&!Us(e.body,0,160)||e.tag!==void 0&&!Us(e.tag,1,80)?null:Object.freeze({title:e.title,...typeof e.body=="string"&&e.body.length?{body:e.body}:{},...typeof e.tag=="string"?{tag:e.tag}:{}})}function W0(n,e,t){if(n.type!==Ql)throw Nr("The payload is not an mdbase notification.");if(e!==1)throw typeof e=="number"&&Number.isSafeInteger(e)&&e>1?sR():Nr("The payload has no valid envelope version.");if(!Us(n.signal_id,1,256)||!B0.test(n.signal_id)||!Us(n.cursor,1,256)||!B0.test(n.cursor)||!Us(n.criterion_id,1,100)||!oR.test(n.criterion_id))throw Nr("The payload is not an mdbase notification.");return Object.freeze({version:1,signalId:n.signal_id,criterionId:n.criterion_id,cursor:n.cursor,presentation:t})}function ou(n){let e=V0(n),t=W0(e,e.version,K0(e.presentation));if(!t.presentation)throw Nr("The push has no valid presentation.");return t}function tg(n){if(!n||typeof n!="object"||Array.isArray(n))throw Nr("The native notification data is not an object.");let e=n,t=typeof e.version=="string"&&/^[1-9][0-9]{0,8}$/.test(e.version)?Number(e.version):e.version;return W0(e,t,null)}function ng(n){try{return tg(n)}catch{return null}}function aR(n){return{type:Ql,version:n.version,signal_id:n.signalId,criterion_id:n.criterionId,cursor:n.cursor}}async function ig(n,e,t={}){let i=ou(e),o=i.presentation;return await n.showNotification(o.title,{...o.body?{body:o.body}:{},...o.tag?{tag:o.tag}:{},...t.icon?{icon:t.icon}:{},...t.badge?{badge:t.badge}:{},data:aR(i)}),i}function Qy(n){return globalThis[n]}function lR(n){let e=globalThis.location;if(typeof e?.origin=="string"&&e.origin!=="null")return e.origin;try{return n?new URL(n).origin:null}catch{return null}}function F0(n,e,t){let i=()=>A("invalid_request",`The notification click ${t} must be on the app's own origin.`,"click_target_cross_origin");if(typeof n!="string")throw i();if(e===null){if(!n.startsWith("/")||n.startsWith("//")||n.startsWith("/\\"))throw i();return n}let o;try{o=new URL(n,`${e}/`)}catch{throw i()}if(o.origin!==e)throw i();return o.href}function H0(n,e={}){let t;try{t=V0(n.data?.text()??null)}catch{return!1}if(t.type!==Ql)return!1;let i=e.registration??Qy("registration");if(!i)throw A("invalid_request","No service worker registration to show the notification.","push_registration_missing");let o={...e.icon?{icon:e.icon}:{},...e.badge?{badge:e.badge}:{}};return n.waitUntil((async()=>{try{ou(t)}catch(s){let r=s instanceof se&&s.reason==="unsupported_push_version"?K0(t.presentation):null;if(!r)throw s;return await i.showNotification(r.title,{...r.body?{body:r.body}:{},...r.tag?{tag:r.tag}:{},...o}),null}return ig(i,t,o)})()),!0}function G0(n,e={}){let t=ng(n.notification.data);if(!t)return!1;n.notification.close();let i=e.clients??Qy("clients"),o=Qy("registration")?.scope,s=lR(o),r=e.scope===void 0?o:F0(e.scope,s,"scope"),a=e.url===void 0?r??"/":F0(e.url,s,"url");return i&&n.waitUntil((async()=>{let l=(await i.matchAll({type:"window",includeUncontrolled:!0})).find(d=>!r||d.url.startsWith(r));if(!l)return i.openWindow(a);await l.focus();let c={type:eg,notification:t};return l.postMessage(c),l})()),!0}su();Je();ie();ge();var $s=class n{constructor(e){this.instance=e}instance;ports=new Map;timer=null;opened=!1;get x(){if(!this.instance)throw A("unavailable","runtime instance was discarded after an ABI failure");return this.instance}discard(){this.instance=null,this.timer&&clearInterval(this.timer),this.timer=null;for(let e of[...this.ports.values()])e.end();this.ports.clear()}static async instantiate(e){return new n(await this.load(e))}static async load(e,t){let i=null,o=null,s=t?.(()=>{if(!o)throw A("unavailable","runtime imports called before initialization");return o})??{},r=new TextDecoder,a={host_app_sql:(c,d)=>0n,host_now_ms:()=>Date.now(),host_local_date:(c,d,u,f)=>{try{let h=r.decode(new Uint8Array(i.buffer,d,u)),m=new Intl.DateTimeFormat("en-CA",{timeZone:h,year:"numeric",month:"2-digit",day:"2-digit"}).format(c);return/^\d{4}-\d{2}-\d{2}$/.test(m)?(new Uint8Array(i.buffer,f,10).set(new TextEncoder().encode(m)),10):0}catch{return 0}},host_default_zone:(c,d)=>{let u=new TextEncoder().encode(Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"),f=Math.min(u.length,d);return new Uint8Array(i.buffer,c,f).set(u.subarray(0,f)),f},host_random:(c,d)=>{let u=new Uint8Array(i.buffer,c,d);for(let f=0;f<d;f+=65536)globalThis.crypto.getRandomValues(u.subarray(f,f+65536))}},{instance:p}=await WebAssembly.instantiate(e,{env:{...a,...s}}),l=p.exports;return o=l,i=l.memory,l}put(e){if(e.length===0)return[0,0];let t=this.x.alloc(e.length);return new Uint8Array(this.x.memory.buffer,t,e.length).set(e),[t,e.length]}takeOut(e){let t=Number(e>>32n),i=Number(e&0xffffffffn);if(i===0)return new Uint8Array(0);let o=new Uint8Array(this.x.memory.buffer,t,i).slice();return this.x.dealloc(t,i),o}info(){let e=ue(this.takeOut(this.x.rt_info())),t=i=>{let[o,s]=i;return{major:o,minor:s}};return{abiMajor:e.get(0),runtimeVersion:e.get(1),sem:t(e.get(2)),serves:e.get(3).map(t)}}open(e){let t=this.x;if(this.opened)throw A("unavailable","runtime is already open");let i=e.queryExecutionProfile,o;if(i!==void 0){if(i!=="memory_constrained"&&i!=="desktop")throw A("invalid_request","unknown query execution profile");if(typeof t.rt_open_profile!="function")throw A("unavailable","runtime does not support explicit query profile initialization");o=i==="memory_constrained"?0:1}let s=qn(new Map([[0,U(e.collection)],[1,U(e.replicaId)],[2,U(e.deviceId)],[3,e.mode==="local_only"?0:1],[4,e.signSecretKey],[5,e.kemSecretKey],[6,e.e2e??!1]])),r;try{let a=this.put(s);r=this.takeOut(o===void 0?t.rt_open(...a):t.rt_open_profile(...a,o))}catch(a){throw this.discard(),a}finally{s.fill(0)}if(r.length)throw A("unavailable",`runtime failed to open: ${new TextDecoder().decode(r)}`);this.markOpened()}markOpened(){this.opened=!0,this.timer??=setInterval(()=>this.tick(),1e3),this.timer.unref?.()}tick(){this.x.rt_tick(Date.now()),this.flush()}connect(e={}){let t=null,i=!1,o=[],s={onframe:null,onclose:null,send:r=>{if(i)throw A("unavailable","port closed");let a=pe(r);if(t===null){let p=e.grant&&e.clientKey?new Uint8Array([...U(e.grant),...e.clientKey]):new Uint8Array(0),l=ue(this.takeOut(this.x.rt_hello(...this.put(p),...this.put(a)))),c=BigInt(l[0]),d=ue(l[1]);queueMicrotask(()=>{s.onframe?.(d),c===0n&&s.end()}),c!==0n&&(t=c,this.ports.set(c,s),this.flush());return}this.x.rt_frame(t,...this.put(a)),this.flush()},close:()=>{i||(i=!0,t!==null&&(this.ports.delete(t),this.x.rt_close(t)),s.onclose?.())},deliver:r=>s.onframe?s.onframe(r):o.push(r),end:()=>{i||(i=!0,t!==null&&this.ports.delete(t),s.onclose?.())}};return s}sessionForPort(e){for(let[t,i]of this.ports)if(i===e)return t;return null}flush(){let e=this.takeOut(this.x.rt_poll());if(!e.length)return;let t=ue(e),i=new Set(t.filter(o=>o[1]===null).map(o=>BigInt(o[0])));for(let o of t){let[s,r]=o,a=this.ports.get(BigInt(s));if(a)if(r===null)a.end();else{let p=ue(r);if(i.has(BigInt(s))){if(p instanceof Map){let l=p;l.get(0)===2&&l.get(1)==="closed"&&a.deliver(p)}}else queueMicrotask(()=>a.deliver(p))}}}dispose(){this.timer&&clearInterval(this.timer);for(let e of[...this.ports.values()])e.close()}};var ec="mdbase protected your edit",cR={conflict:{cause:"This file was also changed on another device while you were editing it.",detail:"Your version is kept here and is not synced until you choose what to keep."},unknown_provenance:{cause:"This file changed on disk in a way mdbase could not trace to an app or a sync.",detail:"The bytes on disk are kept here and are not synced until you confirm them."},deleted_elsewhere:{cause:"This file was deleted on another device after you edited it.",detail:"Your version is kept here; nothing is deleted until you choose."},read_only:{cause:"Changed with view access.",detail:"Edit access will not sync these changes. Submit or discard them."},editor_busy:{cause:"An editor still has this file open with unsaved changes.",detail:"mdbase waits so that it never overwrites what you are typing."},suspect_write:{cause:"The last write to this file looked incomplete, for example after a crash.",detail:"The file is kept aside and is not synced until you confirm it."}},pR={keep_mine:{label:"Keep mine",description:"Sync the version on this device.",resolution:"keep_mine",needs:"records.edit",discardsMine:!1},take_theirs:{label:"Take theirs",description:"Replace this file with the synced version.",resolution:"take_theirs",needs:"records.edit",discardsMine:!0},keep_both:{label:"Keep both",description:"Save your version as a copy next to the synced one.",resolution:"keep_both",needs:"records.edit",discardsMine:!1},delete:{label:"Delete",description:"Accept the deletion and remove this file here too.",resolution:"delete",needs:"records.delete",discardsMine:!0},use:{label:"Use merged",description:"Sync the document you merged.",resolution:"use",needs:"records.edit",discardsMine:!1},compare:{label:"Compare side by side",description:"Open both versions to merge them.",discardsMine:!1}},dR={conflict:["keep_mine","take_theirs","compare","keep_both"],unknown_provenance:["keep_mine","take_theirs","compare","keep_both"],deleted_elsewhere:["keep_mine","delete"],read_only:["keep_mine","take_theirs","compare","keep_both"],editor_busy:["keep_mine","take_theirs","compare"],suspect_write:["keep_mine","take_theirs","compare","keep_both"]},tc="mdbase://hold/compare",au=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function rg(n,e){if(!au.test(n)||!au.test(e))throw new Error("holdCompareLink: collection and id are UUIDs");return`${tc}?collection=${n.toLowerCase()}&id=${e.toLowerCase()}`}function Y0(n){if(typeof n!="string"||n.length>512||!n.startsWith(`${tc}?`))return null;let e=new URLSearchParams(n.slice(tc.length+1)),t=e.get("collection")??"",i=e.get("id")??"";return!au.test(t)||!au.test(i)?null:{collectionId:t.toLowerCase(),id:i.toLowerCase()}}function J0(n,e){let t=n.reason==="read_only",i=n.theirs!==void 0,o=(e.canCompare??!0)&&i,s=p=>!p||!e.capabilities||e.capabilities.includes(p),r=dR[n.reason].filter(p=>p==="compare"?o:(!t||e.host===!0)&&(p!=="take_theirs"||i||t)).map(p=>{let l={action:p,...pR[p]};return t&&p==="take_theirs"&&(l.label="Discard local changes",l.description="Discard unsynced changes on this device.",l.needs="collection.read"),l}).filter(p=>s(p.needs)),a=cR[n.reason];return{id:n.id,path:n.path,reason:n.reason,title:ec,cause:a.cause,detail:a.detail,since:n.since,saves:n.saves,hasTheirs:i,actions:r,reversible:!t,reversibleNote:t?"Copy before discarding.":"You can change your mind later: resolving is an ordinary change, and the previous version stays in the collection's history. Keep both if you want your version kept as a file as well.",compareLink:o?rg(e.collectionId,n.id):null}}function X0(n){return n.length?n.length===1?`${ec}: ${n[0].path} is waiting for your choice.`:`${ec}: ${n.length} files are waiting for your choice.`:null}function Z0(n){let e=(i,o)=>`${i} ${o}`,t=`, plus ${e(n.pending,"pending")}, plus ${e(n.holds,"held")}`;return n.mode==="local_only"?`Saved on this device${t}`:`Confirmed through ${n.confirmedThrough}${t}`}nc();yu();nc();var bu=15e3,fk=(n,e)=>{try{return!!n&&n.id===e&&n.isCurrent()}catch{return!1}},gu=(n,e)=>Lo(n,e?{cpOrigin:e}:{}),Ws=(n,e)=>gu(n,e);function ic(n,e={}){let t=ER(n,e),i=qR(t,n,e);return i.kind==="opening"&&n.status==="opening"&&n.selectedCollectionId===i.collectionId&&n.openingProgress?{...i,progress:n.openingProgress}:i}function ER(n,e){let t=e.cpOrigin,i=n.selection,o=i?.requested??null;if(n.status==="closed")return{kind:"closed"};if(n.problem==="application_not_yet_available"||n.problem==="application_worker_unavailable"||n.problem==="browser_unsupported"||n.problem==="application_storage_unavailable")return{kind:"unavailable",problem:Ws(n.problem,t)};if(i?.state==="invalid")return{kind:"problem",collectionId:null,problem:Ws(i.problem??"application_selection_invalid",t)};let s=n.signIn?.state==="paired";if(i?.state==="approving"||n.status==="authorizing"){let l=i?.approval??null;return s?l?.kind==="add"?{kind:"authorizing",purpose:"add",collectionId:null}:{kind:"authorizing",purpose:"approve",collectionId:l?.collectionId??o?.collectionId??null}:{kind:"authorizing",purpose:"sign_in",collectionId:l?.collectionId??o?.collectionId??null}}if(n.status==="not_started"||n.status==="starting"){let l=o?.collectionId??null;return l&&n.status==="starting"?{kind:"opening",collectionId:l,displayName:o?.displayName??null,slow:!!e.slow}:{kind:"starting"}}if(n.status==="signed_out")return{kind:"signed_out",notice:n.problem?gu(n,t):null};if(n.status==="blocked"){let l=n.selectedCollectionId??o?.collectionId??null;return n.problem==="recovery_account_mismatch"?{kind:"problem",collectionId:l,problem:Lo(n,{cpOrigin:t,recoveryAccountLabel:n.recoveryAccountLabel})}:{kind:"problem",collectionId:l,problem:l&&n.removedScopeIds?.includes(l)?Ws("installation_scope_removed",t):gu(n,t)??Ws("open_failed",t)}}if(i?.state==="approval_required"&&o?.collectionId&&n.removedScopeIds?.includes(o.collectionId))return{kind:"problem",collectionId:o.collectionId,problem:Ws("installation_scope_removed",t)};if(i?.state==="approval_required"&&o?.collectionId)return{kind:"needs_approval",collectionId:o.collectionId,displayName:o.displayName,declined:i.problem==="application_selection_not_approved"};if(i?.state==="pending"&&o?.collectionId)return{kind:"opening",collectionId:o.collectionId,displayName:o.displayName,slow:!!e.slow};let r=i?.usable??(n.status==="ready"||n.status==="setup_required"?n.collections.find(l=>l.collectionId===n.selectedCollectionId)??null:null);if(n.status==="setup_required"&&r)return n.readiness.assessment?.status==="incompatible"?{kind:"problem",collectionId:r.collectionId,problem:gu(n.readiness,t)??Ws("incompatible",t)}:{kind:"needs_setup",collectionId:r.collectionId,collection:r};if(n.status==="ready"&&r&&fk(e.connection,r.collectionId))return{kind:"ready",collectionId:r.collectionId,collection:r,connection:e.connection,rechecking:n.readiness.checking,problem:null,unavailableTypes:n.readiness.assessment?.unavailableTypes??[]};let a=n.status==="opening"||n.status==="ready"||i?.state==="opening"||i?.state==="usable",p=n.selectedCollectionId??o?.collectionId??null;if(a&&p){let l=n.collections.find(c=>c.collectionId===p)?.displayName??o?.displayName??null;return{kind:"opening",collectionId:p,displayName:l,slow:!!e.slow}}return{kind:"choosing",lastApproval:i?.lastApproval??null}}function qR(n,e,t){let i=t.previous;return i?.kind==="needs_setup"&&n.kind==="opening"&&n.collectionId===i.collectionId&&e.selectedCollectionId===i.collectionId&&e.readiness.checking?i:!i||i.kind!=="ready"||n.kind==="ready"||!fk(t.connection,i.collectionId)||e.selectedCollectionId!==i.collectionId?n:n.kind==="opening"&&n.collectionId===i.collectionId?{...i,connection:t.connection,rechecking:!0,problem:null}:n.kind==="problem"&&n.problem.transient?{...i,connection:t.connection,rechecking:!0,problem:n.problem}:n}function hk(n,e){return n?.kind==="ready"&&(e===void 0||n.collectionId===e)}Ea();nc();Jn();If();Ia();bt();var cq=["http","https","file","javascript","data","blob","about","capacitor","chrome-extension","moz-extension"];function PP(n,e,t){if(typeof n!="string"||!n||n.length>2048||n.includes("*"))return!1;let i=e&&typeof e=="object"?e.redirect_uris:void 0;if(!Array.isArray(i)||!i.includes(n))return!1;let{id:o,homepage:s,platform:r}=e,a;try{a=new URL(n)}catch{return!1}if(a.username||a.password||a.hash)return!1;if(a.protocol==="https:"||a.protocol==="http:"){let l;try{l=new URL(String(s))}catch{return!1}return a.origin===l.origin&&(a.protocol==="https:"||r==="native"&&mr(a.origin)||t&&ot(a.origin))}let p=a.protocol.slice(0,-1);return typeof o=="string"&&p.includes(".")&&/^[a-z][a-z0-9+.-]*$/.test(p)&&!cq.includes(p)&&(p===o||p.startsWith(`${o}.`))&&a.hostname.length>0}Tf();Qr();Jn();ie();Of();bt();var Bo={runtime:{sha256:"c30e2e23c1fbc6642936996b8495133ce66e87caaf49a99050fc38f8a7422667",bytes:3803805,maxBytes:3803805,source:{repository:"mdbase-dev/mdbase-connect",commit:"81462447473808e040d3b31d15ede54e987ffa1e"}},sqlite:{sha256:"2ee8f3dab694532afc8840e07703127287662d08b74e6ff50491ce63f00d5752",bytes:868907,maxBytes:11e5,initializer:{sha256:"a6d3fe46aa3f924e7686329f97b0564549ef1f787e0c19924179aef7f72bcc01",bytes:642742},asyncProxy:{sha256:"9f1970e05ee07a79332498858740b705eeb1dcee03bc150f6f690bc0fb5f0a06",bytes:32505}}};var Mf={},mq=Object.freeze({sha256:Bo.runtime.sha256,bytes:Bo.runtime.bytes,maxBytes:Bo.runtime.maxBytes}),yq=Object.freeze({sha256:Bo.sqlite.sha256,bytes:Bo.sqlite.bytes,maxBytes:Bo.sqlite.maxBytes}),zc=()=>A("unavailable","SDK packaged application assets unavailable","application_packaged_assets_unavailable");function qP(n,e,t){if(!Oa(n))throw zc();let i=zo();Xn({environment:n,appOrigin:e,platform:t,release:i});let o,s;try{let p=new URL(Mf.url);if(Cn(p)!==e||p.username||p.password||p.search||p.hash||(o=new URL("../native/runtime.wasm",Mf.url),s=new URL("../native/sqlite3.wasm",Mf.url),Cn(o)!==e||Cn(s)!==e))throw zc()}catch{throw zc()}let r=(p,l)=>Object.freeze({url:p.href,...l}),a=async p=>{let l=globalThis.WorkerGlobalScope;if(typeof l!="function"||!(globalThis instanceof l))throw zc();let c=new URL("../native/sqlite3.js",Mf.url),{default:d}=await import(c.href);return globalThis.sqlite3ApiConfig={disable:{vfs:{opfs:!0,"opfs-wl":!0}}},d(p)};return Object.freeze({release:()=>zo(),runtime:r(o,mq),sqlite:r(s,yq),initializeSqlite:a})}Of();bt();Qr();Jn();var Vt=class extends Error{constructor(t){super("SDK collection selection unavailable");this.code=t;this.name="ApplicationSelectionError"}code},Bc=n=>typeof n=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n)&&n!=="00000000-0000-0000-0000-000000000000",Ft=(n,e,t=null)=>Object.freeze({requestedCollectionId:n,source:e,problem:t});function TP(n,e){return n.source!=="none"?n:e.storedId!==void 0&&e.storedId!==null?Bc(e.storedId)?Ft(e.storedId,"stored"):Ft(null,"stored","application_selection_invalid"):e.collections.length>1024||e.collections.some(t=>!Bc(t.collectionId))||new Set(e.collections.map(t=>t.collectionId)).size!==e.collections.length?Ft(null,"none","application_selection_metadata"):e.preferredId!==void 0&&e.preferredId!==null?Bc(e.preferredId)&&e.collections.some(t=>t.collectionId===e.preferredId)?Ft(e.preferredId,"preferred"):Ft(null,"preferred","application_selection_metadata"):e.collections.length===1?Ft(e.collections[0].collectionId,"sole"):Ft(null,"none")}var Lf=class{port;origin;parameter;fallback;listeners=new Set;snapshot=Ft(null,"none");stopListening=null;started=!1;closed=!1;constructor(e,t={},i=null){let o,s;try{o=new URL(e),s=new URL(t.fallbackPath??"/",o)}catch{throw new Vt("application_selection_binding")}let r=t.parameter??"collection";if(!Lt(e,!0)||Cn(o)!==e||Cn(s)!==e||s.username||s.password||s.search||s.hash||typeof r!="string"||!/^[a-z][a-zA-Z0-9_.-]{0,63}$/.test(r)||["code","state","error","error_description"].includes(r))throw new Vt("application_selection_binding");this.origin=e,this.parameter=r,this.fallback=s.href,this.port=i}getSnapshot(){return this.snapshot}subscribe(e){return this.check(),this.listeners.add(e),()=>{this.listeners.delete(e)}}start(){return this.check(),this.started?this.snapshot:(this.started=!0,this.stopListening=this.port?.listen(()=>{this.closed||this.publish(this.read())})??null,this.publish(this.read()),this.snapshot)}check(){if(this.closed)throw new Vt("application_selection_fenced")}url(){let e;try{e=new URL(this.port.href())}catch{throw new Vt("application_selection_binding")}if(Cn(e)!==this.origin||e.username||e.password)throw new Vt("application_selection_binding");return e}read(){if(!this.port)return Ft(null,"none");let e;try{e=this.url().searchParams.getAll(this.parameter)}catch{return Ft(null,"url","application_selection_binding")}return e.length===0?Ft(null,"none"):e.length!==1?Ft(null,"url","application_selection_duplicate"):e[0]===""?Ft(null,"url","application_selection_empty"):Bc(e[0])?Ft(e[0],"url"):Ft(null,"url","application_selection_invalid")}publish(e){if(!(this.snapshot.requestedCollectionId===e.requestedCollectionId&&this.snapshot.source===e.source&&this.snapshot.problem===e.problem)){this.snapshot=e;for(let t of[...this.listeners])try{t()}catch{}}}select(e,t={}){if(this.check(),e!==null&&!Bc(e))throw new Vt("application_selection_invalid");let i=t.history??"replace";if(i!=="push"&&i!=="replace")throw new Vt("application_selection_binding");if(this.port){let o=this.url(),s=o.href;e===null?o.searchParams.delete(this.parameter):o.searchParams.set(this.parameter,e),o.href!==s&&this.port.write(o.href,i)}return this.publish(Ft(e,e===null?"none":"user")),this.snapshot}returnUrl(e){this.check();try{let t=new URL(e,this.origin);if(Cn(t)===this.origin&&!t.username&&!t.password)return t.href}catch{}return this.fallback}close(){if(this.closed)return;this.closed=!0;let e=this.stopListening;this.stopListening=null,e?.(),this.listeners.clear()}};function MP(){if(typeof window>"u"||!window.location||!window.history)return null;let n=window;return Object.freeze({href:()=>n.location.href,write:(e,t)=>{t==="push"?n.history.pushState(n.history.state,"",e):n.history.replaceState(n.history.state,"",e)},listen:e=>(n.addEventListener("popstate",e),()=>n.removeEventListener("popstate",e))})}var gq=n=>typeof n=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n)&&n!=="00000000-0000-0000-0000-000000000000",qa=n=>n.status==="ready"||n.status==="setup_required",LP=n=>n.signIn?.state==="paired"&&(n.status==="unselected"||n.status==="blocked"||qa(n)),bq=n=>n.status==="not_started"||n.status==="starting"||n.status==="signed_out"||n.status==="authorizing",Fi=(n,e)=>e===null?null:n.collections.find(t=>t.collectionId===e)??null,jf=class{browser;session;memory;preferredId;schedule;listeners=new Set;stops=[];value;key="";startTarget=null;startApplied=!1;attempted=void 0;lastRequested=null;opening=null;approval=null;lastApproval=null;declined=null;remembered=void 0;queued=!1;started=!1;closed=!1;constructor(e){this.browser=e.browser,this.session=e.session,this.memory=e.memory??null,this.preferredId=e.preferredId??null,this.schedule=e.schedule??(t=>{setTimeout(t,0)}),this.value=this.derive(),this.key=JSON.stringify(this.value)}getSnapshot(){return this.value}subscribe(e){return this.check(),this.listeners.add(e),()=>{this.listeners.delete(e)}}start(){return this.check(),this.started?this.value:(this.started=!0,this.browser.start(),this.stops.push(this.browser.subscribe(this.changed),this.session.subscribe(this.changed)),this.changed(),this.value)}select(e,t={}){this.check(),this.startTarget=null,this.browser.select(e,t.history?{history:t.history}:{}),this.declined=null,this.refresh(),e===null&&this.remember(null);let i=this.session.getSnapshot();return e!==null&&i.selectedCollectionId===e&&i.status==="opening"?(this.attempted=e,Promise.resolve(this.value)):this.whenIdle(async()=>{let o=this.session.getSnapshot();this.requested().requestedCollectionId===e&&((e===null?o.selectedCollectionId===null&&o.status!=="opening":o.selectedCollectionId===e&&qa(o)||!Fi(o,e))||await this.run(e,t,!0))}).then(()=>this.value)}chooseAnother(e={}){return this.select(null,{...e,history:"push"})}approve(e,t={}){if(this.check(),e!=null&&!gq(e))return Promise.reject(new Vt("application_selection_invalid"));if(this.approval&&!this.approval.settled)return Promise.reject(new Vt("application_selection_busy"));e!=null&&e!==this.requested().requestedCollectionId&&(this.startTarget=null,this.browser.select(e,t.history?{history:t.history}:{}));let i=this.session.getSnapshot().signIn,o=i?.nativeSelection?.requestId??i?.collectionSelection?.requestId??null,s,r=e===null?null:this.requested().requestedCollectionId;try{s=this.session.authorize({...t.signal?{signal:t.signal}:{},collectionHint:r})}catch(c){return Promise.reject(c)}let a=r===null?"add":"collection",p=new Set(this.session.getSnapshot().collections.map(c=>c.collectionId)),l={receipt:o,kind:a,collectionId:r,before:p,settled:!1};return this.approval=l,this.lastApproval=null,this.declined=null,this.attempted=void 0,this.refresh(),s.then(()=>(l.settled=!0,this.changed(),this.value),c=>{if(this.approval===l){this.approval=null;let d=c?.code;(d==="cancelled"||d==="aborted")&&(this.lastApproval=Object.freeze({kind:a,outcome:"closed",collectionId:r}))}throw this.changed(),c})}clearLastApproval(){this.check(),this.lastApproval=null,this.refresh()}reauthorize(e={}){this.check();let t=this.value.usable?.collectionId??this.requested().requestedCollectionId;return t===null?Promise.reject(new Vt("application_selection_empty")):this.approve(t,e)}resync(){this.closed||(this.attempted=void 0,this.approval=null,this.changed())}close(){if(!this.closed){this.closed=!0;for(let e of this.stops.splice(0))try{e()}catch{}this.browser.close(),this.listeners.clear()}}check(){if(this.closed)throw new Vt("application_selection_fenced")}requested(){let e=this.browser.getSnapshot(),t=this.startTarget;return t&&e.source==="user"&&e.requestedCollectionId===t.requestedCollectionId?t:e}changed=()=>{this.closed||(this.refresh(),!(this.queued||!this.started)&&(this.queued=!0,this.schedule(()=>{this.queued=!1,this.reconcile()})))};refresh(){let e=this.requested().requestedCollectionId;e!==this.lastRequested&&(this.lastRequested=e,this.attempted=void 0,this.declined!==e&&(this.declined=null));let t=this.derive(),i=JSON.stringify(t);if(t.state==="usable"&&this.remember(t.usable.collectionId),i!==this.key){this.key=i,this.value=Object.freeze(t);for(let o of[...this.listeners])try{o()}catch{}}}remember(e){if(!(!this.memory||this.remembered===e)){this.remembered=e;try{this.memory.write(e)}catch{}}}derive(){let e=this.session.getSnapshot(),t=this.requested(),i=t.requestedCollectionId,o=Fi(e,i),s=qa(e)?Fi(e,e.selectedCollectionId):null,r,a=null;t.problem?(r="invalid",a=t.problem):this.approval?r="approving":i===null?r="none":s?.collectionId===i?r="usable":e.selectedCollectionId===i&&(e.status==="blocked"||e.status==="opening")?r=e.status==="blocked"?"blocked":"opening":LP(e)?o?r="opening":this.session.listing?.()?r="pending":(r="approval_required",this.declined===i&&(a="application_selection_not_approved")):r="pending";let p=this.approval?Object.freeze({kind:this.approval.kind,collectionId:this.approval.collectionId,reopenable:this.approval.settled}):null;return Object.freeze({state:r,problem:a,approval:p,lastApproval:this.lastApproval,usable:s?Object.freeze({...s}):null,requested:Object.freeze({collectionId:i,source:t.source,displayName:o?.displayName??null,approved:o!==null})})}async whenIdle(e){for(;this.opening;)await this.opening;this.check(),await e()}run(e,t={},i=!1){this.attempted=e;let o=t.signal?{signal:t.signal}:{},s=Promise.resolve().then(()=>e===null?this.session.clear(o):this.session.open(e,o)),r=s.then(()=>{},()=>{}).finally(()=>{this.opening===r&&(this.opening=null,this.changed())});return this.opening=r,i?s.then(()=>{}):r}async reconcile(){if(this.closed||this.opening)return;let e=this.session.getSnapshot();if(this.approval)if(this.approval.settled&&e.status==="signed_out"&&e.problem!==null){let o=this.approval;this.approval=null,this.attempted=void 0,this.lastApproval=Object.freeze({kind:o.kind,outcome:e.problem==="approval_window_closed"?"closed":"declined",collectionId:o.collectionId}),this.refresh()}else{if(!this.approval.settled||bq(e))return;let o=e.signIn?.nativeSelection;if(o&&o.requestId!==this.approval.receipt&&!Fi(e,o.collectionId)&&this.session.listing?.())return;this.finishApproval(e)}if(!LP(e))return;if(!this.startApplied)if(this.browser.getSnapshot().source==="none"){let o=null;try{o=this.memory?.read()??null}catch{}if(o!==null&&!Fi(e,o)&&this.session.listing?.())return;this.startApplied=!0;let s=TP(this.browser.getSnapshot(),{storedId:o,preferredId:this.preferredId,collections:e.collections});s.requestedCollectionId!==null&&!s.problem&&(this.browser.select(s.requestedCollectionId,{history:"replace"}),this.startTarget=s,this.refresh())}else this.startApplied=!0;let t=this.requested(),i=t.requestedCollectionId;if(!t.problem){if(i===null){this.attempted!==null&&e.selectedCollectionId!==null&&qa(e)&&this.run(null);return}if(e.selectedCollectionId===i&&(qa(e)||e.status==="opening")){this.attempted=i;return}!Fi(e,i)||this.attempted===i||this.run(i)}}finishApproval(e){let t=this.approval,i=t.receipt;this.approval=null,this.attempted=void 0;let o=u=>u!==null&&Fi(e,u)?t.before.has(u)?"unchanged":"added":e.approval?.outcome==="closed"?"closed":"declined",s=e.signIn?.collectionSelection,r=e.signIn?.nativeSelection,p=(r&&r.requestId!==i&&Fi(e,r.collectionId)?r.collectionId:null)??(s&&s.requestId!==i&&Fi(e,s.selectedCollectionId)?s.selectedCollectionId:null);if(p!==null){p!==this.requested().requestedCollectionId&&(this.startTarget=null,this.browser.select(p,{history:"replace"})),this.lastApproval=Object.freeze({kind:t.kind,outcome:o(p),collectionId:p}),this.refresh(),e.selectedCollectionId===p&&(qa(e)||e.status==="opening")?this.attempted=p:this.run(p);return}let l=this.requested().requestedCollectionId;l!==null&&!Fi(e,l)&&(this.declined=l);let c=t.kind==="add"?e.collections.find(u=>!t.before.has(u.collectionId))?.collectionId??null:null,d=t.kind==="add"?c:t.collectionId??l;this.lastApproval=Object.freeze({kind:t.kind,outcome:o(d),collectionId:d}),this.refresh()}};Yf();Vb();ie();th();cu();eo();vu();var vx="mdbn-app-tabs/1",Kb="\0mdbn-port";var ep=n=>typeof n=="string"&&/^[0-9a-f-]{36}$/.test(n);function Nq(n){if(!n||typeof n!="object")return null;let e=n;switch(e.k){case"join":case"leave":return ep(e.tab)?e:null;case"leader":case"bye":case"fault":case"signedOut":case"signedIn":return ep(e.leader)?e:null;case"joined":return ep(e.tab)&&ep(e.leader)&&typeof e.binding=="string"?e:null;case"m":return ep(e.tab)&&typeof e.up=="boolean"&&Number.isSafeInteger(e.s)&&e.s>=0?e:null;default:return null}}function Wb(n){if(!n||typeof n!="object")return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function Hb(n,e,t=0){return n instanceof MessagePort?{[Kb]:e(n)}:t>=6?n:Array.isArray(n)?n.map(i=>Hb(i,e,t+1)):Wb(n)?Object.fromEntries(Object.entries(n).map(([i,o])=>[i,Hb(o,e,t+1)])):n}function Gb(n,e,t,i=0){if(Wb(n)&&Object.keys(n).length===1&&Number.isSafeInteger(n[Kb])){let o=e(n[Kb]);return t.push(o),o}return i>=6?n:Array.isArray(n)?n.map(o=>Gb(o,e,t,i+1)):Wb(n)?Object.fromEntries(Object.entries(n).map(([o,s])=>[o,Gb(s,e,t,i+1)])):n}var nh=class{constructor(e,t){this.send=e;this.up=t;this.next=t?1:2}send;up;streams=new Map;next;bridge(e,t){this.streams.set(t,e),e.onmessage=i=>{let o=i.ports.length?Hb(i.data,s=>{let r=this.next;return this.next+=2,this.bridge(s,r),r}):i.data;try{this.send(t,o)}catch{}}}deliver(e,t){let i=this.streams.get(e);if(!i)return;let o=[],s=Gb(t,r=>{let a=new MessageChannel;return this.bridge(a.port1,r),a.port2},o);try{i.postMessage(s,o)}catch{for(let r of o)r.close()}}close(){for(let e of this.streams.values()){e.onmessage=null;try{e.close()}catch{}}this.streams.clear()}},ih=class{constructor(e,t,i,o=()=>{}){this.env=t;this.lost=i;this.signedInElsewhere=o;this.base=e.storageNamespace===void 0?`${vx}/${e.cpOrigin}/${e.appId}/${e.build}`:`${vx}/namespace/${JSON.stringify([e.cpOrigin,e.appId,e.build,e.storageNamespace])}`}env;lost;signedInElsewhere;tab=crypto.randomUUID();base;channel=null;presence=null;leading=null;hub=null;follower=null;signingOut=!1;announced=!1;joining=null;get leader(){return this.leading!==null}open(){if(this.channel)return this.channel;let e=new this.env.BroadcastChannel(this.base);return e.onmessage=t=>this.received(Nq(t.data)),this.channel=e,e}post(e){this.channel?.postMessage(e)}hold(e,t,i){return new Promise((o,s)=>{let r=p=>{if(!p){o(null);return}return new Promise(l=>o(l))};(t?this.env.locks.request(e,{ifAvailable:!0},r):this.env.locks.request(e,{signal:i},r)).catch(s)})}async elect(e){if(e.throwIfAborted(),this.open(),this.presence??=await this.hold(`${this.base}/tab/${this.tab}`,!0),e.throwIfAborted(),this.leading||(this.leading=await this.hold(`${this.base}/leader`,!0)),this.leading)return e.aborted&&(this.resign(),e.throwIfAborted()),{kind:"leader"};let t=new AbortController,i=()=>t.abort();e.addEventListener("abort",i,{once:!0});let o=this.hold(`${this.base}/leader`,!1,t.signal),s;try{s=await new Promise((c,d)=>{o.then(u=>{u&&c({release:u})},()=>{}),this.joining={resolve:c,reject:d},e.addEventListener("abort",()=>d(e.reason),{once:!0}),this.post({k:"join",tab:this.tab})})}catch(c){throw this.joining=null,t.abort(),c}finally{e.removeEventListener("abort",i)}if(this.joining=null,"release"in s)return this.leading=s.release,e.aborted&&(this.resign(),e.throwIfAborted()),{kind:"leader"};e.aborted&&(t.abort(),e.throwIfAborted());let r=new MessageChannel,a=this.tab,p=new nh((c,d)=>this.post({k:"m",tab:a,up:!0,s:c,d}),!0);p.bridge(r.port2,0);let l={leader:s.leader,tunnel:p,wait:t,port:r.port1,left:!1,signedOut:!1};return this.follower=l,o.then(c=>{if(c){if(this.follower!==l||l.left){c();return}this.leading=c,this.departed(l)}},()=>{}),{kind:"follower",port:r.port1,binding:s.binding,leave:()=>this.leave(l)}}lead(e){!this.leading||this.hub||(this.hub={followers:new Map,worker:e,faulted:!1},this.post({k:"leader",leader:this.tab}))}fault(){!this.hub||this.hub.faulted||(this.hub.faulted=!0,this.post({k:"fault",leader:this.tab}))}signedOut(){this.hub&&(this.signingOut=!0,this.post({k:"signedOut",leader:this.tab}))}signedIn(){!this.hub||this.announced||this.signingOut||(this.announced=!0,this.post({k:"signedIn",leader:this.tab}))}resign(){let e=this.hub,t=this.signingOut;this.hub=null,this.signingOut=!1,this.announced=!1,e&&this.post({k:"bye",leader:this.tab,...t?{signedOut:!0}:{}});let i=this.leading;if(this.leading=null,i?.(),e){for(let o of e.followers.values())o.watch.abort(),o.tunnel.close();e.followers.clear()}}leave(e){e.left||(e.left=!0,e.wait.abort(),e.tunnel.close(),this.follower===e&&(this.follower=null,this.post({k:"leave",tab:this.tab})))}departed(e,t=!1){e.left||this.follower!==e||(e.left=!0,e.wait.abort(),e.tunnel.close(),this.follower=null,this.lost(t||e.signedOut))}release(){this.joining?.reject(new DOMException("released","AbortError")),this.joining=null,this.follower&&this.leave(this.follower),this.resign();let e=this.presence;this.presence=null,e?.(),this.channel&&(this.channel.onmessage=null,this.channel.close(),this.channel=null)}received(e){if(!e)return;let t=this.hub,i=this.follower;switch(e.k){case"join":{if(!t||t.followers.has(e.tab)||e.tab===this.tab)return;let o=crypto.randomUUID(),s=new MessageChannel,r=e.tab,a=new nh((l,c)=>this.post({k:"m",tab:r,up:!1,s:l,d:c}),!1);a.bridge(s.port1,0);let p=new AbortController;t.followers.set(r,{binding:o,tunnel:a,watch:p});try{t.worker.attach(s.port2,o)}catch{t.followers.delete(r),a.close();return}this.post({k:"joined",tab:r,binding:o,leader:this.tab}),t.faulted&&this.post({k:"fault",leader:this.tab}),this.hold(`${this.base}/tab/${r}`,!1,p.signal).then(l=>{l?.(),this.drop(t,r)},()=>{});return}case"leave":t&&this.drop(t,e.tab);return;case"joined":if(e.tab===this.tab&&this.joining){let o=this.joining;this.joining=null,o.resolve({binding:e.binding,leader:e.leader})}return;case"leader":this.joining&&this.post({k:"join",tab:this.tab});return;case"bye":i&&i.leader===e.leader&&this.departed(i,e.signedOut===!0);return;case"signedOut":i&&i.leader===e.leader&&(i.signedOut=!0);return;case"signedIn":!t&&!i&&!this.joining&&e.leader!==this.tab&&this.signedInElsewhere();return;case"fault":i&&!i.left&&i.leader===e.leader&&i.port.dispatchEvent(new MessageEvent("messageerror"));return;case"m":e.up&&t?t.followers.get(e.tab)?.tunnel.deliver(e.s,e.d):!e.up&&i&&e.tab===this.tab&&i.tunnel.deliver(e.s,e.d);return}}drop(e,t){let i=e.followers.get(t);if(i){e.followers.delete(t),i.watch.abort(),i.tunnel.close();try{e.worker.detach(i.binding)}catch{}}}};function Vi(n){try{return n()}catch{return}}function Uq(){let n=Vi(()=>globalThis.crypto?.subtle),e=Vi(()=>globalThis.navigator?.storage),t=Vi(()=>typeof e?.getDirectory=="function"?()=>e.getDirectory.call(e):void 0);return{subtle:n,abortSignalAny:Vi(()=>typeof AbortSignal=="function"&&typeof AbortSignal.any=="function")===!0,randomUUID:Vi(()=>typeof globalThis.crypto?.randomUUID=="function")===!0,worker:Vi(()=>typeof Worker=="function")===!0,messageChannel:Vi(()=>typeof MessageChannel=="function")===!0,locks:Vi(()=>typeof globalThis.navigator?.locks?.request=="function")===!0,broadcastChannel:Vi(()=>typeof BroadcastChannel=="function")===!0,indexedDB:Vi(()=>typeof globalThis.indexedDB<"u")===!0,getDirectory:t}}async function _x(n=Uq()){let e=[];if(n.subtle||e.push("web_crypto"),n.abortSignalAny||e.push("abort_signal_any"),n.randomUUID||e.push("random_uuid"),n.worker||e.push("worker"),n.messageChannel||e.push("message_channel"),n.locks||e.push("web_locks"),n.broadcastChannel||e.push("broadcast_channel"),n.indexedDB||e.push("indexed_db"),n.subtle)try{await n.subtle.generateKey({name:"X25519"},!1,["deriveBits"])}catch{e.push("x25519")}if(e.length)return{ok:!1,problem:"browser_unsupported",missing:Object.freeze(e)};if(typeof n.getDirectory!="function")return{ok:!1,problem:"application_storage_unavailable",missing:Object.freeze(["opfs"])};try{await n.getDirectory()}catch{return{ok:!1,problem:"application_storage_unavailable",missing:Object.freeze(["opfs"])}}return{ok:!0}}function rh(n,e,t={pendingForMs:0,connection:"online"}){if(!Number.isSafeInteger(n)||n<0)throw new RangeError("invalid unsynced count");return n===0?{kind:"no_pending_edits",unsynced:0,warning:null}:{kind:"not_yet_synced",unsynced:n,warning:!e.persistent&&(t.pendingForMs>=3e4||t.connection==="offline")?"storage_may_be_evicted":null}}function Ax(n){switch(n){case"pending":return"not_yet_synced";case"confirmed":return"saved";case"rejected":return"rejected";case"unknown":return"outcome_unknown";default:throw new RangeError("invalid receipt state")}}var kx="Some changes are only on this device. Stay online so they can sync.";async function oh(n,e,t=!1){let i=!1;try{i=await n?.persisted()===!0,!i&&t&&(i=await n?.persist?.()===!0)}catch{}return{persistent:i,installed:e}}ah();var xx=Object.freeze(new Set);function Cx(n,e){let t=`mdbase.${n}.forgotten-collections.v1.${encodeURIComponent(e)}`,i=()=>{try{return globalThis.localStorage??null}catch{return null}},o=null,s=()=>{let a=null;try{a=i()?.getItem(t)??null}catch{}if(o&&o.raw===a)return o;let p=null,l=xx;try{let c=a?JSON.parse(a):null;c?.v===1&&typeof c.account=="string"&&c.account.length<=64&&Array.isArray(c.ids)&&c.ids.length<=1024&&c.ids.every(d=>typeof d=="string"&&d.length>0&&d.length<=64)&&(p=c.account,l=Object.freeze(new Set(c.ids)))}catch{}return o={raw:a,account:p,ids:l},o},r=(a,p)=>{try{p.size?i()?.setItem(t,JSON.stringify({v:1,account:a,ids:[...p].slice(-1024)})):i()?.removeItem(t)}catch{}o=null};return Object.freeze({read(a){let p=s();return a&&p.account===a?p.ids:xx},add(a,p){let l=s(),c=new Set(l.account===a?l.ids:[]);c.has(p)||(c.add(p),r(a,c))},remove(a,p){let l=s();if(l.account!==a||!l.ids.has(p))return!1;let c=new Set(l.ids);return c.delete(p),r(a,c),!0},clear(){try{i()?.removeItem(t)}catch{}o=null}})}var Kq=new Set(["owner","editor","viewer"]),to=(n,e=512)=>typeof n=="string"&&n.length>0&&n.length<=e,Wq=new Set(["unselected","opening","setup_required","ready"]);function Ix(n){let e=n;return!e||typeof e!="object"||!to(e.collectionId,64)||typeof e.displayName!="string"||e.displayName.length>512||!Kq.has(e.role)?null:Object.freeze({collectionId:e.collectionId,displayName:e.displayName,role:e.role})}function Ox(n){let e=n;return!e||typeof e!="object"||e.state!=="paired"||!to(e.requestId,64)||!to(e.installationId,64)||!to(e.deviceId,64)||!to(e.appId,64)||e.kind!=="app-runtime"&&e.kind!=="mobile"||!to(e.verificationUri,2048)||!to(e.accountId,64)||!Array.isArray(e.collectionIds)||e.collectionIds.length>1024||!e.collectionIds.every(t=>to(t,64))?null:Object.freeze({requestId:e.requestId,installationId:e.installationId,deviceId:e.deviceId,appId:e.appId,kind:e.kind,verificationUri:e.verificationUri,state:"paired",accountId:e.accountId,...typeof e.accountEmail=="string"&&e.accountEmail.length<=320?{accountEmail:e.accountEmail}:{},collectionIds:Object.freeze([...e.collectionIds]),createCollections:e.createCollections===!0,requestedCreateCollections:e.requestedCreateCollections===!0})}function Rx(n,e){let t=`mdbase.${n}.session-hint.v1.${encodeURIComponent(e)}`,i=null,o=null,s=()=>{try{return globalThis.localStorage??null}catch{return null}},r=()=>{let p=null;try{p=s()?.getItem(t)??null}catch{return null}if(i&&i.raw===p)return i.value;let l=null;try{let c=p?JSON.parse(p):null,d=c?.v===1?Ox(c.signIn):null,u=Array.isArray(c?.collections)&&c.collections.length<=1024?c.collections.map(Ix):null;d&&u&&u.every(f=>f!==null)&&(l=Object.freeze({signIn:d,collections:Object.freeze(u)}))}catch{l=null}return i={raw:p,value:l},l},a=()=>{o=null;try{s()?.removeItem(t)}catch{}};return Object.freeze({read:r,clear:a,observe(p){if(p.status==="signed_out"&&p.signIn===null){o!==""&&(a(),o="");return}if(!Wq.has(p.status)||p.signIn?.state!=="paired")return;let l=Ox(p.signIn),c=p.collections.map(Ix);if(!l||!c.every(u=>u!==null))return;let d=JSON.stringify({v:1,signIn:l,collections:c});if(d!==o){o=d;try{s()?.setItem(t,d)}catch{}}}})}Dy();ie();function A2(n,e){return new Promise((t,i)=>{let o=()=>{clearTimeout(s),i(A("cancelled","The original collection closed."))};if(n.aborted){i(A("cancelled","The original collection closed."));return}let s=setTimeout(()=>{n.removeEventListener("abort",o),t()},e);n.addEventListener("abort",o,{once:!0})})}var k2=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,Ga=Object.freeze({checking:!1,assessment:null,problem:null}),S2=Object.freeze({capabilities:Ga,contracts:Ga,configuration:Ga,files:Ga,people:Ga,notifications:Ga}),oo=(n,e)=>{let t=e?Object.freeze({status:e,problem:e==="incompatible"?Object.freeze({code:"incompatible"}):null}):null;return Object.freeze({checking:n,assessment:t,problem:null,facets:Object.freeze({...S2,configuration:Object.freeze({checking:n,assessment:t,problem:null})})})},gh=n=>n==="approval_required"?"device_approval_required":n,P2=n=>n.state==="opening"||n.state==="unavailable"&&n.reason!=="sync_required"&&n.reason!=="access_removed"&&n.reason!=="collection_deleted",sC=n=>{if(oe(n)){let e=n.details instanceof Map?n.details.get("availability"):void 0;return typeof e=="string"?gh(e):n.reason??n.code}return"open_failed"},aC=n=>{if(!oe(n))return;let e=A0(n.details);return Object.freeze({name:"MdbaseError",code:n.code,...e?{relay:e}:{}})};function x2(n){let e=n.manifest?.redirect_uris;return(Array.isArray(e)?e.filter(i=>typeof i=="string"):[]).find(i=>{try{return new URL(i).origin===n.origin}catch{return!1}})??new URL("/",n.origin).href}function lC(n,e,t){if(n.signIn?.state!=="paired"||!e.length&&!t)return n;let i=new Set(n.collections.map(p=>p.collectionId)),o=e.filter(p=>!i.has(p.collectionId)),s=o.length?Object.freeze([...n.collections,...o]):n.collections;if(!t||n.status!=="unselected"||i.has(t.collectionId))return s===n.collections?n:Object.freeze({...n,collections:s});let{problemDetail:r,...a}=n;return Object.freeze({...a,collections:s,status:t.status,selectedCollectionId:t.collectionId,problem:t.problem,transport:null,live:null,...t.problemDetail?{problemDetail:t.problemDetail}:{},..."readiness"in n?{readiness:t.readiness}:{}})}var bh=class{options;loading=null;list=Object.freeze([]);open=null;listed=null;settled=null;refreshing=null;closed=!1;bindings=null;bindingsAccount=null;native=null;revision=0;constructor(e){this.options=e}grants(){let e=this.loading??=(this.options.grants??(async()=>{let{MdbaseAppGrants:t}=await Promise.resolve().then(()=>(oC(),rC));return new t({declaration:this.options.declaration,redirectUri:x2(this.options.declaration)})}))();return e.catch(()=>{this.loading===e&&(this.loading=null)}),e}changed(){if(!this.closed){this.revision++;try{this.options.onChange()}catch{}}}bind(e,t){let i=t.filter(o=>o.account_id===e);this.bindingsAccount===e&&JSON.stringify(i)===JSON.stringify(this.bindings)||(this.bindingsAccount=e,this.bindings=Object.freeze([...i]),this.settled=null,this.listed=null,this.setList([]))}async nativeAuthorization(e,t,i){if(e.action==="cancel")return this.native?.life.abort(),this.native?.prepared?.cancel(),this.native=null,null;if(this.closed||i.aborted)throw A("cancelled","Original Native authorization fenced");if(e.action==="prepare"){if(this.native||e.value.authorizationId)throw A("unauthenticated","Original Native preparation unavailable");let a={context:e.value,portal:t,prepared:null,life:new AbortController};this.native=a;let p=AbortSignal.any([i,a.life.signal]),l=await this.grants();if(!l.prepareAuthorization)throw A("unavailable","Native authorization unavailable");let c=btoa(String.fromCharCode(...Uint8Array.from(e.value.challenge.match(/../g),u=>parseInt(u,16)))).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,""),d=await l.prepareAuthorization({authorizationNonce:c,expectedAccountId:e.value.accountId,signal:p});if(a.prepared=d,this.native!==a||p.aborted||d.applicationId!==e.value.appId)throw d.cancel(),A("unauthenticated","Original application registration mismatch");return Object.freeze({authorizationId:d.authorizationId,applicationId:d.applicationId,manifestDigest:d.manifestDigest})}let o=this.native,s=o?.prepared;if(!o||!s||o.portal!==t||o.context.requestId!==e.value.requestId||s.authorizationId!==e.value.authorizationRequestId)throw A("unauthenticated","Original Native preparation unavailable");let r=await s.finish({popup:t,collection:e.value.collectionId,signal:AbortSignal.any([i,o.life.signal])});if(this.native!==o||i.aborted||!r.nativeCompletion)throw A("unauthenticated","Original Native completion unavailable");return r.nativeCompletion}entries(){return this.list}has(e){return this.list.some(t=>t.collectionId===e)||this.open?.id===e}state(){return this.open?.state??null}connection(e){let t=this.open;return t&&t.id===e&&t.state.status==="ready"?t.connection:null}listing(e){return!this.closed&&e!==null&&this.settled!==e}ensure(e){this.settled!==e&&!this.refreshing&&this.refresh(e).catch(()=>{})}refresh(e=this.listed){if(this.closed)return Promise.resolve();if(this.refreshing)return this.refreshing;let t=(async()=>{try{let i=await this.grants(),o=this.bindings,s=[];if(o)for(let a of o)a.account_id===e&&await i.verifiedStoredNativeGrant?.(a)&&s.push(a);let r=await i.collections(o===null?{}:{bindings:s});if(this.closed||o!==this.bindings)return;this.listed=e,this.setList(r)}finally{!this.closed&&e!==null&&this.settled!==e&&(this.settled=e,this.changed())}})().finally(()=>{this.refreshing===t&&(this.refreshing=null)});return this.refreshing=t,t}setList(e){let t=Object.freeze(e.filter(i=>k2.test(i.collectionId)).map(i=>Object.freeze({collectionId:i.collectionId,displayName:i.displayName,role:i.role??"editor",availability:i.availability,kind:"private"})));JSON.stringify(t)!==JSON.stringify(this.list)&&(this.list=t,this.changed())}setAvailability(e,t){this.list.some(i=>i.collectionId===e&&JSON.stringify(i.availability)!==JSON.stringify(t))&&(this.list=Object.freeze(this.list.map(i=>i.collectionId===e?Object.freeze({...i,availability:t}):i)),this.changed())}set(e,t){if(this.open!==e||e.life.signal.aborted)return;let{problemDetail:i,...o}=e.state,{problemDetail:s,...r}=t,a=r.problem===null?void 0:s??(r.problem===void 0?i:void 0);e.state=Object.freeze({...o,...r,...a?{problemDetail:a}:{}}),this.changed()}async openCollection(e,t){if(this.closed)throw A("cancelled","Private collections closed","application_entry_fenced");this.close(!1);let i={id:e,life:new AbortController,client:null,setup:null,connection:null,stopLink:null,state:Object.freeze({collectionId:e,status:"opening",problem:null,readiness:oo(!0,null)})};this.open=i,this.changed();let o=i.life.signal;try{let s=await this.grants(),r=this.bindings?.find(d=>d.account_id===t.account&&d.collection_id===e),a=async()=>{if(this.bindings!==null&&(!r||this.bindingsAccount!==t.account||!this.bindings.includes(r)||!await s.verifiedStoredNativeGrant?.(r)))throw A("unauthenticated","Original account-bound Native grant unavailable");if(o.aborted)throw A("cancelled","Original Native open fenced")};await a();let p=await s.availability(e,{signal:o});if(this.setAvailability(e,p),P2(p)&&(p.state==="unavailable"&&this.set(i,{status:"blocked",problem:gh(p.reason),readiness:oo(!1,null)}),p=await s.waitForAvailable(e,{signal:o,timeoutMs:this.options.waitMs??10*6e4,onAvailability:d=>{this.setAvailability(e,d),d.state==="unavailable"?this.set(i,{status:"blocked",problem:gh(d.reason)}):this.set(i,{status:"opening",problem:null,readiness:oo(!0,null)})}})),p.state!=="available"){if(p.state==="opening")throw A("unavailable","The collection is still getting ready","collection_unavailable");this.set(i,{status:"blocked",problem:gh(p.reason),readiness:oo(!1,null)});return}this.set(i,{status:"opening",problem:null}),await a();let l=await(this.options.connect??C2(this.options.declaration))(s,e,o);if(this.open!==i||o.aborted||l.collection!==e){if(l.close(),this.open===i&&!o.aborted)throw A("invalid_request","a different collection opened","collection_mismatch");return}i.client=l,i.setup=s.setup(l),i.connection=Object.freeze({id:e,displayName:this.list.find(d=>d.collectionId===e)?.displayName??"Collection",scope:Object.freeze({account:t.account,installation:t.installation,collection:e}),generation:crypto.randomUUID(),records:l,files:l.files,people:s.people(e,l),isCurrent:()=>this.open===i&&!o.aborted&&!this.closed}),await this.assessOpen(i);let c=0;i.stopLink=l.onLink((d,u)=>{u?this.set(i,{problem:sC(u),problemDetail:aC(u)}):d==="open"&&this.set(i,{problem:null});let f=++c;s.availability(e,{signal:o}).then(h=>{this.open===i&&!o.aborted&&f===c&&this.setAvailability(e,h)}).catch(()=>{})})}catch(s){throw this.open===i&&!o.aborted&&this.set(i,{status:"blocked",problem:sC(s),problemDetail:aC(s),readiness:oo(!1,null)}),s}}async assessOpen(e){this.set(e,{readiness:oo(!0,e.state.readiness.assessment?.status??null)});let t=1e3;for(;;){if(this.open!==e||e.life.signal.aborted)throw A("cancelled","The original collection closed.");let i;try{i=await e.setup.assess({signal:e.life.signal})}catch(o){if(!oe(o)||o.code!=="rate_limited")throw o;let s=o.retryAfterMs;await A2(e.life.signal,Math.min(2147483647,Math.max(t,typeof s=="number"&&Number.isFinite(s)?s:0))),t=Math.min(3e4,t*2);continue}if(this.open!==e||e.life.signal.aborted)throw A("cancelled","The original collection closed.");return this.set(e,{status:i==="ready"?"ready":"setup_required",problem:null,readiness:oo(!1,i)}),i}}current(){let e=this.open;if(!e?.setup||e.life.signal.aborted)throw A("invalid_request","No Private collection is open","application_connection_fenced");return e}isOpen(){return this.open!==null}async assess(){let e=this.current();return await this.assessOpen(e),e.state.readiness}plan(e){return this.current().setup.plan(e)}async apply(e,t={}){let i=this.current(),o=await i.setup.apply(e,t);this.set(i,{status:o==="ready"?"ready":"setup_required",problem:null,readiness:oo(!1,o)})}async configure(e={}){let i=await this.current().setup.plan(e.signal?{signal:e.signal}:{});await this.apply(i,e)}async add(e,t,i){let o;try{o=await this.grants()}catch(r){throw e.close(),r}let s=await o.authorize({popup:e,...t?{collection:t}:{},...i?{signal:i}:{}});return await this.refresh().catch(()=>{}),s.collectionId}async forget(e){this.open?.id===e&&this.close();let t=await this.grants(),i=this.bindings?.find(o=>o.collection_id===e&&o.account_id===this.bindingsAccount);(this.bindings===null||i&&await t.verifiedStoredNativeGrant?.(i))&&await(i?t.forget(e,{expectedNoisePublicKey:i.client_noise_public_key}):t.forget(e)),this.list.some(o=>o.collectionId===e)&&(this.list=Object.freeze(this.list.filter(o=>o.collectionId!==e)),this.changed())}async forgetAll(){this.native?.life.abort(),this.native?.prepared?.cancel(),this.native=null,this.close();try{await(await this.grants()).forgetAllGrants()}finally{this.list=Object.freeze([]),this.listed=null,this.settled=null,this.changed()}}close(e=!0){let t=this.open;if(t){this.open=null,t.life.abort(),t.stopLink?.();try{t.client?.close()}catch{}e&&this.changed()}}dispose(){this.native?.life.abort(),this.native?.prepared?.cancel(),this.native=null,this.close(!1),this.closed=!0}};function C2(n){return async(e,t,i)=>{let{connect:o}=await Promise.resolve().then(()=>(Ps(),xd));return o({connector:e.connector(t),app:{name:n.id,version:"1"},signal:i})}}var Nh={};function mT(n){let e=globalThis.document;return!e||typeof e.addEventListener!="function"||e.visibilityState!=="hidden"?Promise.resolve():new Promise((t,i)=>{let o=()=>{e.visibilityState!=="hidden"&&(e.removeEventListener("visibilitychange",o),n.removeEventListener("abort",s),t())},s=()=>{e.removeEventListener("visibilitychange",o),i(n.reason)};e.addEventListener("visibilitychange",o),n.addEventListener("abort",s,{once:!0})})}var yp=class extends Error{code="application_not_yet_available";constructor(){super("MdbaseConnect application runtime is not yet available"),this.name="MdbaseApplicationUnavailableError"}},Uw=Object.freeze({code:"application_not_yet_available"}),il=Object.freeze({checking:!1,assessment:null,problem:Uw}),yT=Object.freeze({checking:!1,assessment:null,problem:Uw,facets:Object.freeze({capabilities:il,contracts:il,configuration:il,files:il,people:il,notifications:il})}),rl=Object.freeze({checking:!1,assessment:null,problem:null}),jh=Object.freeze({checking:!1,assessment:null,problem:null,facets:Object.freeze({capabilities:rl,contracts:rl,configuration:rl,files:rl,people:rl,notifications:rl})}),Nw=()=>new yp,aI=Object.freeze({state:"none",problem:null,usable:null,requested:Object.freeze({collectionId:null,source:"none",displayName:null,approved:!1})});function gT(){let n={status:"blocked",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:Uw.code,timing:null,readiness:yT,selection:aI},e=Object.freeze({...n,phase:ic(n),sync:null,writes:null,links:null}),t=()=>Promise.reject(Nw());return Object.freeze({getSnapshot:()=>e,subscribe:()=>()=>{},start:t,authorize:t,select:t,approve:t,reauthorize:t,refreshCollectionList:t,requestAccess:t,chooseAnother:t,assess:t,configure:t,setup:Object.freeze({plan:t,apply:t}),clearSelection:t,forget:t,deleteCollection:t,setForeground(){throw Nw()},close:t,signOut:t})}var bT=n=>typeof Worker=="function"&&typeof MessageChannel=="function"&&Rt()!==null&&Lt(n,!0);function wT(n,e){if(n===void 0)return null;let t=()=>{throw A("invalid_request","Invalid sign-in opener","application_sign_in_opener")};if(!n||typeof n!="object"||typeof n.open!="function"||n.close!==void 0&&typeof n.close!="function")return t();let i=n.returnUrl;i!==void 0&&(PP(i,e.manifest,Qt(e.environment))||t());let o=n.open.bind(n),s=n.close?.bind(n);return Object.freeze({open:o,...s?{close:s}:{},...i!==void 0?{returnUrl:i}:{}})}async function vT(n){let e=!0;if(n.webPush){let t=globalThis.navigator?.serviceWorker,i;t&&typeof t.getRegistration=="function"&&(e=await Promise.race([(async()=>{let o=await(await t.getRegistration())?.pushManager?.getSubscription();return o?await o.unsubscribe():!0})().catch(()=>!1),new Promise(o=>{i=setTimeout(()=>o(!1),5e3)})]).finally(()=>clearTimeout(i)))}try{n.server==="incomplete"&&console.warn("mdbase: signed out on this device, but mdbase could not be reached to end the session. This device stays listed under the account until it is removed there."),(n.local==="incomplete"||!e)&&console.warn("mdbase: signed out, but some local data on this device could not be removed.")}catch{}}function _T(n){let e=`mdbase.${n}.selected-collection.v1`;return Object.freeze({read:()=>{try{return globalThis.localStorage?.getItem(e)??null}catch{return null}},write:t=>{try{t===null?globalThis.localStorage?.removeItem(e):globalThis.localStorage?.setItem(e,t)}catch{}}})}var ol=class{app;declaration;compiled;lifetime=new AbortController;listeners=new Set;nativeListeners=new Set;selection=null;memory=null;runtime=null;initialization=null;closing=null;closed=!1;foreground=!0;incarnation=0;hidden=null;tabs=null;election=null;signingOut=!1;snapshot=Object.freeze({status:"not_started",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:null,timing:null,readiness:jh});composed=null;hint=null;forgotten=null;handledApproval=null;refreshing=null;refreshedAt=0;approvalPortal=null;revision=0;links=null;cpOrigin=null;opening=null;syncing=null;storagePolicy=null;pendingSave=null;signIn;typeIssues;privates=null;overlaid=new WeakMap;constructor(e,t={}){this.declaration=yr(e),this.compiled=Zr(this.declaration);let i=t.readiness?.typeIssues??"block";if(i!=="block"&&i!=="degrade")throw new TypeError('readiness.typeIssues must be "block" or "degrade"');if(this.typeIssues=i,this.signIn=wT(t.signIn,this.declaration),!bT(this.declaration.origin)){this.app=gT();return}try{let s=this.environment().cpOrigin;this.cpOrigin=s,this.hint=Rx(this.declaration.storage.applicationNamespace,s),this.forgotten=Cx(this.declaration.storage.applicationNamespace,s),this.links=Object.freeze({account:`${s}/account`,manageAccess:`${s}/account/applications`})}catch{}t.followVisibility!==!1&&this.followVisibility(),this.followPageLifecycle(),this.followFocus(),this.followStoragePolicy(),this.memory=_T(this.declaration.storage.applicationNamespace),t.privateCollections!==!1&&(this.privates=new bh({declaration:this.declaration,onChange:()=>{this.revision++,this.notify()}})),this.selection=new jf({browser:new Lf(this.declaration.origin,{},MP()),session:this.selectionSession(),memory:this.memory}),this.selection.subscribe(()=>{this.unforgetApproved(),this.notify(!1)});let o=()=>this.getSnapshot();this.app=Object.freeze({getSnapshot:o,subscribe:s=>(this.listeners.add(s),()=>{this.listeners.delete(s)}),start:s=>this.track(()=>this.call(async r=>{let a=r.getNativeSnapshot();a.status==="blocked"&&a.signIn&&a.selectedCollectionId===null?await r.queue(()=>r.start(s)):await this.started(r,s);let p=this.choose(),l=p.getSnapshot();l.state==="blocked"&&l.requested.approved&&l.requested.collectionId!==null&&await p.select(l.requested.collectionId,s)}).catch(r=>{let a=this.runtime?.getNativeSnapshot();if(!(r?.code==="open_in_another_tab"&&a?.status==="blocked"&&a.problem==="open_in_another_tab"))throw r})),authorize:s=>this.track(()=>this.approve(void 0,s)),approve:(s,r)=>this.track(()=>this.approve(s,r)),reauthorize:s=>this.track(()=>{let r=this.choose(),a=r.getSnapshot(),p=this.privates?.state()?.collectionId??a.usable?.collectionId??a.requested.collectionId;return p?this.approve(p,s):r.reauthorize(s)}),addPrivateCollection:s=>this.track(()=>this.approve(null,s)),refreshCollectionList:s=>this.track(()=>Promise.all([this.call(r=>r.queue(()=>r.refreshCollections(s))),this.privates?.refresh(this.account()).catch(()=>{})])),requestAccess:(s,r)=>this.requestAccess(s,r),select:(s,r)=>this.track(()=>this.choose().select(s,{...r,history:"push"})),clearSelection:s=>this.track(()=>this.choose().select(null,s)),chooseAnother:s=>this.track(()=>this.choose().chooseAnother(s)),forget:(s,r)=>this.track(async()=>{let a=this.choose(),p=this.account();if(this.privates?.has(s)){await this.privates.forget(s),a.getSnapshot().requested.collectionId===s&&await a.select(null,r);return}if(p&&this.forgotten){this.forgotten.add(p,s),this.revision++,(a.getSnapshot().requested.collectionId===s||(this.runtime?.getSnapshot()??this.snapshot).selectedCollectionId===s)&&await a.select(null,r),this.notify(!1);return}await this.call(l=>l.queue(()=>l.forget(s,r))),a.getSnapshot().requested.collectionId===s&&await a.select(null,r)}),deleteCollection:(s,r)=>this.track(async()=>{let a=this.choose(),{confirmName:p,...l}=r??{};await this.call(c=>c.queue(()=>c.deleteCollection(s,p,l))),a.getSnapshot().requested.collectionId===s&&await a.select(null,l)}),assess:s=>this.privates?.isOpen()?this.privates.assess():this.call(r=>r.queue(()=>r.assess(s))),configure:s=>this.track(()=>this.privates?.isOpen()?this.privates.configure(s):this.call(r=>r.queue(()=>r.configure(s)))),setup:Object.freeze({plan:s=>(this.privates?.isOpen()?this.privates.plan(s):this.call(r=>r.queue(()=>r.planSetup(s)))).then(r=>Px(r,this.getSnapshot().readiness)),apply:(s,r)=>this.track(()=>this.privates?.isOpen()?this.privates.apply(s,r):this.call(a=>a.queue(()=>a.applySetup(s,r))))}),setForeground:s=>this.setForeground(s),close:()=>this.close(),signOut:s=>this.signOut(s)})}withPrivate(e){let t=this.privates;if(!t)return e;let i=this.overlaid.get(e);if(i&&i.revision===t.revision)return i.value;let o=lC(e,t.entries(),t.state());return this.overlaid.set(e,{revision:t.revision,value:o}),o}getSnapshot(){let e=this.withPrivate(this.runtime?.getSnapshot()??this.snapshot),t=this.selection?.getSnapshot()??aI,i=this.composed,o=e.signIn===null&&(e.status==="starting"||e.status==="blocked"&&e.problem==="open_in_another_tab")?this.hint?.read()??null:null;if(i&&i.base===e&&i.selection===t&&i.revision===this.revision&&i.hint===o)return i.value;let s=o?Object.freeze({...e,signIn:o.signIn,collections:o.collections}):e,r=this.forgotten?.read(s.signIn?.accountId)??null,a=r?.size&&s.collections.some(m=>r.has(m.collectionId)&&m.collectionId!==s.selectedCollectionId)?Object.freeze({...s,collections:Object.freeze(s.collections.filter(m=>!r.has(m.collectionId)||m.collectionId===s.selectedCollectionId))}):s,p=a.selectedCollectionId,l=p&&!this.closed?this.privates?.connection(p)??this.runtime?.connection(p)??null:null,c=ic({...a,selection:t},{connection:l,previous:i?.value.phase??null,...this.cpOrigin?{cpOrigin:this.cpOrigin}:{}});c=this.trackOpening(c);let d=this.trackSync(c,a.problem,a.transport??null,a.live??null),u=this.syncing?.writes()??null,f=this.trackSaveWarning(),h=Object.freeze({...a,selection:t,phase:c,sync:d,writes:u,storage:this.storagePolicy,saveWarning:f,links:this.linksFor(p)});return this.composed={base:e,selection:t,revision:this.revision,hint:o,value:h},h}linksFor(e){return this.links&&e?Object.freeze({...this.links,manageAccess:`${this.cpOrigin}/access?collection=${encodeURIComponent(e)}`}):this.links}trackSaveWarning(){let e=this.syncing,t=e?.status,i=t?.pending??0;if(this.pendingSave&&(this.closed||this.hidden||!i||this.pendingSave.id!==e?.id)&&this.clearPendingSave(),this.closed||this.hidden||!e||!t||!i)return null;if(!this.pendingSave){let o={id:e.id,since:performance.now(),timer:null};o.timer=setTimeout(()=>{this.pendingSave===o&&(o.timer=null,this.revision++,this.notify(!1))},3e4),this.pendingSave=o}return rh(i,this.storagePolicy??{persistent:!1,installed:!1},{pendingForMs:performance.now()-this.pendingSave.since,connection:t.connection}).warning}clearPendingSave(){this.pendingSave?.timer!==null&&this.pendingSave?.timer!==void 0&&clearTimeout(this.pendingSave.timer),this.pendingSave=null}trackOpening(e){let t=e.kind==="opening"?e.collectionId:null;if(this.opening&&this.opening.id!==t&&(clearTimeout(this.opening.timer),this.opening=null),t===null||this.closed)return e;if(!this.opening){let i={id:t,slow:!1,timer:setTimeout(()=>{this.opening===i&&(i.slow=!0,this.revision++,this.notify(!1))},bu)};this.opening=i}return e.kind==="opening"&&this.opening.slow?{...e,slow:!0}:e}trackSync(e,t,i,o){let s=e.kind==="ready"?e.collectionId:null;if(this.syncing&&this.syncing.id!==s){try{this.syncing.stop()}catch{}this.syncing=null}if(e.kind!=="ready"||this.closed)return null;if(!this.syncing){let r=e.connection.records,a=null;try{a=r.status}catch{}let p={id:e.collectionId,stop:()=>{},status:a,writes:()=>null},l=()=>{this.syncing===p&&(this.revision++,this.getSnapshot(),this.notify(!1))},c=()=>{},d=()=>{};try{c=r.onStatus(u=>{p.status=u,l()})}catch{}try{let u=r.ledger;d=u.subscribe(l),p.writes=()=>{try{return u.getSnapshot()}catch{return null}}}catch{}p.stop=()=>{c(),d()},this.syncing=p}try{e.connection.records.setTransportDeferred(i!==null)}catch{}return this.syncing.status?eu(this.syncing.status,t,i,o):null}nativeAuthorization(e,t,i){return!this.privates||this.closed||this.hidden?Promise.reject(A("unavailable","Native authorization unavailable")):this.privates.nativeAuthorization(e,t,AbortSignal.any([i,this.lifetime.signal]))}account(){return(this.runtime?.getSnapshot()??this.snapshot).signIn?.accountId??null}unforgetApproved(){let e=this.selection?.getSnapshot().lastApproval??null,t=this.account();!e||e===this.handledApproval||(this.handledApproval=e,t&&e.collectionId&&(e.outcome==="added"||e.outcome==="unchanged")&&this.forgotten?.remove(t,e.collectionId)&&this.revision++)}followFocus(){let e=typeof window>"u"?void 0:window,t=globalThis.document;if(!e||typeof e.addEventListener!="function")return;let i=()=>{t?.visibilityState!=="hidden"&&this.refreshCollections()};e.addEventListener("focus",i,{signal:this.lifetime.signal}),t&&typeof t.addEventListener=="function"&&t.addEventListener("visibilitychange",i,{signal:this.lifetime.signal})}refreshCollections(){let e=this.runtime,t=Date.now();if(!e||this.closed||this.hidden||this.refreshing||t-this.refreshedAt<2e3)return;let i=e.getNativeSnapshot();i.signIn?.state!=="paired"||i.status!=="unselected"&&i.status!=="ready"&&i.status!=="setup_required"||(this.refreshedAt=t,this.privates?.refresh(i.signIn.accountId).catch(()=>{}),this.refreshing=e.queue(()=>e.refreshCollections()).catch(()=>{}).finally(()=>{this.refreshing=null}))}followStoragePolicy(){let e=globalThis.navigator?.storage;if(!e||typeof e.persisted!="function")return;let t=()=>{try{return globalThis.matchMedia?.("(display-mode: standalone)").matches===!0||globalThis.navigator?.standalone===!0}catch{return!1}},i=(s=!1)=>{this.closed||oh(e,t(),s).then(r=>{this.closed||this.storagePolicy?.persistent===r.persistent&&this.storagePolicy?.installed===r.installed||(this.storagePolicy=r,this.revision++,this.notify(!1))}).catch(()=>{})},o=globalThis.document;o&&typeof o.addEventListener=="function"&&o.addEventListener("visibilitychange",()=>{o.visibilityState!=="hidden"&&i()},{signal:this.lifetime.signal}),i(!0)}notify(e=!0){let t=this.runtime?.getSnapshot(),i=t?.signIn?.state==="paired"?t.signIn.accountId:null;if(i&&!this.closed&&!this.hidden&&(this.privates?.bind(i,t?.signIn?.nativeGrants??[]),this.privates?.ensure(i)),e)for(let o of[...this.nativeListeners])try{o()}catch{}for(let o of[...this.listeners])try{o()}catch{}}choose(){this.check();let e=this.selection;return e.start(),e}async track(e){return await e(),this.getSnapshot()}selectionSession(){return Object.freeze({getSnapshot:()=>this.withPrivate(this.runtime?.getNativeSnapshot()??this.snapshot),subscribe:e=>(this.nativeListeners.add(e),()=>{this.nativeListeners.delete(e)}),open:(e,t={})=>this.call(async i=>{let o=this.privates,s=i.getNativeSnapshot().collections.some(p=>p.collectionId===e);if(!o||s||!o.has(e))return o?.close(),i.queue(()=>i.select(e,t));i.getNativeSnapshot().selectedCollectionId!==null&&await i.queue(()=>i.clearSelection(t));let r=i.getNativeSnapshot().signIn?.accountId,a=i.getNativeSnapshot().signIn?.installationId;if(!r||!a)throw A("unauthenticated","Sign in before opening a collection");o.openCollection(e,{account:r,installation:a}).catch(()=>{})}),clear:(e={})=>(this.privates?.close(),this.call(t=>t.queue(()=>t.clearSelection(e)))),authorize:(e={})=>this.authorize(e,e.collectionHint??null),listing:()=>this.privates?.listing(this.account())??!1})}check(){if(this.closed||this.hidden||this.lifetime.signal.aborted)throw A("cancelled","Application entry fenced","application_entry_fenced")}environment(){return Xn({environment:this.declaration.environment,appOrigin:this.declaration.origin,platform:this.declaration.manifest.platform==="native"?"native":void 0,release:zo()})}initialize(){if(this.initialization)return this.initialization;let e=this.incarnation,t=Promise.resolve().then(async()=>{if(this.check(),typeof Nh.url!="string")throw Nw();let i=new URL(Nh.url);if(Cn(i)!==this.declaration.origin||Rt()!==this.declaration.origin)throw A("unavailable","Application module binding unavailable","application_worker_module_binding");let o=this.environment();qP(this.declaration.environment,this.declaration.origin,this.declaration.manifest.platform==="native"?"native":void 0);let s=await _x();if(this.check(),!s.ok)throw A("unavailable","This browser can't run mdbase",{reason:s.problem,details:new Map([["missing",s.missing.join(",")]])});let r=await qf({declaration:this.declaration,signal:this.lifetime.signal,isCurrent:()=>!this.closed});this.check();let{ApplicationRuntime:a}=await Promise.resolve().then(()=>(sI(),oI));if(this.check(),e!==this.incarnation)throw A("cancelled","Application entry fenced","application_entry_fenced");let p=SP(this.declaration,r);r.supersededDeclaredId&&console.info(`mdbase: ${hu("application_registration_id_superseded")}`);let l=wu(this.declaration),c=Object.freeze({cpOrigin:o.cpOrigin,appId:p.id,...l===null?{}:{storageNamespace:l}}),d=v=>(this.runtime=v,v.subscribe(()=>{this.hint?.observe(v.getNativeSnapshot()),this.observeSignOut(v),v.getNativeSnapshot().signIn?.state==="paired"&&this.tabs?.signedIn(),this.notify(),this.awaitOtherTab(v,c)}),v.setForeground(this.foreground),this.notify(),v),u=this.tabsFor(c),f=new AbortController;this.election?.abort(),this.election=f;let h=u?await u.elect(AbortSignal.any([this.lifetime.signal,f.signal])):{kind:"leader"};if(this.closed||this.hidden||e!==this.incarnation||f.signal.aborted)throw h.kind==="follower"?h.leave():u?.resign(),A("cancelled","Application entry fenced","application_entry_fenced");if(h.kind==="follower")return d(new a({declaration:p,compiledManifest:this.compiled,typeIssues:this.typeIssues,cpOrigin:o.cpOrigin,port:h.port,binding:h.binding,releaseWorker:()=>h.leave(),nativeAuthorization:(v,_,k)=>this.nativeAuthorization(v,_,k)}));let m=new MessageChannel,b=crypto.randomUUID(),w;try{w=new Worker(new URL("./worker.js",Nh.url),{type:"module"})}catch{throw u?.resign(),m.port1.close(),m.port2.close(),A("unavailable","Application Worker construction unavailable","application_worker_unavailable")}let g=v=>{v.preventDefault(),m.port1.dispatchEvent(new MessageEvent("messageerror")),u?.fault()};w.addEventListener("error",g);let y=new a({declaration:p,compiledManifest:this.compiled,typeIssues:this.typeIssues,cpOrigin:o.cpOrigin,port:m.port1,binding:b,releaseWorker:()=>{w.removeEventListener("error",g),w.terminate(),u?.resign()},nativeAuthorization:(v,_,k)=>this.nativeAuthorization(v,_,k)});try{w.postMessage([Qn,b,p,...l===null?[]:[l]],[m.port2])}catch{throw w.removeEventListener("error",g),w.terminate(),u?.resign(),m.port1.close(),m.port2.close(),A("unavailable","Application bootstrap unavailable","application_worker_binding")}return u?.lead({attach:(v,_)=>w.postMessage([Qn,b,"attach",_],[v]),detach:v=>w.postMessage([Qn,b,"detach",v])}),d(y)}).catch(i=>{let o=this.initialization===t;if(o&&(this.initialization=null),!this.closed&&o){let{problemDetail:s,...r}=this.snapshot,a=i instanceof se&&i.reason==="application_registration_refused"?Mo(i.details):null;this.snapshot=Object.freeze({...r,status:"blocked",problem:typeof i?.reason=="string"?i.reason:typeof i?.code=="string"?i.code:"application_entry_unavailable",...a?{problemDetail:Object.freeze({name:"MdbaseError",code:i.code,registration:a})}:{}}),this.notify()}throw i});this.initialization=t;{let{problemDetail:i,signOutResult:o,...s}=this.snapshot;this.snapshot=Object.freeze({...s,status:"starting",problem:null})}return this.notify(),t}async call(e){this.check();let t=await this.initialize();return this.check(),e(t)}started(e,t){this.choose();let i=e.getNativeSnapshot().status;return i==="not_started"||i==="starting"||i==="blocked"&&!e.getNativeSnapshot().signIn?e.queue(()=>e.start(t)):Promise.resolve()}reservePortal(e){this.check();let t=this.environment(),i=e.signal?AbortSignal.any([this.lifetime.signal,e.signal]):this.lifetime.signal,o=Qt(this.declaration.environment),s=()=>!this.closed,r=this.signIn?hx(t.cpOrigin,i,s,this.signIn,o):Xf(t.cpOrigin,i,s,o);return{portal:Jf(r),signal:i}}requestAccess(e,t){try{this.check();let i=this.runtime,o=i?.getNativeSnapshot(),s=o?.selectedCollectionId??null,r=Qf(this.compiled),a=()=>s&&i?eh(i.getNativeSnapshot(),s):[],p=gx(r,e,t,a()),l=s?i.connection(s):null;if(!i||!s||!l)throw A("invalid_request","requestAccess needs an open collection","access_no_collection");let c=()=>bx(l.files,r,a());if(!p.length)return Promise.resolve(c());let{portal:d,signal:u}=this.reservePortal(t);return wx({granted:c,native:()=>i.getNativeSnapshot(),start:()=>i.queue(()=>i.requestFileAccess(d,s,p,t.reason,{signal:u})),poll:f=>i.queue(()=>i.pollFileAccess(f))},d,u)}catch(i){return Promise.reject(i)}}approve(e,t={}){let i=this.choose(),o=i.getSnapshot(),s=this.approvalPortal;if(s&&o.approval){if((e===void 0?o.requested.collectionId:e)!==o.approval.collectionId)return Promise.reject(new Vt("application_selection_busy"));if(t.signal?.aborted)throw A("cancelled","Application entry fenced","application_entry_fenced");return s.closed||s.focus(),Promise.resolve()}return i.approve(e,t)}authorize(e={},t=null){let i;try{i=this.approvalPortal=this.reservePortal(e).portal}catch(o){return Promise.reject(o)}return this.call(async o=>(await this.started(o,e),o.queue(()=>o.authorizeReserved(i,e,t)))).catch(o=>{try{i.close()}catch{}throw o})}async signOut(e={}){let t=await this.call(async s=>(await this.started(s,e),s));this.signingOut=!0;try{await t.queue(()=>t.signOut(e))}finally{this.signingOut=!1}let i=t.getNativeSnapshot().signOutResult??null;await this.signedOut(t,i);let o=this.snapshot.signOutResult??i;return o&&await vT(o),this.getSnapshot()}async signedOut(e,t,i=!1){i||this.tabs?.signedOut(),this.clearPendingSave(),++this.incarnation,this.runtime===e&&(this.runtime=null),this.initialization=null,this.hint?.clear(),this.forgotten?.clear(),this.handledApproval=null;let o=null;if(this.privates)try{await this.privates.forgetAll(),o="erased"}catch{o="incomplete"}let s=t&&o?Object.freeze({...t,grants:o,...o==="incomplete"?{local:"incomplete"}:{}}):t;this.snapshot=Object.freeze({status:"signed_out",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:!s&&o==="incomplete"?"sign_out_failed":null,timing:null,readiness:jh,...s?{signOutResult:s}:{}});try{this.memory?.write(null)}catch{}if(this.selection&&!this.closed&&(this.selection.resync(),await this.selection.select(null,{history:"replace"}).catch(()=>{})),this.revision++,this.notify(),i){e.abandon();return}await e.close().catch(()=>{})}observeSignOut(e){let t=e.getNativeSnapshot().signOutResult;!t||this.signingOut||this.closed||this.runtime!==e||this.signedOut(e,t)}tabsFor(e){if(this.tabs)return this.tabs;let t=globalThis.navigator?.locks,i=globalThis.BroadcastChannel;return!t||typeof t.request!="function"||typeof i!="function"?null:(this.tabs=new ih({...e,build:Nh.url},{locks:t,BroadcastChannel:i},this.leaderLost,this.signedInElsewhere),this.tabs)}leaderLost=e=>{if(this.closed||this.hidden)return;let t=this.runtime,i=t!==null||this.initialization!==null;if(this.election?.abort(),this.election=null,e&&t&&!this.signingOut?this.signedOut(t,t.getNativeSnapshot().signOutResult??null,!0):e&&i&&(++this.incarnation,this.initialization=null),!i||e){this.tabs?.resign();return}++this.incarnation,this.initialization=null,this.runtime=null,t?.abandon();let{problemDetail:o,...s}=this.snapshot;this.snapshot=Object.freeze({...s,status:"starting",problem:null,selectedCollectionId:null,readiness:jh}),this.notify(),this.selection?.resync(),this.app.start().catch(()=>{})};signedInElsewhere=()=>{this.closed||this.hidden||this.signingOut||this.runtime!==null||this.initialization!==null||this.snapshot.status!=="signed_out"||(this.selection?.resync(),this.app.start().catch(()=>{}))};setForeground(e){this.foreground=e,this.runtime?.setForeground(e)}followVisibility(){let e=globalThis.document;if(!e||typeof e.addEventListener!="function")return;let t=()=>{this.closed||this.setForeground(e.visibilityState!=="hidden")},i=()=>{e.visibilityState!=="hidden"&&t()};e.addEventListener("visibilitychange",t,{signal:this.lifetime.signal});let o=typeof window>"u"?void 0:window;o&&typeof o.addEventListener=="function"&&(o.addEventListener("focus",i,{signal:this.lifetime.signal}),o.addEventListener("online",i,{signal:this.lifetime.signal})),t()}followPageLifecycle(){let e=typeof window>"u"?void 0:window;if(!e||typeof e.addEventListener!="function")return;e.addEventListener("pagehide",this.pageHidden,{signal:this.lifetime.signal}),e.addEventListener("pageshow",this.pageShown,{signal:this.lifetime.signal});let t=globalThis.document;t&&typeof t.addEventListener=="function"&&(t.addEventListener("freeze",()=>this.pageHidden(),{signal:this.lifetime.signal}),t.addEventListener("resume",()=>this.pageShown({persisted:!0}),{signal:this.lifetime.signal}))}pageHidden=()=>{if(this.closed||this.hidden)return;let e=this.runtime,t=e!==null||this.initialization!==null;++this.incarnation,this.hidden=Object.freeze({resume:t}),this.clearPendingSave(),this.initialization=null,this.runtime=null,this.election?.abort(),this.election=null,e?.abandon(),this.tabs?.release();let{problemDetail:i,...o}=this.snapshot;this.snapshot=Object.freeze({...o,status:t?"starting":this.snapshot.status,problem:null,selectedCollectionId:null,readiness:jh})};pageShown=e=>{let t=this.hidden;this.closed||!t||!e.persisted||(this.hidden=null,this.notify(),t.resume&&(this.selection?.resync(),this.app.start().catch(()=>{})))};awaitingOtherTab=!1;awaitOtherTab(e,t){let i=e.getNativeSnapshot(),o=globalThis.navigator?.locks;if(this.awaitingOtherTab||this.closed||i.status!=="blocked"||i.problem!=="open_in_another_tab"||!o)return;this.awaitingOtherTab=!0;let s=this.incarnation,r=this.lifetime.signal,a=()=>!this.closed&&!this.hidden&&s===this.incarnation&&this.runtime===e;VP(o,t,r).then(()=>mT(r)).then(()=>{this.awaitingOtherTab=!1,a()&&(this.selection?.resync(),this.app.start().catch(()=>{}))},()=>{this.awaitingOtherTab=!1})}close(){if(this.closing)return this.closing;if(this.closed=!0,this.lifetime.abort(),this.selection?.close(),this.election?.abort(),this.privates?.dispose(),this.opening&&(clearTimeout(this.opening.timer),this.opening=null),this.clearPendingSave(),this.syncing){try{this.syncing.stop()}catch{}this.syncing=null}return this.closing=Promise.resolve().then(async()=>{await this.initialization?.catch(()=>{}),await this.runtime?.close(),this.tabs?.release();{let{problemDetail:e,...t}=this.snapshot;this.snapshot=Object.freeze({...t,status:"closed",problem:null,selectedCollectionId:null})}this.runtime=null,this.notify(),this.listeners.clear(),this.nativeListeners.clear()}),this.closing}application(){return this.app}connection(e){return this.closed?null:this.privates?.connection(e)??this.runtime?.connection(e)??null}};ie();var bn=n=>n;function lI(n,e={}){return AT(new ol(n,e))}function AT(n){let e=n.application(),t=()=>bn(e.getSnapshot()),i=async o=>bn(await e.approve(null,o));return Object.freeze({getSnapshot:t,subscribe:o=>e.subscribe(o),start:async o=>bn(await e.start(o)),signIn:async o=>bn(await e.authorize(o)),addCollection:i,addPrivateCollection:i,approve:async(o,s)=>bn(await e.approve(o,s)),refreshCollectionList:async o=>{if(!e.refreshCollectionList)throw A("unavailable","Refreshing the collection list isn't available here.","application_not_yet_available");return bn(await e.refreshCollectionList(o))},reauthorize:async o=>bn(await e.reauthorize(o)),configure:async o=>bn(await e.configure(o)),select:async(o,s)=>bn(await e.select(o,s)),chooseAnother:async o=>bn(await e.chooseAnother(o)),forget:async(o,s)=>bn(await e.forget(o,s)),deleteCollection:async(o,s)=>bn(await e.deleteCollection(o,s)),requestAccess:(o,s)=>e.requestAccess(o,s),assess:o=>e.assess(o),setup:Object.freeze({plan:o=>e.setup.plan(o),async apply(o,s){try{return Object.freeze({outcome:"applied",snapshot:bn(await e.setup.apply(o,s))})}catch(r){if(oe(r,"conflict")&&r.reason==="setup_changed")return Object.freeze({outcome:"changed",snapshot:t()});if(oe(r,"outcome_unknown"))return Object.freeze({outcome:"unknown",snapshot:t()});throw r}}}),connection:o=>n.connection(o),setForeground:o=>e.setForeground(o),signOut:async o=>{if(!e.signOut)throw A("unavailable","Sign out isn't available here.","application_not_yet_available");return bn(await e.signOut(o))},close:()=>e.close(),application:e})}Ea();If();ie();function cI(n,e){let t=Zr(yr(n)).manifest.requirements.capabilities;if(t?.contract_version!==2)return null;if(!e.isCurrent())throw A("invalid_request","the application connection is not current","application_connection_fenced");let i=new Set(e.records.hello.grant.capabilities),o=new Set(t.required),s=Object.freeze([...new Set([...t.required,...t.optional??[]])].map(r=>Object.freeze({id:r,requirement:o.has(r)?"required":"optional",state:i.has(r)?"available":"missing"})));return Object.freeze({values:s,requiredAvailable:s.every(r=>r.requirement==="optional"||r.state==="available"),missing:Object.freeze(s.filter(r=>r.state==="missing").map(r=>r.id))})}Ps();var Zw={};ls(Zw,{APP_BASES_PROFILE:()=>Fm,APP_COLLECTION_SETUP_LIMITS:()=>wr,AppCloudCopyBootstrapError:()=>en,AppCloudCopyHostError:()=>co,AppCollectionControlError:()=>ti,AppCollectionJoinError:()=>lo,AppCollectionJoinLedger:()=>Xa,AppCollectionSetupError:()=>nn,AppCollectionSetupJournal:()=>Ba,AppCpAuthorityError:()=>Zn,AppCpCloudCopyBootstrap:()=>$a,AppCpDeviceRegistration:()=>sl,AppCpLogAuthority:()=>Da,AppCpPeopleAuthority:()=>ul,AppDeviceRegistrationError:()=>ts,AppHttpLogError:()=>mn,AppHttpLogTransport:()=>Ua,AppIndexedDbDeviceKeyProtectedStore:()=>cl,AppIndexedDbDeviceKeyProvider:()=>ll,AppIndexedDbNoiseProtectedStore:()=>dl,AppInstallationSignInError:()=>Xe,AppLogHostError:()=>pt,AppLogPump:()=>is,AppProtectedInstallationSignIn:()=>ja,AppReplicaOwnerError:()=>We,AppStrictDeviceApprovalError:()=>an,AppWasmRuntime:()=>fl,AppWebCloudCopyHost:()=>ml,AppWebCollectionError:()=>up,AppWebDeviceKeyCustody:()=>al,AppWebNoiseCustody:()=>pl,AppWebSignInSession:()=>Zh,UNSYNCED_STORAGE_WARNING:()=>kx,acquireAppInstallationLease:()=>Wc,acquireAppReplicaLease:()=>Kc,appBrowserDirectAccess:()=>Vh,appCollectionControlClient:()=>uh,appInstallationLockName:()=>Eb,appLocalConnector:()=>Ph,appLogHealth:()=>Bw,appModelPackPlan:()=>Ho,appModelResourcePlan:()=>xt,appMutationSaveState:()=>Ax,appReplicaLockName:()=>Uf,appSaveState:()=>rh,appStoragePolicy:()=>oh,attachAppLocalFacade:()=>Sh,createAppCollectionPeople:()=>ph,createAppWebCollectionAdapter:()=>TC,decodeAppBasesCell:()=>yo,decodeAppBasesDiscoveryResult:()=>td,decodeAppBasesResult:()=>Zp,decodeAppBasesSourceResult:()=>nd,decodeAppCollectionSetupIntent:()=>Et,encodeAppBasesDiscoveryRequest:()=>Qp,encodeAppBasesRequest:()=>Xp,encodeAppBasesSourceRequest:()=>ed,openAppWebCollectionClient:()=>Ch,openOwnedAppWorker:()=>KP,probeAppStorage:()=>AI,selectAppEnvironment:()=>Xn,verifyAppHandover:()=>dI});xh();Vm();function pI(n,e){return n.seq===e.seq&&n.chain===e.chain&&n.policyGeneration===e.policyGeneration&&n.catalogGeneration===e.catalogGeneration}async function dI(n,e){let t=null;try{let{runtime:i,localPort:o,localClient:s,hostedClient:r,source:a}=n,p=r.hello,l=s.hello,c=a.collection,d=a.deviceId,u=r.authenticatedDevice;if(!(P=>typeof P=="string"&&P.replace(/-/g,"").toLowerCase()===d.replace(/-/g,"").toLowerCase())(u))return null;let h=p.status.confirmedHead,m=h?Object.freeze({...h}):void 0;if(!m||!p.headWitness||p.headWitness.length>64*1024||m.seq===0||p.collection!==c||l.collection!==c)return null;t=new Uint8Array(p.headWitness);let b=t,w=()=>{try{return!e.aborted&&n.isCurrent()===!0&&a.isCurrent()===!0&&l.collection===c&&a.collection===c&&a.deviceId===d&&s.hello===l}catch{return!1}},g=()=>{try{let P=i.observations();return!P.requiresReopen&&!P.keyringRebuilding&&!P.keyringRebuildFailed&&P.status.mode==="synced"&&P.status.confirmedHead!==void 0&&P.status.confirmedHead.seq>=m.seq}catch{return!1}},y=()=>{if(!w()||!g())return!1;let P=i.verifyHandover(o,a,b);return P!==null&&pI(P,m)},v=()=>{try{return!e.aborted&&w()&&r.hello===p&&r.authenticatedDevice===u}catch{return!1}};if(!v()||!y())return null;let _=await s.appliedPrefix(m.seq,e);if(!v()||!y()||_.seq!==m.seq||_.appliedThrough<m.seq||_.chain!==m.chain)return null;let k=Object.freeze({...m}),S=!1,x={head:k,appliedThrough:_.appliedThrough,isCurrent:()=>{if(S)return!1;try{return y()&&pI(k,m)}catch{return!1}},dispose:()=>{S=!0,b.fill(0)}};return t=null,x}catch{return null}finally{t?.fill(0)}}bt();ge();var ts=class extends Error{constructor(t){super(`app device registration: ${t}`);this.reason=t;this.name="AppDeviceRegistrationError"}reason},wt=n=>new ts(n),Uh=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),sl=class{constructor(e,t,i,o,s={}){this.runtime=e;this.session=t;this.persistence=o;try{this.scope=Object.freeze({connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId,kind:t.kind});for(let a of[this.scope.connectorId,this.scope.deviceId,this.scope.installationId])if(U(a).every(p=>p===0))throw wt("binding");if(t.kind!=="mobile"&&t.kind!=="app-runtime")throw wt("binding");this.rawOrigin=t.cpOrigin;let r=new URL(this.rawOrigin);if(r.username||r.password||r.pathname!=="/"||r.search||r.hash||r.protocol!=="https:"&&!(s.allowLoopbackHttp===!0&&ot(this.rawOrigin))||(this.origin=r.origin,this.now=s.now??Date.now,this.fetchImpl=s.fetch??globalThis.fetch,!(i.envelope instanceof Uint8Array)||!i.envelope.length||i.envelope.length>1024)||!e.deviceCustodyCurrent(t,i)||(this.custody=Object.freeze({signPublicKey:new Uint8Array(i.signPublicKey),kemPublicKey:new Uint8Array(i.kemPublicKey),noisePublicKey:new Uint8Array(i.noisePublicKey),envelope:new Uint8Array(i.envelope)}),!this.current()))throw wt("binding")}catch{throw e.retireLog(),wt("binding")}}runtime;session;persistence;attempted=!1;lifetime=new AbortController;origin;rawOrigin;scope;custody;now;fetchImpl;current(){try{return!this.lifetime.signal.aborted&&this.runtime.deviceCustodyCurrent(this.session,this.custody)&&this.session.isCurrent()===!0&&this.session.cpOrigin===this.rawOrigin&&this.session.connectorId===this.scope.connectorId&&this.session.deviceId===this.scope.deviceId&&this.session.installationId===this.scope.installationId&&this.session.kind===this.scope.kind}catch{return!1}}check(e){if(!this.current()||e.aborted)throw this.close(),wt("fenced")}async json(e,t,i,o){this.check(o);let s=new AbortController,r=()=>s.abort(),a=setTimeout(r,15e3);a.unref?.(),o.addEventListener("abort",r,{once:!0}),this.lifetime.signal.addEventListener("abort",r,{once:!0});let p=new Uint8Array(32*1024),l=0,c=null,d=null;try{let u=this.fetchImpl;if(c=await u(`${this.origin}${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,...i===void 0?{}:{"content-type":"application/json"}},body:i,signal:s.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(o),s.signal.aborted||!c.ok)throw wt("unavailable");let f=c.headers.get("content-length");if(f!==null&&/^(0|[1-9][0-9]*)$/.test(f)&&Number(f)>p.length)throw s.abort(),wt("response");if(!c.body)throw wt("response");for(d=c.body.getReader();;){let{done:m,value:b}=await d.read();try{if(this.check(o),s.signal.aborted)throw wt("unavailable");if(m)break;if(l+b.length>p.length)throw s.abort(),wt("response");p.set(b,l),l+=b.length}finally{b?.fill(0)}}let h=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(p.subarray(0,l)));if(!h||typeof h!="object"||Array.isArray(h))throw wt("response");return h}catch(u){throw this.check(o),u instanceof ts?u:wt("unavailable")}finally{p.fill(0),(d?.cancel()??c?.body?.cancel())?.catch(()=>{}),d?.releaseLock(),clearTimeout(a),o.removeEventListener("abort",r),this.lifetime.signal.removeEventListener("abort",r)}}async register(e){let t=null,i=null;try{if(this.check(e.signal),this.attempted)throw wt("fenced");this.attempted=!0,await this.persistence.pending(new Uint8Array(this.custody.envelope),e),this.check(e.signal);let o=await this.session.connectorBearer(e);if(this.check(e.signal),typeof o!="string"||!o||o.length>16*1024||/[^\x21-\x7e]/.test(o))throw wt("binding");let s=await this.json("/v1/next/devices/challenge",o,void 0,e.signal);if(this.check(e.signal),typeof s.challenge!="string"||!/^[0-9a-f]{64}$/.test(s.challenge)||typeof s.expires_at!="number"||!Number.isSafeInteger(s.expires_at)||s.expires_at-this.now()<=5e3||s.expires_at-this.now()>16*6e4)throw wt("response");t=Uint8Array.from(s.challenge.match(/../g).map(l=>parseInt(l,16)));let r=this.runtime.signCpEnrol(t);this.check(e.signal),i=r.signature;let a=await this.json("/v1/next/devices",o,JSON.stringify({device_id:this.scope.deviceId,kind:this.scope.kind,capabilities:["collection_mode_switch_v1"],challenge:s.challenge,sign_pk:Uh(r.signPublicKey),kem_pk:Uh(r.kemPublicKey),noise_pk:Uh(r.noisePublicKey),sig:Uh(i)}),e.signal);if(this.check(e.signal),a.device_id!==this.scope.deviceId)throw wt("response");let p=Object.freeze({connectorId:this.scope.connectorId,deviceId:this.scope.deviceId,installationId:this.scope.installationId,signPublicKey:new Uint8Array(r.signPublicKey),kemPublicKey:new Uint8Array(r.kemPublicKey),noisePublicKey:new Uint8Array(r.noisePublicKey)});return await this.persistence.registered(p,e),this.check(e.signal),this.runtime.acknowledgeDeviceRegistration(p),p}catch(o){throw this.close(),o instanceof ts?o:wt("unavailable")}finally{t?.fill(0),i?.fill(0)}}close(){this.lifetime.signal.aborted||(this.lifetime.abort(),this.custody.envelope.fill(0),this.runtime.retireLog())}};Je();ge();var Wt=()=>new Error("app device key custody unavailable; preserve storage and reopen"),al=class{constructor(e,t,i){this.pin=e;this.key=t;this.store=i;try{this.scope=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId}),this.current=e.isCurrent,this.owned=e.installationOwned;let o=[this.scope.accountId,this.scope.connectorId,this.scope.deviceId,this.scope.installationId].map(U);if(o.some(s=>s.every(r=>r===0))||t.type!=="secret"||t.extractable||t.algorithm.name!=="AES-GCM"||t.algorithm.length!==256||!t.usages.includes("encrypt")||!t.usages.includes("decrypt"))throw Wt();this.namespace=`mdbase.app-device-keys.v1:${o.map(s=>Array.from(s,r=>r.toString(16).padStart(2,"0")).join("")).join(":")}`,this.aad=pe(["mdbase/v1/app-device-keys-platform",...o]),this.check(new AbortController().signal)}catch{throw Wt()}}pin;key;store;scope;namespace;aad;current;owned;attempted=!1;check(e){try{if(e.aborted||this.pin.isCurrent!==this.current||this.pin.installationOwned!==this.owned||this.current.call(this.pin)!==!0||this.owned.call(this.pin)!==!0||this.pin.accountId!==this.scope.accountId||this.pin.connectorId!==this.scope.connectorId||this.pin.deviceId!==this.scope.deviceId||this.pin.installationId!==this.scope.installationId)throw Wt()}catch{throw Wt()}}async openNativeDevice(e,t){let i=null,o=null,s=!1;try{if(this.attempted)throw Wt();this.attempted=!0;let r=t.signal,a=t.mode;if(this.check(r),!["fresh","existing"].includes(a)||t.noise.mode!==a||t.noise.mode==="existing"&&!(t.noise.envelope instanceof Uint8Array))throw Wt();let p=t.noise.mode==="fresh"?{mode:"fresh"}:{mode:"existing",envelope:new Uint8Array(t.noise.envelope)};if(p.mode==="existing"&&(!p.envelope.length||p.envelope.length>1024))throw Wt();let l=await this.store.read(this.namespace,{signal:r});if(this.check(r),a==="fresh"){if(l!==null)throw Wt();i=globalThis.crypto.getRandomValues(new Uint8Array(64));let u=globalThis.crypto.getRandomValues(new Uint8Array(12)),f=new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:u,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,i));if(this.check(r),o=pe(new Map([[0,1],[1,u],[2,f]])),await this.store.create(this.namespace,o,{signal:r})!==!0)throw Wt();this.check(r)}else{if(!(l instanceof Uint8Array)||l.length===0||l.length>256)throw Wt();o=new Uint8Array(l);let u=ue(o);if(!(u instanceof Map))throw Wt();let f=u;if(f.size!==3||f.get(0)!==1)throw Wt();let h=f.get(1),m=f.get(2);if(!(h instanceof Uint8Array)||h.length!==12||!(m instanceof Uint8Array)||m.length!==80||(i=new Uint8Array(await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(h),additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(m))),this.check(r),i.length!==64))throw Wt()}this.check(r);let c=Object.freeze({connectorId:this.scope.connectorId,deviceId:this.scope.deviceId,installationId:this.scope.installationId,isCurrent:()=>{try{return this.check(r),!0}catch{return!1}}});s=!0;let d=e.openDeviceConsuming({pin:c,signSecretKey:i.subarray(0,32),kemSecretKey:i.subarray(32),opened:p});return this.check(r),d}catch{if(s)try{e.retireLog()}catch{}throw Wt()}finally{i?.fill(0),o?.fill(0)}}};Jn();ge();var Dh="device-key-kek",uI="original-device-kek",vt=()=>new Error("app device key provider unavailable; preserve storage and reopen");function $h(n){if(typeof globalThis.CryptoKey!="function"||!(n instanceof CryptoKey)||n.type!=="secret"||n.extractable||n.algorithm.name!=="AES-GCM"||n.algorithm.length!==256||n.usages.length!==2||!n.usages.includes("encrypt")||!n.usages.includes("decrypt"))throw vt();return n}function kT(n){if(n===void 0)return null;if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).length!==2||!Object.hasOwn(n,"version")||!Object.hasOwn(n,"key")||n.version!==1)throw vt();return $h(n.key)}var ll=class n{constructor(e,t,i){this.source=e;this.origin=t;this.lifetime=i;this.scope=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId}),this.current=e.isCurrent,this.owned=e.installationOwned}source;origin;lifetime;db=null;value=null;closed=!1;loaned=!1;scope;current;owned;static async open(e){let t=null;try{let{source:i,origin:o,mode:s,signal:r}=e;t=new n(i,o,r);let a=Object.values(t.scope).map(u=>{let f=U(u);if(f.every(h=>h===0))throw vt();return Array.from(f,h=>h.toString(16).padStart(2,"0")).join("")});if(!Lt(o,e.allowLoopbackHttp===!0,e.allowNativeLoopbackHttp===!0?"native":void 0)||!["fresh","existing"].includes(s)||!globalThis.indexedDB||!globalThis.crypto?.subtle||typeof globalThis.CryptoKey!="function")throw vt();t.check(r);let p=crypto.subtle.generateKey.bind(crypto.subtle),l=`mdbase.app.device-key-kek.v1.${a.join(".")}`,c=await t.openDatabase(l,s);t.db=c,c.onversionchange=()=>t.close(),t.check(r);let d=await t.transaction("readonly",r,null);if(t.check(r),s==="existing"){if(d===null||typeof d=="boolean")throw vt();t.value=d}else{if(d!==null)throw vt();let u=$h(await p({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]));if(t.check(r),await t.transaction("readwrite",r,u)!==!0)throw vt();t.check(r),t.value=u}return t.check(r),t}catch{throw t?.close(),vt()}}check(e){try{if(this.closed||this.lifetime.aborted||e.aborted||Rt()!==this.origin||this.source.isCurrent!==this.current||this.source.installationOwned!==this.owned||this.current.call(this.source)!==!0||this.owned.call(this.source)!==!0||Object.entries(this.scope).some(([t,i])=>this.source[t]!==i))throw vt()}catch{throw vt()}}openDatabase(e,t){return new Promise((i,o)=>{this.check(this.lifetime);let s=indexedDB.open(e,1),r=!1,a=!1,p=()=>{r=!0,o(vt())};this.lifetime.addEventListener("abort",p,{once:!0});let l=()=>this.lifetime.removeEventListener("abort",p);s.onblocked=p,s.onupgradeneeded=()=>{try{if(this.check(this.lifetime),r||t!=="fresh"||s.result.objectStoreNames.length!==0)throw vt();s.result.createObjectStore(Dh),a=!0}catch{s.transaction?.abort()}},s.onerror=()=>{l(),o(vt())},s.onsuccess=()=>{l();try{if(this.check(this.lifetime),r||t==="fresh"&&!a||s.result.objectStoreNames.length!==1||!s.result.objectStoreNames.contains(Dh))throw vt();i(s.result)}catch{s.result.close(),o(vt())}}})}transaction(e,t,i){return new Promise((o,s)=>{if(this.check(t),!this.db)throw vt();let r=this.db.transaction(Dh,e,{durability:"strict"}),a=r.objectStore(Dh),p=null,l=!1,c=()=>{l=!0;try{r.abort()}catch{}};t.addEventListener("abort",c,{once:!0}),this.lifetime.addEventListener("abort",c,{once:!0});let d=()=>{t.removeEventListener("abort",c),this.lifetime.removeEventListener("abort",c)};r.onerror=r.onabort=()=>{d(),p=null,s(vt())},r.oncomplete=()=>{d();try{if(this.check(t),l)throw vt();o(p)}catch{p=null,s(vt())}};let u=a.get(uI);u.onsuccess=()=>{try{this.check(t);let f=kT(u.result);e==="readonly"?p=f:(p=f===null,p===!0&&i!==null&&a.add({version:1,key:$h(i)},uI))}catch{c()}}})}deviceCustodyKek(e){if(this.check(e.signal),this.loaned||!this.value)throw vt();return this.loaned=!0,$h(this.value)}close(){this.closed||(this.closed=!0,this.value=null,this.db?.close(),this.db=null)}};Jn();ge();var zh="original-device-keys",fI="custody",ST=256,sn=()=>new Error("app device key custody store unavailable");function hI(n){if(!(n instanceof Uint8Array)||!n.length||n.length>ST)throw sn();return new Uint8Array(n)}var cl=class n{constructor(e,t,i,o,s){this.db=e;this.source=t;this.scope=i;this.namespace=o;this.origin=s;this.current=t.isCurrent,this.owned=t.installationOwned,e.onversionchange=()=>this.close()}db;source;scope;namespace;origin;closed=!1;current;owned;static async open(e){try{return await this.openChecked(e)}catch{throw sn()}}static async openChecked(e){let{source:t,signal:i,mode:o,origin:s}=e,r=Object.freeze({accountId:t.accountId,connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId}),a=t.isCurrent,p=t.installationOwned,l=()=>{try{return!i.aborted&&t.isCurrent===a&&t.installationOwned===p&&a.call(t)===!0&&p.call(t)===!0&&Object.keys(r).every(m=>t[m]===r[m])}catch{return!1}},c=[r.accountId,r.connectorId,r.deviceId,r.installationId].map(m=>{let b=U(m);if(b.every(w=>w===0))throw sn();return Array.from(b,w=>w.toString(16).padStart(2,"0")).join("")});if(!Lt(s,e.allowLoopbackHttp===!0,e.allowNativeLoopbackHttp===!0?"native":void 0)||Rt()!==s||!["fresh","existing"].includes(o)||!l()||!globalThis.indexedDB)throw sn();let d=`mdbase.app-device-keys.v1:${c.join(":")}`,u=`mdbase.app.device-keys.v1.${c.join(".")}`,f=await new Promise((m,b)=>{let w=indexedDB.open(u,1),g=!1,y=()=>{g=!0,b(sn())};i.addEventListener("abort",y,{once:!0});let v=()=>i.removeEventListener("abort",y);w.onblocked=y,w.onupgradeneeded=()=>{if(g||o!=="fresh"||!l()||w.result.objectStoreNames.length!==0){w.transaction?.abort();return}w.result.createObjectStore(zh)},w.onerror=()=>{v(),b(sn())},w.onsuccess=()=>{if(v(),g||!l()||w.result.objectStoreNames.length!==1||!w.result.objectStoreNames.contains(zh)){w.result.close(),b(sn());return}m(w.result)}}),h=new n(f,t,r,d,s);try{h.check(i);let m=await h.read(d,{signal:i});try{if(o==="fresh"!=(m===null))throw sn();return h.check(i),h}finally{m?.fill(0)}}catch{throw h.close(),sn()}}check(e,t=this.namespace){try{if(this.closed||e.aborted||t!==this.namespace||Rt()!==this.origin||this.source.isCurrent!==this.current||this.source.installationOwned!==this.owned||this.current.call(this.source)!==!0||this.owned.call(this.source)!==!0||Object.keys(this.scope).some(i=>this.source[i]!==this.scope[i]))throw sn()}catch{throw sn()}}async read(e,t){let i=await this.transaction("readonly",e,t.signal,null);try{return this.check(t.signal,e),i}catch{throw i instanceof Uint8Array&&i.fill(0),sn()}}async create(e,t,i){this.check(i.signal,e);let o=hI(t);try{let s=await this.transaction("readwrite",e,i.signal,o);return this.check(i.signal,e),s===!0}finally{o.fill(0)}}transaction(e,t,i,o){return new Promise((s,r)=>{this.check(i,t);let a=this.db.transaction(zh,e,{durability:"strict"}),p=a.objectStore(zh),l=null,c=!1,d=()=>{c=!0;try{a.abort()}catch{}},u=()=>i.removeEventListener("abort",d);i.addEventListener("abort",d,{once:!0}),a.onabort=a.onerror=()=>{u(),l instanceof Uint8Array&&l.fill(0),r(sn())},a.oncomplete=()=>{u();try{if(this.check(i,t),c)throw sn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),r(sn())}};let f=p.get(fI);f.onsuccess=()=>{let h=null;try{this.check(i,t),h=f.result===void 0?null:hI(f.result),e==="readonly"?(l=h,h=null):(l=h===null,l===!0&&o!==null&&p.add(new Uint8Array(o),fI))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db.close())}};Je();ge();var Me=()=>new Error("app Noise custody unavailable; preserve storage and reopen"),gp=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),pl=class{constructor(e,t,i){this.pin=e;this.key=t;this.store=i;try{this.scope=Object.freeze({connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId});let o=[this.scope.connectorId,this.scope.deviceId,this.scope.installationId].map(U);if(o.some(s=>s.every(r=>r===0))||t.type!=="secret"||t.extractable||t.algorithm.name!=="AES-GCM"||t.algorithm.length!==256||!t.usages.includes("encrypt")||!t.usages.includes("decrypt"))throw Me();this.namespace=`mdbase.app-noise.v1:${this.scope.connectorId}:${this.scope.deviceId}:${this.scope.installationId}`,this.aad=pe(["mdbase/v1/app-noise-platform",...o]),this.check(new AbortController().signal)}catch{throw Me()}}pin;key;store;scope;namespace;aad;check(e){try{if(e.aborted||this.pin.isCurrent()!==!0||this.pin.connectorId!==this.scope.connectorId||this.pin.deviceId!==this.scope.deviceId||this.pin.installationId!==this.scope.installationId)throw Me()}catch{throw Me()}}receiptValue(e){if(e.connectorId!==this.scope.connectorId||e.deviceId!==this.scope.deviceId||e.installationId!==this.scope.installationId)throw Me();let t=[e.signPublicKey,e.kemPublicKey,e.noisePublicKey];if(t.some(i=>!(i instanceof Uint8Array)||i.length!==32||i.every(o=>o===0)))throw Me();return t.map(i=>new Uint8Array(i))}receipt(e){if(e===null)return null;if(!Array.isArray(e)||e.length!==3||e.some(t=>!(t instanceof Uint8Array)||t.length!==32||t.every(i=>i===0)))throw Me();return Object.freeze({...this.scope,signPublicKey:new Uint8Array(e[0]),kemPublicKey:new Uint8Array(e[1]),noisePublicKey:new Uint8Array(e[2])})}markerValue(e){let t=U(e.collection);if(t.every(i=>i===0)||typeof e.acknowledged!="boolean"||!(e.sasCommitment instanceof Uint8Array)||e.sasCommitment.length!==32||e.sasCommitment.every(i=>i===0))throw Me();return[t,...this.receiptValue(e),new Uint8Array(e.sasCommitment),e.acknowledged]}marker(e,t){if(e===null)return null;if(!t||!Array.isArray(e)||e.length!==6||!(e[0]instanceof Uint8Array)||e[0].length!==16||e[0].every(r=>r===0)||typeof e[5]!="boolean")throw Me();let i=this.receipt(e.slice(1,4));for(let r of["signPublicKey","kemPublicKey","noisePublicKey"])if(!gp(i[r],t[r]))throw Me();let o=e[4];if(!(o instanceof Uint8Array)||o.length!==32||o.every(r=>r===0))throw Me();let s=Array.from(e[0],r=>r.toString(16).padStart(2,"0")).join("");return Object.freeze({...i,collection:`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`,sasCommitment:new Uint8Array(o),acknowledged:e[5]})}async restore(e){let t=await this.read(e);return this.check(e.signal),t?.value??null}async read(e){let t=null,i=null;try{this.check(e.signal);let o=await this.store.read(this.namespace,e);if(this.check(e.signal),o===null)return null;if(!(o instanceof Uint8Array)||o.length===0||o.length>4096)throw Me();t=new Uint8Array(o);let s=ue(t);if(!(s instanceof Map))throw Me();let r=s,a=r.get(1),p=r.get(2);if(r.size!==3||r.get(0)!==1||!(a instanceof Uint8Array)||a.length!==12||!(p instanceof Uint8Array)||p.length<16||p.length>2064||(i=new Uint8Array(await globalThis.crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(a),additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(p))),this.check(e.signal),i.length>2048))throw Me();let l=ue(i);if(!(l instanceof Map))throw Me();let c=l,d=c.get(1);if(!(c.get(0)===1&&c.size===3||c.get(0)===2&&c.size===4&&c.has(3))||!(d instanceof Uint8Array)||d.length===0||d.length>1024||!c.has(2))throw Me();let u=this.receipt(c.get(2)),f=c.get(0)===2?this.marker(c.get(3),u):null;return{value:Object.freeze({envelope:new Uint8Array(d),receipt:u,privateEnrolMarker:f}),encrypted:new Uint8Array(t)}}catch{throw Me()}finally{t?.fill(0),i?.fill(0)}}async write(e,t,i,o,s=null){let r=null,a=null;try{if(this.check(o.signal),!(e instanceof Uint8Array)||!e.length||e.length>1024)throw Me();let p=new Map([[0,s===null?1:2],[1,new Uint8Array(e)],[2,t===null?null:this.receiptValue(t)]]);if(s!==null){let u=this.markerValue(s);this.marker(u,t),p.set(3,u)}if(r=pe(p),r.length>2048)throw Me();let l=globalThis.crypto.getRandomValues(new Uint8Array(12)),c=new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:l,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(r)));this.check(o.signal),a=pe(new Map([[0,1],[1,l],[2,c]]));let d=await this.store.compareAndSet(this.namespace,i,a,o);if(this.check(o.signal),d!==!0)throw Me()}catch{throw Me()}finally{r?.fill(0),a?.fill(0)}}async pending(e,t){let i=await this.read(t);if(this.check(t.signal),i){if(!gp(i.value.envelope,e))throw Me();return}await this.write(e,null,null,t),this.check(t.signal)}async privateEnrolPending(e,t){try{if(e.acknowledged!==!1)throw Me();await this.writePrivateMarker(e,!1,t)}catch{throw Me()}}async privateEnrolAcknowledged(e,t){try{await this.writePrivateMarker(e,!0,t)}catch{throw Me()}}async writePrivateMarker(e,t,i){this.check(i.signal);let o=this.marker(this.markerValue(e),e),s=await this.read(i);if(this.check(i.signal),!s?.value.receipt)throw Me();for(let a of["signPublicKey","kemPublicKey","noisePublicKey"])if(!gp(o[a],s.value.receipt[a]))throw Me();let r=s.value.privateEnrolMarker;if(r){if(r.collection!==o.collection||!gp(r.sasCommitment,o.sasCommitment))throw Me();if(r.acknowledged){if(!t)throw Me();return}if(!t)return}else if(t)throw Me();await this.write(s.value.envelope,s.value.receipt,s.encrypted,i,Object.freeze({...o,acknowledged:t})),this.check(i.signal)}async registered(e,t){let i=await this.read(t);if(this.check(t.signal),!i)throw Me();if(i.value.receipt){for(let o of["signPublicKey","kemPublicKey","noisePublicKey"])if(!gp(i.value.receipt[o],e[o]))throw Me();this.receiptValue(e);return}await this.write(i.value.envelope,e,i.encrypted,t),this.check(t.signal)}};Jn();ge();var Bh="opaque-noise",mI="custody",PT=4096,wn=()=>new Error("app noise custody store unavailable");function Dw(n){if(!(n instanceof Uint8Array)||n.byteLength<1||n.byteLength>PT)throw wn();return new Uint8Array(n)}function xT(n,e){return n===null||e===null?n===e:n.length===e.length&&n.every((t,i)=>t===e[i])}function $w(n){if(U(n).every(t=>t===0))throw wn();return n.toLowerCase()}function zw(n,e){try{return n.isCurrent()===!0&&n.connectorId===e[0]&&n.deviceId===e[1]&&n.installationId===e[2]}catch{return!1}}var dl=class n{constructor(e,t,i,o){this.db=e;this.source=t;this.pins=i;this.origin=o;e.onversionchange=()=>this.close()}db;source;pins;origin;closed=!1;static async open(e){try{return await this.openChecked(e)}catch{throw wn()}}static async openChecked(e){let{source:t,signal:i}=e,o=[t.connectorId,t.deviceId,t.installationId];if(!Lt(e.origin,e.allowLoopbackHttp===!0,e.allowNativeLoopbackHttp===!0?"native":void 0)||Rt()!==e.origin||!["fresh","existing"].includes(e.mode)||i.aborted||!zw(t,o)||typeof globalThis.indexedDB>"u")throw wn();let s=`mdbase.app.noise.v1.${$w(o[2])}.${$w(o[0])}.${$w(o[1])}`,r=await new Promise((p,l)=>{let c=indexedDB.open(s,1),d=!1,u=()=>{d=!0,l(wn())};i.addEventListener("abort",u,{once:!0});let f=()=>i.removeEventListener("abort",u);c.onblocked=u,c.onupgradeneeded=()=>{if(d||i.aborted||e.mode!=="fresh"||!zw(t,o)||c.result.objectStoreNames.length!==0){c.transaction?.abort();return}c.result.createObjectStore(Bh)},c.onerror=()=>{f(),l(wn())},c.onsuccess=()=>{if(f(),d||i.aborted||c.result.objectStoreNames.length!==1||!c.result.objectStoreNames.contains(Bh)){c.result.close(),l(wn());return}p(c.result)}}),a=new n(r,t,o,e.origin);try{let p=await a.read(a.namespace,{signal:i});if(e.mode==="fresh"!=(p===null))throw wn();return p?.fill(0),a.check(i),a}catch{throw a.close(),wn()}}get namespace(){return`mdbase.app-noise.v1:${this.pins[0]}:${this.pins[1]}:${this.pins[2]}`}check(e,t=this.namespace){if(this.closed||e.aborted||t!==this.namespace||Rt()!==this.origin||!zw(this.source,this.pins))throw wn()}async read(e,t){this.check(t.signal,e);let i=await this.transaction("readonly",t.signal,null,null);try{return this.check(t.signal),i}catch{throw i instanceof Uint8Array&&i.fill(0),wn()}}async compareAndSet(e,t,i,o){this.check(o.signal,e);let s=null,r=null;try{s=t===null?null:Dw(t),r=Dw(i);let a=await this.transaction("readwrite",o.signal,s,r);return this.check(o.signal),a===!0}finally{s?.fill(0),r?.fill(0)}}transaction(e,t,i,o){return new Promise((s,r)=>{this.check(t);let a=this.db.transaction(Bh,e,{durability:"strict"}),p=a.objectStore(Bh),l=null,c=!1,d=()=>{c=!0;try{a.abort()}catch{}},u=()=>t.removeEventListener("abort",d);t.addEventListener("abort",d,{once:!0}),a.onabort=a.onerror=()=>{u(),l instanceof Uint8Array&&l.fill(0),r(wn())},a.oncomplete=()=>{u();try{if(this.check(t),c)throw wn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),r(wn())}};let f=p.get(mI);f.onsuccess=()=>{let h=null;try{this.check(t),h=f.result===void 0?null:Dw(f.result),e==="readonly"?(l=h,h=null):(l=xT(h,i),l===!0&&o!==null&&p.put(new Uint8Array(o),mI))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db.close())}};Qc();Zc();bt();ge();ie();var ki=()=>A("unavailable","people metadata is unavailable","people_response");function yI(n){if(!n||typeof n!="object"||Array.isArray(n))throw ki();return n}function gI(n){if(typeof n=="number"&&!Number.isSafeInteger(n))throw ki();let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw ki();return e}var ul=class{constructor(e,t={}){this.session=e;this.rawOrigin=e.cpOrigin;let i=new URL(this.rawOrigin);if(i.username||i.password||i.pathname!=="/"||i.search||i.hash||i.protocol!=="https:"&&!(t.allowLoopbackHttp===!0&&ot(e.cpOrigin)))throw A("invalid_request","invalid people CP origin","people_binding");this.cpOrigin=i.origin,this.collection=e.collection,this.connector=e.connectorId,this.device=e.deviceId,this.ep=gI(e.endpoint);for(let o of[this.collection,this.connector,this.device])if(U(o).every(s=>s===0))throw A("invalid_request","nil people binding","people_binding");if(this.fetchImpl=t.fetch??globalThis.fetch,!this.isCurrent())throw A("unauthenticated","people scope is not current","people_fenced")}session;cpOrigin;rawOrigin;collection;connector;device;ep;fetchImpl;lifetime=new AbortController;isCurrent(){try{return!this.lifetime.signal.aborted&&this.session.isCurrent()===!0&&this.session.cpOrigin===this.rawOrigin&&this.session.collection===this.collection&&this.session.connectorId===this.connector&&this.session.deviceId===this.device&&gI(this.session.endpoint)===this.ep}catch{return!1}}check(e){if(e?.throwIfAborted(),!this.isCurrent())throw A("unauthenticated","people scope changed","people_fenced")}async request(e,t={}){if(e!=="identity"&&e!=="members")throw A("invalid_request","invalid people resource");this.check(t.signal);let i=new AbortController,o=()=>i.abort();t.signal?.addEventListener("abort",o,{once:!0}),this.lifetime.signal.addEventListener("abort",o,{once:!0});let s=setTimeout(o,15e3);s.unref?.();let r=new Uint8Array(1024*1024),a=0,p,l;try{let c=await this.session.connectorBearer({signal:i.signal});if(this.check(t.signal),i.signal.aborted)throw ki();if(typeof c!="string"||!/^(idev_|ct_)/.test(c)||c.length>16*1024||/[^\x21-\x7e]/.test(c))throw A("unauthenticated","invalid people credential","people_binding");let d=this.fetchImpl;if(p=await d(`${this.cpOrigin}/v1/authorities/${this.collection}/${e}?device_id=${this.device}`,{method:"GET",headers:{authorization:`Bearer ${c}`},signal:i.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(t.signal),i.signal.aborted)throw ki();let u=p.headers.get("content-length");if(u!==null&&/^(0|[1-9][0-9]*)$/.test(u)&&Number(u)>r.length||!p.body)throw ki();for(l=p.body.getReader();;){let{done:h,value:m}=await l.read();try{if(this.check(t.signal),i.signal.aborted)throw ki();if(h)break;if(a+m.length>r.length)throw ki();r.set(m,a),a+=m.length}finally{m?.fill(0)}}let f=yI(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(r.subarray(0,a))));if(this.check(t.signal),p.status===401)throw A("unauthenticated","people credential is no longer current","people_fenced");if(p.status===403){let h=yI(f.error);throw A("forbidden","people access was refused",e==="members"&&h.code==="people_permission_declined"?"people_permission_declined":"people_access")}if(p.status===404)throw A("upgrade_required","people metadata is unsupported","people_unsupported");if(!p.ok)throw ki();return f}catch(c){throw this.check(t.signal),c instanceof se?c:ki()}finally{i.abort(),r.fill(0),(l?.cancel()??p?.body?.cancel())?.catch(()=>{}),l?.releaseLock(),clearTimeout(s),t.signal?.removeEventListener("abort",o),this.lifetime.signal.removeEventListener("abort",o)}}close(){this.lifetime.abort()}};Xc();Je();ge();ie();At();Cr();Je();ge();Fn();var bI=16*1024*1024,CT=9*1024*1024,IT=64,OT=64*1024*1024,RT=new Set(["append","read","head","subscribe","unsubscribe","put_object","get_object","has_objects","put_snapshot","get_snapshot","endorse_snapshot","stream_join","stream_leave","stream_send"]),pt=class extends Error{constructor(t){super(`app log host: ${t}`);this.reason=t;this.name="AppLogHostError"}reason};function ns(n){if((typeof n!="number"||!Number.isSafeInteger(n))&&typeof n!="bigint")throw new pt("invalid_call");let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw new pt("invalid_call");return e}function Fh(n,e){return n.length===e.length&&n.every((t,i)=>t===e[i])}var ET=new Set(["read","head","subscribe","get_object","has_objects","put_object","get_snapshot"]),qT=6;function wI(n){try{return n.server}catch{return null}}function TT(n){try{return n.reason}catch{return null}}function Bw(n,e=globalThis.navigator?.onLine){let t=wI(n);if(kn(t)){let i=t.retryAfterMs;return t.status===429?{kind:"rate_limited",retryAfterMs:i}:t.status>=500?{kind:"server_busy",retryAfterMs:i}:t.status===401||t.status===403?{kind:"auth"}:null}return TT(n)!=="unavailable"?null:e===!1?{kind:"offline"}:{kind:"unreachable"}}var is=class{constructor(e,t,i){this.runtime=e;this.transport=t;try{if(this.endpoint=ns(i.endpoint),this.collection=U(i.collection),ns(t.endpoint)!==this.endpoint||!Fh(U(t.collection),this.collection))throw new Error}catch{throw new pt("invalid_binding")}if(this.rounds=i.maxRounds??64,!Number.isSafeInteger(this.rounds)||this.rounds<1||this.rounds>64)throw new RangeError("invalid app log pump rounds")}runtime;transport;abort=new AbortController;endpoint;collection;rounds;work=null;closed=!1;failed=!1;retired=!1;problem=null;terminal=null;health=null;sent=0;readAfter=[-1n,-1n];readAdvances=0;get fenced(){return this.failed}get callsSent(){return this.sent}get readProgress(){return this.readAdvances}responseProgress(){return this.transport.responseProgress?.()??[]}get serverProblem(){return this.problem}get terminalProblem(){return this.terminal}get transportHealth(){return this.health}current(){if(this.closed||this.failed)return!1;if(ns(this.transport.endpoint)!==this.endpoint||!Fh(U(this.transport.collection),this.collection))throw new pt("invalid_binding");return this.transport.isCurrent()===!0?!0:(this.retire(),!1)}retire(){if(this.closed=!0,this.abort.abort(),!this.retired){this.retired=!0;try{this.runtime.retireLog()}catch{throw this.failed=!0,new pt("fenced")}}}capture(e){if(!Array.isArray(e)||e.length>IT)throw new pt("invalid_call");let t=0,i=new Set,o=[];try{for(let s of e){if(ns(s.endpoint)!==this.endpoint||!(s.frame instanceof Uint8Array)||s.frame.length>bI||s.sidecar!==void 0&&(!(s.sidecar instanceof Uint8Array)||s.sidecar.length>CT))throw new pt("invalid_call");if(t+=s.frame.length+(s.sidecar?.length??0),t>OT)throw new pt("invalid_call");let r=ue(s.frame);if(!(r instanceof Map))throw new pt("invalid_call");let a=r;if(a.size!==4||a.get(0)!==0||!RT.has(a.get(2)))throw new pt("invalid_call");let p=ns(a.get(1));if(i.has(p))throw new pt("invalid_call");i.add(p);let l=a.get(3),c=l instanceof Map?l.get(0):void 0;if(!(c instanceof Uint8Array)||!Fh(c,this.collection)||s.sidecar!==void 0&&a.get(2)!=="put_object")throw new pt("invalid_call");if(s.sidecar!==void 0){let u=l,f=u.get(4);if(s.sidecar.length<=1024*1024||ns(u.get(3))!==BigInt(s.sidecar.length)||u.has(5)||!(f instanceof Uint8Array)||!Fh(f,it(s.sidecar)))throw new pt("invalid_call")}let d=a.get(2)==="read"?{after:ns(l.get(1)),control:l.get(3)===1}:void 0;o.push({id:p,method:a.get(2),...d?{read:d}:{},call:{endpoint:this.endpoint,frame:s.frame.slice(),...s.sidecar?{sidecar:s.sidecar.slice()}:{}}})}return o}catch{for(let s of o)this.wipe(s);throw new pt("invalid_call")}}wipe(e){e.call.frame.fill(0),e.call.sidecar?.fill(0)}pump(){return this.work?this.work:this.failed?Promise.reject(new pt("fenced")):this.closed?Promise.resolve({quiet:!0}):(this.work=Promise.resolve().then(()=>this.drive()).finally(()=>{this.work=null}),this.work)}async drive(){try{for(let e=0;e<this.rounds;e++){if(!this.current())return{quiet:!0};let t=this.capture(this.runtime.takeLogCalls());if(!t.length)return{quiet:!0};this.sent+=t.length;let i=[];try{for(let o=0;o<t.length;){if(!this.current())return{quiet:!0};let s=o+1,r=l=>ET.has(t[l].method);if(r(o))for(;s<t.length&&s-o<qT&&r(s);)s++;let a=t.slice(o,s);o=s;let p=a.map(l=>this.transport.send(l.call,{signal:this.abort.signal}).then(c=>({reply:c,error:null}),c=>({reply:null,error:c})));i.push(...p);for(let[l,c]of a.entries()){let{reply:d,error:u}=await p[l];if(d===null){if(!this.current())return{quiet:!0};let f=wI(u);if(kn(f)){let m=St(f);m&&(this.problem=f),(m||f.status===403&&f.code==="forbidden")&&(this.terminal??=f)}let h=Bw(u);h&&(this.health=h),this.runtime.logNoResponse(c.id);continue}try{if(!this.current())return{quiet:!0};if(!(d instanceof Uint8Array)||d.length>bI){this.runtime.logNoResponse(c.id);continue}if(this.runtime.acceptLogReply(c.id,d)!==!0)this.runtime.logNoResponse(c.id);else if(this.problem=null,this.health=null,c.read){let f=c.read.control?1:0;c.read.after>this.readAfter[f]&&(this.readAfter[f]=c.read.after,this.readAdvances++)}}finally{d instanceof Uint8Array&&d.fill(0)}}}}finally{for(let o of await Promise.all(i))o.reply instanceof Uint8Array&&o.reply.fill(0);for(let o of t)this.wipe(o)}}return{quiet:!1}}catch{throw this.failed=!0,this.retire(),new pt("fenced")}}async drainForAuthenticatedReconnect(){if(this.closed||this.failed||this.retired)throw new pt("fenced");if(this.closed=!0,this.abort.abort(),this.retired=!0,await this.work?.catch(()=>{}),this.failed)throw new pt("fenced")}async close(){this.retire(),await this.work?.catch(()=>{})}};no();Go();function bp(n,e,t=0,i={nodes:0}){if(t>32||++i.nodes>65536)throw A("invalid_request","resource DATA exceeds bound");if(n===null||typeof n=="boolean"||typeof n=="string"||typeof n=="number"&&Number.isFinite(n))return n;if(Array.isArray(n))return n.map(r=>bp(r,e,t+1,i));let o=e?n!==null&&typeof n=="object"&&Object.getPrototypeOf(n)===Object.prototype?Object.entries(n):null:n instanceof Map?[...n]:null;if(!o)throw A("invalid_request","invalid resource DATA");let s=new Map;for(let[r,a]of o){if(typeof r!="string"||s.has(r))throw A("invalid_request","invalid resource DATA");s.set(r,bp(a,e,t+1,i))}return e?s:Object.fromEntries(s)}var an=class extends Error{reason="strict_device_approval";constructor(){super("this account uses strict device approval; add this device from your desktop"),this.name="AppStrictDeviceApprovalError"}},M=()=>A("unavailable","app runtime unavailable; reopen and reconcile");function vI(n){if(!(n instanceof Uint8Array)||n.length===0||n.length>64*1024)throw M();return new Uint8Array(n)}function vn(n){if((typeof n!="number"||!Number.isSafeInteger(n))&&typeof n!="bigint")throw M();let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw M();return e}var _I=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]);function Ht(n){if(!(n instanceof Uint8Array)||n.length!==32)throw M();return n}var fl=class n extends $s{constructor(t,i){super(t);this.sqlBinding=i}sqlBinding;attempted=!1;active=!1;retired=!1;collection=null;deviceId=null;connectorId=null;cpPin=null;deviceAttempted=!1;deviceActive=!1;deviceRegistered=!1;devicePin=null;installationId=null;publicIdentity=null;noiseEnvelope=null;cloudSource=null;cloudCallback=null;cloudCollection=null;cloudPurpose=null;cloudIssued=!1;privateAttempted=!1;privateSource=null;prospectiveCollection=null;privatePurpose=null;sasCommitment=null;privateEnrolAcknowledged=!1;endpoint=null;logGeneration=0n;pump=null;transport=null;get sql(){return this.sqlBinding.sql}get app(){return this.x}static async create(t,i){if(i.needsRecovery)throw M();return this.instantiateApp(t,i)}static async createDevice(t){return this.instantiateApp(t,null)}static async instantiateApp(t,i){let o={sql:i,exports:null,run:null},s=await this.load(t,a=>(o.exports=a,o.run=i?.import(a)??null,{host_app_sql:(p,l)=>o.run?.(p,l)??0n})),r=["rt_app_account_key_unlock","rt_app_account_key_status","rt_app_account_key_device_setup","rt_app_private_collection_pin","rt_app_private_enrol_restore","rt_app_private_enrol_commitment","rt_app_private_create_sign","rt_app_private_device_enrol_sign","rt_app_device_open","rt_app_device_registered","rt_app_device_adopt","rt_app_device_retire","rt_app_cp_enrol_sign","rt_app_verify_handover","rt_app_cp_bind_connector","rt_app_cp_log_token_sign","rt_app_open","rt_app_log_bind","rt_app_log_generation","rt_app_log_reconnect","rt_app_log_http_sign","rt_app_log_calls","rt_app_log_reply","rt_app_log_no_response","rt_app_log_retire","rt_app_log_push","rt_app_observations","rt_app_shutdown"];if(!(s.memory instanceof WebAssembly.Memory)||r.some(a=>typeof s[a]!="function"))throw M();return new n(s,o)}open(t){throw M()}fail(){try{(this.active||this.attempted)&&this.sql?.fence()}finally{this.active=!1,this.deviceActive=!1,this.discard()}}guard(t){try{return t()}catch{throw this.fail(),M()}}openAppConsuming(t){let i=null;try{if(this.attempted||this.deviceAttempted||!this.sql||this.sql.needsRecovery)throw M();this.attempted=!0;let o=vn(t.endpoint);if(!Array.isArray(t.trustedRoots)||t.trustedRoots.length<1||t.trustedRoots.length>64||!Array.isArray(t.trustedSigners)||t.trustedSigners.length>1024||!Number.isSafeInteger(t.sqliteVersion)||t.sqliteVersion<0||t.sqliteVersion>4294967295)throw M();let s=t.state==="e2e"?0:t.state==="cloud_copy"?1:-1,r=t.opened==="fresh"?0:t.opened==="existing"?1:t.opened==="unclean"?2:-1;if(s<0||r<0||typeof t.cloudCopyOptIn!="boolean"||s===1!==t.cloudCopyOptIn||(i=qn(new Map([[0,3],[1,U(t.collection)],[2,U(t.replicaId)],[3,U(t.deviceId)],[4,o],[5,t.trustedRoots.map(Ht)],[6,t.trustedSigners.map(U)],[7,Ap(t.expectedGenesis)],[8,s],[9,t.cloudCopyOptIn],[10,Ht(t.signSecretKey)],[11,Ht(t.kemSecretKey)],[12,r],[13,t.sqliteVersion],[16,vI(t.policyPins)]])),i.length>64*1024)||this.guard(()=>this.takeOut(this.app.rt_app_open(...this.put(i)))).length)throw M();this.collection=t.collection,this.deviceId=t.deviceId,this.endpoint=o,this.active=!0,this.markOpened()}catch{throw this.retireLog(),this.fail(),M()}finally{i?.fill(0),t.signSecretKey?.fill(0),t.kemSecretKey?.fill(0)}}tick(){this.active&&!this.retired&&this.guard(()=>super.tick())}connect(t={}){if(!this.active||this.retired||t.collection!==void 0&&(typeof t.collection!="string"||t.collection.toLowerCase()!==this.collection?.toLowerCase()))throw M();let i=super.connect(t),o=i.send.bind(i),s=i.close.bind(i);return i.send=r=>this.guard(()=>o(r)),i.close=()=>this.guard(()=>s()),i}executeBases(t,i){return this.readBases(t,i,"execute")}discoverBases(t,i,o){if(i!=="list-views"&&i!=="read-view-source")throw M();return this.readBases(t,o,i)}readBases(t,i,o){let s=this.sessionForPort(t),r=o==="execute"?this.app.rt_app_bases_execute:o==="list-views"?this.app.rt_app_bases_list_views:this.app.rt_app_bases_read_view_source;if(!this.active||this.retired||!this.sql||this.sql.needsRecovery||s===null||typeof r!="function")throw M();if(!(i instanceof Uint8Array)||!i.length||i.length>128*1024)throw A("invalid_request","Bases request bytes exceed bound");let a=new Uint8Array(i);try{let p=this.guard(()=>{let l=vn(r.call(this.app,s,...this.put(a))),c=Number(l&0xffffffffn);if(!c||c>(o==="execute"?16:1)*1024*1024)throw M();return this.takeOut(l)});if(!this.active||this.retired||this.sql.needsRecovery||this.sessionForPort(t)!==s)throw p.fill(0),M();return p}finally{a.fill(0)}}setupResources(t,i,o,s,r){let a=this.sessionForPort(t),p=this.app.rt_app_resources;if(!this.active||this.retired||!this.sql||this.sql.needsRecovery||a===null||typeof p!="function")throw A("unavailable","resource setup unsupported","resource_setup_unsupported");if(i!=="assess"&&i!=="apply"||i==="apply"&&(typeof s!="string"||!/^sha256:[0-9a-f]{64}$/.test(s)))throw M();let l=r!==void 0,c=[1,i==="apply"?1:0,bp(o,!0),s??null];l&&c.push(bp(ei(r),!0));let d=pe(c);if(!d.length||d.length>512*1024)throw d.fill(0),A("invalid_request","resource DATA exceeds bound");let u;try{if(u=this.guard(()=>{let m=vn(p.call(this.app,a,...this.put(d))),b=Number(m&0xffffffffn);if(!b||b>512*1024)throw M();return this.takeOut(m)}),!this.active||this.retired||this.sql.needsRecovery||this.sessionForPort(t)!==a)throw M();let f=this.guard(()=>ue(u));if(!Array.isArray(f)||f.length!==3||f[0]!==1||typeof f[1]!="boolean")throw M();if(f[1]===!1)throw A("unavailable","resource setup unavailable","resource_setup_unavailable");let h=bp(f[2],!1);return i==="assess"?Jo(h,l):xt(h)}finally{d.fill(0),u?.fill(0)}}resourceRejected(t,i){let o=null;try{let s=this.sessionForPort(t),r=this.app.rt_app_receipt_rejected;return!this.active||this.retired||s===null||typeof r!="function"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(i)?!1:(o=U(i),this.guard(()=>r.call(this.app,s,...this.put(o)))===1&&this.active&&!this.retired&&this.sessionForPort(t)===s)}catch{return!1}finally{o?.fill(0)}}verifyHandover(t,i,o){let s=null,r=null;try{let a=this.sessionForPort(t),p=i.collection,l=i.deviceId;if(!this.active||this.retired||a===null||p!==this.collection||i.isCurrent()!==!0||!(o instanceof Uint8Array)||o.length>64*1024)return null;s=new Uint8Array(o),r=U(l);let c=this.guard(()=>this.takeOut(this.app.rt_app_verify_handover(a,...this.put(r),...this.put(s))));if(c.length===0||this.sessionForPort(t)!==a||i.isCurrent()!==!0||i.collection!==p||i.deviceId!==l)return null;let d=this.guard(()=>Lp.dec(ue(c)));return d.seq===0||[d.chain,d.policyGeneration,d.catalogGeneration].some(u=>u===`sha256:${"00".repeat(32)}`)?null:d}catch{return null}finally{s?.fill(0),r?.fill(0)}}bindCpConnector(t){let i=null;try{if(!this.active||this.retired||this.pump||this.cpPin||t.isCurrent()!==!0||t.deviceId!==this.deviceId||t.collection!==this.collection)throw M();let o=t.connectorId;if(i=U(o),i.every(s=>s===0)||this.guard(()=>this.app.rt_app_cp_bind_connector(...this.put(i)))!==1)throw M();this.connectorId=o,this.cpPin=t}catch{throw M()}finally{i?.fill(0)}}deviceCurrent(){try{let t=this.devicePin;return this.deviceActive&&!this.retired&&t!==null&&t.isCurrent()===!0&&t.connectorId===this.connectorId&&t.deviceId===this.deviceId&&t.installationId===this.installationId}catch{return!1}}publicResult(t){if(t.length>1024)throw M();let i=ue(t);if(!(i instanceof Map))throw M();let o=i;if(o.size!==4||[0,1,2,3].some(r=>!o.has(r)))throw M();let s=r=>{let a=o.get(r);if(!(a instanceof Uint8Array)||a.length!==32||a.every(p=>p===0))throw M();return new Uint8Array(a)};return{m:o,identity:Object.freeze({signPublicKey:s(0),kemPublicKey:s(1),noisePublicKey:s(2)})}}openDeviceConsuming(t){let i=null;try{if(this.deviceAttempted||this.attempted||this.retired)throw M();this.deviceAttempted=!0;let o=t.pin;if(this.devicePin=o,this.connectorId=o.connectorId,this.deviceId=o.deviceId,this.installationId=o.installationId,this.deviceActive=!0,!this.deviceCurrent())throw M();let s=[this.connectorId,this.deviceId,this.installationId].map(U);if(s.some(l=>l.every(c=>c===0)))throw M();let r=t.opened;if(r.mode!=="fresh"&&r.mode!=="existing"||r.mode==="existing"&&(!(r.envelope instanceof Uint8Array)||!r.envelope.length||r.envelope.length>1024))throw M();i=qn(new Map([[0,1],[1,s[0]],[2,s[1]],[3,s[2]],[4,r.mode==="fresh"?0:1],[5,Ht(t.signSecretKey)],[6,Ht(t.kemSecretKey)],[7,r.mode==="fresh"?new Uint8Array:new Uint8Array(r.envelope)]]));let a=this.guard(()=>this.takeOut(this.app.rt_app_device_open(...this.put(i))));if(!a.length||!this.deviceCurrent())throw M();let p=this.guard(()=>{let{m:l,identity:c}=this.publicResult(a),d=l.get(3);if(!(d instanceof Uint8Array)||!d.length||d.length>1024)throw M();return{...c,envelope:new Uint8Array(d)}});return this.publicIdentity={signPublicKey:new Uint8Array(p.signPublicKey),kemPublicKey:new Uint8Array(p.kemPublicKey),noisePublicKey:new Uint8Array(p.noisePublicKey)},this.noiseEnvelope=new Uint8Array(p.envelope),Object.freeze(p)}catch{throw this.retireLog(),M()}finally{i?.fill(0),t.signSecretKey?.fill(0),t.kemSecretKey?.fill(0)}}deviceCustodyCurrent(t,i){try{return this.deviceCurrent()&&!this.active&&this.publicIdentity!==null&&this.noiseEnvelope!==null&&t.isCurrent()===!0&&t.connectorId===this.connectorId&&t.deviceId===this.deviceId&&t.installationId===this.installationId&&i.envelope instanceof Uint8Array&&i.envelope.length===this.noiseEnvelope.length&&i.envelope.every((o,s)=>o===this.noiseEnvelope[s])&&["signPublicKey","kemPublicKey","noisePublicKey"].every(o=>i[o]instanceof Uint8Array&&i[o].length===32&&i[o].every((s,r)=>s===this.publicIdentity[o][r]))}catch{return!1}}acknowledgeDeviceRegistration(t){let i=null;try{if(!this.deviceCurrent()||this.active||this.deviceRegistered||!this.publicIdentity||t.connectorId!==this.connectorId||t.deviceId!==this.deviceId||t.installationId!==this.installationId)throw M();for(let o of["signPublicKey","kemPublicKey","noisePublicKey"])if(Ht(t[o]).some((s,r)=>s!==this.publicIdentity[o][r]))throw M();if(i=qn(new Map([[0,U(t.connectorId)],[1,U(t.deviceId)],[2,U(t.installationId)],[3,new Uint8Array(t.signPublicKey)],[4,new Uint8Array(t.kemPublicKey)],[5,new Uint8Array(t.noisePublicKey)]])),this.guard(()=>this.app.rt_app_device_registered(...this.put(i)))!==1||!this.deviceCurrent())throw M();this.deviceRegistered=!0}catch{throw this.retireLog(),M()}finally{i?.fill(0)}}prepareCloudCopyCollection(t){let i=null;try{if(t.approvalMode==="strict")throw new an;if(this.cloudSource||this.privateAttempted||!this.deviceCurrent()||!this.deviceRegistered||this.active||t.approvalMode!=="password-ak1"||!["create","join"].includes(t.purpose)||(this.cloudSource=t,this.cloudCallback=t.isCurrent,this.cloudCollection=t.collection,this.cloudPurpose=t.purpose,!this.cloudCopyCollectionCurrent(t)))throw M();let o=U(t.collection);if(o.every(s=>s===0)||(i=qn(new Map([[0,o],[1,t.purpose==="create"?0:1]])),this.guard(()=>this.app.rt_app_cloud_copy_pin(...this.put(i)))!==1||!this.cloudCopyCollectionCurrent(t)))throw M()}catch(o){throw this.retireLog(),o instanceof an?o:M()}finally{i?.fill(0)}}cloudCopyCollectionCurrent(t){try{let i=this.cloudSource;return this.deviceCurrent()&&!this.active&&this.deviceRegistered&&i!==null&&(!t||t===i)&&i.isCurrent===this.cloudCallback&&i.isCurrent()===!0&&i.connectorId===this.connectorId&&i.deviceId===this.deviceId&&i.installationId===this.installationId&&i.collection===this.cloudCollection&&i.purpose===this.cloudPurpose&&i.approvalMode==="password-ak1"}catch{return!1}}signCloudCopyCreate(t){return this.signCloudCopy(t,"create")}signCloudCopyJoin(t){return this.signCloudCopy(t,"join")}signCloudCopy(t,i){let o=null,s=null;try{if(this.cloudIssued||!this.cloudCopyCollectionCurrent()||this.cloudPurpose!==i||(this.cloudIssued=!0,o=new Uint8Array(Ht(t)),s=this.guard(()=>this.takeOut(i==="create"?this.app.rt_app_cloud_copy_create_sign(...this.put(o)):this.app.rt_app_cloud_copy_join_sign(...this.put(o)))),s.length!==64||!this.cloudCopyCollectionCurrent()))throw M();return s}catch{throw s?.fill(0),this.retireLog(),M()}finally{o?.fill(0)}}preparePrivateCollection(t,i){let o=null,s=null;try{if(t.approvalMode==="strict")throw new an;if(this.cloudSource||this.privateAttempted||!this.deviceCurrent()||!this.deviceRegistered||this.active||t.approvalMode!=="password-ak1"||!["create","enrol"].includes(t.purpose)||(this.privateAttempted=!0,this.privateSource=t,this.prospectiveCollection=t.collection,this.privatePurpose=t.purpose,!this.privateCollectionCurrent()))throw M();let r=U(t.collection);if(r.every(a=>a===0))throw M();if(i.mode==="fresh"){if(o=qn(new Map([[0,r],[1,t.purpose==="create"?0:1]])),this.guard(()=>this.app.rt_app_private_collection_pin(...this.put(o)))!==1)throw M()}else if(i.mode==="existing"){let a=i.marker,p=this.publicIdentity;if(t.purpose!=="enrol"||!p||a.collection!==t.collection||a.connectorId!==this.connectorId||a.deviceId!==this.deviceId||a.installationId!==this.installationId||typeof a.acknowledged!="boolean")throw M();for(let c of["signPublicKey","kemPublicKey","noisePublicKey"])if(!_I(Ht(a[c]),p[c]))throw M();let l=new Uint8Array(Ht(a.sasCommitment));if(l.every(c=>c===0)||(s=l,o=qn(new Map([[0,1],[1,r],[2,U(a.connectorId)],[3,U(a.deviceId)],[4,U(a.installationId)],[5,new Uint8Array(a.signPublicKey)],[6,new Uint8Array(a.kemPublicKey)],[7,new Uint8Array(a.noisePublicKey)],[8,l],[9,a.acknowledged]])),this.privateEnrolAcknowledged=a.acknowledged,this.guard(()=>this.app.rt_app_private_enrol_restore(...this.put(o)))!==1))throw M()}else throw M();if(!this.privateCollectionCurrent())throw M();if(t.purpose==="enrol"){let a=this.guard(()=>this.takeOut(this.app.rt_app_private_enrol_commitment()));if(a.length!==32||a.every(p=>p===0)||s!==null&&!_I(a,s))throw M();this.sasCommitment=new Uint8Array(a)}}catch(r){throw this.retireLog(),r instanceof an?r:M()}finally{o?.fill(0)}}registeredDeviceReceipt(){if(!this.deviceCurrent()||!this.deviceRegistered||!this.publicIdentity)throw M();let t=this.publicIdentity;return Object.freeze({connectorId:this.connectorId,deviceId:this.deviceId,installationId:this.installationId,signPublicKey:new Uint8Array(t.signPublicKey),kemPublicKey:new Uint8Array(t.kemPublicKey),noisePublicKey:new Uint8Array(t.noisePublicKey)})}privateEnrolMarker(){if(!this.privateCollectionCurrent()||this.privatePurpose!=="enrol"||!this.sasCommitment||!this.publicIdentity)throw M();let t=this.publicIdentity;return Object.freeze({connectorId:this.connectorId,deviceId:this.deviceId,installationId:this.installationId,collection:this.prospectiveCollection,sasCommitment:new Uint8Array(this.sasCommitment),acknowledged:this.privateEnrolAcknowledged,signPublicKey:new Uint8Array(t.signPublicKey),kemPublicKey:new Uint8Array(t.kemPublicKey),noisePublicKey:new Uint8Array(t.noisePublicKey)})}privateCollectionCurrent(t){try{if(t&&(t.isCurrent()!==!0||t.connectorId!==this.connectorId||t.deviceId!==this.deviceId||t.installationId!==this.installationId||t.collection!==this.prospectiveCollection||t.purpose!==this.privatePurpose||t.approvalMode!=="password-ak1"))return!1;let i=this.privateSource;return this.deviceCurrent()&&!this.active&&this.deviceRegistered&&i!==null&&i.isCurrent()===!0&&i.connectorId===this.connectorId&&i.deviceId===this.deviceId&&i.installationId===this.installationId&&i.collection===this.prospectiveCollection&&i.purpose===this.privatePurpose&&i.approvalMode==="password-ak1"}catch{return!1}}signPrivateCreate(t){let i=null;try{if(!this.privateCollectionCurrent()||this.privatePurpose!=="create")throw M();i=new Uint8Array(Ht(t));let o=this.guard(()=>this.takeOut(this.app.rt_app_private_create_sign(...this.put(i))));if(o.length!==64||!this.privateCollectionCurrent())throw M();return o}catch{throw this.retireLog(),M()}finally{i?.fill(0)}}signPrivateDeviceEnrol(t){let i=null;try{if(!this.privateCollectionCurrent()||this.privatePurpose!=="enrol"||!this.sasCommitment||this.privateEnrolAcknowledged)throw M();i=new Uint8Array(Ht(t));let o=this.guard(()=>this.takeOut(this.app.rt_app_private_device_enrol_sign(...this.put(i))));if(o.length!==64||!this.privateCollectionCurrent())throw M();return Object.freeze({signature:o,sasCommitment:new Uint8Array(this.sasCommitment)})}catch{throw this.retireLog(),M()}finally{i?.fill(0)}}adoptDevice(t,i){let o=null;try{if(!this.deviceCurrent()||!this.deviceRegistered||this.attempted||this.active||t.deviceId!==this.deviceId||this.privateSource&&(!this.privateCollectionCurrent()||t.collection!==this.prospectiveCollection)||this.cloudSource&&(!this.cloudCopyCollectionCurrent()||t.collection!==this.cloudCollection||t.state!=="cloud_copy"||t.cloudCopyOptIn!==!0))throw M();let s=vI(t.policyPins);if(i){if(this.sql||i.needsRecovery||!this.sqlBinding.exports)throw M();this.sqlBinding.sql=i,this.sqlBinding.run=i.import(this.sqlBinding.exports)}if(!this.sql||this.sql.needsRecovery)throw M();this.attempted=!0;let r=vn(t.endpoint),a=t.state==="e2e"?0:t.state==="cloud_copy"?1:-1,p=t.opened==="fresh"?0:t.opened==="existing"?1:t.opened==="unclean"?2:-1;if(a<0||p<0||typeof t.cloudCopyOptIn!="boolean"||a===1!==t.cloudCopyOptIn||!Array.isArray(t.trustedRoots)||t.trustedRoots.length<1||t.trustedRoots.length>64||!Array.isArray(t.trustedSigners)||t.trustedSigners.length>1024||!Number.isSafeInteger(t.sqliteVersion)||t.sqliteVersion<0||t.sqliteVersion>4294967295||(o=qn(new Map([[0,4],[1,U(t.collection)],[2,U(t.replicaId)],[3,U(t.deviceId)],[4,r],[5,t.trustedRoots.map(Ht)],[6,t.trustedSigners.map(U)],[7,Ap(t.expectedGenesis)],[8,a],[9,t.cloudCopyOptIn],[10,null],[11,null],[12,p],[13,t.sqliteVersion],[14,U(this.connectorId)],[15,U(this.installationId)],[16,s]])),o.length>64*1024)||this.guard(()=>this.takeOut(this.app.rt_app_device_adopt(...this.put(o)))).length||!this.deviceCurrent())throw M();this.collection=t.collection,this.endpoint=r,this.active=!0,this.markOpened()}catch{throw this.retireLog(),this.fail(),M()}finally{o?.fill(0)}}signCpEnrol(t){let i=null;try{if(!this.deviceCurrent()||!this.publicIdentity||this.active||this.pump)throw this.retireLog(),M();i=new Uint8Array(Ht(t));let o=this.guard(()=>this.takeOut(this.app.rt_app_cp_enrol_sign(...this.put(i))));if(!this.deviceCurrent())throw this.retireLog(),M();if(!o.length)throw M();let{m:s,identity:r}=this.guard(()=>this.publicResult(o)),a=s.get(3);if(!(a instanceof Uint8Array)||a.length!==64||["signPublicKey","kemPublicKey","noisePublicKey"].some(p=>r[p].some((l,c)=>l!==this.publicIdentity[p][c])))throw M();return Object.freeze({...r,signature:new Uint8Array(a)})}catch{throw this.retireLog(),M()}finally{i?.fill(0)}}signCpLogToken(t){let i=null;try{if(!this.active||this.retired||!this.cpPin)throw M();let o=this.cpPin,s=!1;try{s=o.isCurrent()===!0&&o.connectorId===this.connectorId&&o.deviceId===this.deviceId&&o.collection===this.collection}catch{}if(!s)throw this.retireLog(),M();i=new Uint8Array(Ht(t));let r=this.guard(()=>this.takeOut(this.app.rt_app_cp_log_token_sign(...this.put(i))));if(r.length!==64)throw r.fill(0),M();return r}catch{throw M()}finally{i?.fill(0)}}bindLogTransport(t){try{if(!this.active||this.retired||this.pump||this.endpoint===null||this.collection===null||t.isCurrent()!==!0||vn(t.endpoint)!==this.endpoint||t.collection!==this.collection)throw M()}catch{throw M()}let i=U(this.collection);if(this.guard(()=>this.app.rt_app_log_bind(this.endpoint,...this.put(i)))!==1)throw M();if(this.logGeneration=this.guard(()=>vn(this.app.rt_app_log_generation())),this.logGeneration===0n)throw this.retireLog(),M();return this.pump=new is(this,t,{endpoint:this.endpoint,collection:this.collection}),this.transport=t,this.pump}requestLogHead(){return!this.active||this.retired||this.pump===null||typeof this.app.rt_app_log_head!="function"?!1:this.guard(()=>this.app.rt_app_log_head())===1}get supportsLogPush(){return typeof this.app.rt_app_log_hello_sign=="function"}signLogHello(t,i){let o=null;try{if(!this.supportsLogPush||!this.active||this.retired||!this.pump||!this.transport||this.logGeneration===0n||!this.transport.isCurrent()||!(t instanceof Uint8Array)||t.length!==32||typeof i!="string"||i.length===0||i.length>16*1024||/[^\x21-\x7e]/.test(i))return null;let s=new TextEncoder().encode(i);o=new Uint8Array(32+s.length),o.set(t,0),o.set(s,32),s.fill(0);let r=this.logGeneration,a=this.guard(()=>this.takeOut(this.app.rt_app_log_hello_sign(r,...this.put(o))));return a.length!==64?(a.fill(0),null):a}catch{return null}finally{o?.fill(0)}}async reconnectLogTransport(t){let i=this.pump,o=this.logGeneration,s=()=>this.active&&!this.retired&&this.pump===i&&i!==null&&this.transport===t&&t.isCurrent()===!0&&vn(t.endpoint)===this.endpoint&&t.collection===this.collection;try{if(!s()||(await i.drainForAuthenticatedReconnect(),!s()))throw M();this.pump=null,this.transport=null;let r=U(this.collection);try{if(this.guard(()=>this.app.rt_app_log_reconnect(this.endpoint,...this.put(r)))!==1)throw M()}finally{r.fill(0)}if(this.logGeneration=this.guard(()=>vn(this.app.rt_app_log_generation())),this.logGeneration<=o||!t.isCurrent()||this.retired||!this.active)throw M();return this.pump=new is(this,t,{endpoint:this.endpoint,collection:this.collection}),this.transport=t,this.pump}catch{throw this.retireLog(),M()}}signLogHttp(t){let i=null;try{if(!this.active||!this.pump||!this.transport||this.logGeneration===0n||this.endpoint===null||t.path!=="/v1/rpc"||t.collection!==this.collection||vn(t.endpoint)!==this.endpoint||!this.transport.isCurrent()||!(t.frame instanceof Uint8Array)||t.frame.length===0||t.frame.length>16*1024*1024||!(t.nonce instanceof Uint8Array)||t.nonce.length!==32||typeof t.token!="string"||t.token.length===0||t.token.length>16*1024||/[^\x21-\x7e]/.test(t.token))throw M();i=qn(new Map([[0,t.frame],[1,t.token],[2,t.nonce]]));let o=this.guard(()=>this.takeOut(this.app.rt_app_log_http_sign(this.endpoint,this.logGeneration,vn(t.originalCallId),...this.put(i))));if(o.length!==64)throw o.fill(0),M();return o}catch{throw M()}finally{i?.fill(0)}}takeLogCalls(){return!this.active||this.retired?[]:this.guard(()=>{let t=this.takeOut(this.app.rt_app_log_calls());if(!t.length)return[];let i=ue(t);if(!Array.isArray(i)||i.length>64)throw M();return i.map(o=>{if(!(o instanceof Map))throw M();let s=o,r=s.get(0),a=s.get(1),p=s.get(2);if(vn(r)!==this.endpoint||!(a instanceof Uint8Array)||p!==void 0&&!(p instanceof Uint8Array))throw M();return{endpoint:r,frame:a,...p!==void 0?{sidecar:p}:{}}})})}acceptLogReply(t,i){return!this.active||this.retired?!1:this.guard(()=>this.app.rt_app_log_reply(vn(t),...this.put(i))===1)}logNoResponse(t){this.active&&!this.retired&&this.guard(()=>this.app.rt_app_log_no_response(vn(t)))}retireLog(){this.logGeneration=0n,!this.retired&&(this.retired=!0,this.cpPin=null,this.connectorId=null,this.devicePin=null,this.installationId=null,this.privateSource=null,this.prospectiveCollection=null,this.privatePurpose=null,this.sasCommitment?.fill(0),this.sasCommitment=null,this.publicIdentity=null,this.noiseEnvelope?.fill(0),this.noiseEnvelope=null,this.deviceActive=!1,this.deviceRegistered=!1,this.active?this.guard(()=>{super.dispose(),this.app.rt_app_log_retire()}):this.deviceAttempted&&this.guard(()=>this.app.rt_app_device_retire()))}pushLog(t){return!this.active||this.retired||!this.pump||!this.transport?!1:this.guard(()=>{let i=this.transport;return i.isCurrent()!==!0||vn(i.endpoint)!==this.endpoint||i.collection!==this.collection?(this.retireLog(),!1):this.app.rt_app_log_push(...this.put(t))===1})}accountKeyCurrent(t){try{return this.active&&!this.retired&&t.isCurrent()===!0&&t.approvalMode==="password-ak1"&&t.collection===this.collection&&t.deviceId===this.deviceId&&t.connectorId===this.connectorId&&t.installationId===this.installationId&&this.devicePin!==null&&this.devicePin.isCurrent()===!0&&this.devicePin.connectorId===this.connectorId&&this.devicePin.deviceId===this.deviceId&&this.devicePin.installationId===this.installationId}catch{return!1}}accountKeyState(t){let i=ue(t);if(!(i instanceof Map))throw M();let o=i;if(o.size!==2||!o.has(0)||!o.has(1))throw M();let s=o.get(0),r=o.get(1);if(s===0||s===1){if(r!==null)throw M();return Object.freeze({state:s===0?"pending":"keyed"})}if(s!==2||typeof r!="string"||!["not_private","not_ready","not_enrolled","not_authorized","device_missing","enrolment_mismatch","not_keyed","no_wrap","inconsistent","failed","outcome_unknown"].includes(r))throw M();return Object.freeze({state:"refused",reason:r})}unlockAccountKeyConsuming(t,i){try{if(t.approvalMode==="strict")throw new an;if(!this.accountKeyCurrent(t))throw M();Ht(i);let o=this.guard(()=>this.accountKeyState(this.takeOut(this.app.rt_app_account_key_unlock(...this.put(i)))));if(!this.accountKeyCurrent(t))throw M();return o}catch(o){throw this.retireLog(),o instanceof an?o:M()}finally{i instanceof Uint8Array&&i.fill(0)}}setupAccountKeyDeviceConsuming(t,i){try{if(t.approvalMode==="strict")throw new an;if(!this.accountKeyCurrent(t))throw M();Ht(i);let o=this.guard(()=>this.accountKeyState(this.takeOut(this.app.rt_app_account_key_device_setup(...this.put(i)))));if(!this.accountKeyCurrent(t))throw M();return o.state==="refused"?o:Object.freeze({state:o.state==="keyed"?"recovery_keyed":"recovery_pending"})}catch(o){throw this.retireLog(),o instanceof an?o:M()}finally{i instanceof Uint8Array&&i.fill(0)}}accountKeyStatus(t){try{if(!this.accountKeyCurrent(t))throw M();let i=this.guard(()=>this.accountKeyState(this.takeOut(this.app.rt_app_account_key_status())));if(!this.accountKeyCurrent(t))throw M();return i}catch{throw this.retireLog(),M()}}observations(){if(!this.active||this.retired)throw M();return this.guard(()=>{let t=ue(this.takeOut(this.app.rt_app_observations()));if(!(t instanceof Map))throw M();let i=t;for(let o of[1,2,3,4])if(typeof i.get(o)!="boolean")throw M();return{status:er.dec(i.get(0)),keyringRebuilding:i.get(1),keyringRebuildFailed:i.get(2),snapshotInstallAvailable:i.get(3),requiresReopen:i.get(4)}})}async close(){return this.pump&&(await this.pump.close(),this.pump=null,this.transport=null),this.shutdown()}shutdown(){if(!this.active)return this.deviceAttempted&&!this.retired&&this.retireLog(),this.discard(),!1;if(this.pump)return this.pump.close().catch(()=>{}),this.fail(),!1;try{return this.retireLog(),super.dispose(),this.guard(()=>this.app.rt_app_shutdown()===1)&&this.sql!==null&&!this.sql.needsRecovery}finally{this.active=!1,this.discard()}}dispose(){this.shutdown()}};async function AI(n){if(!n.worker)return{supported:!1,reason:"worker_required"};if(!n.storage?.getDirectory)return{supported:!1,reason:"opfs_unavailable"};let e,t,i=!1,o,s={supported:!1,reason:"probe_failed"};try{let r=n.randomUUID();if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(r))return s;t=r.toLowerCase(),e=await(await n.storage.getDirectory()).getDirectoryHandle(".mdbase-app-probes",{create:!0});let a=await e.getFileHandle(t,{create:!0});if(i=!0,!a.createSyncAccessHandle)s={supported:!1,reason:"sync_handle_unavailable"};else{o=await a.createSyncAccessHandle();let p=new Uint8Array([109,100,98,110]),l=new Uint8Array(p.length);if(o.write(p,{at:0})!==p.length)throw new Error("short probe write");if(o.flush(),o.read(l,{at:0})!==p.length||l.some((c,d)=>c!==p[d]))throw new Error("probe readback failed");s={supported:!0,backend:"opfs_sahpool_candidate",crashDurability:"unqualified",eviction:"possible"}}}catch{s={supported:!1,reason:"probe_failed"}}finally{let r=!0;try{o?.close()}catch{r=!1,s={supported:!1,reason:"cleanup_failed"}}if(i&&r&&e&&t)try{await e.removeEntry(t)}catch{s={supported:!1,reason:"cleanup_failed"}}}return s}eo();Qr();vw();no();rp();Go();Jb();kh();Yc();var Fw=Object.freeze({status:"unsupported"}),Vh=Object.freeze({snapshot(){return Fw},async check(n={}){return n.signal?.throwIfAborted(),Fw},async request(n={}){return n.signal?.throwIfAborted(),Fw},disable(){}});Fn();Yc();var Kw="mdbase.app.log-token.v1",hl="tokens";function kI(){return new Promise(n=>{let e;try{e=indexedDB.open(Kw,1)}catch{n(null);return}e.onupgradeneeded=()=>{try{e.result.createObjectStore(hl)}catch{}},e.onsuccess=()=>{let t=e.result;t.onversionchange=()=>t.close(),n(t.objectStoreNames.contains(hl)?t:(t.close(),null))},e.onerror=e.onblocked=()=>n(null)})}function Vw(n,e){return kI().then(t=>new Promise(i=>{if(!t){i(null);return}let o=null;try{let s=t.transaction(hl,n),r=e(s.objectStore(hl));r&&(r.onsuccess=()=>{o=r.result??null}),s.oncomplete=()=>{t.close(),i(o)},s.onerror=s.onabort=()=>{t.close(),i(null)}}catch{t.close(),i(null)}}))}function SI(){return typeof indexedDB>"u"?null:Object.freeze({async read(n,e){let t=await Vw("readonly",i=>i.get(n)).catch(()=>null);return!t||typeof t.value!="string"||!t.value||t.value.length>16*1024||/[^\x21-\x7e]/.test(t.value)||typeof t.expires!="number"||!Number.isSafeInteger(t.expires)||t.expires-e<6e4||t.expires-e>16*6e4?null:Object.freeze({value:t.value,expires:t.expires})},async write(n,e){await Vw("readwrite",t=>t.put({value:e.value,expires:e.expires},n)).catch(()=>null)},async drop(n){await Vw("readwrite",e=>e.delete(n)).catch(()=>null)}})}async function PI(n){let{cpOrigin:e,connectorId:t,deviceId:i}=n;if(!t||!i)return!0;let o=await kI();return o?new Promise(s=>{try{let r=o.transaction(hl,"readwrite"),a=r.objectStore(hl).openCursor();a.onsuccess=()=>{let p=a.result;if(p){if(typeof p.key=="string"){let l=p.key.split(" ");l.length===5&&l[0]===e&&l[2]===t&&l[3]===i&&p.delete()}p.continue()}},r.oncomplete=()=>{o.close(),s(!0)},r.onerror=r.onabort=()=>{o.close(),s(!1)}}catch{o.close(),s(!1)}}):!1}cw();Jn();ge();Fc();Ps();ie();su();Zc();bt();Je();ge();var MT=4401,LT=4403,jT=4410,NT=3e4,UT=1e4,DT=6e4,$T=6e4,zT=15e3,BT=4,FT=64*1024,VT=1024*1024;function KT(n,e){let t=new URL(n);if(t.protocol==="https:")return`wss://${t.host}`;if(e&&ot(n))return`ws://${t.host}`;throw new Error("app log push: origin")}var WT=n=>[...n].map(e=>e.toString(16).padStart(2,"0")).join(""),xI=(n,e,t)=>pe(new Map([[0,0],[1,n],[2,e],[3,t]]));function HT(n){let e=n.get(3);if(!(e instanceof Map))return null;let t=e.get(0),i=e.get(1);return{code:typeof t=="string"?t:"unavailable",reason:typeof i=="string"?i:""}}var Kh=class{constructor(e,t,i={}){this.source=e;this.events=t;this.base=KT(e.origin,i.allowLoopbackHttp===!0),this.collectionBytes=U(e.collection);let o=i.WebSocket??globalThis.WebSocket;if(typeof o!="function")throw new Error("app log push: no WebSocket");this.Ws=o,this.random=i.random??Math.random,this.now=i.now??Date.now}source;events;base;collectionBytes;Ws;random;now;socket=null;connecting=!1;closed=!1;finished=null;unsupported=!1;paused=!1;isLive=!1;attempts=0;liveSince=0;retry=null;ping=null;pongDue=null;opening=null;unsigned=0;life=new AbortController;token=null;get live(){return this.isLive}get available(){return!this.unsupported&&this.finished===null&&!this.closed}get suspended(){return this.paused}start(){this.connect()}nudge(){this.unsupported=!1,this.unsigned=0,!(this.paused||this.socket||this.connecting||!this.available)&&(this.attempts=0,this.clearRetry(),this.connect())}suspend(){this.paused||!this.available||(this.paused=!0,this.clearRetry(),this.drop(1e3,"hidden"))}resume(){if(!this.paused){this.nudge();return}this.paused=!1,this.nudge()}close(){this.closed||(this.closed=!0,this.life.abort(),this.clearRetry(),this.drop(1e3,"closed"))}clearRetry(){this.retry!==null&&clearTimeout(this.retry),this.retry=null}clearPing(){this.ping!==null&&clearInterval(this.ping),this.ping=null,this.pongDue!==null&&clearTimeout(this.pongDue),this.pongDue=null,this.opening!==null&&clearTimeout(this.opening),this.opening=null}setLive(e){if(this.isLive!==e){this.isLive=e,e&&(this.liveSince=this.now());try{this.events.live(e)}catch{}}}end(e){if(!(this.finished||this.closed)){this.finished=e,this.clearRetry(),this.drop(1e3,e);try{this.events.ended(e)}catch{}}}drop(e,t){this.clearPing();let i=this.socket;if(this.socket=null,i){i.onopen=i.onmessage=i.onclose=i.onerror=null;try{i.close(e,t)}catch{}}this.setLive(!1)}schedule(e=!1){if(this.paused||!this.available||this.retry!==null)return;let t=e?0:Math.floor(this.random()*Math.min($T,1e3*2**Math.min(this.attempts,6)));this.attempts++,this.retry=setTimeout(()=>{this.retry=null,this.connect()},t)}async connect(){if(this.paused||this.socket||this.connecting||!this.available)return;if(!this.source.isCurrent()){this.close();return}this.connecting=!0;let e,t,i;try{let r=this.life.signal;if(e=await this.source.accessToken({signal:r}),t=await this.source.nonce({signal:r}),this.paused||!this.available||!this.source.isCurrent())return;if(i=this.source.signHello(t,e),!i){++this.unsigned>=BT?this.unsupported=!0:this.schedule();return}this.unsigned=0}catch{this.connecting=!1,this.schedule();return}finally{this.connecting=!1}this.token=e;let o;try{o=new this.Ws(`${this.base}/v1/ws?c=${this.source.collection}&n=${WT(t)}`)}catch{this.schedule();return}o.binaryType="arraybuffer",this.socket=o;let s=xI(1,"hello",new Map([[0,[1,0]],[1,e],[2,U(this.source.deviceId)],[3,i]]));i.fill(0),t.fill(0),o.onopen=()=>{try{o.send(s)}catch{this.lost(o,1006)}},o.onmessage=r=>this.message(o,r.data),o.onclose=r=>this.lost(o,r.code),o.onerror=()=>{},this.opening=setTimeout(()=>{this.opening=null,this.lost(o,1006)},zT)}message(e,t){if(e!==this.socket)return;if(typeof t=="string"){t==="pong"&&this.pongDue!==null&&(clearTimeout(this.pongDue),this.pongDue=null);return}if(!(t instanceof ArrayBuffer)||t.byteLength>VT){this.lost(e,1009);return}let i=new Uint8Array(t),o;try{let a=ue(i);if(!(a instanceof Map))throw new Error;o=a}catch{this.lost(e,1007);return}if(o.get(0)===2){if(!this.isLive)return;if(this.deliver(i),o.get(1)==="closed"){let a=o.get(2),p=a instanceof Map?a.get(1):null;this.end(p==="gone"?"gone":p==="revoked"?"revoked":"forbidden")}return}if(o.get(0)!==1)return;let s=o.get(1),r=HT(o);if(s===1){if(r){this.refused(e,r);return}try{e.send(xI(2,"subscribe",new Map([[0,this.collectionBytes],[1,0],[2,FT]])))}catch{this.lost(e,1006)}return}if(s===2){if(r){this.refused(e,r);return}let a=o.get(2);if(!(a instanceof Map)){this.lost(e,1007);return}let p=a.get(0),l=a.get(1);this.startPing(e),this.setLive(!0),(typeof p=="number"||typeof p=="bigint")&&l instanceof Uint8Array&&l.length===32&&this.deliver(pe(new Map([[0,2],[1,"head"],[2,new Map([[0,this.collectionBytes],[1,p],[2,l]])]])))}}deliver(e){try{this.events.push(e)}catch{}}refused(e,t){if(t.code==="forbidden"&&t.reason==="credentials_revoked"){this.end("revoked");return}if(t.code==="forbidden"||t.code==="not_found"){this.end(t.code==="not_found"?"gone":"forbidden");return}if(t.code==="gone"){this.end("gone");return}t.code==="unauthenticated"&&this.token&&(this.source.invalidateToken?.(this.token),this.token=null),this.lost(e,1008)}startPing(e){this.clearPing(),this.ping=setInterval(()=>{if(!(e!==this.socket||this.pongDue!==null)){try{e.send("ping")}catch{this.lost(e,1006);return}this.pongDue=setTimeout(()=>{this.pongDue=null,this.lost(e,1006)},UT)}},NT)}lost(e,t){if(e!==this.socket)return;let i=this.isLive&&this.now()-this.liveSince>=DT;if(this.drop(1e3,"lost"),t===LT){this.end("forbidden");return}if(t===jT){this.end("gone");return}if(i&&(this.attempts=0),t===MT){this.token&&this.source.invalidateToken?.(this.token),this.token=null,this.attempts=0,this.schedule(!0);return}this.schedule()}};uw();Fn();Xc();function Wh(n){return n.mode==="local_only"?null:n.incidents.some(e=>e.kind==="waiting_for_key")?"waiting_for_key":n.installing?"installing":n.resyncing?"resyncing":n.connection==="offline"?"offline":n.headKnown===0?"head_unknown":n.confirmedThrough<n.headKnown?"behind":null}function CI(n){let e=n.incidents.find(r=>r.kind==="waiting_for_key");if(!e)return null;let t={through:n.confirmedThrough,head:n.headKnown},i=e.details,o=r=>i instanceof Map?i.get(r):i&&typeof i=="object"?i[r]:void 0,s=o("reason");typeof s=="string"&&/^[a-z_]{1,32}$/.test(s)&&(t.key=s);for(let r of["position","at"]){let a=o(r);(typeof a=="number"||typeof a=="bigint")&&(t[r]=Number(a))}return t}xh();Qc();Je();ge();Fc();var Hh=264*1024+256,Ww=264*1024,De=()=>new Error("app cloud copy outcome unavailable; preserve storage and reopen"),Hw=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),GT=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),Gh=class{constructor(e,t,i,o,s){this.source=e;this.store=o;this.key=i;try{this.mode=s.mode,this.lifetime=s.signal,this.fields=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId,collection:e.collection,purpose:e.purpose,cpOrigin:e.cpOrigin,logOrigin:e.logOrigin,assetSha256:e.assetSha256});let r=e.displayName;if(this.displayName=r===void 0?void 0:br(r),this.displayName!==void 0&&e.purpose!=="create"||r!==this.displayName)throw De();this.current=e.isCurrent,this.owned=e.installationOwned,this.io=Object.freeze({read:o.read,cas:o.compareAndSet});let a=[e.accountId,e.connectorId,e.deviceId,e.installationId,e.collection].map(U);if(a.some(p=>p.every(l=>l===0))||!["create","join"].includes(e.purpose)||!["fresh","existing"].includes(this.mode)||!/^[0-9a-f]{64}$/.test(e.assetSha256)||(this.keys=Object.freeze([t.signPublicKey,t.kemPublicKey,t.noisePublicKey].map(p=>{if(!(p instanceof Uint8Array)||p.length!==32||p.every(l=>l===0))throw De();return new Uint8Array(p)})),t.connectorId!==e.connectorId||t.deviceId!==e.deviceId||t.installationId!==e.installationId)||typeof globalThis.CryptoKey!="function"||!(i instanceof CryptoKey)||i.type!=="secret"||i.extractable||i.algorithm.name!=="AES-GCM"||i.algorithm.length!==256||i.usages.length!==2||!i.usages.includes("encrypt")||!i.usages.includes("decrypt"))throw De();this.aad=pe(["mdbase/v1/app-cloud-copy-outcome-platform",...a,e.purpose,e.cpOrigin,e.logOrigin,e.assetSha256,...this.keys]),this.check(this.lifetime)}catch{throw De()}}source;store;closed=!1;key;fields;displayName;current;owned;io;keys;aad;mode;lifetime;check(e){try{if(this.closed||!this.key||e!==this.lifetime||e.aborted||this.source.displayName!==this.displayName||this.source.isCurrent!==this.current||this.source.installationOwned!==this.owned||this.current.call(this.source)!==!0||this.owned.call(this.source)!==!0||this.store.read!==this.io.read||this.store.compareAndSet!==this.io.cas||Object.entries(this.fields).some(([t,i])=>this.source[t]!==i))throw De()}catch{throw De()}}operation(e){if(e){if(e.displayName!==this.displayName)throw De();for(let t of Object.keys(this.fields))if(e[t]!==this.fields[t])throw De();for(let[t,i]of["signPublicKey","kemPublicKey","noisePublicKey"].entries())if(!(e[i]instanceof Uint8Array)||!Hw(e[i],this.keys[t]))throw De()}return Object.freeze({...this.fields,...this.displayName===void 0?{}:{displayName:this.displayName},signPublicKey:new Uint8Array(this.keys[0]),kemPublicKey:new Uint8Array(this.keys[1]),noisePublicKey:new Uint8Array(this.keys[2])})}metadata(e){let t=this.operation(e.operation);if(!(e.genesisItem instanceof Uint8Array)||!e.genesisItem.length||e.genesisItem.length>256*1024||typeof e.expectedGenesis!="string"||!/^sha256:[0-9a-f]{64}$/.test(e.expectedGenesis))throw De();return Object.freeze({operation:t,genesisItem:new Uint8Array(e.genesisItem),expectedGenesis:e.expectedGenesis})}async hashChecked(e,t){let i=new TextEncoder().encode("mdbase/v1/chain"),o=new Uint8Array(1+i.length+e.genesisItem.length);o[0]=i.length,o.set(i,1),o.set(e.genesisItem,1+i.length);let s=new Uint8Array(await crypto.subtle.digest("SHA-256",o));if(this.check(t),e.expectedGenesis!==`sha256:${GT(s)}`)throw De()}async read(e){let t=null;try{this.check(e);let i=await this.io.read.call(this.store,Object.freeze({signal:e}));if(this.check(e),i===null){if(this.mode!=="fresh")throw De();return null}if(!(i instanceof Uint8Array)||!i.length||i.length>Hh)throw De();let o=new Uint8Array(i),s=ue(o);if(!(s instanceof Map))throw De();let r=s;if(r.size!==3||r.get(0)!==1)throw De();let a=r.get(1),p=r.get(2);if(!(a instanceof Uint8Array)||a.length!==12||!(p instanceof Uint8Array)||p.length<16||p.length>Ww+16||(t=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(a),additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(p))),this.check(e),t.length>Ww))throw De();let l=ue(t);if(!(l instanceof Map))throw De();let c=l,d=c.get(0)===1&&c.size===3;if(!d&&!(c.get(0)===2&&c.size===4)||(d?null:c.get(3))!==(this.displayName??null))throw De();let u=c.get(1);if(!Array.isArray(u)||u.length!==3||u.some((m,b)=>!(m instanceof Uint8Array)||!Hw(m,this.keys[b])))throw De();let f=c.get(2),h=null;if(f!==null){if(!Array.isArray(f)||f.length!==2||!(f[0]instanceof Uint8Array)||typeof f[1]!="string")throw De();h=this.metadata({operation:this.operation(),genesisItem:f[0],expectedGenesis:f[1]}),await this.hashChecked(h,e)}return{encrypted:o,metadata:h}}catch{throw De()}finally{t?.fill(0)}}async write(e,t,i){let o=null,s=null;try{if(this.check(i),o=pe(new Map([[0,2],[1,this.keys.map(l=>new Uint8Array(l))],[2,e===null?null:[e.genesisItem,e.expectedGenesis]],[3,this.displayName??null]])),o.length>Ww)throw De();let r=crypto.getRandomValues(new Uint8Array(12)),a=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:r,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(o)));if(this.check(i),s=pe(new Map([[0,1],[1,r],[2,a]])),s.length>Hh)throw De();let p=await this.io.cas.call(this.store,t,s,Object.freeze({signal:i}));if(this.check(i),p!==!0)throw De()}catch{throw De()}finally{o?.fill(0),s?.fill(0)}}async restore(e){let{signal:t}=e,i=await this.read(t);return this.check(t),i===null?Object.freeze({state:"none"}):i.metadata===null?Object.freeze({state:"pending",operation:this.operation()}):Object.freeze({state:"completed",metadata:this.metadata(i.metadata)})}async pending(e,t){let{signal:i}=t;this.check(i),this.operation(e);let o=await this.read(i);this.check(i),!o&&await this.write(null,null,i)}async completed(e,t){let{signal:i}=t;this.check(i);let o=this.metadata(e);await this.hashChecked(o,i);let s=await this.read(i);if(this.check(i),!s)throw De();if(s.metadata){if(!Hw(s.metadata.genesisItem,o.genesisItem)||s.metadata.expectedGenesis!==o.expectedGenesis)throw De();return}await this.write(o,s.encrypted,i)}close(){this.closed=!0,this.key=null}};Jn();ge();var Yh="public-outcome",Gw="operation",Gt=()=>new Error("app cloud copy outcome store unavailable; preserve storage and reopen"),YT=(n,e)=>n===null||e===null?n===e:n.length===e.length&&n.every((t,i)=>t===e[i]);function Yw(n){if(!(n instanceof Uint8Array)||!n.length||n.length>Hh)throw Gt();return new Uint8Array(n)}var Jh=class n{constructor(e,t,i){this.source=e;this.origin=t;this.lifetime=i;this.fields=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId,collection:e.collection,purpose:e.purpose,cpOrigin:e.cpOrigin,logOrigin:e.logOrigin,assetSha256:e.assetSha256}),this.current=e.isCurrent,this.owned=e.installationOwned}source;origin;lifetime;db=null;closed=!1;fields;current;owned;get fenced(){return this.closed||this.lifetime.aborted}check(e){try{if(this.fenced||e!==this.lifetime||e.aborted||Rt()!==this.origin||this.source.isCurrent!==this.current||this.source.installationOwned!==this.owned||this.current.call(this.source)!==!0||this.owned.call(this.source)!==!0||Object.entries(this.fields).some(([t,i])=>this.source[t]!==i))throw Gt()}catch{throw Gt()}}static async open(e){let{source:t,origin:i,mode:o,signal:s,allowLoopbackHttp:r}=e,a=null;try{a=new n(t,i,s);let p=[a.fields.accountId,a.fields.connectorId,a.fields.deviceId,a.fields.installationId,a.fields.collection].map(c=>{if(U(c).every(d=>d===0))throw Gt();return c.toLowerCase()});if(!Lt(i,r===!0,e.allowNativeLoopbackHttp===!0?"native":void 0)||!["fresh","existing"].includes(o)||!["create","join"].includes(a.fields.purpose)||!/^[0-9a-f]{64}$/.test(a.fields.assetSha256)||!globalThis.indexedDB)throw Gt();a.check(s),a.db=await a.openDatabase(`mdbase.app.cloud-copy-outcome.v1.${p.join(".")}.${a.fields.purpose}`,o),a.db.onversionchange=()=>a.close(),a.check(s);let l=await a.read(Object.freeze({signal:s}));try{if(o==="fresh"!=(l===null))throw Gt();a.check(s)}finally{l?.fill(0)}return a}catch{throw a?.close(),Gt()}}openDatabase(e,t){return new Promise((i,o)=>{this.check(this.lifetime);let s=indexedDB.open(e,1),r=!1,a=!1,p=()=>{r=!0,o(Gt())},l=()=>this.lifetime.removeEventListener("abort",p);this.lifetime.addEventListener("abort",p,{once:!0}),s.onblocked=p,s.onupgradeneeded=()=>{try{if(this.check(this.lifetime),r||t!=="fresh"||s.result.objectStoreNames.length!==0)throw Gt();s.result.createObjectStore(Yh),a=!0}catch{s.transaction?.abort()}},s.onerror=()=>{l(),o(Gt())},s.onsuccess=()=>{l();try{if(this.check(this.lifetime),r||t==="fresh"&&!a||s.result.objectStoreNames.length!==1||!s.result.objectStoreNames.contains(Yh))throw Gt();i(s.result)}catch{s.result.close(),o(Gt())}}})}async read(e){let{signal:t}=e;this.check(t);let i=await this.transaction("readonly",t,null,null);return this.check(t),i}async compareAndSet(e,t,i){let{signal:o}=i;this.check(o);let s=e===null?null:Yw(e),r=Yw(t);try{let a=await this.transaction("readwrite",o,s,r);return this.check(o),a===!0}finally{s?.fill(0),r.fill(0)}}transaction(e,t,i,o){return new Promise((s,r)=>{if(this.check(t),!this.db)throw Gt();let a=this.db.transaction(Yh,e,{durability:"strict"}),p=a.objectStore(Yh),l=null,c=!1,d=()=>{c=!0;try{a.abort()}catch{}},u=()=>t.removeEventListener("abort",d);t.addEventListener("abort",d,{once:!0}),a.onabort=a.onerror=()=>{u(),l instanceof Uint8Array&&l.fill(0),r(Gt())},a.oncomplete=()=>{u();try{if(this.check(t),c)throw Gt();s(l)}catch{l instanceof Uint8Array&&l.fill(0),r(Gt())}};let f=p.get(Gw);f.onsuccess=()=>{let h=null;try{this.check(t),h=f.result===void 0?null:Yw(f.result),e==="readonly"?(l=h,h=null):(l=YT(h,i),l===!0&&o!==null&&(i===null?p.add(new Uint8Array(o),Gw):p.put(new Uint8Array(o),Gw)))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db?.close(),this.db=null)}};var co=class extends Error{constructor(t){super(`app cloud copy host: ${t}`);this.reason=t;this.name="AppCloudCopyHostError"}reason},JT=32,XT=8,Ae=n=>new co(n),II=(n,e)=>n.length===e.length&&n.every((t,i)=>t===e[i]),ml=class n{constructor(e,t,i,o,s){this.source=e;this.installation=t;this.originalRelease=i;this.origin=o;this.lifetime=s;this.selected=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,installationId:e.installationId,kind:e.kind,cpOrigin:e.cpOrigin,logOrigin:e.logOrigin,approvalMode:e.approvalMode}),this.currentCallback=e.isCurrent,this.bearerCallback=e.connectorBearer,this.ownershipCallback=t.isCurrent;for(let r of[e.accountId,e.connectorId,e.deviceId,e.installationId])if(U(r).every(a=>a===0))throw Ae("binding");if(e.kind!=="app-runtime"&&e.kind!=="mobile"||i.schema!=="mdbn-app-trust/release/1"||i.cpOrigin!==e.cpOrigin||i.logOrigin!==e.logOrigin||!/^[0-9a-f]{64}$/.test(i.assetSha256)||!i.trustedRoots.length||i.trustedRoots.length>64||!i.policyPins.length||i.policyPins.length>65536)throw Ae("binding");if(this.trust=Object.freeze({...i,source:Object.freeze({...i.source}),trustedRoots:Object.freeze(i.trustedRoots.map(r=>{if(!(r instanceof Uint8Array)||r.length!==32||r.every(a=>a===0))throw Ae("binding");return new Uint8Array(r)})),policyPins:new Uint8Array(i.policyPins)}),this.pin=Object.freeze({...this.selected,isCurrent:()=>this.current(),installationOwned:()=>this.current(),connectorBearer:async({signal:r})=>{this.check(r);let a=await this.bearerCallback.call(this.source,Object.freeze({signal:r}));return this.check(r),a}}),e.approvalMode==="strict")throw new an;this.check(s)}source;installation;originalRelease;origin;lifetime;closing=!1;closeResult=null;provider=null;keys=null;noiseStore=null;key=null;noise=null;native=null;publicReceipt=null;signIn=null;originalCustody=null;collectionAttempted=!1;collectionSignal=null;collectionCurrent=null;outcomeStore=null;outcome=null;bootstrap=null;bootstrapConfirmed=!1;collectionScope=null;collectionSession=null;adoptedEndpoint=null;sqlAttempted=!1;sqlClose=null;collectionSql=null;logRequest=null;logLoopback=!1;logWork=null;authority=null;peopleMetadata=null;pump=null;timerPorts=new Set;readWork=null;readAbort=null;readClient=null;readVerified=!1;facades=new Map;logWorkListener=null;selected;currentCallback;bearerCallback;ownershipCallback;trust;pin;current(){try{let e=this.originalRelease,t=this.trust;return!this.closing&&!this.lifetime.aborted&&Rt()===this.origin&&this.source.isCurrent===this.currentCallback&&this.source.connectorBearer===this.bearerCallback&&this.installation.isCurrent===this.ownershipCallback&&this.currentCallback.call(this.source)===!0&&this.ownershipCallback.call(this.installation)===!0&&this.installation.scope.account===this.selected.accountId&&this.installation.scope.installation===this.selected.installationId&&Object.entries(this.selected).every(([i,o])=>this.source[i]===o)&&e.schema===t.schema&&e.environment===t.environment&&e.cpOrigin===t.cpOrigin&&e.logOrigin===t.logOrigin&&e.assetSha256===t.assetSha256&&e.source.repository===t.source.repository&&e.source.commit===t.source.commit&&e.source.version===t.source.version&&e.trustedRoots.length===t.trustedRoots.length&&e.trustedRoots.every((i,o)=>II(i,t.trustedRoots[o]))&&II(e.policyPins,t.policyPins)}catch{return!1}}check(e){if(e.aborted||!this.current())throw Ae("fenced")}operationSignal(e){let t=AbortSignal.any([this.lifetime,...this.collectionSignal?[this.collectionSignal]:[],e]);return this.check(t),t}static async openOriginalDevice(e){let{session:t,installation:i,release:o,origin:s,mode:r,signal:a,loadRuntime:p,fetch:l,allowLoopbackHttp:c,allowNativeLoopbackHttp:d}=e,u=null;try{if(!["fresh","existing"].includes(r))throw Ae("binding");u=new n(t,i,o,s,a);let{custody:f,restored:h}=await u.openOwnedDevice({mode:r,signal:a,loadRuntime:p,allowLoopbackHttp:c,allowNativeLoopbackHttp:d,requireReceipt:!0});if(r==="existing")u.native.acknowledgeDeviceRegistration(h.receipt),u.check(a),u.publicReceipt=u.native.registeredDeviceReceipt();else{let m=await new sl(u.native,u.pin,f,u.noise,{fetch:l,allowLoopbackHttp:c}).register(Object.freeze({signal:a}));u.check(a),u.publicReceipt=m}return u}catch(f){throw await u?.close(),f instanceof co||f instanceof an?f:Ae("unavailable")}}static async openInstallationDevice(e){let{signIn:t,installation:i,release:o,origin:s,signal:r,loadRuntime:a,allowLoopbackHttp:p,allowNativeLoopbackHttp:l}=e,c=null;try{let d=t.confirmedHostSession(o.logOrigin,o.environment);c=new n(d,i,o,s,r),c.signIn=t;let u=await t.prepareOriginalDevice(i);c.check(r);let{custody:f,restored:h}=await c.openOwnedDevice({mode:u.mode,signal:r,loadRuntime:a,allowLoopbackHttp:p,allowNativeLoopbackHttp:l,requireReceipt:!1});if(c.originalCustody=f,h?.receipt&&t.view().state!=="paired")throw Ae("recovery_required");return await c.noise.pending(new Uint8Array(f.envelope),{signal:r}),c.check(r),t.view().state==="paired"&&await c.completeInstallationSignIn(),c}catch(d){throw await c?.close(),d}}async attestInstallation(){if(this.check(this.lifetime),!this.signIn||!this.native||!this.originalCustody||!this.noise)throw Ae("binding");let e=await this.signIn.attest({runtime:this.native,custody:this.originalCustody,persistence:this.noise,installation:this.installation});return this.check(this.lifetime),e}async completeInstallationSignIn(){if(this.check(this.lifetime),!this.signIn||!this.native||!this.originalCustody||!this.noise)throw Ae("binding");return await this.signIn.acknowledge({runtime:this.native,custody:this.originalCustody,persistence:this.noise,installation:this.installation}),this.check(this.lifetime),this.publicReceipt=this.native.registeredDeviceReceipt(),this.registeredReceipt()}async openOwnedDevice(e){let{mode:t,signal:i,loadRuntime:o,allowLoopbackHttp:s,allowNativeLoopbackHttp:r,requireReceipt:a}=e;this.check(i),this.provider=await ll.open({source:this.pin,origin:this.origin,mode:t,signal:i,allowLoopbackHttp:s,allowNativeLoopbackHttp:r}),this.check(i),this.key=this.provider.deviceCustodyKek({signal:i}),this.check(i),this.keys=await cl.open({source:this.pin,origin:this.origin,mode:t,signal:i,allowLoopbackHttp:s,allowNativeLoopbackHttp:r}),this.check(i),this.noiseStore=await dl.open({source:this.pin,origin:this.origin,mode:t,signal:i,allowLoopbackHttp:s,allowNativeLoopbackHttp:r}),this.check(i),this.noise=new pl(this.pin,this.key,this.noiseStore);let p=await this.noise.restore({signal:i});if(this.check(i),t==="existing"?!p||a&&!p.receipt:p!==null)throw Ae("recovery_required");let l=await o(Object.freeze({signal:i}));if(this.check(i),!(l instanceof Uint8Array)||!l.length)throw Ae("binding");this.native=await fl.createDevice(new Uint8Array(l)),this.check(i);let c=await new al(this.pin,this.key,this.keys).openNativeDevice(this.native,{signal:i,mode:t,noise:t==="fresh"?{mode:"fresh"}:{mode:"existing",envelope:p.envelope}});return this.check(i),{custody:c,restored:p}}async bootstrapCloudCopy(e){let{scope:t,collectionCurrent:i,purpose:o,outcomeMode:s,signal:r,reconcile:a,fetch:p,allowLoopbackHttp:l,allowNativeLoopbackHttp:c}=e,d=this.operationSignal(r),u=e.displayName,f=u===void 0?void 0:br(u);if(f!==void 0&&o!=="create"||(this.check(d),this.collectionAttempted||!this.native||!this.key||!this.publicReceipt||t.account!==this.selected.accountId||t.installation!==this.selected.installationId||!["create","join"].includes(o)||!["fresh","existing"].includes(s)||U(t.collection).every(w=>w===0)))throw Ae("binding");let h=Object.freeze({account:t.account,installation:t.installation,collection:t.collection}),m=()=>{try{return this.current()&&!d.aborted&&e.scope===t&&e.collectionCurrent===i&&Object.entries(h).every(([w,g])=>t[w]===g)&&i.call(e)===!0&&this.outcomeStore?.fenced!==!0}catch{return!1}};if(!m())throw Ae("fenced");this.collectionAttempted=!0,this.collectionSignal=d,this.collectionCurrent=m,this.collectionScope=h;let b=Object.freeze({...this.pin,collection:h.collection,purpose:o,assetSha256:this.trust.assetSha256,...f===void 0?{}:{displayName:f},isCurrent:m});this.collectionSession=b;try{this.outcomeStore=await Jh.open({source:b,origin:this.origin,mode:s,signal:d,allowLoopbackHttp:l,allowNativeLoopbackHttp:c}),this.checkCollection(d),this.outcome=new Gh(b,this.publicReceipt,this.key,this.outcomeStore,{mode:s,signal:d}),this.native.prepareCloudCopyCollection(b),this.checkCollection(d),this.bootstrap=new $a(this.native,b,this.trust,this.outcome,{fetch:p,allowLoopbackHttp:l,...f===void 0?{}:{displayName:f}});let w=await this.bootstrap.bootstrap(Object.freeze({signal:d,...a?{reconcile:a}:{}}));return this.checkCollection(d),this.bootstrapConfirmed=!0,w}catch(w){throw await this.close(),w}}checkCollection(e){if(this.check(e),this.collectionCurrent?.()!==!0)throw Ae("fenced")}adoptCloudCopy(e,t){let i=this.operationSignal(e.signal);if(this.checkCollection(i),!this.bootstrap||!this.bootstrapConfirmed||this.adoptedEndpoint!==null)throw Ae("fenced");let o=e.endpoint;this.bootstrap.adoptCollection({...e,signal:this.collectionSignal},t),this.checkCollection(i),this.adoptedEndpoint=o}async openCollectionSql(e){let{replicaId:t,endpoint:i,openSql:o}=e,s=this.operationSignal(e.signal);if(this.checkCollection(s),!this.bootstrapConfirmed||!this.collectionScope||this.sqlAttempted||this.adoptedEndpoint!==null||U(t).every(r=>r===0)||typeof i!="bigint"&&!Number.isSafeInteger(i)||BigInt(i)<0n||BigInt(i)>(1n<<64n)-1n)throw Ae("binding");this.sqlAttempted=!0;try{let r=await o.call(e,Object.freeze({scope:this.collectionScope,signal:s})),a=r.close;if(this.sqlClose=async()=>{await a.call(r)},this.collectionSql=r.sql,this.checkCollection(s),e.openSql!==o)throw Ae("fenced");this.adoptCloudCopy({signal:s,replicaId:t,endpoint:i,opened:r.opened,sqliteVersion:r.sqliteVersion,cloudCopyOptIn:!0},r.sql)}catch(r){throw await this.close(),r}}async startCollectionLog(e){let{fetch:t,allowLoopbackHttp:i}=e,o=this.operationSignal(e.signal);if(this.checkCollection(o),!this.native||!this.collectionSession||this.adoptedEndpoint===null)throw Ae("binding");let s=t??globalThis.fetch,r=i===!0;if(this.authority&&(s!==this.logRequest||r!==this.logLoopback))throw Ae("fenced");if(this.pump)return;if(this.logWork){await this.logWork,this.checkCollection(o);return}this.authority||(this.logRequest=s,this.logLoopback=r,this.authority=new Da(this.native,Object.freeze({...this.collectionSession,endpoint:this.adoptedEndpoint,directOrigins:Object.freeze([])}),{fetch:s,allowLoopbackHttp:i,tokenCache:SI()}));let a=this.authority,p=(async()=>{await a.accessToken(Object.freeze({signal:o})),this.checkCollection(o),this.pump=this.native.bindLogTransport(a.logTransport())})();this.logWork=p;try{await p}finally{this.logWork===p&&(this.logWork=null)}}peopleAuthority(){if(this.checkCollection(this.lifetime),!this.collectionSession||this.adoptedEndpoint===null||!this.logRequest)throw Ae("binding");if(!this.peopleMetadata){let e=this.adoptedEndpoint,t=this.collectionSession,i=new ul(Object.freeze({...t,endpoint:e,directOrigins:Object.freeze([]),isCurrent:()=>this.collectionCurrent?.()===!0&&this.adoptedEndpoint===e,connectorBearer:async({signal:s})=>{s.throwIfAborted(),this.checkCollection(this.lifetime);let r=await t.connectorBearer({signal:this.lifetime});return this.checkCollection(this.lifetime),s.throwIfAborted(),r}}),{fetch:this.logRequest,allowLoopbackHttp:this.logLoopback}),o=Object.freeze({collection:i.collection,isCurrent:()=>i.isCurrent(),request:(s,r)=>i.request(s,r)});this.peopleMetadata={authority:i,view:o}}return this.peopleMetadata.view}openTimersPort(e){if(this.checkCollection(this.lifetime),!this.readVerified||!this.logRequest||!this.collectionScope||e.signal.aborted)throw Ae("binding");let{scope:t,generation:i,signal:o}=e,s=this.collectionScope;if(t.account!==s.account||t.installation!==s.installation||t.collection!==s.collection||U(i).every(h=>h===0))throw Ae("binding");let r=this.source.timerConsent,a=r?.call(this.source);if(!a?.approved)return null;let p=a.grants.find(h=>h.collectionId===t.collection);if(!p)return null;let l=globalThis.WorkerGlobalScope;if(typeof l!="function"||!(globalThis instanceof l)||U(p.grantId).every(h=>h===0)||!/^[0-9a-f]{64}$/.test(p.declarationDigest))throw Ae("binding");let c=JSON.stringify(a),d=new MessageChannel,u=()=>{try{return!o.aborted&&e.signal===o&&e.scope===t&&e.generation===i&&this.collectionCurrent?.()===!0&&this.current()&&t.account===s.account&&t.installation===s.installation&&t.collection===s.collection&&this.source.timerConsent===r&&JSON.stringify(r?.call(this.source))===c}catch{return!1}},f=hC(d.port1,{scope:s,generation:i,grantId:p.grantId,cpOrigin:new URL(this.selected.cpOrigin).origin,signal:o,isCurrent:u,fetch:this.logRequest,...this.signIn?{journal:{read:()=>this.signIn.originalTimerChannel(p.grantId),write:h=>this.signIn.retainTimerChannel(p.grantId,h)}}:{},bearer:async()=>{if(!u())throw Ae("fenced");let h=await this.bearerCallback.call(this.source,{signal:this.lifetime});if(!u())throw Ae("fenced");return h}});return this.timerPorts.add(f),Object.freeze({port:d.port2,close:async()=>{await f.close(),d.port2.close(),this.timerPorts.delete(f)}})}serverProblem(){return this.pump?.serverProblem??null}transportHealth(){return this.pump?.transportHealth??null}initialSync(){try{return this.native?Wh(this.native.observations().status):"unavailable"}catch{return"unavailable"}}keyWaitDetail(){try{return this.native?CI(this.native.observations().status):null}catch{return null}}pendingWrites(){try{return this.native?.observations().status.pending??0}catch{return 0}}pushLog(e){try{return this.native?.pushLog(e)===!0}catch{return!1}}openLogPush(e){this.checkCollection(this.lifetime);let t=this.native,i=this.authority,o=this.collectionSession,s=this.logRequest;if(!t||!this.pump||!i||!o||!s)throw Ae("binding");if(!t.supportsLogPush||typeof WebSocket!="function")return null;let r=this.logLoopback,a=i.origin,p=()=>{try{return this.collectionCurrent?.()===!0&&this.current()&&this.authority===i&&i.isCurrent()}catch{return!1}};return new Kh({origin:a,collection:i.collection,deviceId:o.deviceId,isCurrent:p,accessToken:l=>i.accessToken(l),invalidateToken:l=>i.invalidateToken(l),nonce:async({signal:l})=>{let c=await s(`${a}/v1/nonce`,{signal:l,cache:"no-store",credentials:"omit",redirect:"error",referrerPolicy:"no-referrer"}),d=(await c.text()).trim();if(!c.ok||!/^[0-9a-f]{64}$/.test(d))throw Ae("unavailable");return Uint8Array.from(d.match(/../g).map(u=>parseInt(u,16)))},signHello:(l,c)=>p()?t.signLogHello(l,c):null},e,{allowLoopbackHttp:r})}async driveCollection(e){let t=this.operationSignal(e.signal);if(this.checkCollection(t),!this.native||!this.pump||this.adoptedEndpoint===null)throw Ae("binding");for(let i=0;i<XT;i++){let o=this.pump.callsSent;if(this.native.tick(),await this.pump.pump(),this.checkCollection(t),this.pump?.callsSent===o)break}}async wakeCollectionLog(e){let t=this.operationSignal(e.signal);if(this.checkCollection(t),!this.native||!this.pump||this.adoptedEndpoint===null)throw Ae("binding");this.native.tick(),(await this.pump.pump()).quiet&&(this.checkCollection(t),this.native.requestLogHead()&&(await this.pump.pump(),this.checkCollection(t),this.native.tick()))}waitForVerifiedRead(e){let{timeoutMs:t=15e3,cold:i=!1}=e,o=this.operationSignal(e.signal);if(this.checkCollection(o),!this.native||!this.collectionScope||this.adoptedEndpoint===null||!Number.isSafeInteger(t)||t<1||t>15e3||typeof i!="boolean"||i&&!this.pump)throw Ae("binding");if(this.readWork)return this.readWork.then(()=>{this.checkCollection(o)});let s=this.verifyRead(o,t,i,e.onProgress);return this.readWork=s,s.finally(()=>{this.readWork===s&&(this.readWork=null)}).catch(()=>{}),s}async verifyRead(e,t,i,o){let s=new AbortController,r=()=>s.abort();this.readAbort=s,e.addEventListener("abort",r,{once:!0});let a=null,p=Ae(i?"sync_stalled":"unavailable"),l,c=new Promise((h,m)=>{l=()=>m(p),s.signal.addEventListener("abort",l,{once:!0})});c.catch(()=>{});let d=null,u=h=>{if(h!==d){d=h;try{o?.(h)}catch{}}},f=()=>{this.checkCollection(e);let h=i?this.pump.terminalProblem:null;if(kn(h))throw new mn(St(h)??"unavailable",h);let m=this.native.observations();if(m.requiresReopen||m.keyringRebuildFailed)throw Ae("recovery_required");let b=Wh(m.status);return u(b==="installing"?"loading_snapshot":b==="waiting_for_key"?"waiting_for_key":b==="behind"?"replaying":b===null?"verifying_read":"syncing"),m};this.readVerified=!1;try{if(this.pump){let m=()=>{let _=f();return[_.status.confirmedThrough,_.status.installing?.done??0,_.status.installing?.total??0,this.pump.readProgress]},b=m(),w=Date.now(),g=new Map,y=null,v=()=>{try{let _=Date.now(),k=m();k.some((C,E)=>C>b[E])&&(w=_,y=null),b=k.map((C,E)=>Math.max(C,b[E]));let S=this.pump.responseProgress(),x=new Set(S.map(C=>C.id));for(let C of g.keys())x.has(C)||g.delete(C);for(let C of S){let E=g.get(C.id);C.bytes>(E?.bytes??0)&&g.set(C.id,{bytes:C.bytes,at:_})}let P=t-(_-w);P<=0&&(y??=new Set(g.keys()),P=Math.max(0,...[...y].map(C=>{let E=g.get(C);return E?t-(_-E.at):0}))),P<=0?r():a=setTimeout(v,Math.min(250,P))}catch(_){p=_,r()}};a=setTimeout(v,Math.min(250,t))}else a=setTimeout(r,t);this.readClient=await Promise.race([Ei.connect({app:{name:"app-local-read-gate",version:"1"},connector:Ds(this.native,{collection:this.collectionScope.collection}),reconnect:!1,signal:s.signal}).then(m=>{if(s.signal.aborted)throw m.close(),Ae("unavailable");return m}),c]),this.checkCollection(e);let h=250;for(;!s.signal.aborted;){this.native.tick(),this.pump&&await Promise.race([this.pump.pump(),c]),this.checkCollection(e);let m=f();if(i&&Wh(m.status)!==null){await pp(h,s.signal),h=Math.min(1e3,h*2);continue}try{if(await Promise.race([this.readClient.query({limit:1},void 0,s.signal),c]),this.checkCollection(e),s.signal.aborted)throw Ae("unavailable");this.readVerified=!0;return}catch(b){if(this.checkCollection(e),!(b instanceof se)||b.code!=="unavailable"||!this.pump||s.signal.aborted)throw b}await pp(h,s.signal),h=Math.min(1e3,h*2)}throw Ae("unavailable")}catch(h){throw this.checkCollection(e),s.signal.aborted?p:h}finally{a!==null&&clearTimeout(a),e.removeEventListener("abort",r),s.signal.removeEventListener("abort",l),this.readClient?.close(),this.readClient=null,this.readAbort=null}}onLogWork(e){this.logWorkListener=e}attachDataFacade(e){if(this.checkCollection(this.lifetime),!this.native||!this.collectionScope||!this.readVerified||this.facades.size>=JT||this.facades.has(e))throw Ae("fenced");let t=Object.freeze({...this.collectionScope,isCurrent:()=>{try{return this.checkCollection(this.lifetime),!0}catch{return!1}}}),i=Sh(this.native,e,t,()=>this.logWorkListener?.());return this.facades.set(e,i),i.resourceSetup}detachDataFacade(e){let t=this.facades.get(e);t&&(this.facades.delete(e),t.close())}registeredReceipt(){this.check(this.lifetime);let e=this.publicReceipt;if(!e)throw Ae("fenced");return Object.freeze({...e,signPublicKey:new Uint8Array(e.signPublicKey),kemPublicKey:new Uint8Array(e.kemPublicKey),noisePublicKey:new Uint8Array(e.noisePublicKey)})}close(){if(this.closing=!0,this.readVerified=!1,this.readAbort?.abort(),this.closeResult)return this.closeResult;let e=!1;for(let t of[()=>this.readClient?.close(),()=>{for(let i of this.facades.values())i.close();this.facades.clear()},()=>this.peopleMetadata?.authority.close(),()=>this.bootstrap?.close(),()=>this.outcome?.close()])try{t()}catch{e=!0}return this.closeResult??=(async()=>{try{await Promise.all([...this.timerPorts].map(async i=>{try{await i.close()}catch{e=!0}})),this.timerPorts.clear();let t=await this.native?.close();if(this.collectionSql&&t!==!0&&this.collectionSql.fence(),this.authority?.close(),await this.sqlClose?.(),e)throw Ae("unavailable")}finally{this.key=null,this.noise=null,this.originalCustody?.envelope.fill(0),this.originalCustody=null,this.signIn=null,this.publicReceipt=null,this.outcomeStore?.close(),this.noiseStore?.close(),this.keys?.close(),this.provider?.close()}})()}};lx();ie();Yc();Qc();Go();no();kh();Zc();Xc();eo();Fn();var ZT=new Set(["binding","fenced","busy","open_in_another_tab","account_confirmation_required","recovery_account_mismatch","outcome_unknown","response","refused","expired","recovery_required","unavailable","collection_migrating","collection_not_yet_migrated","account_suspended","update_required"]),QT=new Set(["AbortError","ConstraintError","DataCloneError","InvalidStateError","NotAllowedError","NotFoundError","NotReadableError","OperationError","QuotaExceededError","SecurityError","TimeoutError","TransactionInactiveError","UnknownError","VersionError"]),po=(n,e,t,i)=>Object.freeze({problem:n,detail:Object.freeze({name:e,code:t,...i?{server:i}:{}})});function Jw(n){try{for(let[e,t]of[[Xe,"AppInstallationSignInError"],[co,"AppCloudCopyHostError"],[en,"AppCloudCopyBootstrapError"],[nn,"AppCollectionSetupError"],[ti,"AppCollectionControlError"],[lo,"AppCollectionJoinError"],[Zn,"AppCpAuthorityError"],[mn,"AppHttpLogError"]])if(n instanceof e){let i=n.reason,o=("server"in n?Ur(n.server):null)??void 0;return i==="sync_stalled"?po("unavailable",t,i,o):ZT.has(i)?po(i,t,i,o):po("open_failed",t,null,o)}if(n instanceof We&&n.reason==="busy")return po("open_in_another_tab","AppReplicaOwnerError","busy");if(n instanceof se){let e=Sr(n.code)?n.code:null;return po(e==="outcome_unknown"?e:"open_failed","MdbaseError",e)}if(typeof DOMException<"u"&&n instanceof DOMException){let e=QT.has(n.name)?n.name:null;return po("open_failed","DOMException",e)}for(let[e,t]of[[TypeError,"TypeError"],[RangeError,"RangeError"],[SyntaxError,"SyntaxError"],[ReferenceError,"ReferenceError"],[URIError,"URIError"],[EvalError,"EvalError"],[Error,"Error"]])if(n instanceof e)return po("open_failed",t,null)}catch{}return po("open_failed","UnknownError",null)}Qc();Qr();eo();ge();var eM=5e3,tM=n=>Array.from(U(n),e=>e.toString(16).padStart(2,"0")).join(""),Si=n=>(U(n),n.toLowerCase());function Xh(n,e,t=eM){let i;return Promise.race([n.catch(()=>e),new Promise(o=>{i=setTimeout(()=>o(e),t)})]).finally(()=>clearTimeout(i))}function Xw(n){return Xh(new Promise(e=>{let t=indexedDB.deleteDatabase(n);t.onsuccess=()=>e(!0),t.onerror=()=>e(!1)}),!1)}function nM(n){let e=encodeURIComponent(n.cpOrigin),t=`mdbase.app.installation.v1.${e}.${n.appId}`;return[n.owner===void 0?t:`mdbase.app.installation.v2.${e}.${encodeURIComponent(n.owner)}.${n.appId}`,t]}async function iM(n,e,t){let i=new Set(n.isolated?[]:n.databases);!n.isolated&&n.storageNamespace===void 0&&i.add(t);let{accountId:o,connectorId:s,deviceId:r,installationId:a}=n;if(o&&s&&r&&a){let p=[o,s,r,a].map(tM).join(".");i.add(`mdbase.app.device-key-kek.v1.${p}`),i.add(`mdbase.app.device-keys.v1.${p}`),i.add(`mdbase.app.noise.v1.${Si(a)}.${Si(s)}.${Si(r)}`);let l=[o,s,r,a].map(Si).join("."),c=[`mdbase.app.cloud-copy-outcome.v1.${l}.`,`mdbase.app.private-bootstrap.v1.${l}.`];for(let u of n.collectionIds){let f=Si(u);for(let h of["create","join"])i.add(`${c[0]}${f}.${h}`);for(let h of["create","enrol"])i.add(`${c[1]}${f}.${h}`)}let d=indexedDB.databases;if(typeof d=="function"){let u=await Xh(d.call(indexedDB),[]);for(let{name:f}of u)f&&c.some(h=>f.startsWith(h))&&i.add(f)}}return i.delete(e),[...i]}async function rM(n,e){let t=globalThis.navigator?.storage;return typeof t?.getDirectory!="function"?!0:Xh((async()=>{let i=await t.getDirectory(),o=`.mdbase-app-${Si(n)}-${Si(e)}-`,s=[];for await(let a of i.keys())a.startsWith(o)&&s.push(a);let r=!0;for(let a of s)try{await i.removeEntry(a,{recursive:!0})}catch{r=!1}return r})(),!1)}async function OI(n,e){try{if(!globalThis.indexedDB||!n.accountId||!n.connectorId||!n.deviceId||!n.installationId)return!1;let t=Si(e),i=[n.accountId,n.connectorId,n.deviceId,n.installationId].map(Si).join("."),o=["create","join"].map(a=>`mdbase.app.cloud-copy-outcome.v1.${i}.${t}.${a}`);o.push(...["create","enrol"].map(a=>`mdbase.app.private-bootstrap.v1.${i}.${t}.${a}`));let s=await Promise.all(o.map(Xw)),r=globalThis.navigator?.storage;if(typeof r?.getDirectory=="function"){let a=await r.getDirectory();try{await a.removeEntry(`.mdbase-app-${Si(n.accountId)}-${Si(n.installationId)}-${t}`,{recursive:!0})}catch(p){if(!(p instanceof DOMException&&p.name==="NotFoundError"))return!1}}return s.every(Boolean)}catch{return!1}}async function RI(n){if(!globalThis.indexedDB)return Object.freeze({ledger:!1,complete:!1});let[e,t]=nM(n),i=await Xw(e),o=null;try{o=await iM(n,e,t)}catch{}let s=o?await Promise.all([...o,...n.isolated||n.storageNamespace!==void 0?[]:[Kw]].map(Xw)):[!1],r=n.storageNamespace===void 0?!0:await Xh(PI(n),!1),a=n.accountId&&n.installationId?await rM(n.accountId,n.installationId).catch(()=>!1):!0;return Object.freeze({ledger:i,complete:i&&r&&a&&s.every(Boolean)})}ie();var oM=Object.freeze({status:"unselected",problem:null,transport:null,live:null}),_t=n=>new Xe(n),sM=new Set(["collection_not_yet_migrated","collection_migrating","account_suspended","update_required"]),Zh=class{lifetime=new AbortController;flowLifetime=new AbortController;options;environment;listeners=new Set;flow=null;host=null;installation=null;installationLease=null;slots=new Map;focus=null;openingSlot=null;abortCollections=()=>{for(let e of this.slots.values())e.lifetime?.abort()};base=Object.freeze({status:"not_started",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:null,timing:null});snapshotValue=this.base;authorizationStartedAt=null;authorizationRetryAt=0;authorizationRateLimit=null;pending=null;polling=null;timer=null;closing=null;foreground=!0;receiptRead=null;foregroundRead=null;attested=!1;acknowledged=!1;consentPending=!1;fileAccess=null;freshApproval=!1;approvalWindow=null;nativePending=null;forgotten=new Set;removedScopes=new Set;onAbort=()=>{this.close().catch(()=>{})};constructor(e){this.options=Object.freeze({...e}),this.environment=Xn({environment:e.environment,appOrigin:e.origin,platform:e.allowNativeLoopbackHttp?"native":void 0,release:e.release}),e.signal.addEventListener("abort",this.onAbort,{once:!0}),this.lifetime.signal.addEventListener("abort",this.abortCollections,{once:!0})}getSnapshot(){return this.snapshotValue}snapshot(){return this.getSnapshot()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}viewFor(e,t={}){return t.bystander&&this.base.status==="authorizing"&&this.consentPending&&e!==null&&this.slots.has(e)?this.compose(e,!0):e===this.focus?this.snapshotValue:this.compose(e)}collectionView(e){return this.slots.get(e)?.view??null}heldCollections(){return[...this.slots.keys()]}compose(e,t=!1){let i=this.base,o=e===null?void 0:this.slots.get(e);if(!o)return i;if(i.status!=="unselected"&&!t)return Object.freeze({...i,selectedCollectionId:o.id,transport:o.view.transport,live:o.view.live});let{problemDetail:s,...r}=i,{problemDetail:a,...p}=o.view;return Object.freeze({...r,...t?{status:"unselected",problem:null,approval:null}:{},...p,selectedCollectionId:o.id,...a?{problemDetail:a}:{}})}connection(e=this.focus){let t=e===null?void 0:this.slots.get(e),i=this.base.status==="unselected"||this.base.status==="authorizing"&&this.consentPending;return!t||this.closing||this.options.signal.aborted||!t.usable||t.lifetime?.signal.aborted||!this.installation?.isCurrent()||!i||!["ready","setup_required"].includes(t.view.status)||!this.sameScope(t.scope,t.leaseScope)||t.scope?.collection!==t.id?null:t.selected?.connection??null}sameScope(e,t){return e!==null&&t!==null&&e.account===t.account&&e.installation===t.installation&&e.collection===t.collection&&e.account===this.installation?.scope.account&&e.installation===this.installation?.scope.installation}directAccess=Vh;checkDirectAccess(e){return this.check(),this.directAccess.check(e)}requestDirectAccess(e){return this.check(),this.directAccess.request(e)}check(){if(this.closing||this.options.signal.aborted||this.lifetime.signal.aborted)throw _t("fenced")}publish(e){this.check(),this.setBase(e),this.changed()}setBase(e){let{problemDetail:t,...i}=this.base,o=e.problem===null?void 0:e.problemDetail??t;this.base=Object.freeze({...i,...e,selectedCollectionId:null,signIn:this.flow?.view()??null,...o?{problemDetail:o}:{}})}publishSlot(e,t){if(this.check(),this.slots.get(e.id)!==e)return;let i=this.base.timing;if(this.authorizationStartedAt!==null&&(t.status==="ready"||t.status==="setup_required")){let p=Math.max(0,performance.now()-this.authorizationStartedAt);i=Object.freeze({firstScreenMs:i?.firstScreenMs??p,readyMs:t.status==="ready"?i?.readyMs??p:i?.readyMs??null})}this.setBase({timing:i});let{problemDetail:o,...s}=e.view,r=t.problem===null?void 0:t.problemDetail??o,a=(t.status??s.status)==="opening"?"openingProgress"in t?t.openingProgress??null:s.openingProgress??null:null;e.view=Object.freeze({...s,...t,openingProgress:a,...r?{problemDetail:r}:{}}),this.changed()}changed(){this.snapshotValue=this.compose(this.focus);for(let e of[...this.listeners])try{e()}catch{}}poll(e){this.pending||(this.operation(e).catch(()=>{}),this.polling=this.pending)}stopPolling(){this.timer!==null&&clearTimeout(this.timer),this.timer=null}operation(e,t=!1){if(this.check(),this.pending)return Promise.reject(_t("busy"));this.foregroundRead=null,this.stopPolling();let o=Promise.resolve().then(()=>(this.check(),e())).catch(async s=>{if(!t&&!this.closing&&!this.options.signal.aborted){let{problem:r,detail:a}=Jw(s);if(r==="open_failed")try{console.error("mdbase web sign-in open failed",a.name,a.code)}catch{}let p=this.openingSlot;if(this.openingSlot=null,p&&this.slots.get(p.id)===p){let l=!1;try{l=s instanceof en&&s.reason==="unavailable"&&s.retryable===!0&&p.view.status==="opening"&&this.base.collections.some(c=>c.collectionId===p.id)&&this.flow?.view().state==="paired"&&this.installation?.isCurrent()===!0}catch{}if(l){try{await this.closeSlot(p),this.check()}catch(c){throw!this.closing&&!this.options.signal.aborted&&this.publishSlot(p,{status:"blocked",problem:"recovery_required",problemDetail:Jw(c).detail}),c}this.publishSlot(p,{status:"unselected",problem:r,problemDetail:a})}else this.publishSlot(p,{status:"blocked",problem:r,problemDetail:a})}else this.publish({status:"blocked",problem:r,problemDetail:a})}throw s});return this.pending=o,o.finally(()=>{this.pending===o&&(this.pending=null),this.schedulePoll()})}start(){return this.operation(async()=>{if(this.flow&&this.base.status!=="blocked")return this.getSnapshot();this.publish({status:"starting",problem:null,signOutResult:null});let e=this.options;this.flow??=await ja.open({...e,mode:e.storeMode??"open",signal:this.flowLifetime.signal,environmentSelection:this.environment}),this.check();let t=this.flow.view();if(t.state==="paired"){if(this.flow.pendingNativeSelection?.()&&!t.nativeSelection)throw _t("recovery_required");await this.openDevice(!1,this.options.recoveryFor!==void 0),this.flow.collectionConsentView()?.state==="pending"?(this.consentPending=!0,this.publish({status:"authorizing"})):await this.refreshCollections()}else this.publish({status:t.state==="pending"?"signed_out":"authorizing"});return this.getSnapshot()})}authorize(e={}){if(this.check(),this.authorizationRateLimit&&Date.now()<this.authorizationRetryAt)return Promise.reject(this.authorizationRateLimit);let t=this.pending!==null&&this.pending===this.polling?this.pending:null;if(!this.flow||this.pending&&!t)return Promise.reject(_t("busy"));let i=this.options.openPortal();return t?t.catch(()=>{}).then(()=>{try{this.check()}catch(s){throw i.close(),s}if(this.pending)throw i.close(),_t("busy");let o=this.base.status;return o!=="authorizing"&&o!=="signed_out"?(i.close(),this.getSnapshot()):this.beginAuthorization(i,e)}):this.beginAuthorization(i,e)}beginAuthorization(e,t){let i={collectionHint:t.collectionHint??null},o=this.flow.view();return this.authorizationStartedAt=performance.now(),this.publish({timing:Object.freeze({firstScreenMs:null,readyMs:null}),approval:null}),this.operation(async()=>{try{if(o.state==="paired"){if(this.flow.pendingNativeSelection?.()&&!o.nativeSelection)throw _t("recovery_required");await this.openDevice(),this.check();let s=await this.flow.startCollectionConsent(this.installation,this.options.requestedCreateCollections??this.options.freshRequestedCreateCollections??!1,i);this.check(),this.consentPending=!0,e.navigate(s.verificationUri)}else{let s=await this.flow.start(i).catch(r=>this.renewFromGesture(r));this.check(),e.navigate(s.verificationUri)}return this.holdApprovalWindow(e),this.publish({status:"authorizing",problem:null}),await this.advance(),this.getSnapshot()}catch(s){throw s instanceof Xe&&s.server?.status===429&&(this.authorizationRateLimit=s,this.authorizationRetryAt=Date.now()+Math.min(Fs,Math.max(Bs,s.server.retryAfterMs??3e4))),e.close(),s}})}requestFileAccess(e,t,i){if(this.check(),!this.flow||this.pending)return Promise.reject(_t("busy"));let o=this.options.openPortal();return this.operation(async()=>{try{if(this.flow.view().state!=="paired"||!this.installation||!this.base.collections.some(r=>r.collectionId===e))throw _t("refused");let s=await this.flow.startFileAccess(this.installation,e,t,i);return this.check(),this.fileAccess=s,o.navigate(s.verificationUri),this.holdApprovalWindow(o),this.publish({fileAccess:Object.freeze({requestId:s.requestId,collectionId:e,actions:s.actions,state:"pending"})}),this.getSnapshot()}catch(s){throw o.close(),s}},!0)}pollFileAccess(e){let t=this.fileAccess;return!t||t.requestId!==e||this.pending||!this.flow||!this.installation?Promise.resolve(this.getSnapshot()):this.operation(async()=>{let i={state:"pending"};try{i=await this.flow.exchangeFileAccess(this.installation,t)}catch{}if(this.check(),this.fileAccess!==t||i.state==="pending"&&Date.now()<t.expiresAt)return this.getSnapshot();this.fileAccess=null,this.closeApprovalWindow();let o=i.state==="granted"?i.actions:null,s=o?Object.freeze(this.base.collections.map(r=>r.collectionId!==t.collectionId?r:Object.freeze({...r,fileActions:Object.freeze([...new Set([...r.fileActions??[],...o])])}))):this.base.collections;return this.publish({collections:s,fileAccess:Object.freeze({requestId:e,collectionId:t.collectionId,actions:o??t.actions,state:i.state==="pending"?"expired":i.state})}),this.getSnapshot()},!0)}async renewFromGesture(e){if(!(e instanceof Xe)||e.reason!=="expired"&&e.reason!=="refused")throw e;try{return await this.flow.renewExpiredPairing()}catch(t){throw t instanceof Xe&&t.reason==="recovery_required"?e:t}}renewExpiredPairing(){return this.operation(async()=>{if(!this.flow)throw _t("binding");return await this.flow.renewExpiredPairing(),this.check(),this.publish({status:"signed_out",problem:null}),this.getSnapshot()})}receiptGeneration(e){try{if(!e.isCurrent())return null;let t=e.view(),i=this.consentPending?e.collectionConsentView():null;return(this.consentPending?i?.state!=="pending":!["pending","awaiting_approval"].includes(t.state))?null:JSON.stringify([t.requestId,t.installationId,t.deviceId,t.accountId,t.state,this.consentPending,i?.requestId,i?.state])}catch{return null}}currentReceipt(e){try{return!this.closing&&!this.lifetime.signal.aborted&&!this.flowLifetime.signal.aborted&&!e.caller.aborted&&this.options.signal===e.caller&&this.flow===e.flow&&this.installation===e.installation&&(e.installation===null||e.installation.isCurrent()===!0)&&this.attested===e.attested&&this.acknowledged===e.acknowledged&&this.receiptGeneration(e.flow)===e.generation}catch{return!1}}async exchangeReceipt(e){let t=this.flow,i=this.pending,o=t?this.receiptGeneration(t):null,s=t&&i&&o!==null?Object.freeze({flow:t,operation:i,generation:o,caller:this.options.signal,installation:this.installation,attested:this.attested,acknowledged:this.acknowledged}):null;this.receiptRead=s;let r=!1;try{let a=await e();return r=a!=null,a}catch(a){if(a instanceof Xe&&a.reason==="outcome_unknown"&&this.flow?.isCurrent())return this.publish({status:"authorizing",problem:"outcome_unknown"}),null;throw a}finally{this.receiptRead===s&&(this.receiptRead=null),this.foregroundRead===s&&(!r||!s||!this.currentReceipt(s))&&(this.foregroundRead=null)}}async advance(){if(this.consentPending){let t;try{t=await this.exchangeReceipt(()=>this.flow.exchangeCollectionConsent(this.installation))}catch(i){if(!(i instanceof Xe)||i.reason!=="refused"&&i.reason!=="expired")throw i;this.check(),this.consentPending=!1,this.closeApprovalWindow(),this.publish({status:"unselected",problem:null,approval:Object.freeze({outcome:"cancelled"})}),await this.refreshCollections();return}if(this.check(),!t)return;if(t.state==="scope_updated"){if(t.accountSelectionConfirmed!==!0)throw _t("account_confirmation_required");let i=this.flow.pendingNativeSelection?.();if(i?.requestId===t.requestId)await this.finishNativeChoice(i);else if(this.flow.view().collectionSelection?.requestId!==t.requestId)throw _t("response");this.consentPending=!1,this.freshApproval=!0,this.closeApprovalWindow(),await this.refreshCollections()}else await this.prepareNativeChoice(),this.publish({status:"authorizing",problem:null});return}let e=await this.exchangeReceipt(()=>this.flow.exchange());if(this.check(),!!e)if(e.state==="account_selected"&&(e=await this.flow.confirmPortalSelectedAccount(),this.check()),(e.state==="account_confirmed"||e.state==="awaiting_approval")&&(await this.openDevice(),this.check(),this.attested||(await this.host.attestInstallation(),this.check(),this.attested=!0),await this.prepareNativeChoice()),e.state==="paired"){let t=this.flow.pendingNativeSelection?.();if(t?.requestId===e.requestId)await this.finishNativeChoice(t);else if(e.collectionSelection?.requestId!==e.requestId)throw _t("response");this.freshApproval=!0,this.closeApprovalWindow(),await this.openDevice(),this.check(),await this.refreshCollections()}else this.publish({status:"authorizing",problem:null})}async prepareNativeChoice(){let e=this.approvalWindow?.nativeAuthorization;if(!e||!this.installation)return;let t=this.flow.nativeAuthorizationContext(this.installation);if(!t)return;let i=this.nativePending;if(!i){if(i={context:t,port:e,life:new AbortController,prepared:null,failed:!1,attempted:!1},this.nativePending=i,t.authorizationId){i.failed=!0;return}let o=i,s=AbortSignal.any([this.lifetime.signal,this.flowLifetime.signal,i.life.signal]);e.prepare(t,s).then(r=>{this.nativePending!==o||s.aborted||(o.prepared=Object.freeze({...r}))},()=>{o.failed=!0})}if(i.context.requestId!==t.requestId||i.context.accountId!==t.accountId||i.context.challenge!==t.challenge)throw _t("fenced");if(i.prepared&&!i.attempted){i.attempted=!0;try{await this.flow.attachNativeAuthorization(this.installation,i.context,i.prepared),this.check()}catch{i.failed=!0}}}async finishNativeChoice(e){let t=this.nativePending;if(!t||!t.prepared||!t.attempted||t.context.requestId!==e.requestId||t.prepared.authorizationId!==e.authorizationRequestId)throw _t("recovery_required");await this.openDevice(),this.check();let i=await t.port.finish(e,AbortSignal.any([this.lifetime.signal,this.flowLifetime.signal,t.life.signal]));if(this.check(),this.nativePending!==t||!this.acknowledged||!this.installation)throw _t("fenced");await this.flow.completeNativeAuthorization(this.installation,i),this.check()}holdApprovalWindow(e){this.approvalWindow!==e&&this.closeApprovalWindow(),this.approvalWindow=e}closeApprovalWindow(){let e=this.approvalWindow;this.approvalWindow=null;let t=this.nativePending;this.nativePending=null,t?.life.abort();try{t?.port.cancel()}catch{}if(e)try{e.close()}catch{}}async openDevice(e=!1,t=!1){if(!this.installation){let i=this.flow.confirmedSelection(),o=Object.freeze({account:i.accountId,installation:i.installationId});this.installationLease=await Wc(this.options.locks,o,this.lifetime.signal),this.check(),this.installation=Object.freeze({scope:o,isCurrent:()=>!this.closing&&!this.options.signal.aborted&&!this.lifetime.signal.aborted&&this.installationLease!==null})}t||!this.host&&!e&&this.acknowledged&&this.flow.view().state==="paired"&&[...this.slots.values()].some(i=>i.host!==null)||(this.host?!this.acknowledged&&this.flow.view().state==="paired"&&(await this.host.completeInstallationSignIn(),this.check(),this.acknowledged=!0):(this.host=await ml.openInstallationDevice({signIn:this.flow,installation:this.installation,release:this.options.release,origin:this.options.origin,signal:this.lifetime.signal,loadRuntime:this.options.loadRuntime,allowLoopbackHttp:this.environment.allowLoopbackHttp,allowNativeLoopbackHttp:this.environment.allowNativeLoopbackHttp}),this.check(),this.acknowledged=this.flow.view().state==="paired"))}async refreshCollections(){let e=await this.flow.listApprovedCollections(this.installation);this.check();for(let o of this.flow.view().collectionIds)e.some(s=>s.collectionId===o)||this.removedScopes.add(o);let t=Object.freeze(e.filter(o=>!this.forgotten.has(o.collectionId)));for(let o of this.slots.values()){if(o.usable&&o.selected&&!t.some(p=>p.collectionId===o.id)){o.usable=!1,o.lifetime?.abort(),await this.closeSlot(o),this.check(),this.deleteSlot(o);continue}let s=o.usable&&o.selected!==null&&t.some(p=>p.collectionId===o.id),{problemDetail:r,...a}=o.view;o.view=Object.freeze({...a,status:s?o.selected.state:"unselected",problem:null})}this.publish({status:"unselected",collections:t,problem:null});let i=this.flow.view().collectionSelection?.selectedCollectionId;(this.options.autoSelect??"only")==="only"&&(this.freshApproval&&i&&t.some(o=>o.collectionId===i)?await this.openSlot(i,!0):t.length===1&&await this.openSlot(t[0].collectionId,!0))}schedulePoll(){if(this.pending&&!this.closing&&!this.options.signal.aborted)return;let e=this.foregroundRead;this.foregroundRead=null;for(let i of this.closing||this.options.signal.aborted?[]:this.slots.values()){let o=this.retryAfterMs(i);o===null||i.timer!==null||i.view.status!=="blocked"||(i.timer=setTimeout(()=>{i.timer=null,!(this.slots.get(i.id)!==i||i.view.status!=="blocked"||i.view.problem!=="collection_migrating"||this.flow?.view().state!=="paired")&&this.operation(()=>this.openSlot(i.id)).catch(()=>{})},o))}if(this.closing||this.options.signal.aborted||this.timer!==null||this.base.status!=="authorizing")return;let t=this.foreground&&e&&this.currentReceipt(e)?e:null;this.timer=setTimeout(()=>{this.timer=null,this.poll(async()=>{t&&(!this.foreground||!this.currentReceipt(t))||await this.advanceApproval()})},t?0:this.foreground?this.base.problem==="outcome_unknown"?5e3:1e3:1e4)}retryAfterMs(e){let t=e.view;if(t.problem!=="collection_migrating")return null;let i=null;try{i=Ur(t.problemDetail?.server)?.retryAfterMs??null}catch{i=null}return Math.min(Fs,Math.max(Bs,i??3e4))}setForeground(e){this.check();let t=e&&!this.foreground;this.foreground=e,this.stopPolling(),e?t&&this.receiptRead?.operation===this.pending&&(this.foregroundRead=this.receiptRead):this.foregroundRead=null,e&&this.base.status==="authorizing"&&!this.pending?this.poll(()=>this.advanceApproval()):this.schedulePoll()}approvalWindowClosed(){this.check(),!(this.pending||this.base.status!=="authorizing"||!this.approvalWindowGone())&&(this.stopPolling(),this.poll(()=>this.advanceApproval()))}approvalWindowGone(){let e=this.approvalWindow;try{return e?.closed===!0}catch{return!1}}async advanceApproval(){let e=this.approvalWindowGone()?this.approvalWindow:null;if(await this.advance(),this.check(),!(!e||this.approvalWindow!==e||this.base.status!=="authorizing")&&this.base.problem!=="outcome_unknown"){if(this.closeApprovalWindow(),this.consentPending){this.consentPending=!1,this.publish({status:"unselected",problem:null,approval:Object.freeze({outcome:"closed"})}),await this.refreshCollections();return}this.publish({status:"signed_out",problem:"approval_window_closed",approval:Object.freeze({outcome:"closed"})})}}select(e){return this.operation(async()=>(await this.openSlot(e,!0),this.getSnapshot()))}openCollection(e){return this.operation(async()=>(await this.openSlot(e),this.viewFor(e)))}releaseCollection(e){return this.slots.has(e)?this.operation(async()=>{let t=this.slots.get(e);return t&&(await this.closeSlot(t),this.check(),this.deleteSlot(t),this.changed()),this.getSnapshot()}):Promise.resolve(this.getSnapshot())}async openSlot(e,t=!1){this.check();let i=this.base.collections.find(d=>d.collectionId===e);if(!i||this.flow?.view().state!=="paired"||!this.installation)throw _t("refused");let o=t?[...this.slots.values()].filter(d=>d.id!==e):[],s=this.slots.get(e);if(s&&s.usable&&s.selected&&!s.lifetime?.signal.aborted&&this.sameScope(s.scope,s.leaseScope)&&s.scope?.collection===e){for(let d of o)d.usable=!1,d.lifetime?.abort();this.focus=e,this.settleBase(),this.publishSlot(s,{status:s.selected.state,problem:null});for(let d of o)await this.closeSlot(d),this.check(),this.deleteSlot(d),this.changed();return}for(let d of o)d.usable=!1,d.lifetime?.abort();let r=s??{id:e,host:null,lease:null,leaseScope:null,selected:null,scope:null,lifetime:null,usable:!1,stopAssessment:null,timer:null,view:oM};r.usable=!1,r.lifetime?.abort(),this.slots.set(e,r),this.focus=e,this.openingSlot=r,this.settleBase(),this.publishSlot(r,{status:"opening",problem:null,openingProgress:null});for(let d of o)await this.closeSlot(d),this.check(),this.deleteSlot(d),this.changed();(r.lease||r.selected||r.host)&&await this.closeSlot(r),this.check(),await this.openDevice(!0),this.check(),r.host=this.host,this.host=null;let a=Object.freeze({...this.installation.scope,collection:e});r.lease=await Kc(this.options.locks,a,this.lifetime.signal),r.leaseScope=a,this.check(),r.lifetime=new AbortController;let p=this.freshApproval&&this.flow.view().collectionSelection?.createdCollectionIds.includes(e)===!0,l=r.lifetime,c=await this.options.openCollection({host:r.host,installation:this.installation,scope:a,collection:i,setupPolicy:p?"approved-new-collection":"explicit",signal:l.signal,onProgress:d=>{this.closing||this.slots.get(r.id)!==r||r.lifetime!==l||l.signal.aborted||r.view.status!=="opening"||r.view.openingProgress!==d&&this.publishSlot(r,{openingProgress:d})}});if(r.selected=c,r.scope=a,this.check(),c.state!=="ready"&&c.state!=="setup_required")throw _t("response");r.usable=!0,this.openingSlot===r&&(this.openingSlot=null),r.stopAssessment=c.subscribe?.(()=>{if(this.closing||this.slots.get(r.id)!==r||!r.usable||r.selected!==c||r.lifetime?.signal.aborted||!this.sameScope(r.scope,r.leaseScope)||r.scope?.collection!==r.id)return;let d=null;try{d=c.ended??null}catch{d=null}if(d){this.accessEnded(r,c,d);return}(c.state==="ready"||c.state==="setup_required")&&this.publishSlot(r,{status:c.state,...this.liveProblem(r,c)})})??null,this.publishSlot(r,{status:c.state,transport:null,live:null,openingProgress:null})}settleBase(){(this.base.status==="blocked"||this.base.status==="unselected")&&this.setBase({status:"unselected",problem:null})}deleteSlot(e){e.timer!==null&&clearTimeout(e.timer),e.timer=null,this.slots.get(e.id)===e&&this.slots.delete(e.id),this.focus===e.id&&(this.focus=null),this.openingSlot===e&&(this.openingSlot=null)}accessEnded(e,t,i){if(e.selected!==t||!e.usable)return;let o=i==="gone"?"collection_deleted":i==="revoked"?"unauthenticated":"access_removed";i!=="gone"&&this.removedScopes.add(e.id),e.usable=!1,this.publishSlot(e,{status:"blocked",problem:o,transport:null,live:null});let s=()=>{if(!(this.closing||this.options.signal.aborted||e.selected!==t||this.slots.get(e.id)!==e)){if(this.pending){this.pending.catch(()=>{}).then(s);return}this.operation(async()=>{if(await this.closeSlot(e),this.publishSlot(e,{status:"blocked",problem:o}),!(!this.flow||!this.installation||this.flow.view().state!=="paired"))try{let r=await this.flow.listApprovedCollections(this.installation);this.check(),this.publish({collections:Object.freeze(r.filter(a=>!this.forgotten.has(a.collectionId)))})}catch{}}).catch(()=>{})}};s()}liveProblem(e,t){let i=null;try{i=t.problem??null}catch{i=null}let o=null;try{o=t.health??null}catch{o=null}let s=o?Object.freeze({...o}):null,r=null;try{let p=t.live;r=typeof p=="boolean"?p:null}catch{r=null}let a=kn(i)?St(i):null;return a&&i?{problem:a,problemDetail:Object.freeze({name:"AppHttpLogError",code:a,server:i}),transport:s,live:r}:{...sM.has(e.view.problem??"")?{problem:null}:{},transport:s,live:r}}async closeSlot(e){e.usable=!1,e.timer!==null&&clearTimeout(e.timer),e.timer=null;let t=e.stopAssessment;e.stopAssessment=null;try{t?.()}catch{}e.lifetime?.abort(),await e.selected?.close(),e.selected=null,e.scope=null,e.lifetime=null,await e.host?.close(),e.host=null,await e.lease?.release(),e.lease=null,e.leaseScope=null}async closeSlots(){for(let t of[...this.slots.values()])await this.closeSlot(t),this.deleteSlot(t);let e=this.host;this.host=null,await e?.close()}clearSelection(){return this.operation(async()=>(await this.closeSlots(),this.focus=null,this.publish({status:"unselected",problem:null}),this.getSnapshot()))}refreshCollectionList(){return this.pending||!this.flow||!this.installation||this.consentPending||this.flow.view().state!=="paired"||this.base.status!=="unselected"?Promise.resolve(this.getSnapshot()):this.operation(async()=>(await this.refreshCollections(),this.getSnapshot()),!0)}scopeWasRemoved(e){return this.removedScopes.has(e)}removedScopeIds(){return Object.freeze([...this.removedScopes])}canAbandonWrongAccount(){return!this.closing&&!this.options.signal.aborted&&this.pending===null&&this.flow?.canAbandonWrongAccount()===!0&&this.installation===null&&this.host===null&&this.slots.size===0&&!this.attested&&!this.acknowledged}scopeRecoveryContext(){if(!this.flow||!this.installation||this.flow.view().state!=="paired")return null;let e=this.flow.view();return Object.freeze({accountId:this.installation.scope.account,accountLabel:e.accountEmail??(e.accountLogin?`@${e.accountLogin}`:null),references:this.flow.collectionRecoveries()})}prepareScopedRecovery(e,t){return this.check(),this.pending?this.pending.catch(()=>{}).then(()=>this.prepareScopedRecovery(e,t)):this.operation(async()=>{if(!this.flow||!this.installation||this.consentPending||this.flow.view().state!=="paired"||!this.flow.view().collectionIds.includes(e))throw _t("binding");let i=this.flow.collectionRecoveries(),o=this.slots.get(e);if(t===void 0&&!Object.hasOwn(i,e)&&!this.scopeWasRemoved(e))throw _t("binding");o&&(await this.closeSlot(o),this.check(),this.deleteSlot(o)),await this.flow.retireCollectionScope(this.installation,e,t??null),this.check();let s=this.flow.confirmedSelection(),r=this.options;if(!await OI({cpOrigin:r.cpOrigin,appId:r.appId,accountId:s.accountId,connectorId:s.connectorId,installationId:s.installationId,deviceId:s.deviceId,collectionIds:[e],databases:[]},e))throw _t("recovery_required");this.check();let a=await this.flow.freshCollectionInstallation(this.installation,e);return this.check(),Object.freeze({accountId:s.accountId,reference:a})},!0)}forget(e){return this.operation(async()=>{let t=this.slots.get(e);return t&&(await this.closeSlot(t),this.check(),this.deleteSlot(t)),this.forgotten.add(e),this.publish({collections:Object.freeze(this.base.collections.filter(i=>i.collectionId!==e))}),this.getSnapshot()})}deleteCollection(e,t){let i=null;return this.operation(async()=>{let o=this.base.collections.find(s=>s.collectionId===e);if(!this.flow||!this.installation||!o)i=new vi("collection_delete_not_found");else if(o.role!=="owner")i=new vi("collection_delete_not_owner");else{try{await this.flow.deleteApprovedCollection(this.installation,e,t)}catch(s){i=ax(s)}this.check()}return this.getSnapshot()}).then(o=>{if(i)throw i;return o})}signOut(){this.check();let e=this.pending!==null&&this.pending===this.polling?this.pending:null;return Promise.resolve(e?.catch(()=>{})).then(()=>this.operation(async()=>{let t=this.flow,i=null,o=null,s=!1;try{i=t?.view()??null}catch{i=null}try{o=t?.confirmedSelection().connectorId??null}catch{o=null}try{s=t?.hasWebPushChannel()===!0}catch{s=!1}let r=[...new Set([...i?.collectionIds??[],...this.base.collections.map(c=>c.collectionId)])];this.closeApprovalWindow(),this.fileAccess=null,this.consentPending=!1;try{await this.closeSlots()}catch(c){throw this.failSignOut(),c}this.check();let a="not_paired";if(t&&i?.state==="paired"){try{a=await t.signOutInstallation()}catch{a="incomplete"}this.check()}this.flow=null,this.installation=null;try{await t?.close()}catch{}this.flowLifetime.abort(),this.flowLifetime=new AbortController,await this.installationLease?.release(),this.installationLease=null,this.attested=!1,this.acknowledged=!1,this.freshApproval=!1,this.authorizationStartedAt=null,this.receiptRead=null,this.foregroundRead=null,this.forgotten.clear(),this.removedScopes.clear();let p=this.options,l=await RI({cpOrigin:p.cpOrigin,appId:p.appId,...p.owner===void 0?{}:{owner:p.owner},...p.storageNamespace===void 0?{}:{storageNamespace:p.storageNamespace},accountId:i?.accountId??null,connectorId:o,installationId:i?.installationId??null,deviceId:i?.deviceId??null,collectionIds:r,databases:p.localDatabases??[],...p.recoveryFor?{isolated:!0}:{}});if(this.check(),!l.ledger)throw this.failSignOut(),A("unavailable","This device couldn't remove its sign-in data.","sign_out_failed");return this.emit(Object.freeze({status:"signed_out",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:null,timing:null,signOutResult:Object.freeze({server:a,local:l.complete?"erased":"incomplete",webPush:s})})),this.getSnapshot()},!0))}failSignOut(){if(this.closing||this.options.signal.aborted)return;let e=null;try{e=this.flow?.view()??null}catch{e=null}let{problemDetail:t,...i}=this.base;this.focus=null,this.emit(Object.freeze({...i,status:"blocked",signIn:e,selectedCollectionId:null,problem:"sign_out_failed"}))}emit(e){if(this.check(),this.base=e,e.status==="signed_out"){for(let t of[...this.slots.values()])this.deleteSlot(t);this.focus=null}this.changed()}close(){if(this.closing)return this.closing;let e=this.pending;return this.foregroundRead=null,this.stopPolling(),this.options.signal.removeEventListener("abort",this.onAbort),this.closing=Promise.resolve().then(async()=>{await e?.catch(()=>{}),await this.closeSlots(),this.focus=null,await this.flow?.close(),this.flowLifetime.abort(),this.flow=null,this.installation=null,await this.installationLease?.release(),this.installationLease=null,this.base=Object.freeze({status:"closed",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:null,timing:this.base.timing}),this.snapshotValue=this.base;for(let t of[...this.listeners])try{t()}catch{}this.listeners.clear()}),this.lifetime.abort(),this.closing}};return UI(aM);})();
|