@mdbase-dev/sdk 0.2.51 → 0.2.53

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.
@@ -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 r="end"in t.value?t.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.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)){$h(o,t.start),o.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,o=r&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",s=[];if(o&&t.sep&&!t.value){let i=[];for(let a=0;a<t.sep.length;++a){let c=t.sep[a];switch(c.type){case"newline":i.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(i.length=0);break;default:i.length=0}}i.length>=2&&(s=t.sep.splice(i[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(Ko(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(IC(t.key)&&!Ko(t.sep,"newline")){let i=dl(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:a,sep:c}]})}else s.length>0?t.sep=t.sep.concat(s,this.sourceToken):t.sep.push(this.sourceToken);else if(Ko(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let i=dl(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||o?e.items.push({start:s,key:null,sep:[this.sourceToken]}):Ko(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 i=this.flowScalar(this.type);o||t.value?(e.items.push({start:s,key:i,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(i):(Object.assign(t,{key:i,sep:[]}),this.onKeyLine=!0);return}default:{let i=this.startBlockValue(e);if(i){if(i.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Ko(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 r&&e.items.push({start:s});this.stack.push(i);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 r="end"in t.value?t.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.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)){$h(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||Ko(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.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 r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let o=zh(r),s=dl(o);CC(e);let i=e.end.splice(1,e.end.length);i.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:i}]};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=zh(e),r=dl(t);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=zh(e),r=dl(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(r=>r.type==="newline"||r.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 UM(n){let e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new sd||null,prettyErrors:e}}function kv(n,e={}){let{lineCounter:t,prettyErrors:r}=UM(e),o=new ad(t?.addNewLine),s=new id(e),i=null;for(let a of s.compose(o.parse(n),!0,n.length))if(!i)i=a;else if(i.options.logLevel!=="silent"){i.errors.push(new Xr(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&t&&(i.errors.forEach(nv(n,t)),i.warnings.forEach(nv(n,t))),i}var OC=I(()=>{hv();Xp();ed();Lw();Ne();_v();Av()});var Sv=I(()=>{hv();Xp();tv();ed();Mp();Ne();No();Tt();zo();$o();Nh();vv();_v();Av();OC();Tp()});var RC=I(()=>{Sv();Sv()});function kr(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=kr.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){for(let l in n)if(!(l==="app-runtime"||l==="mobile")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};i===null?i=[p]:i.push(p),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"};i===null?i=[f]:i.push(f),a++}let p=l.length;for(let f=0;f<p;f++){let h=l[f];if(typeof h=="string"){if(W(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"};i===null?i=[m]:i.push(m),a++}if(W(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"};i===null?i=[m]:i.push(m),a++}if(!Kn(h)){let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};i===null?i=[m]:i.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"};i===null?i=[m]:i.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)"};i===null?i=[m]:i.push(m),a++;break}f[h]=d}}}}else{let p={instancePath:e+"/app-runtime",schemaPath:"#/$defs/installationOrigins/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[p]:i.push(p),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"};i===null?i=[f]:i.push(f),a++}let p=l.length;for(let f=0;f<p;f++){let h=l[f];if(typeof h=="string"){if(W(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"};i===null?i=[m]:i.push(m),a++}if(W(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"};i===null?i=[m]:i.push(m),a++}if(!Kn(h)){let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};i===null?i=[m]:i.push(m),a++}}else{let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[m]:i.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)"};i===null?i=[m]:i.push(m),a++;break}f[h]=d}}}}else{let p={instancePath:e+"/mobile",schemaPath:"#/$defs/installationOrigins/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[p]:i.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[l]:i.push(l),a++}return kr.errors=i,a===0}function ul(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=ul.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.push(l),a++}for(let l in n)if(!(l==="contract_version"||l==="required"||l==="optional")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};i===null?i=[p]:i.push(p),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"};i===null?i=[l]:i.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"};i===null?i=[f]:i.push(f),a++}let p=l.length;for(let f=0;f<p;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"||h==="history.read")){let m={instancePath:e+"/required/"+f,schemaPath:"#/$defs/applicationCapability/enum",keyword:"enum",params:{allowedValues:TC.enum},message:"must be equal to one of the allowed values"};i===null?i=[m]:i.push(m),a++}}let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(or(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)"};i===null?i=[f]:i.push(f),a++;break e}}}else{let p={instancePath:e+"/required",schemaPath:"#/properties/required/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[p]:i.push(p),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"};i===null?i=[f]:i.push(f),a++}let p=l.length;for(let f=0;f<p;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"||h==="history.read")){let m={instancePath:e+"/optional/"+f,schemaPath:"#/$defs/applicationCapability/enum",keyword:"enum",params:{allowedValues:TC.enum},message:"must be equal to one of the allowed values"};i===null?i=[m]:i.push(m),a++}}let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(or(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)"};i===null?i=[f]:i.push(f),a++;break e}}}else{let p={instancePath:e+"/optional",schemaPath:"#/properties/optional/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[p]:i.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[l]:i.push(l),a++}return ul.errors=i,a===0}function fl(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=fl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.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'"};i===null?i=[d]:i.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'"};i===null?i=[d]:i.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"};i===null?i=[u]:i.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"};i===null?i=[m]:i.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"};i===null?i=[m]:i.push(m),a++}let u=d.length;for(let m=0;m<u;m++){let w=d[m];if(!(w==="list"||w==="read"||w==="add"||w==="replace"||w==="move"||w==="delete")){let b={instancePath:e+"/required/"+m,schemaPath:"#/$defs/fileActions/items/enum",keyword:"enum",params:{allowedValues:MC.items.enum},message:"must be equal to one of the allowed values"};i===null?i=[b]:i.push(b),a++}}let f=d.length,h;if(f>1){e:for(;f--;)for(h=f;h--;)if(or(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)"};i===null?i=[m]:i.push(m),a++;break e}}}else{let u={instancePath:e+"/required",schemaPath:"#/$defs/fileActions/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[u]:i.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"};i===null?i=[m]:i.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"};i===null?i=[m]:i.push(m),a++}let u=d.length;for(let m=0;m<u;m++){let w=d[m];if(!(w==="list"||w==="read"||w==="add"||w==="replace"||w==="move"||w==="delete")){let b={instancePath:e+"/optional/"+m,schemaPath:"#/$defs/fileActions/items/enum",keyword:"enum",params:{allowedValues:MC.items.enum},message:"must be equal to one of the allowed values"};i===null?i=[b]:i.push(b),a++}}let f=d.length,h;if(f>1){e:for(;f--;)for(h=f;h--;)if(or(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)"};i===null?i=[m]:i.push(m),a++;break e}}}else{let u={instancePath:e+"/optional",schemaPath:"#/$defs/fileActions/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[u]:i.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 b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};i===null?i=[b]:i.push(b),a++}if(d.folders===void 0){let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/required",keyword:"required",params:{missingProperty:"folders"},message:"must have required property 'folders'"};i===null?i=[b]:i.push(b),a++}for(let b in d)if(!(b==="kind"||b==="folders")){let g={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:b},message:"must NOT have additional properties"};i===null?i=[g]:i.push(g),a++}if(d.kind!==void 0&&d.kind!=="selected_folders"){let b={instancePath:e+"/scope/kind",schemaPath:"#/$defs/fileScope/oneOf/0/properties/kind/const",keyword:"const",params:{allowedValue:"selected_folders"},message:"must be equal to constant"};i===null?i=[b]:i.push(b),a++}if(d.folders!==void 0){let b=d.folders;if(Array.isArray(b)){if(b.length>100){let v={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"};i===null?i=[v]:i.push(v),a++}if(b.length<1){let v={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"};i===null?i=[v]:i.push(v),a++}let g=b.length;for(let v=0;v<g;v++){let k=b[v];if(typeof k=="string"){if(W(k)>1024){let S={instancePath:e+"/scope/folders/"+v,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};i===null?i=[S]:i.push(S),a++}if(W(k)<1){let S={instancePath:e+"/scope/folders/"+v,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[S]:i.push(S),a++}if(!VC.test(k)){let S={instancePath:e+"/scope/folders/"+v,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)(?:/|$))(?!.*/$).+$"'};i===null?i=[S]:i.push(S),a++}}else{let S={instancePath:e+"/scope/folders/"+v,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[S]:i.push(S),a++}}let y=b.length,_;if(y>1){let v={};for(;y--;){let k=b[y];if(typeof k=="string"){if(typeof v[k]=="number"){_=v[k];let S={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/uniqueItems",keyword:"uniqueItems",params:{i:y,j:_},message:"must NOT have duplicate items (items ## "+_+" and "+y+" are identical)"};i===null?i=[S]:i.push(S),a++;break}v[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"};i===null?i=[g]:i.push(g),a++}}}else{let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[b]:i.push(b),a++}var p=m===a;if(p){f=!0,h=0;var l=!0}let w=a;if(d&&typeof d=="object"&&!Array.isArray(d)){if(d.kind===void 0){let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};i===null?i=[b]:i.push(b),a++}for(let b in d)if(b!=="kind"){let g={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:b},message:"must NOT have additional properties"};i===null?i=[g]:i.push(g),a++}if(d.kind!==void 0&&d.kind!=="collection"){let b={instancePath:e+"/scope/kind",schemaPath:"#/$defs/fileScope/oneOf/1/properties/kind/const",keyword:"const",params:{allowedValue:"collection"},message:"must be equal to constant"};i===null?i=[b]:i.push(b),a++}}else{let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[b]:i.push(b),a++}var p=w===a;if(p&&f?(f=!1,h=[h,1]):p&&(f=!0,h=1,l!==!0&&(l=!0)),f)a=u,i!==null&&(u?i.length=u:i=null);else{let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf",keyword:"oneOf",params:{passingSchemas:h},message:"must match exactly one schema in oneOf"};i===null?i=[b]:i.push(b),a++}}}else{let d={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[d]:i.push(d),a++}return fl.errors=i,a===0}function hl(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=hl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.id===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};i===null?i=[p]:i.push(p),a++}if(n.path===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"path"},message:"must have required property 'path'"};i===null?i=[p]:i.push(p),a++}if(n.predicate===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"predicate"},message:"must have required property 'predicate'"};i===null?i=[p]:i.push(p),a++}if(n.value===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"value"},message:"must have required property 'value'"};i===null?i=[p]:i.push(p),a++}for(let p in n)if(!(p==="id"||p==="path"||p==="predicate"||p==="value")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};i===null?i=[d]:i.push(d),a++}if(n.id!==void 0){let p=n.id;if(typeof p=="string"){if(W(p)>100){let d={instancePath:e+"/id",schemaPath:"#/properties/id/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};i===null?i=[d]:i.push(d),a++}if(W(p)<1){let d={instancePath:e+"/id",schemaPath:"#/properties/id/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[d]:i.push(d),a++}if(!Kh.test(p)){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]+)*$"'};i===null?i=[d]:i.push(d),a++}}else{let d={instancePath:e+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[d]:i.push(d),a++}}if(n.path!==void 0){let p=n.path;if(typeof p=="string"){if(W(p)>1024){let d={instancePath:e+"/path",schemaPath:"#/properties/path/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};i===null?i=[d]:i.push(d),a++}if(W(p)<1){let d={instancePath:e+"/path",schemaPath:"#/properties/path/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[d]:i.push(d),a++}}else{let d={instancePath:e+"/path",schemaPath:"#/properties/path/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[d]:i.push(d),a++}}if(n.predicate!==void 0&&n.predicate!=="contains"){let p={instancePath:e+"/predicate",schemaPath:"#/properties/predicate/const",keyword:"const",params:{allowedValue:"contains"},message:"must be equal to constant"};i===null?i=[p]:i.push(p),a++}if(n.value!==void 0){let p=n.value,d=a,u=!1,f=a;if(typeof p!="string"){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/0/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[b]:i.push(b),a++}var l=f===a;u=u||l;let h=a;if(!(typeof p=="number"&&isFinite(p))){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/1/type",keyword:"type",params:{type:"number"},message:"must be number"};i===null?i=[b]:i.push(b),a++}var l=h===a;u=u||l;let m=a;if(typeof p!="boolean"){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/2/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};i===null?i=[b]:i.push(b),a++}var l=m===a;u=u||l;let w=a;if(p!==null){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/3/type",keyword:"type",params:{type:"null"},message:"must be null"};i===null?i=[b]:i.push(b),a++}var l=w===a;if(u=u||l,u)a=d,i!==null&&(d?i.length=d:i=null);else{let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};i===null?i=[b]:i.push(b),a++}}}else{let p={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[p]:i.push(p),a++}return hl.errors=i,a===0}function Pr(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=Pr.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.push(l),a++}for(let l in n)if(!(l==="id"||l==="version"||l==="digest")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};i===null?i=[p]:i.push(p),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(W(l)>100){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};i===null?i=[p]:i.push(p),a++}if(W(l)<1){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[p]:i.push(p),a++}if(!Rl.test(l)){let p={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]+)*$"'};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}if(n.version!==void 0){let l=n.version;if(typeof l=="string"){if(!Wh.test(l)){let p={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-]+)*)?$"'};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/version",schemaPath:"#/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}if(n.digest!==void 0){let l=n.digest;if(typeof l=="string"){if(!ml.test(l)){let p={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}$"'};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/digest",schemaPath:"#/properties/digest/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[l]:i.push(l),a++}return Pr.errors=i,a===0}function yl(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=yl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.access===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"access"},message:"must have required property 'access'"};i===null?i=[p]:i.push(p),a++}if(n.contracts===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"contracts"},message:"must have required property 'contracts'"};i===null?i=[p]:i.push(p),a++}for(let p in n)if(!(p==="capabilities"||p==="access"||p==="collection_kind"||p==="people"||p==="files"||p==="configuration"||p==="contracts")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};i===null?i=[d]:i.push(d),a++}if(n.capabilities!==void 0&&(ul(n.capabilities,{instancePath:e+"/capabilities",parentData:n,parentDataProperty:"capabilities",rootData:o,dynamicAnchors:s})||(i=i===null?ul.errors:i.concat(ul.errors),a=i.length)),n.access!==void 0&&n.access!=="full_collection"){let p={instancePath:e+"/access",schemaPath:"#/properties/access/const",keyword:"const",params:{allowedValue:"full_collection"},message:"must be equal to constant"};i===null?i=[p]:i.push(p),a++}if(n.collection_kind!==void 0&&n.collection_kind!=="hosted"){let p={instancePath:e+"/collection_kind",schemaPath:"#/properties/collection_kind/const",keyword:"const",params:{allowedValue:"hosted"},message:"must be equal to constant"};i===null?i=[p]:i.push(p),a++}if(n.people!==void 0){let p=n.people,d=a,u=!1,f=a;if(p&&typeof p=="object"&&!Array.isArray(p)&&p.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'"};i===null?i=[m]:i.push(m),a++}var l=f===a;u=u||l;let h=a;if(p&&typeof p=="object"&&!Array.isArray(p)&&p.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'"};i===null?i=[m]:i.push(m),a++}var l=h===a;if(u=u||l,u)a=d,i!==null&&(d?i.length=d:i=null);else{let m={instancePath:e+"/people",schemaPath:"#/properties/people/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};i===null?i=[m]:i.push(m),a++}if(p&&typeof p=="object"&&!Array.isArray(p)){if(p.version===void 0){let m={instancePath:e+"/people",schemaPath:"#/properties/people/required",keyword:"required",params:{missingProperty:"version"},message:"must have required property 'version'"};i===null?i=[m]:i.push(m),a++}for(let m in p)if(!(m==="version"||m==="required"||m==="optional")){let w={instancePath:e+"/people",schemaPath:"#/properties/people/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:m},message:"must NOT have additional properties"};i===null?i=[w]:i.push(w),a++}if(p.version!==void 0&&p.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"};i===null?i=[m]:i.push(m),a++}if(p.required!==void 0){let m=p.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"};i===null?i=[y]:i.push(y),a++}let w=m.length;for(let y=0;y<w;y++){let _=m[y];if(!(_==="identity"||_==="members")){let v={instancePath:e+"/people/required/"+y,schemaPath:"#/$defs/peoplePermissions/items/enum",keyword:"enum",params:{allowedValues:qC.items.enum},message:"must be equal to one of the allowed values"};i===null?i=[v]:i.push(v),a++}}let b=m.length,g;if(b>1){e:for(;b--;)for(g=b;g--;)if(or(m[b],m[g])){let y={instancePath:e+"/people/required",schemaPath:"#/$defs/peoplePermissions/uniqueItems",keyword:"uniqueItems",params:{i:b,j:g},message:"must NOT have duplicate items (items ## "+g+" and "+b+" are identical)"};i===null?i=[y]:i.push(y),a++;break e}}}else{let w={instancePath:e+"/people/required",schemaPath:"#/$defs/peoplePermissions/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[w]:i.push(w),a++}}if(p.optional!==void 0){let m=p.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"};i===null?i=[y]:i.push(y),a++}let w=m.length;for(let y=0;y<w;y++){let _=m[y];if(!(_==="identity"||_==="members")){let v={instancePath:e+"/people/optional/"+y,schemaPath:"#/$defs/peoplePermissions/items/enum",keyword:"enum",params:{allowedValues:qC.items.enum},message:"must be equal to one of the allowed values"};i===null?i=[v]:i.push(v),a++}}let b=m.length,g;if(b>1){e:for(;b--;)for(g=b;g--;)if(or(m[b],m[g])){let y={instancePath:e+"/people/optional",schemaPath:"#/$defs/peoplePermissions/uniqueItems",keyword:"uniqueItems",params:{i:b,j:g},message:"must NOT have duplicate items (items ## "+g+" and "+b+" are identical)"};i===null?i=[y]:i.push(y),a++;break e}}}else{let w={instancePath:e+"/people/optional",schemaPath:"#/$defs/peoplePermissions/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[w]:i.push(w),a++}}}else{let m={instancePath:e+"/people",schemaPath:"#/properties/people/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[m]:i.push(m),a++}}if(n.files!==void 0&&(fl(n.files,{instancePath:e+"/files",parentData:n,parentDataProperty:"files",rootData:o,dynamicAnchors:s})||(i=i===null?fl.errors:i.concat(fl.errors),a=i.length)),n.configuration!==void 0){let p=n.configuration;if(Array.isArray(p)){if(p.length>50){let u={instancePath:e+"/configuration",schemaPath:"#/properties/configuration/maxItems",keyword:"maxItems",params:{limit:50},message:"must NOT have more than 50 items"};i===null?i=[u]:i.push(u),a++}let d=p.length;for(let u=0;u<d;u++)hl(p[u],{instancePath:e+"/configuration/"+u,parentData:p,parentDataProperty:u,rootData:o,dynamicAnchors:s})||(i=i===null?hl.errors:i.concat(hl.errors),a=i.length)}else{let d={instancePath:e+"/configuration",schemaPath:"#/properties/configuration/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[d]:i.push(d),a++}}if(n.contracts!==void 0){let p=n.contracts;if(Array.isArray(p)){if(p.length>20){let h={instancePath:e+"/contracts",schemaPath:"#/properties/contracts/maxItems",keyword:"maxItems",params:{limit:20},message:"must NOT have more than 20 items"};i===null?i=[h]:i.push(h),a++}let d=p.length;for(let h=0;h<d;h++)Pr(p[h],{instancePath:e+"/contracts/"+h,parentData:p,parentDataProperty:h,rootData:o,dynamicAnchors:s})||(i=i===null?Pr.errors:i.concat(Pr.errors),a=i.length);let u=p.length,f;if(u>1){e:for(;u--;)for(f=u;f--;)if(or(p[u],p[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)"};i===null?i=[h]:i.push(h),a++;break e}}}else{let d={instancePath:e+"/contracts",schemaPath:"#/properties/contracts/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[d]:i.push(d),a++}}}else{let p={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[p]:i.push(p),a++}return yl.errors=i,a===0}function gl(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=gl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.requirement===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"requirement"},message:"must have required property 'requirement'"};i===null?i=[p]:i.push(p),a++}if(n.operation===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"operation"},message:"must have required property 'operation'"};i===null?i=[p]:i.push(p),a++}if(n.path===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"path"},message:"must have required property 'path'"};i===null?i=[p]:i.push(p),a++}if(n.value===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"value"},message:"must have required property 'value'"};i===null?i=[p]:i.push(p),a++}for(let p in n)if(!(p==="requirement"||p==="operation"||p==="path"||p==="value")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};i===null?i=[d]:i.push(d),a++}if(n.requirement!==void 0){let p=n.requirement;if(typeof p=="string"){if(W(p)>100){let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};i===null?i=[d]:i.push(d),a++}if(W(p)<1){let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[d]:i.push(d),a++}if(!Kh.test(p)){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]+)*$"'};i===null?i=[d]:i.push(d),a++}}else{let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[d]:i.push(d),a++}}if(n.operation!==void 0&&n.operation!=="set_add"){let p={instancePath:e+"/operation",schemaPath:"#/properties/operation/const",keyword:"const",params:{allowedValue:"set_add"},message:"must be equal to constant"};i===null?i=[p]:i.push(p),a++}if(n.path!==void 0){let p=n.path;if(typeof p=="string"){if(W(p)>1024){let d={instancePath:e+"/path",schemaPath:"#/properties/path/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};i===null?i=[d]:i.push(d),a++}if(W(p)<1){let d={instancePath:e+"/path",schemaPath:"#/properties/path/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[d]:i.push(d),a++}}else{let d={instancePath:e+"/path",schemaPath:"#/properties/path/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[d]:i.push(d),a++}}if(n.value!==void 0){let p=n.value,d=a,u=!1,f=a;if(typeof p!="string"){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/0/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[b]:i.push(b),a++}var l=f===a;u=u||l;let h=a;if(!(typeof p=="number"&&isFinite(p))){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/1/type",keyword:"type",params:{type:"number"},message:"must be number"};i===null?i=[b]:i.push(b),a++}var l=h===a;u=u||l;let m=a;if(typeof p!="boolean"){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/2/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};i===null?i=[b]:i.push(b),a++}var l=m===a;u=u||l;let w=a;if(p!==null){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/3/type",keyword:"type",params:{type:"null"},message:"must be null"};i===null?i=[b]:i.push(b),a++}var l=w===a;if(u=u||l,u)a=d,i!==null&&(d?i.length=d:i=null);else{let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};i===null?i=[b]:i.push(b),a++}}}else{let p={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[p]:i.push(p),a++}return gl.errors=i,a===0}function bl(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=bl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.kind===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};i===null?i=[p]:i.push(p),a++}if(n.mode===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"mode"},message:"must have required property 'mode'"};i===null?i=[p]:i.push(p),a++}if(n.source===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"source"},message:"must have required property 'source'"};i===null?i=[p]:i.push(p),a++}if(n.target===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"target"},message:"must have required property 'target'"};i===null?i=[p]:i.push(p),a++}if(n.digest===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"digest"},message:"must have required property 'digest'"};i===null?i=[p]:i.push(p),a++}for(let p in n)if(!(p==="kind"||p==="mode"||p==="upgrade_from"||p==="source"||p==="target"||p==="digest")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};i===null?i=[d]:i.push(d),a++}if(n.kind!==void 0){let p=n.kind;if(!(p==="contract"||p==="type"||p==="schema")){let d={instancePath:e+"/kind",schemaPath:"#/properties/kind/enum",keyword:"enum",params:{allowedValues:LC.properties.kind.enum},message:"must be equal to one of the allowed values"};i===null?i=[d]:i.push(d),a++}}if(n.mode!==void 0){let p=n.mode;if(!(p==="managed"||p==="seed")){let d={instancePath:e+"/mode",schemaPath:"#/properties/mode/enum",keyword:"enum",params:{allowedValues:LC.properties.mode.enum},message:"must be equal to one of the allowed values"};i===null?i=[d]:i.push(d),a++}}if(n.upgrade_from!==void 0){let p=n.upgrade_from,d=a,u=!1,f=null,h=a;if(p&&typeof p=="object"&&!Array.isArray(p)){if(p.digest===void 0){let w={instancePath:e+"/upgrade_from",schemaPath:"#/$defs/typePackUpgradeBaseline/required",keyword:"required",params:{missingProperty:"digest"},message:"must have required property 'digest'"};i===null?i=[w]:i.push(w),a++}if(p.document===void 0){let w={instancePath:e+"/upgrade_from",schemaPath:"#/$defs/typePackUpgradeBaseline/required",keyword:"required",params:{missingProperty:"document"},message:"must have required property 'document'"};i===null?i=[w]:i.push(w),a++}for(let w in p)if(!(w==="digest"||w==="document"||w==="version")){let b={instancePath:e+"/upgrade_from",schemaPath:"#/$defs/typePackUpgradeBaseline/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:w},message:"must NOT have additional properties"};i===null?i=[b]:i.push(b),a++}if(p.digest!==void 0){let w=p.digest;if(typeof w=="string"){if(!ml.test(w)){let b={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}$"'};i===null?i=[b]:i.push(b),a++}}else{let b={instancePath:e+"/upgrade_from/digest",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/digest/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[b]:i.push(b),a++}}if(p.document!==void 0){let w=p.document;if(typeof w=="string"){if(W(w)>262144){let b={instancePath:e+"/upgrade_from/document",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/document/maxLength",keyword:"maxLength",params:{limit:262144},message:"must NOT have more than 262144 characters"};i===null?i=[b]:i.push(b),a++}}else{let b={instancePath:e+"/upgrade_from/document",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/document/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[b]:i.push(b),a++}}if(p.version!==void 0){let w=p.version;if(!(typeof w=="number"&&!(w%1)&&!isNaN(w)&&isFinite(w))){let b={instancePath:e+"/upgrade_from/version",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/version/type",keyword:"type",params:{type:"integer"},message:"must be integer"};i===null?i=[b]:i.push(b),a++}if(typeof w=="number"&&isFinite(w)&&(w<1||isNaN(w))){let b={instancePath:e+"/upgrade_from/version",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/version/minimum",keyword:"minimum",params:{comparison:">=",limit:1},message:"must be >= 1"};i===null?i=[b]:i.push(b),a++}}}else{let w={instancePath:e+"/upgrade_from",schemaPath:"#/$defs/typePackUpgradeBaseline/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[w]:i.push(w),a++}var l=h===a;l&&(u=!0,f=0);let m=a;if(Array.isArray(p)){if(p.length<1){let b={instancePath:e+"/upgrade_from",schemaPath:"#/properties/upgrade_from/oneOf/1/minItems",keyword:"minItems",params:{limit:1},message:"must NOT have fewer than 1 items"};i===null?i=[b]:i.push(b),a++}let w=p.length;for(let b=0;b<w;b++){let g=p[b];if(g&&typeof g=="object"&&!Array.isArray(g)){if(g.digest===void 0){let y={instancePath:e+"/upgrade_from/"+b,schemaPath:"#/$defs/typePackUpgradeBaseline/required",keyword:"required",params:{missingProperty:"digest"},message:"must have required property 'digest'"};i===null?i=[y]:i.push(y),a++}if(g.document===void 0){let y={instancePath:e+"/upgrade_from/"+b,schemaPath:"#/$defs/typePackUpgradeBaseline/required",keyword:"required",params:{missingProperty:"document"},message:"must have required property 'document'"};i===null?i=[y]:i.push(y),a++}for(let y in g)if(!(y==="digest"||y==="document"||y==="version")){let _={instancePath:e+"/upgrade_from/"+b,schemaPath:"#/$defs/typePackUpgradeBaseline/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};i===null?i=[_]:i.push(_),a++}if(g.digest!==void 0){let y=g.digest;if(typeof y=="string"){if(!ml.test(y)){let _={instancePath:e+"/upgrade_from/"+b+"/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}$"'};i===null?i=[_]:i.push(_),a++}}else{let _={instancePath:e+"/upgrade_from/"+b+"/digest",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/digest/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[_]:i.push(_),a++}}if(g.document!==void 0){let y=g.document;if(typeof y=="string"){if(W(y)>262144){let _={instancePath:e+"/upgrade_from/"+b+"/document",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/document/maxLength",keyword:"maxLength",params:{limit:262144},message:"must NOT have more than 262144 characters"};i===null?i=[_]:i.push(_),a++}}else{let _={instancePath:e+"/upgrade_from/"+b+"/document",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/document/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[_]:i.push(_),a++}}if(g.version!==void 0){let y=g.version;if(!(typeof y=="number"&&!(y%1)&&!isNaN(y)&&isFinite(y))){let _={instancePath:e+"/upgrade_from/"+b+"/version",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/version/type",keyword:"type",params:{type:"integer"},message:"must be integer"};i===null?i=[_]:i.push(_),a++}if(typeof y=="number"&&isFinite(y)&&(y<1||isNaN(y))){let _={instancePath:e+"/upgrade_from/"+b+"/version",schemaPath:"#/$defs/typePackUpgradeBaseline/properties/version/minimum",keyword:"minimum",params:{comparison:">=",limit:1},message:"must be >= 1"};i===null?i=[_]:i.push(_),a++}}}else{let y={instancePath:e+"/upgrade_from/"+b,schemaPath:"#/$defs/typePackUpgradeBaseline/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[y]:i.push(y),a++}}}else{let w={instancePath:e+"/upgrade_from",schemaPath:"#/properties/upgrade_from/oneOf/1/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[w]:i.push(w),a++}var l=m===a;if(l&&u?(u=!1,f=[f,1]):l&&(u=!0,f=1),u)a=d,i!==null&&(d?i.length=d:i=null);else{let w={instancePath:e+"/upgrade_from",schemaPath:"#/properties/upgrade_from/oneOf",keyword:"oneOf",params:{passingSchemas:f},message:"must match exactly one schema in oneOf"};i===null?i=[w]:i.push(w),a++}}if(n.source!==void 0){let p=n.source;if(typeof p=="string"){if(W(p)>240){let d={instancePath:e+"/source",schemaPath:"#/properties/source/maxLength",keyword:"maxLength",params:{limit:240},message:"must NOT have more than 240 characters"};i===null?i=[d]:i.push(d),a++}if(W(p)<1){let d={instancePath:e+"/source",schemaPath:"#/properties/source/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[d]:i.push(d),a++}}else{let d={instancePath:e+"/source",schemaPath:"#/properties/source/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[d]:i.push(d),a++}}if(n.target!==void 0){let p=n.target;if(typeof p=="string"){if(W(p)>240){let d={instancePath:e+"/target",schemaPath:"#/properties/target/maxLength",keyword:"maxLength",params:{limit:240},message:"must NOT have more than 240 characters"};i===null?i=[d]:i.push(d),a++}if(W(p)<1){let d={instancePath:e+"/target",schemaPath:"#/properties/target/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[d]:i.push(d),a++}}else{let d={instancePath:e+"/target",schemaPath:"#/properties/target/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[d]:i.push(d),a++}}if(n.digest!==void 0){let p=n.digest;if(typeof p=="string"){if(!ml.test(p)){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}$"'};i===null?i=[d]:i.push(d),a++}}else{let d={instancePath:e+"/digest",schemaPath:"#/properties/digest/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[d]:i.push(d),a++}}}else{let p={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[p]:i.push(p),a++}return bl.errors=i,a===0}function wl(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=wl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.push(l),a++}for(let l in n)if(!(l==="kind"||l==="id"||l==="version"||l==="name"||l==="description"||l==="resources"||FC.test(l))){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};i===null?i=[p]:i.push(p),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"};i===null?i=[l]:i.push(l),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(W(l)>100){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};i===null?i=[p]:i.push(p),a++}if(W(l)<1){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[p]:i.push(p),a++}if(!Rl.test(l)){let p={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]+)*$"'};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}if(n.version!==void 0){let l=n.version;if(typeof l=="string"){if(!Wh.test(l)){let p={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-]+)*)?$"'};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/version",schemaPath:"#/$defs/contract/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}if(n.name!==void 0){let l=n.name;if(typeof l=="string"){if(W(l)>100){let p={instancePath:e+"/name",schemaPath:"#/properties/name/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};i===null?i=[p]:i.push(p),a++}if(W(l)<1){let p={instancePath:e+"/name",schemaPath:"#/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}if(n.description!==void 0){let l=n.description;if(typeof l=="string"){if(W(l)>500){let p={instancePath:e+"/description",schemaPath:"#/properties/description/maxLength",keyword:"maxLength",params:{limit:500},message:"must NOT have more than 500 characters"};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),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"};i===null?i=[d]:i.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"};i===null?i=[d]:i.push(d),a++}let p=l.length;for(let d=0;d<p;d++)bl(l[d],{instancePath:e+"/resources/"+d,parentData:l,parentDataProperty:d,rootData:o,dynamicAnchors:s})||(i=i===null?bl.errors:i.concat(bl.errors),a=i.length)}else{let p={instancePath:e+"/resources",schemaPath:"#/properties/resources/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[p]:i.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[l]:i.push(l),a++}return wl.errors=i,a===0}function vl(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=vl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.push(l),a++}for(let l in n)if(!(l==="manifest"||l==="resources"||l==="provides")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};i===null?i=[p]:i.push(p),a++}if(n.manifest!==void 0&&(wl(n.manifest,{instancePath:e+"/manifest",parentData:n,parentDataProperty:"manifest",rootData:o,dynamicAnchors:s})||(i=i===null?wl.errors:i.concat(wl.errors),a=i.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"};i===null?i=[d]:i.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"};i===null?i=[d]:i.push(d),a++}let p=l.length;for(let d=0;d<p;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'"};i===null?i=[f]:i.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'"};i===null?i=[f]:i.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"};i===null?i=[h]:i.push(h),a++}if(u.source!==void 0){let f=u.source;if(typeof f=="string"){if(W(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"};i===null?i=[h]:i.push(h),a++}if(W(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"};i===null?i=[h]:i.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"};i===null?i=[h]:i.push(h),a++}}if(u.document!==void 0){let f=u.document;if(typeof f=="string"){if(W(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"};i===null?i=[h]:i.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"};i===null?i=[h]:i.push(h),a++}}}else{let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[f]:i.push(f),a++}}}else{let p={instancePath:e+"/resources",schemaPath:"#/properties/resources/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[p]:i.push(p),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"};i===null?i=[f]:i.push(f),a++}let p=l.length;for(let f=0;f<p;f++)Pr(l[f],{instancePath:e+"/provides/"+f,parentData:l,parentDataProperty:f,rootData:o,dynamicAnchors:s})||(i=i===null?Pr.errors:i.concat(Pr.errors),a=i.length);let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(or(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)"};i===null?i=[f]:i.push(f),a++;break e}}}else{let p={instancePath:e+"/provides",schemaPath:"#/properties/provides/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[p]:i.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[l]:i.push(l),a++}return vl.errors=i,a===0}function _l(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=_l.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.push(l),a++}for(let l in n)if(!(l==="id"||l==="event"||l==="if"||l==="debounce"||l==="minimum_interval"||l==="presentation")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};i===null?i=[p]:i.push(p),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(W(l)>100){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};i===null?i=[p]:i.push(p),a++}if(W(l)<1){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[p]:i.push(p),a++}if(!Rl.test(l)){let p={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]+)*$"'};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}if(n.event!==void 0&&(Pr(n.event,{instancePath:e+"/event",parentData:n,parentDataProperty:"event",rootData:o,dynamicAnchors:s})||(i=i===null?Pr.errors:i.concat(Pr.errors),a=i.length)),n.if!==void 0){let l=n.if;if(l&&typeof l=="object"&&!Array.isArray(l)){if(l.$expr===void 0){let p={instancePath:e+"/if",schemaPath:"#/properties/if/required",keyword:"required",params:{missingProperty:"$expr"},message:"must have required property '$expr'"};i===null?i=[p]:i.push(p),a++}for(let p in l)if(p!=="$expr"){let d={instancePath:e+"/if",schemaPath:"#/properties/if/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};i===null?i=[d]:i.push(d),a++}if(l.$expr!==void 0){let p=l.$expr;if(typeof p=="string"){if(W(p)>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"};i===null?i=[d]:i.push(d),a++}if(W(p)<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"};i===null?i=[d]:i.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"};i===null?i=[d]:i.push(d),a++}}}else{let p={instancePath:e+"/if",schemaPath:"#/properties/if/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[p]:i.push(p),a++}}if(n.debounce!==void 0){let l=n.debounce;if(typeof l=="string"){if(!Bh.test(l)){let p={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)$"'};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/debounce",schemaPath:"#/$defs/duration/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}if(n.minimum_interval!==void 0){let l=n.minimum_interval;if(typeof l=="string"){if(!Bh.test(l)){let p={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)$"'};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/minimum_interval",schemaPath:"#/$defs/duration/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}if(n.presentation!==void 0){let l=n.presentation;if(l&&typeof l=="object"&&!Array.isArray(l)){if(l.title===void 0){let p={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/required",keyword:"required",params:{missingProperty:"title"},message:"must have required property 'title'"};i===null?i=[p]:i.push(p),a++}for(let p in l)if(!(p==="title"||p==="body"||p==="tag")){let d={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};i===null?i=[d]:i.push(d),a++}if(l.title!==void 0){let p=l.title;if(typeof p=="string"){if(W(p)>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"};i===null?i=[d]:i.push(d),a++}if(W(p)<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"};i===null?i=[d]:i.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"};i===null?i=[d]:i.push(d),a++}}if(l.body!==void 0){let p=l.body;if(typeof p=="string"){if(W(p)>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"};i===null?i=[d]:i.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"};i===null?i=[d]:i.push(d),a++}}if(l.tag!==void 0){let p=l.tag;if(typeof p=="string"){if(W(p)>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"};i===null?i=[d]:i.push(d),a++}if(W(p)<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"};i===null?i=[d]:i.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"};i===null?i=[d]:i.push(d),a++}}}else{let p={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[p]:i.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[l]:i.push(l),a++}return _l.errors=i,a===0}function Vh(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=Vh.evaluated;c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0);let l=a,p=!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'"};i===null?i=[g]:i.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'"};i===null?i=[g]:i.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"};i===null?i=[g]:i.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"};i===null?i=[g]:i.push(g),a++}}var m=u===a;if(m){p=!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'"};i===null?i=[g]:i.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"};i===null?i=[g]:i.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"};i===null?i=[g]:i.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"};i===null?i=[g]:i.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"};i===null?i=[g]:i.push(g),a++}}var m=h===a;if(m&&p?(p=!1,d=[d,1]):m&&(p=!0,d=1,f!==!0&&(f=f||{},f.distribution=!0,f.platform=!0,f.homepage=!0,f.redirect_uris=!0)),p)a=l,i!==null&&(l?i.length=l:i=null);else{let g={instancePath:e,schemaPath:"#/oneOf",keyword:"oneOf",params:{passingSchemas:d},message:"must match exactly one schema in oneOf"};i===null?i=[g]:i.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'"};i===null?i=[g]:i.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'"};i===null?i=[g]:i.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'"};i===null?i=[g]:i.push(g),a++}for(let g in n)if(!zC.call(EC.properties,g)){let y={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:g},message:"must NOT have additional properties"};i===null?i=[y]:i.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"};i===null?i=[g]:i.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:EC.properties.distribution.enum},message:"must be equal to one of the allowed values"};i===null?i=[y]:i.push(y),a++}}if(n.id!==void 0){let g=n.id;if(typeof g=="string"){if(W(g)>150){let y={instancePath:e+"/id",schemaPath:"#/properties/id/maxLength",keyword:"maxLength",params:{limit:150},message:"must NOT have more than 150 characters"};i===null?i=[y]:i.push(y),a++}if(W(g)<5){let y={instancePath:e+"/id",schemaPath:"#/properties/id/minLength",keyword:"minLength",params:{limit:5},message:"must NOT have fewer than 5 characters"};i===null?i=[y]:i.push(y),a++}if(!$C.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,}$"'};i===null?i=[y]:i.push(y),a++}}else{let y={instancePath:e+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[y]:i.push(y),a++}}if(n.name!==void 0){let g=n.name;if(typeof g=="string"){if(W(g)>100){let y={instancePath:e+"/name",schemaPath:"#/properties/name/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};i===null?i=[y]:i.push(y),a++}if(W(g)<1){let y={instancePath:e+"/name",schemaPath:"#/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[y]:i.push(y),a++}}else{let y={instancePath:e+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[y]:i.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"};i===null?i=[g]:i.push(g),a++}if(n.homepage!==void 0){let g=n.homepage;if(typeof g=="string"){if(!Wo.test(g)){let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};i===null?i=[y]:i.push(y),a++}if(!Kn(g)){let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};i===null?i=[y]:i.push(y),a++}}else{let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[y]:i.push(y),a++}}if(n.project_url!==void 0){let g=n.project_url;if(typeof g=="string"){if(!Wo.test(g)){let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};i===null?i=[y]:i.push(y),a++}if(!Kn(g)){let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};i===null?i=[y]:i.push(y),a++}}else{let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[y]:i.push(y),a++}}if(n.icon!==void 0){let g=n.icon;if(typeof g=="string"){if(!Wo.test(g)){let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};i===null?i=[y]:i.push(y),a++}if(!Kn(g)){let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};i===null?i=[y]:i.push(y),a++}}else{let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[y]:i.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"};i===null?i=[k]:i.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"};i===null?i=[k]:i.push(k),a++}let y=g.length;for(let k=0;k<y;k++){let S=g[k];if(typeof S=="string"){if(!Kn(S)){let x={instancePath:e+"/redirect_uris/"+k,schemaPath:"#/properties/redirect_uris/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};i===null?i=[x]:i.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"};i===null?i=[x]:i.push(x),a++}}let _=g.length,v;if(_>1){let k={};for(;_--;){let S=g[_];if(typeof S=="string"){if(typeof k[S]=="number"){v=k[S];let x={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/uniqueItems",keyword:"uniqueItems",params:{i:_,j:v},message:"must NOT have duplicate items (items ## "+v+" and "+_+" are identical)"};i===null?i=[x]:i.push(x),a++;break}k[S]=_}}}}else{let y={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[y]:i.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 _={instancePath:e+"/installation_origins",schemaPath:"#/properties/installation_origins/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};i===null?i=[_]:i.push(_),a++}g.lab!==void 0&&(kr(g.lab,{instancePath:e+"/installation_origins/lab",parentData:g,parentDataProperty:"lab",rootData:o,dynamicAnchors:s})||(i=i===null?kr.errors:i.concat(kr.errors),a=i.length)),g.staging!==void 0&&(kr(g.staging,{instancePath:e+"/installation_origins/staging",parentData:g,parentDataProperty:"staging",rootData:o,dynamicAnchors:s})||(i=i===null?kr.errors:i.concat(kr.errors),a=i.length)),g.production!==void 0&&(kr(g.production,{instancePath:e+"/installation_origins/production",parentData:g,parentDataProperty:"production",rootData:o,dynamicAnchors:s})||(i=i===null?kr.errors:i.concat(kr.errors),a=i.length))}else{let y={instancePath:e+"/installation_origins",schemaPath:"#/properties/installation_origins/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[y]:i.push(y),a++}}if(n.requirements!==void 0&&(yl(n.requirements,{instancePath:e+"/requirements",parentData:n,parentDataProperty:"requirements",rootData:o,dynamicAnchors:s})||(i=i===null?yl.errors:i.concat(yl.errors),a=i.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'"};i===null?i=[y]:i.push(y),a++}for(let y in g)if(!(y==="configuration"||y==="type_packs")){let _={instancePath:e+"/provisions",schemaPath:"#/properties/provisions/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};i===null?i=[_]:i.push(_),a++}if(g.configuration!==void 0){let y=g.configuration;if(Array.isArray(y)){if(y.length>50){let v={instancePath:e+"/provisions/configuration",schemaPath:"#/properties/provisions/properties/configuration/maxItems",keyword:"maxItems",params:{limit:50},message:"must NOT have more than 50 items"};i===null?i=[v]:i.push(v),a++}let _=y.length;for(let v=0;v<_;v++)gl(y[v],{instancePath:e+"/provisions/configuration/"+v,parentData:y,parentDataProperty:v,rootData:o,dynamicAnchors:s})||(i=i===null?gl.errors:i.concat(gl.errors),a=i.length)}else{let _={instancePath:e+"/provisions/configuration",schemaPath:"#/properties/provisions/properties/configuration/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[_]:i.push(_),a++}}if(g.type_packs!==void 0){let y=g.type_packs;if(Array.isArray(y)){if(y.length>20){let v={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"};i===null?i=[v]:i.push(v),a++}let _=y.length;for(let v=0;v<_;v++)vl(y[v],{instancePath:e+"/provisions/type_packs/"+v,parentData:y,parentDataProperty:v,rootData:o,dynamicAnchors:s})||(i=i===null?vl.errors:i.concat(vl.errors),a=i.length)}else{let _={instancePath:e+"/provisions/type_packs",schemaPath:"#/properties/provisions/properties/type_packs/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[_]:i.push(_),a++}}}else{let y={instancePath:e+"/provisions",schemaPath:"#/properties/provisions/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[y]:i.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'"};i===null?i=[y]:i.push(y),a++}for(let y in g)if(!(y==="criteria"||y==="native_delivery")){let _={instancePath:e+"/notifications",schemaPath:"#/properties/notifications/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};i===null?i=[_]:i.push(_),a++}if(g.criteria!==void 0){let y=g.criteria;if(Array.isArray(y)){if(y.length>50){let v={instancePath:e+"/notifications/criteria",schemaPath:"#/properties/notifications/properties/criteria/maxItems",keyword:"maxItems",params:{limit:50},message:"must NOT have more than 50 items"};i===null?i=[v]:i.push(v),a++}let _=y.length;for(let v=0;v<_;v++)_l(y[v],{instancePath:e+"/notifications/criteria/"+v,parentData:y,parentDataProperty:v,rootData:o,dynamicAnchors:s})||(i=i===null?_l.errors:i.concat(_l.errors),a=i.length)}else{let _={instancePath:e+"/notifications/criteria",schemaPath:"#/properties/notifications/properties/criteria/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[_]:i.push(_),a++}}if(g.native_delivery!==void 0){let y=g.native_delivery,_=a,v=!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'"};i===null?i=[P]:i.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'"};i===null?i=[P]:i.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"};i===null?i=[C]:i.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"};i===null?i=[P]:i.push(P),a++}if(y.firebase_project_id!==void 0){let P=y.firebase_project_id;if(typeof P=="string"){if(W(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"};i===null?i=[C]:i.push(C),a++}if(W(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"};i===null?i=[C]:i.push(C),a++}if(!BC.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]$"'};i===null?i=[C]:i.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"};i===null?i=[C]:i.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"};i===null?i=[P]:i.push(P),a++}var b=S===a;if(b){v=!0,k=0;var w=!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'"};i===null?i=[P]:i.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'"};i===null?i=[P]:i.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"};i===null?i=[C]:i.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"};i===null?i=[P]:i.push(P),a++}if(y.url!==void 0){let P=y.url;if(typeof P=="string"){if(!Wo.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://"'};i===null?i=[C]:i.push(C),a++}if(!Kn(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"'};i===null?i=[C]:i.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"};i===null?i=[C]:i.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"};i===null?i=[P]:i.push(P),a++}var b=x===a;if(b&&v?(v=!1,k=[k,1]):b&&(v=!0,k=1,w!==!0&&(w=!0)),v)a=_,i!==null&&(_?i.length=_:i=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"};i===null?i=[P]:i.push(P),a++}}}else{let y={instancePath:e+"/notifications",schemaPath:"#/properties/notifications/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[y]:i.push(y),a++}}}else{let g={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[g]:i.push(g),a++}return Vh.errors=i,a===0}function Sr(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=Sr.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){for(let l in n)if(!(l==="app-runtime"||l==="mobile")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};i===null?i=[p]:i.push(p),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"};i===null?i=[f]:i.push(f),a++}let p=l.length;for(let f=0;f<p;f++){let h=l[f];if(typeof h=="string"){if(W(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"};i===null?i=[m]:i.push(m),a++}if(W(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"};i===null?i=[m]:i.push(m),a++}if(!Kn(h)){let m={instancePath:e+"/app-runtime/"+f,schemaPath:"#/$defs/installationOrigins/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};i===null?i=[m]:i.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"};i===null?i=[m]:i.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)"};i===null?i=[m]:i.push(m),a++;break}f[h]=d}}}}else{let p={instancePath:e+"/app-runtime",schemaPath:"#/$defs/installationOrigins/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[p]:i.push(p),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"};i===null?i=[f]:i.push(f),a++}let p=l.length;for(let f=0;f<p;f++){let h=l[f];if(typeof h=="string"){if(W(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"};i===null?i=[m]:i.push(m),a++}if(W(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"};i===null?i=[m]:i.push(m),a++}if(!Kn(h)){let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};i===null?i=[m]:i.push(m),a++}}else{let m={instancePath:e+"/mobile/"+f,schemaPath:"#/$defs/installationOrigins/items/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[m]:i.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)"};i===null?i=[m]:i.push(m),a++;break}f[h]=d}}}}else{let p={instancePath:e+"/mobile",schemaPath:"#/$defs/installationOrigins/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[p]:i.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[l]:i.push(l),a++}return Sr.errors=i,a===0}function Al(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=Al.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.push(l),a++}for(let l in n)if(!(l==="contract_version"||l==="required"||l==="optional")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};i===null?i=[p]:i.push(p),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"};i===null?i=[l]:i.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"};i===null?i=[f]:i.push(f),a++}let p=l.length;for(let f=0;f<p;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:UC.enum},message:"must be equal to one of the allowed values"};i===null?i=[m]:i.push(m),a++}}let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(or(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)"};i===null?i=[f]:i.push(f),a++;break e}}}else{let p={instancePath:e+"/required",schemaPath:"#/properties/required/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[p]:i.push(p),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"};i===null?i=[f]:i.push(f),a++}let p=l.length;for(let f=0;f<p;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:UC.enum},message:"must be equal to one of the allowed values"};i===null?i=[m]:i.push(m),a++}}let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(or(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)"};i===null?i=[f]:i.push(f),a++;break e}}}else{let p={instancePath:e+"/optional",schemaPath:"#/properties/optional/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[p]:i.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[l]:i.push(l),a++}return Al.errors=i,a===0}function kl(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=kl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.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'"};i===null?i=[d]:i.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'"};i===null?i=[d]:i.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"};i===null?i=[u]:i.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"};i===null?i=[m]:i.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"};i===null?i=[m]:i.push(m),a++}let u=d.length;for(let m=0;m<u;m++){let w=d[m];if(!(w==="list"||w==="read"||w==="add"||w==="replace"||w==="move"||w==="delete")){let b={instancePath:e+"/actions/"+m,schemaPath:"#/properties/actions/items/enum",keyword:"enum",params:{allowedValues:DM.properties.actions.items.enum},message:"must be equal to one of the allowed values"};i===null?i=[b]:i.push(b),a++}}let f=d.length,h;if(f>1){e:for(;f--;)for(h=f;h--;)if(or(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)"};i===null?i=[m]:i.push(m),a++;break e}}}else{let u={instancePath:e+"/actions",schemaPath:"#/properties/actions/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[u]:i.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 b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};i===null?i=[b]:i.push(b),a++}if(d.folders===void 0){let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/required",keyword:"required",params:{missingProperty:"folders"},message:"must have required property 'folders'"};i===null?i=[b]:i.push(b),a++}for(let b in d)if(!(b==="kind"||b==="folders")){let g={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:b},message:"must NOT have additional properties"};i===null?i=[g]:i.push(g),a++}if(d.kind!==void 0&&d.kind!=="selected_folders"){let b={instancePath:e+"/scope/kind",schemaPath:"#/$defs/fileScope/oneOf/0/properties/kind/const",keyword:"const",params:{allowedValue:"selected_folders"},message:"must be equal to constant"};i===null?i=[b]:i.push(b),a++}if(d.folders!==void 0){let b=d.folders;if(Array.isArray(b)){if(b.length>100){let v={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"};i===null?i=[v]:i.push(v),a++}if(b.length<1){let v={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"};i===null?i=[v]:i.push(v),a++}let g=b.length;for(let v=0;v<g;v++){let k=b[v];if(typeof k=="string"){if(W(k)>1024){let S={instancePath:e+"/scope/folders/"+v,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};i===null?i=[S]:i.push(S),a++}if(W(k)<1){let S={instancePath:e+"/scope/folders/"+v,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[S]:i.push(S),a++}if(!VC.test(k)){let S={instancePath:e+"/scope/folders/"+v,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)(?:/|$))(?!.*/$).+$"'};i===null?i=[S]:i.push(S),a++}}else{let S={instancePath:e+"/scope/folders/"+v,schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/items/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[S]:i.push(S),a++}}let y=b.length,_;if(y>1){let v={};for(;y--;){let k=b[y];if(typeof k=="string"){if(typeof v[k]=="number"){_=v[k];let S={instancePath:e+"/scope/folders",schemaPath:"#/$defs/fileScope/oneOf/0/properties/folders/uniqueItems",keyword:"uniqueItems",params:{i:y,j:_},message:"must NOT have duplicate items (items ## "+_+" and "+y+" are identical)"};i===null?i=[S]:i.push(S),a++;break}v[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"};i===null?i=[g]:i.push(g),a++}}}else{let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/0/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[b]:i.push(b),a++}var p=m===a;if(p){f=!0,h=0;var l=!0}let w=a;if(d&&typeof d=="object"&&!Array.isArray(d)){if(d.kind===void 0){let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/required",keyword:"required",params:{missingProperty:"kind"},message:"must have required property 'kind'"};i===null?i=[b]:i.push(b),a++}for(let b in d)if(b!=="kind"){let g={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:b},message:"must NOT have additional properties"};i===null?i=[g]:i.push(g),a++}if(d.kind!==void 0&&d.kind!=="collection"){let b={instancePath:e+"/scope/kind",schemaPath:"#/$defs/fileScope/oneOf/1/properties/kind/const",keyword:"const",params:{allowedValue:"collection"},message:"must be equal to constant"};i===null?i=[b]:i.push(b),a++}}else{let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf/1/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[b]:i.push(b),a++}var p=w===a;if(p&&f?(f=!1,h=[h,1]):p&&(f=!0,h=1,l!==!0&&(l=!0)),f)a=u,i!==null&&(u?i.length=u:i=null);else{let b={instancePath:e+"/scope",schemaPath:"#/$defs/fileScope/oneOf",keyword:"oneOf",params:{passingSchemas:h},message:"must match exactly one schema in oneOf"};i===null?i=[b]:i.push(b),a++}}}else{let d={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[d]:i.push(d),a++}return kl.errors=i,a===0}function Sl(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=Sl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.id===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"id"},message:"must have required property 'id'"};i===null?i=[p]:i.push(p),a++}if(n.path===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"path"},message:"must have required property 'path'"};i===null?i=[p]:i.push(p),a++}if(n.predicate===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"predicate"},message:"must have required property 'predicate'"};i===null?i=[p]:i.push(p),a++}if(n.value===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"value"},message:"must have required property 'value'"};i===null?i=[p]:i.push(p),a++}for(let p in n)if(!(p==="id"||p==="path"||p==="predicate"||p==="value")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};i===null?i=[d]:i.push(d),a++}if(n.id!==void 0){let p=n.id;if(typeof p=="string"){if(W(p)>100){let d={instancePath:e+"/id",schemaPath:"#/properties/id/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};i===null?i=[d]:i.push(d),a++}if(W(p)<1){let d={instancePath:e+"/id",schemaPath:"#/properties/id/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[d]:i.push(d),a++}if(!Kh.test(p)){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]+)*$"'};i===null?i=[d]:i.push(d),a++}}else{let d={instancePath:e+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[d]:i.push(d),a++}}if(n.path!==void 0){let p=n.path;if(typeof p=="string"){if(W(p)>1024){let d={instancePath:e+"/path",schemaPath:"#/properties/path/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};i===null?i=[d]:i.push(d),a++}if(W(p)<1){let d={instancePath:e+"/path",schemaPath:"#/properties/path/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[d]:i.push(d),a++}}else{let d={instancePath:e+"/path",schemaPath:"#/properties/path/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[d]:i.push(d),a++}}if(n.predicate!==void 0&&n.predicate!=="contains"){let p={instancePath:e+"/predicate",schemaPath:"#/properties/predicate/const",keyword:"const",params:{allowedValue:"contains"},message:"must be equal to constant"};i===null?i=[p]:i.push(p),a++}if(n.value!==void 0){let p=n.value,d=a,u=!1,f=a;if(typeof p!="string"){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/0/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[b]:i.push(b),a++}var l=f===a;u=u||l;let h=a;if(!(typeof p=="number"&&isFinite(p))){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/1/type",keyword:"type",params:{type:"number"},message:"must be number"};i===null?i=[b]:i.push(b),a++}var l=h===a;u=u||l;let m=a;if(typeof p!="boolean"){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/2/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};i===null?i=[b]:i.push(b),a++}var l=m===a;u=u||l;let w=a;if(p!==null){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/3/type",keyword:"type",params:{type:"null"},message:"must be null"};i===null?i=[b]:i.push(b),a++}var l=w===a;if(u=u||l,u)a=d,i!==null&&(d?i.length=d:i=null);else{let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};i===null?i=[b]:i.push(b),a++}}}else{let p={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[p]:i.push(p),a++}return Sl.errors=i,a===0}function xr(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=xr.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.push(l),a++}for(let l in n)if(!(l==="id"||l==="version"||l==="digest")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};i===null?i=[p]:i.push(p),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(W(l)>100){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};i===null?i=[p]:i.push(p),a++}if(W(l)<1){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[p]:i.push(p),a++}if(!Rl.test(l)){let p={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]+)*$"'};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}if(n.version!==void 0){let l=n.version;if(typeof l=="string"){if(!Wh.test(l)){let p={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-]+)*)?$"'};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/version",schemaPath:"#/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}if(n.digest!==void 0){let l=n.digest;if(typeof l=="string"){if(!ml.test(l)){let p={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}$"'};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/digest",schemaPath:"#/properties/digest/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[l]:i.push(l),a++}return xr.errors=i,a===0}function Pl(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=Pl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.push(l),a++}for(let l in n)if(!(l==="capabilities"||l==="access"||l==="collection_kind"||l==="files"||l==="configuration"||l==="contracts")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};i===null?i=[p]:i.push(p),a++}if(n.capabilities!==void 0&&(Al(n.capabilities,{instancePath:e+"/capabilities",parentData:n,parentDataProperty:"capabilities",rootData:o,dynamicAnchors:s})||(i=i===null?Al.errors:i.concat(Al.errors),a=i.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"};i===null?i=[l]:i.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"};i===null?i=[l]:i.push(l),a++}if(n.files!==void 0&&(kl(n.files,{instancePath:e+"/files",parentData:n,parentDataProperty:"files",rootData:o,dynamicAnchors:s})||(i=i===null?kl.errors:i.concat(kl.errors),a=i.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"};i===null?i=[d]:i.push(d),a++}let p=l.length;for(let d=0;d<p;d++)Sl(l[d],{instancePath:e+"/configuration/"+d,parentData:l,parentDataProperty:d,rootData:o,dynamicAnchors:s})||(i=i===null?Sl.errors:i.concat(Sl.errors),a=i.length)}else{let p={instancePath:e+"/configuration",schemaPath:"#/properties/configuration/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[p]:i.push(p),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"};i===null?i=[f]:i.push(f),a++}let p=l.length;for(let f=0;f<p;f++)xr(l[f],{instancePath:e+"/contracts/"+f,parentData:l,parentDataProperty:f,rootData:o,dynamicAnchors:s})||(i=i===null?xr.errors:i.concat(xr.errors),a=i.length);let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(or(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)"};i===null?i=[f]:i.push(f),a++;break e}}}else{let p={instancePath:e+"/contracts",schemaPath:"#/properties/contracts/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[p]:i.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[l]:i.push(l),a++}return Pl.errors=i,a===0}function xl(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=xl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0),n&&typeof n=="object"&&!Array.isArray(n)){if(n.requirement===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"requirement"},message:"must have required property 'requirement'"};i===null?i=[p]:i.push(p),a++}if(n.operation===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"operation"},message:"must have required property 'operation'"};i===null?i=[p]:i.push(p),a++}if(n.path===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"path"},message:"must have required property 'path'"};i===null?i=[p]:i.push(p),a++}if(n.value===void 0){let p={instancePath:e,schemaPath:"#/required",keyword:"required",params:{missingProperty:"value"},message:"must have required property 'value'"};i===null?i=[p]:i.push(p),a++}for(let p in n)if(!(p==="requirement"||p==="operation"||p==="path"||p==="value")){let d={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};i===null?i=[d]:i.push(d),a++}if(n.requirement!==void 0){let p=n.requirement;if(typeof p=="string"){if(W(p)>100){let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};i===null?i=[d]:i.push(d),a++}if(W(p)<1){let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[d]:i.push(d),a++}if(!Kh.test(p)){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]+)*$"'};i===null?i=[d]:i.push(d),a++}}else{let d={instancePath:e+"/requirement",schemaPath:"#/properties/requirement/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[d]:i.push(d),a++}}if(n.operation!==void 0&&n.operation!=="set_add"){let p={instancePath:e+"/operation",schemaPath:"#/properties/operation/const",keyword:"const",params:{allowedValue:"set_add"},message:"must be equal to constant"};i===null?i=[p]:i.push(p),a++}if(n.path!==void 0){let p=n.path;if(typeof p=="string"){if(W(p)>1024){let d={instancePath:e+"/path",schemaPath:"#/properties/path/maxLength",keyword:"maxLength",params:{limit:1024},message:"must NOT have more than 1024 characters"};i===null?i=[d]:i.push(d),a++}if(W(p)<1){let d={instancePath:e+"/path",schemaPath:"#/properties/path/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[d]:i.push(d),a++}}else{let d={instancePath:e+"/path",schemaPath:"#/properties/path/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[d]:i.push(d),a++}}if(n.value!==void 0){let p=n.value,d=a,u=!1,f=a;if(typeof p!="string"){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/0/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[b]:i.push(b),a++}var l=f===a;u=u||l;let h=a;if(!(typeof p=="number"&&isFinite(p))){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/1/type",keyword:"type",params:{type:"number"},message:"must be number"};i===null?i=[b]:i.push(b),a++}var l=h===a;u=u||l;let m=a;if(typeof p!="boolean"){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/2/type",keyword:"type",params:{type:"boolean"},message:"must be boolean"};i===null?i=[b]:i.push(b),a++}var l=m===a;u=u||l;let w=a;if(p!==null){let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf/3/type",keyword:"type",params:{type:"null"},message:"must be null"};i===null?i=[b]:i.push(b),a++}var l=w===a;if(u=u||l,u)a=d,i!==null&&(d?i.length=d:i=null);else{let b={instancePath:e+"/value",schemaPath:"#/$defs/configurationValue/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};i===null?i=[b]:i.push(b),a++}}}else{let p={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[p]:i.push(p),a++}return xl.errors=i,a===0}function Cl(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=Cl.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.push(l),a++}for(let l in n)if(!(l==="kind"||l==="id"||l==="version"||l==="name"||l==="description"||l==="resources"||FC.test(l))){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};i===null?i=[p]:i.push(p),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"};i===null?i=[l]:i.push(l),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(W(l)>100){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};i===null?i=[p]:i.push(p),a++}if(W(l)<1){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[p]:i.push(p),a++}if(!Rl.test(l)){let p={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]+)*$"'};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}if(n.version!==void 0){let l=n.version;if(typeof l=="string"){if(!Wh.test(l)){let p={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-]+)*)?$"'};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/version",schemaPath:"#/$defs/contract/properties/version/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}if(n.name!==void 0){let l=n.name;if(typeof l=="string"){if(W(l)>100){let p={instancePath:e+"/name",schemaPath:"#/properties/name/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};i===null?i=[p]:i.push(p),a++}if(W(l)<1){let p={instancePath:e+"/name",schemaPath:"#/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}if(n.description!==void 0){let l=n.description;if(typeof l=="string"){if(W(l)>500){let p={instancePath:e+"/description",schemaPath:"#/properties/description/maxLength",keyword:"maxLength",params:{limit:500},message:"must NOT have more than 500 characters"};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/description",schemaPath:"#/properties/description/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),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"};i===null?i=[d]:i.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"};i===null?i=[d]:i.push(d),a++}let p=l.length;for(let d=0;d<p;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'"};i===null?i=[f]:i.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'"};i===null?i=[f]:i.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'"};i===null?i=[f]:i.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'"};i===null?i=[f]:i.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'"};i===null?i=[f]:i.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"};i===null?i=[h]:i.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:NC.properties.kind.enum},message:"must be equal to one of the allowed values"};i===null?i=[h]:i.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:NC.properties.mode.enum},message:"must be equal to one of the allowed values"};i===null?i=[h]:i.push(h),a++}}if(u.source!==void 0){let f=u.source;if(typeof f=="string"){if(W(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"};i===null?i=[h]:i.push(h),a++}if(W(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"};i===null?i=[h]:i.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"};i===null?i=[h]:i.push(h),a++}}if(u.target!==void 0){let f=u.target;if(typeof f=="string"){if(W(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"};i===null?i=[h]:i.push(h),a++}if(W(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"};i===null?i=[h]:i.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"};i===null?i=[h]:i.push(h),a++}}if(u.digest!==void 0){let f=u.digest;if(typeof f=="string"){if(!ml.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}$"'};i===null?i=[h]:i.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"};i===null?i=[h]:i.push(h),a++}}}else{let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackManifestResource/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[f]:i.push(f),a++}}}else{let p={instancePath:e+"/resources",schemaPath:"#/properties/resources/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[p]:i.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[l]:i.push(l),a++}return Cl.errors=i,a===0}function Il(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=Il.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.push(l),a++}for(let l in n)if(!(l==="manifest"||l==="resources"||l==="provides")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};i===null?i=[p]:i.push(p),a++}if(n.manifest!==void 0&&(Cl(n.manifest,{instancePath:e+"/manifest",parentData:n,parentDataProperty:"manifest",rootData:o,dynamicAnchors:s})||(i=i===null?Cl.errors:i.concat(Cl.errors),a=i.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"};i===null?i=[d]:i.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"};i===null?i=[d]:i.push(d),a++}let p=l.length;for(let d=0;d<p;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'"};i===null?i=[f]:i.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'"};i===null?i=[f]:i.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"};i===null?i=[h]:i.push(h),a++}if(u.source!==void 0){let f=u.source;if(typeof f=="string"){if(W(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"};i===null?i=[h]:i.push(h),a++}if(W(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"};i===null?i=[h]:i.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"};i===null?i=[h]:i.push(h),a++}}if(u.document!==void 0){let f=u.document;if(typeof f=="string"){if(W(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"};i===null?i=[h]:i.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"};i===null?i=[h]:i.push(h),a++}}}else{let f={instancePath:e+"/resources/"+d,schemaPath:"#/$defs/typePackSourceResource/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[f]:i.push(f),a++}}}else{let p={instancePath:e+"/resources",schemaPath:"#/properties/resources/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[p]:i.push(p),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"};i===null?i=[f]:i.push(f),a++}let p=l.length;for(let f=0;f<p;f++)xr(l[f],{instancePath:e+"/provides/"+f,parentData:l,parentDataProperty:f,rootData:o,dynamicAnchors:s})||(i=i===null?xr.errors:i.concat(xr.errors),a=i.length);let d=l.length,u;if(d>1){e:for(;d--;)for(u=d;u--;)if(or(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)"};i===null?i=[f]:i.push(f),a++;break e}}}else{let p={instancePath:e+"/provides",schemaPath:"#/properties/provides/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[p]:i.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[l]:i.push(l),a++}return Il.errors=i,a===0}function Ol(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=Ol.evaluated;if(c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.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'"};i===null?i=[l]:i.push(l),a++}for(let l in n)if(!(l==="id"||l==="event"||l==="if"||l==="debounce"||l==="minimum_interval"||l==="presentation")){let p={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:l},message:"must NOT have additional properties"};i===null?i=[p]:i.push(p),a++}if(n.id!==void 0){let l=n.id;if(typeof l=="string"){if(W(l)>100){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};i===null?i=[p]:i.push(p),a++}if(W(l)<1){let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[p]:i.push(p),a++}if(!Rl.test(l)){let p={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]+)*$"'};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/id",schemaPath:"#/$defs/identifier/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}if(n.event!==void 0&&(xr(n.event,{instancePath:e+"/event",parentData:n,parentDataProperty:"event",rootData:o,dynamicAnchors:s})||(i=i===null?xr.errors:i.concat(xr.errors),a=i.length)),n.if!==void 0){let l=n.if;if(l&&typeof l=="object"&&!Array.isArray(l)){if(l.$expr===void 0){let p={instancePath:e+"/if",schemaPath:"#/properties/if/required",keyword:"required",params:{missingProperty:"$expr"},message:"must have required property '$expr'"};i===null?i=[p]:i.push(p),a++}for(let p in l)if(p!=="$expr"){let d={instancePath:e+"/if",schemaPath:"#/properties/if/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};i===null?i=[d]:i.push(d),a++}if(l.$expr!==void 0){let p=l.$expr;if(typeof p=="string"){if(W(p)>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"};i===null?i=[d]:i.push(d),a++}if(W(p)<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"};i===null?i=[d]:i.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"};i===null?i=[d]:i.push(d),a++}}}else{let p={instancePath:e+"/if",schemaPath:"#/properties/if/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[p]:i.push(p),a++}}if(n.debounce!==void 0){let l=n.debounce;if(typeof l=="string"){if(!Bh.test(l)){let p={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)$"'};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/debounce",schemaPath:"#/$defs/duration/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}if(n.minimum_interval!==void 0){let l=n.minimum_interval;if(typeof l=="string"){if(!Bh.test(l)){let p={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)$"'};i===null?i=[p]:i.push(p),a++}}else{let p={instancePath:e+"/minimum_interval",schemaPath:"#/$defs/duration/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[p]:i.push(p),a++}}if(n.presentation!==void 0){let l=n.presentation;if(l&&typeof l=="object"&&!Array.isArray(l)){if(l.title===void 0){let p={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/required",keyword:"required",params:{missingProperty:"title"},message:"must have required property 'title'"};i===null?i=[p]:i.push(p),a++}for(let p in l)if(!(p==="title"||p==="body"||p==="tag")){let d={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:p},message:"must NOT have additional properties"};i===null?i=[d]:i.push(d),a++}if(l.title!==void 0){let p=l.title;if(typeof p=="string"){if(W(p)>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"};i===null?i=[d]:i.push(d),a++}if(W(p)<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"};i===null?i=[d]:i.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"};i===null?i=[d]:i.push(d),a++}}if(l.body!==void 0){let p=l.body;if(typeof p=="string"){if(W(p)>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"};i===null?i=[d]:i.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"};i===null?i=[d]:i.push(d),a++}}if(l.tag!==void 0){let p=l.tag;if(typeof p=="string"){if(W(p)>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"};i===null?i=[d]:i.push(d),a++}if(W(p)<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"};i===null?i=[d]:i.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"};i===null?i=[d]:i.push(d),a++}}}else{let p={instancePath:e+"/presentation",schemaPath:"#/properties/presentation/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[p]:i.push(p),a++}}}else{let l={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[l]:i.push(l),a++}return Ol.errors=i,a===0}function Fh(n,{instancePath:e="",parentData:t,parentDataProperty:r,rootData:o=n,dynamicAnchors:s={}}={}){let i=null,a=0,c=Fh.evaluated;c.dynamicProps&&(c.props=void 0),c.dynamicItems&&(c.items=void 0);let l=a,p=!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'"};i===null?i=[g]:i.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'"};i===null?i=[g]:i.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"};i===null?i=[g]:i.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"};i===null?i=[g]:i.push(g),a++}}var m=u===a;if(m){p=!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'"};i===null?i=[g]:i.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"};i===null?i=[g]:i.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"};i===null?i=[g]:i.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"};i===null?i=[g]:i.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"};i===null?i=[g]:i.push(g),a++}}var m=h===a;if(m&&p?(p=!1,d=[d,1]):m&&(p=!0,d=1,f!==!0&&(f=f||{},f.distribution=!0,f.platform=!0,f.homepage=!0,f.redirect_uris=!0)),p)a=l,i!==null&&(l?i.length=l:i=null);else{let g={instancePath:e,schemaPath:"#/oneOf",keyword:"oneOf",params:{passingSchemas:d},message:"must match exactly one schema in oneOf"};i===null?i=[g]:i.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'"};i===null?i=[g]:i.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'"};i===null?i=[g]:i.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'"};i===null?i=[g]:i.push(g),a++}for(let g in n)if(!zC.call(jC.properties,g)){let y={instancePath:e,schemaPath:"#/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:g},message:"must NOT have additional properties"};i===null?i=[y]:i.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"};i===null?i=[g]:i.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:jC.properties.distribution.enum},message:"must be equal to one of the allowed values"};i===null?i=[y]:i.push(y),a++}}if(n.id!==void 0){let g=n.id;if(typeof g=="string"){if(W(g)>150){let y={instancePath:e+"/id",schemaPath:"#/properties/id/maxLength",keyword:"maxLength",params:{limit:150},message:"must NOT have more than 150 characters"};i===null?i=[y]:i.push(y),a++}if(W(g)<5){let y={instancePath:e+"/id",schemaPath:"#/properties/id/minLength",keyword:"minLength",params:{limit:5},message:"must NOT have fewer than 5 characters"};i===null?i=[y]:i.push(y),a++}if(!$C.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,}$"'};i===null?i=[y]:i.push(y),a++}}else{let y={instancePath:e+"/id",schemaPath:"#/properties/id/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[y]:i.push(y),a++}}if(n.name!==void 0){let g=n.name;if(typeof g=="string"){if(W(g)>100){let y={instancePath:e+"/name",schemaPath:"#/properties/name/maxLength",keyword:"maxLength",params:{limit:100},message:"must NOT have more than 100 characters"};i===null?i=[y]:i.push(y),a++}if(W(g)<1){let y={instancePath:e+"/name",schemaPath:"#/properties/name/minLength",keyword:"minLength",params:{limit:1},message:"must NOT have fewer than 1 characters"};i===null?i=[y]:i.push(y),a++}}else{let y={instancePath:e+"/name",schemaPath:"#/properties/name/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[y]:i.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"};i===null?i=[g]:i.push(g),a++}if(n.homepage!==void 0){let g=n.homepage;if(typeof g=="string"){if(!Wo.test(g)){let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};i===null?i=[y]:i.push(y),a++}if(!Kn(g)){let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};i===null?i=[y]:i.push(y),a++}}else{let y={instancePath:e+"/homepage",schemaPath:"#/properties/homepage/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[y]:i.push(y),a++}}if(n.project_url!==void 0){let g=n.project_url;if(typeof g=="string"){if(!Wo.test(g)){let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};i===null?i=[y]:i.push(y),a++}if(!Kn(g)){let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};i===null?i=[y]:i.push(y),a++}}else{let y={instancePath:e+"/project_url",schemaPath:"#/properties/project_url/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[y]:i.push(y),a++}}if(n.icon!==void 0){let g=n.icon;if(typeof g=="string"){if(!Wo.test(g)){let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/pattern",keyword:"pattern",params:{pattern:"^https://"},message:'must match pattern "^https://"'};i===null?i=[y]:i.push(y),a++}if(!Kn(g)){let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};i===null?i=[y]:i.push(y),a++}}else{let y={instancePath:e+"/icon",schemaPath:"#/properties/icon/type",keyword:"type",params:{type:"string"},message:"must be string"};i===null?i=[y]:i.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"};i===null?i=[k]:i.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"};i===null?i=[k]:i.push(k),a++}let y=g.length;for(let k=0;k<y;k++){let S=g[k];if(typeof S=="string"){if(!Kn(S)){let x={instancePath:e+"/redirect_uris/"+k,schemaPath:"#/properties/redirect_uris/items/format",keyword:"format",params:{format:"uri"},message:'must match format "uri"'};i===null?i=[x]:i.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"};i===null?i=[x]:i.push(x),a++}}let _=g.length,v;if(_>1){let k={};for(;_--;){let S=g[_];if(typeof S=="string"){if(typeof k[S]=="number"){v=k[S];let x={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/uniqueItems",keyword:"uniqueItems",params:{i:_,j:v},message:"must NOT have duplicate items (items ## "+v+" and "+_+" are identical)"};i===null?i=[x]:i.push(x),a++;break}k[S]=_}}}}else{let y={instancePath:e+"/redirect_uris",schemaPath:"#/properties/redirect_uris/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[y]:i.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 _={instancePath:e+"/installation_origins",schemaPath:"#/properties/installation_origins/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};i===null?i=[_]:i.push(_),a++}g.lab!==void 0&&(Sr(g.lab,{instancePath:e+"/installation_origins/lab",parentData:g,parentDataProperty:"lab",rootData:o,dynamicAnchors:s})||(i=i===null?Sr.errors:i.concat(Sr.errors),a=i.length)),g.staging!==void 0&&(Sr(g.staging,{instancePath:e+"/installation_origins/staging",parentData:g,parentDataProperty:"staging",rootData:o,dynamicAnchors:s})||(i=i===null?Sr.errors:i.concat(Sr.errors),a=i.length)),g.production!==void 0&&(Sr(g.production,{instancePath:e+"/installation_origins/production",parentData:g,parentDataProperty:"production",rootData:o,dynamicAnchors:s})||(i=i===null?Sr.errors:i.concat(Sr.errors),a=i.length))}else{let y={instancePath:e+"/installation_origins",schemaPath:"#/properties/installation_origins/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[y]:i.push(y),a++}}if(n.requirements!==void 0&&(Pl(n.requirements,{instancePath:e+"/requirements",parentData:n,parentDataProperty:"requirements",rootData:o,dynamicAnchors:s})||(i=i===null?Pl.errors:i.concat(Pl.errors),a=i.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'"};i===null?i=[y]:i.push(y),a++}for(let y in g)if(!(y==="configuration"||y==="type_packs")){let _={instancePath:e+"/provisions",schemaPath:"#/properties/provisions/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};i===null?i=[_]:i.push(_),a++}if(g.configuration!==void 0){let y=g.configuration;if(Array.isArray(y)){if(y.length>50){let v={instancePath:e+"/provisions/configuration",schemaPath:"#/properties/provisions/properties/configuration/maxItems",keyword:"maxItems",params:{limit:50},message:"must NOT have more than 50 items"};i===null?i=[v]:i.push(v),a++}let _=y.length;for(let v=0;v<_;v++)xl(y[v],{instancePath:e+"/provisions/configuration/"+v,parentData:y,parentDataProperty:v,rootData:o,dynamicAnchors:s})||(i=i===null?xl.errors:i.concat(xl.errors),a=i.length)}else{let _={instancePath:e+"/provisions/configuration",schemaPath:"#/properties/provisions/properties/configuration/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[_]:i.push(_),a++}}if(g.type_packs!==void 0){let y=g.type_packs;if(Array.isArray(y)){if(y.length>20){let v={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"};i===null?i=[v]:i.push(v),a++}let _=y.length;for(let v=0;v<_;v++)Il(y[v],{instancePath:e+"/provisions/type_packs/"+v,parentData:y,parentDataProperty:v,rootData:o,dynamicAnchors:s})||(i=i===null?Il.errors:i.concat(Il.errors),a=i.length)}else{let _={instancePath:e+"/provisions/type_packs",schemaPath:"#/properties/provisions/properties/type_packs/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[_]:i.push(_),a++}}}else{let y={instancePath:e+"/provisions",schemaPath:"#/properties/provisions/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[y]:i.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'"};i===null?i=[y]:i.push(y),a++}for(let y in g)if(!(y==="criteria"||y==="native_delivery")){let _={instancePath:e+"/notifications",schemaPath:"#/properties/notifications/additionalProperties",keyword:"additionalProperties",params:{additionalProperty:y},message:"must NOT have additional properties"};i===null?i=[_]:i.push(_),a++}if(g.criteria!==void 0){let y=g.criteria;if(Array.isArray(y)){if(y.length>50){let v={instancePath:e+"/notifications/criteria",schemaPath:"#/properties/notifications/properties/criteria/maxItems",keyword:"maxItems",params:{limit:50},message:"must NOT have more than 50 items"};i===null?i=[v]:i.push(v),a++}let _=y.length;for(let v=0;v<_;v++)Ol(y[v],{instancePath:e+"/notifications/criteria/"+v,parentData:y,parentDataProperty:v,rootData:o,dynamicAnchors:s})||(i=i===null?Ol.errors:i.concat(Ol.errors),a=i.length)}else{let _={instancePath:e+"/notifications/criteria",schemaPath:"#/properties/notifications/properties/criteria/type",keyword:"type",params:{type:"array"},message:"must be array"};i===null?i=[_]:i.push(_),a++}}if(g.native_delivery!==void 0){let y=g.native_delivery,_=a,v=!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'"};i===null?i=[P]:i.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'"};i===null?i=[P]:i.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"};i===null?i=[C]:i.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"};i===null?i=[P]:i.push(P),a++}if(y.firebase_project_id!==void 0){let P=y.firebase_project_id;if(typeof P=="string"){if(W(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"};i===null?i=[C]:i.push(C),a++}if(W(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"};i===null?i=[C]:i.push(C),a++}if(!BC.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]$"'};i===null?i=[C]:i.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"};i===null?i=[C]:i.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"};i===null?i=[P]:i.push(P),a++}var b=S===a;if(b){v=!0,k=0;var w=!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'"};i===null?i=[P]:i.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'"};i===null?i=[P]:i.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"};i===null?i=[C]:i.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"};i===null?i=[P]:i.push(P),a++}if(y.url!==void 0){let P=y.url;if(typeof P=="string"){if(!Wo.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://"'};i===null?i=[C]:i.push(C),a++}if(!Kn(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"'};i===null?i=[C]:i.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"};i===null?i=[C]:i.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"};i===null?i=[P]:i.push(P),a++}var b=x===a;if(b&&v?(v=!1,k=[k,1]):b&&(v=!0,k=1,w!==!0&&(w=!0)),v)a=_,i!==null&&(_?i.length=_:i=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"};i===null?i=[P]:i.push(P),a++}}}else{let y={instancePath:e+"/notifications",schemaPath:"#/properties/notifications/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[y]:i.push(y),a++}}}else{let g={instancePath:e,schemaPath:"#/type",keyword:"type",params:{type:"object"},message:"must be object"};i===null?i=[g]:i.push(g),a++}return Fh.errors=i,a===0}var DC,EC,zC,W,$C,Wo,BC,Kn,qC,TC,or,MC,VC,Kh,Rl,Wh,ml,FC,LC,Bh,KC,jC,UC,DM,NC,WC=I(()=>{"use strict";DC=Vh,EC={$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","history.read"]},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://"}}}]}}},zC=Object.prototype.hasOwnProperty,W=(function(e){let t=e.length,r=0,o=0,s;for(;o<t;)r++,s=e.charCodeAt(o++),s>=55296&&s<=56319&&o<t&&(s=e.charCodeAt(o),(s&64512)===56320&&o++);return r}),$C=new RegExp("^[a-z][a-z0-9-]*(\\.[a-z][a-z0-9-]*){2,}$","u"),Wo=new RegExp("^https://","u"),BC=new RegExp("^[a-z][a-z0-9-]*[a-z0-9]$","u"),Kn=(()=>{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(r){return n.test(r)&&e.test(r)}})();kr.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};qC={type:"array",minItems:1,uniqueItems:!0,items:{enum:["identity","members"]}},TC={enum:["collection.read","records.create","records.edit","records.delete","views.manage","definitions.manage","background.schedule","offline.replica","history.read"]},or=(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 r,o,s;if(Array.isArray(e)){if(r=e.length,r!=t.length)return!1;for(o=r;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),r=s.length,r!==Object.keys(t).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(t,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!n(e[i],t[i]))return!1}return!0}return e!==e&&t!==t});ul.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};MC={type:"array",minItems:1,maxItems:6,uniqueItems:!0,items:{enum:["list","read","add","replace","move","delete"]}},VC=new RegExp("^(?!/)(?!\\.)(?!.*//)(?!.*\\\\)(?!.*/\\.)(?!(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*\\/(?:_contracts|_schemas|_types|_views|node_modules)(?:/|$))(?!.*/$).+$","u");fl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Kh=new RegExp("^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$","u");hl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Rl=new RegExp("^[a-z0-9]+(?:[._-][a-z0-9]+)*$","u"),Wh=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"),ml=new RegExp("^sha256:[0-9a-f]{64}$","u");Pr.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};yl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};gl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};FC=new RegExp("^x-[A-Za-z][A-Za-z0-9._:-]{0,127}$","u"),LC={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}$"}}};bl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};wl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};vl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Bh=new RegExp("^[0-9]+(ms|s|m|h|d)$","u");_l.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Vh.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};KC=Fh,jC={$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://"}}}]}}};Sr.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};UC={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"]};Al.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};DM={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"}}};kl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Sl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};xr.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Pl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};xl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};NC={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}$"}}};Cl.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Il.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Ol.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1};Fh.evaluated={props:!0,dynamicProps:!1,dynamicItems:!1}});function Pv(n,e){let t=n===1?$M:n===2?zM:void 0;if(!(!t||!Object.hasOwn(t,e)))return[...t[e]]}var zM,HC,$M,aK,xv,Hh=I(()=>{zM={"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"],"history.read":["record_history","record_version"]},HC=["assess_collection_setup","apply_collection_setup"],$M=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([])});aK=Object.freeze([1,2]),xv=Object.freeze(["application-authorization-v2-issuance"])});function GC(n,e={}){return{actions:[...new Set([...n.required,...e.includeOptional===!1?[]:n.optional??[]])],scope:structuredClone(n.scope)}}var cK,pK,Cv=I(()=>{cK=new Uint8Array([77,68,66,70]),pK=new Uint8Array([77,68,66,82])});var YC,Iv=I(()=>{YC={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_abandoned:{category:"conflict",recovery:"none"},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 VM(n,e,...[t={}]){let r=YC[n];return{problem_version:1,code:n,category:r.category,recovery:r.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 JC(n,e,...t){let r=t[0];return new Ov(VM(n,e,...t),{status:r?.status,cause:r?.cause})}var Ov,XC=I(()=>{Iv();Ov=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 Gh(n){let e=structuredClone(n);return{...e,requirements:{configuration:[],...e.requirements},provisions:{type_packs:[],configuration:[],...e.provisions},notifications:e.notifications??{criteria:[]}}}function io(n){let e=n.capabilities===void 0?1:n.capabilities?.contract_version;return e!==1&&e!==2&&El("Unsupported declared capability contract version."),e}function El(n){throw JC("invalid_application_manifest",n,{details:{issues:[{path:"/requirements/capabilities",keyword:"authorizationSelection",message:n,params:{}}]}})}function ZC(n,e){if(e.operations!==void 0&&e.capabilities!==void 0&&El("Specify operations or capabilities, not both."),e.operations!==void 0&&io(n)!==1&&El("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(r=>!t.has(r)||Pv(io(n),r)===void 0)&&El("Authorization can only include capabilities declared by the application.")}}function Rv(n,e){let{requirements:t}=n;if(ZC(t,e),io(t)===1){if(e.operations!==void 0)return[...new Set(e.operations)];if(e.capabilities===void 0)return[...QC]}let r=t.capabilities,s=[...r?.required??[],...e.capabilities??r?.optional??[]].flatMap(a=>Pv(io(t),a)??[]),i=(n.provisions?.type_packs.length??0)>0||(n.provisions?.configuration?.length??0)>0;return[...new Set([...s,...io(t)===2&&i?HC:[]])]}function Ev(n){let e=n.files;if(e)return io(n)===1?((!("actions"in e)||"required"in e||"optional"in e)&&El("Legacy file declarations must use exact files.actions."),{actions:[...e.actions],scope:structuredClone(e.scope)}):("actions"in e&&El("V2 file declarations must use required/optional file actions."),GC(e))}var QC,qv=I(()=>{Hh();Cv();XC();QC=["describe","changes","read","query"]});var e1,t1,Yh=I(()=>{e1="/settings/record_extensions",t1="yaml-document-records-v1"});var n1=I(()=>{});function YM(n,e){let t=JM(e)?e:{};if(t.dry_run===!0&&GM.has(n))return null;if(n==="file_control"){let o=typeof t.type=="string"?t.type:"";return HM.has(o)?`file_control:${o}`:null}let r=WM[n];return r==="always"?n:r==="sync_action"&&t.action==="mutate"?"sync:mutate":null}function Jh(n,e){return YM(n,e)!==null}function JM(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)}var FM,KM,WM,HM,GM,_K,AK,Xh=I(()=>{FM=["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","record_history","record_version"],KM=["list_files","stat_file","open_file_upload","open_file_download","move_file","delete_file","get_file_transfer_status","commit_file_upload","abort_file_transfer"],WM={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",record_history:"never",record_version:"never"},HM=new Set(["open_file_upload","move_file","delete_file","commit_file_upload","abort_file_transfer"]),GM=new Set(["delete","rename"]),_K=new Set(FM),AK=new Set(KM)});var r1=I(()=>{});var PK,i1=I(()=>{PK=new TextEncoder});function a1(n,e,t=[],r=2){let o={operation_transport:ld,authorization_binding:oo,semantic_capabilities:r},s=[...new Set(t)].filter(i=>i!==ld).sort((i,a)=>a-i);return s.length>0&&(o.operation_transport_recovery=s),(n.some(i=>Jh(i,{action:"mutate"}))||e?.actions.some(i=>i!=="list"&&i!=="read")===!0)&&(o.durable_mutation=1),o}function Mv(n){return o1.includes(n)}function l1(n){return s1.includes(n)}var ld,QM,o1,oo,Tv,s1,ZM,eL,IK,Qh=I(()=>{Xh();ld=3,QM=2,o1=[ld,QM],oo=5,Tv=4,s1=[oo,Tv],ZM=2,eL=1,IK={operation_transport:[...o1],authorization_binding:[...s1],semantic_capabilities:[ZM,1],durable_mutation:[eL]}});async function p1(n){let e=Zh(n),r=new Uint8Array(await crypto.subtle.digest("SHA-256",Ds([tL,Gt(e)]))).slice(0,16);return r[6]=r[6]&15|128,r[8]=r[8]&63|128,[cd(r.slice(0,4)),cd(r.slice(4,6)),cd(r.slice(6,8)),cd(r.slice(8,10)),cd(r.slice(10,16))].join("-")}function d1(n){let e=[Zh(n.installation_signing_public_key),Zh(n.grant_agreement_public_key),Zh(n.grant_signing_public_key)];if(e.some((c,l)=>e.slice(l+1).some(p=>cL(c,p))))throw new Error("Application authorization keys must be distinct.");let t=Lv(n.authorization_nonce),r=Lv(n.code_challenge),o=n.contracts,s=o.operation_transport_recovery??[],i=n.requested_operations.some(c=>Jh(c,{action:"mutate"}))||n.requested_files?.actions.some(c=>!["list","read"].includes(c))===!0;if(!l1(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)||r.byteLength!==32||![o.operation_transport,o.authorization_binding,o.semantic_capabilities,o.durable_mutation??1].every(c=>Number.isInteger(c)&&c>0)||o.authorization_binding!==n.protocol_version||!Mv(o.operation_transport)||n.protocol_version===oo&&o.operation_transport!==ld||s.some(c=>!Mv(c)||c===o.operation_transport)||new Set(s).size!==s.length||n.protocol_version===Tv&&s.length>0||s.length>0&&!i||(i?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(c=>!c||c.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.");oL(n.requested_files);let a=n.requested_operations.map(c=>Gt(new TextEncoder().encode(c)));return Ds([n.protocol_version===oo?rL:nL,Zr(n.protocol_version),Gt(em(n.application_id)),Gt(em(n.authorization_id)),Gt(new TextEncoder().encode(n.application_declaration_id)),Gt(u1(n.application_manifest_digest)),Gt(em(n.application_installation_id)),...e.map(Gt),Gt(new TextEncoder().encode(n.flow)),Gt(t),Gt(new TextEncoder().encode(n.issued_at)),Gt(new TextEncoder().encode(n.expires_at)),c1(n.redirect_uri),c1(n.state),Gt(new TextEncoder().encode(n.code_challenge)),Zr(o.operation_transport),...n.protocol_version===oo?[Zr(s.length),...s.map(Zr)]:[],Zr(o.authorization_binding),Zr(o.semantic_capabilities),iL(o.durable_mutation),Zr(a.length),...a,sL(n.requested_files),aL(n.collection_id)])}function iL(n){return n===void 0?new Uint8Array(1):Ds([new Uint8Array([1]),Zr(n)])}function oL(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 sL(n){if(n===void 0)return new Uint8Array(1);let e=n.actions.map(t=>Gt(new TextEncoder().encode(t)));return Ds([new Uint8Array([1]),Zr(e.length),...e,Gt(new TextEncoder().encode(n.scope.kind)),...n.scope.kind==="selected_folders"?[Zr(n.scope.folders.length),...n.scope.folders.map(t=>Gt(new TextEncoder().encode(t)))]:[]])}function c1(n){return n===void 0?new Uint8Array(1):Ds([new Uint8Array([1]),Gt(new TextEncoder().encode(n))])}function aL(n){return n===void 0?new Uint8Array(1):Ds([new Uint8Array([1]),Gt(em(n))])}function Zh(n){let e=Lv(n);if(e.byteLength!==65||e[0]!==4)throw new Error("Application authorization public key is invalid.");return e}function Lv(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,"="),r=Uint8Array.from(atob(t),o=>o.charCodeAt(0));if(lL(r)!==n)throw new Error("Non-canonical base64url value.");return r}function em(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 u1(e)}function u1(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 Gt(n){return Ds([Zr(n.byteLength),n])}function Zr(n){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n,!1),e}function Ds(n){let e=new Uint8Array(n.reduce((r,o)=>r+o.byteLength,0)),t=0;for(let r of n)e.set(r,t),t+=r.byteLength;return e}function lL(n){return btoa(String.fromCharCode(...n)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function cL(n,e){return n.byteLength===e.byteLength&&n.every((t,r)=>t===e[r])}function cd(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}var tL,nL,rL,f1=I(()=>{Xh();Qh();tL=new TextEncoder().encode("mdbase-connect application installation id v2\0"),nL=new TextEncoder().encode("mdbase-connect application authorization proof v4\0"),rL=new TextEncoder().encode("mdbase-connect application authorization proof v5\0")});var tm,h1=I(()=>{tm={id:"mdbase.runtime.timer.fired",version:"1.0.0",digest:"sha256:41105be7a7abf33b31ced47e1e1965242236e40ccaea286b959b0a8c591f5642"}});function y1(n,e){let t=n.protocol.slice(0,-1),r=e?.toLowerCase().split(".").reverse().join(".");return t.includes(".")&&/^[a-z][a-z0-9+.-]*$/.test(t)&&!["http","https","file","javascript","data"].includes(t)&&(!r||t===r||t.startsWith(`${r}.`))&&n.username===""&&n.password===""&&n.hostname.length>0&&n.hash===""}var pL,dL,uL,fL,hL,mL,yL,NK,gL,DK,jv,m1,pd,dd=I(()=>{Hh();n1();Yh();Iv();qv();Cv();Xh();r1();i1();Qh();Hh();f1();h1();Yh();Qh();pL="contract-setup-v1",dL="file-relay-v1",uL="protocol-usage-report-v1",fL="policy-freshness-lease-v1",hL=["application-authorization-v4","authorization-activation","encrypted-relay","policy-ack"],mL=["durable-mutation-journal-v1","durable-file-lifecycle-v1","contract-metadata-read-v1"],yL="candidate-b-activation-v1",NK=[...xv,...mL,"mutation-replay-after-credential-retirement-v1",yL],gL="application-declaration-evidence-v1",DK=[...xv,gL,...hL,fL,"application-authorization-v5",pL,dL,uL,t1],jv=1,m1="mdbase-authority-request-proof-v1",pd={version:"x-mdbase-proof-version",timestamp:"x-mdbase-proof-timestamp",nonce:"x-mdbase-proof-nonce",signature:"x-mdbase-proof-signature"}});function vL(n,e={}){return _L(n,e,!0)}function v1(n){let e=Ue(Ue(n).requirements);return e.capabilities===void 0?1:Ue(e.capabilities).contract_version}function _L(n,e,t){let r=PL(n,e.maxBytes??im);if(r)return rm([r]);let o=t?v1(n):2;if(o!==1&&o!==2)return rm([me("/requirements/capabilities/contract_version","contractVersion","must declare supported contract version 1 or 2")]);let s=Ue(n).platform==="native",i=e.allowLocal||s?LL(n,!e.allowLocal):n,a=kL(o===1?wL:bL,i);if(!a.valid)return a;let c=[...xL(n,e.allowLocal===!0),...o===1?ML(n):TL(n),...IL(n),...EL(n)];return c.length===0?{valid:!0,issues:[]}:rm(c)}function ud(n,e={}){let t=vL(n,e);if(!t.valid)throw new Nv(t.issues);return v1(n)===1?{contractVersion:1,manifest:Gh(n)}:{contractVersion:2,manifest:Gh(n)}}function AL(n){return n.map(e=>`${e.path||"/"} ${e.message}`).join("; ")}function kL(n,e){if(n(e))return{valid:!0,issues:[]};let t=(n.errors??[]).map(SL),r=t.filter(o=>o.keyword!=="oneOf");return rm(r.length>0?r:t)}function SL(n){let e=n.params;return n.keyword==="required"&&typeof e.missingProperty=="string"?{path:Dv(n.instancePath,e.missingProperty),keyword:n.keyword,message:"is required",params:e}:n.keyword==="additionalProperties"&&typeof e.additionalProperty=="string"?{path:Dv(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 Dv(n,e){let t=e.replaceAll("~","~0").replaceAll("/","~1");return`${n}/${t}`}function PL(n,e){let t=_1(n,"",new WeakSet);if(t)return t;try{let r=JSON.stringify(n),o=new TextEncoder().encode(r).byteLength;return o<=e?void 0:me("/","maxBytes",`must not exceed ${e} UTF-8 bytes`,{maxBytes:e,actualBytes:o})}catch{return me("/","json","must be serializable as JSON")}}function _1(n,e,t){if(n===null||typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n))return;if(typeof n!="object")return me(e||"/","json","must be a JSON value");if(t.has(n))return me(e||"/","json","must not contain circular references");let r=Object.getPrototypeOf(n);if(!Array.isArray(n)&&r!==Object.prototype&&r!==null)return me(e||"/","json","must be a plain JSON object");t.add(n);let o=Array.isArray(n)?n.map((s,i)=>[String(i),s]):Object.entries(n);for(let[s,i]of o){let a=_1(i,Dv(e,s),t);if(a)return a}t.delete(n)}function xL(n,e){let t=Ue(n),r=t.platform==="native";for(let[o,s]of Object.entries(Ue(t.installation_origins)))for(let[i,a]of Object.entries(Ue(s)))for(let[c,l]of a.entries()){let p=`/installation_origins/${o}/${i}/${c}`;try{if(r&&(i!=="app-runtime"||!zs(l)))return[me(p,"origin","native applications require canonical IPv4 loopback HTTP app-runtime origins")];let d=new URL(l),u=(Uv(d,o==="lab")||r&&zs(l))&&d.origin===l,f=i==="mobile"&&d.protocol==="capacitor:"&&/^[a-z0-9.-]+$/u.test(d.hostname)&&`${d.protocol}//${d.host}`===l,h=i==="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[me(p,"origin","must be an exact HTTPS, loopback HTTP, mobile capacitor or Chrome extension origin without wildcards")]}catch{return[me(p,"origin","must be an exact installation origin")]}}if(t.distribution==="portable"){if(t.project_url===void 0)return t.icon===void 0?[]:[me("/icon","origin","requires a project_url on the same origin")];try{let o=new URL(String(t.project_url));return o.protocol!=="https:"?[me("/project_url","protocol","must use HTTPS")]:t.icon!==void 0&&new URL(String(t.icon)).origin!==o.origin?[me("/icon","origin","must use the project_url origin")]:[]}catch{return[me("/","url","contains an invalid URL")]}}try{let o=new URL(String(t.homepage));if(r?!nm(String(t.homepage)):!Uv(o,e))return[me("/homepage","protocol",r?"native applications require canonical IPv4 loopback HTTP":"must use HTTPS (or loopback HTTP in local mode)")];for(let[s,i]of t.redirect_uris.entries()){if(String(i).includes("*"))return[me(`/redirect_uris/${s}`,"url","must be an exact URI without wildcards")];let a=new URL(String(i));if(r&&["http:","https:"].includes(a.protocol)&&!nm(String(i)))return[me(`/redirect_uris/${s}`,"origin","native HTTP(S) redirects require canonical IPv4 loopback HTTP")];if(a.origin===o.origin&&!Uv(a,e)&&!(r&&nm(String(i))))return[me(`/redirect_uris/${s}`,"protocol","must use HTTPS (or loopback HTTP in local mode)")];let c=CL(a,String(t.id));if(a.origin!==o.origin&&!c)return[me(`/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?[me("/icon","origin","must use the homepage origin")]:[]}catch{return[me("/","url","contains an invalid URL")]}}function CL(n,e){let t=n.protocol.slice(0,-1);return y1(n)&&(t===e||t.startsWith(`${e}.`))}function IL(n){let e=Ue(n),t=Ue(e.requirements),r=Array.isArray(t.contracts)?t.contracts:[],o=new Set(r.map(c=>{let l=Ue(c);return`${l.id}@${l.version}`})),s=Ue(e.provisions),i=Array.isArray(s.type_packs)?s.type_packs:[],a=[];for(let[c,l]of i.entries()){let p=Ue(l),d=Array.isArray(p.provides)?p.provides:[];for(let u of d){let f=Ue(u);o.has(`${f.id}@${f.version}`)||a.push(me(`/provisions/type_packs/${c}/provides`,"contractRequirement","may only contain contracts required by the application"))}a.push(...OL(p,`/provisions/type_packs/${c}`))}return a}function OL(n,e=""){let t=Ue(n),r=Ue(t.manifest),o=Array.isArray(r.resources)?r.resources.map(Ue):[],s=Array.isArray(t.resources)?t.resources.map(Ue):[],i=new Map(s.map(c=>[String(c.source),c.document]));if(i.size!==s.length||new Set(o.map(c=>String(c.source))).size!==o.length||o.length!==s.length)return[me(`${e}/resources`,"resourceSet","must match manifest source paths exactly")];let a=[];for(let[c,l]of o.entries()){let p=`${e}/manifest/resources/${c}`,d=String(l.source),u=i.get(d);if(typeof u!="string"){a.push(me(`${e}/resources`,"resourceSet",`is missing manifest source ${d}`));continue}A1(u)!==l.digest&&a.push(me(`${p}/digest`,"digest","does not match the embedded document")),l.upgrade_from!==void 0&&a.push(...RL(l,u,`${p}/upgrade_from`))}return a}function RL(n,e,t){if(n.kind!=="type"||n.mode!=="seed")return[me(t,"seedUpgrade","is only allowed for seed types")];let r=g1(e),o=Array.isArray(n.upgrade_from),s=(o?n.upgrade_from:[n.upgrade_from]).map(Ue),i=new Set,a=[];for(let[c,l]of s.entries()){let p=o?`${t}/${c}`:t,d=String(l.document);l.digest!==A1(d)?a.push(me(`${p}/digest`,"digest","does not match the baseline document")):i.has(l.digest)?a.push(me(`${p}/digest`,"uniqueBaseline","duplicates another upgrade baseline")):l.digest===n.digest&&a.push(me(`${p}/digest`,"seedUpgrade","must not be the resource's own document")),i.add(l.digest);let u=g1(d);!r||!u||u.kind!==r.kind||u.name!==r.name?a.push(me(`${p}/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(me(`${p}/version`,"seedUpgrade","must equal the version the baseline document declares"))}return a}function g1(n){let e=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(n)?.[1];if(e===void 0)return;let t=kv(e,{uniqueKeys:!0});if(!(t.errors.length>0||!ir(t.contents)))return{kind:t.get("kind"),name:t.get("name"),version:t.get("version")}}function A1(n){return`sha256:${Ta(Qe(Cb(n)))}`}function EL(n){let e=Ue(n),t=Ue(e.requirements),r=Ue(e.provisions),o=Array.isArray(t.configuration)?t.configuration:[],s=Array.isArray(r.configuration)?r.configuration:[],i=[],a=new Map;for(let[p,d]of o.entries()){let u=Ue(d),f=String(u.id),h=String(u.path),m=b1(h,u.value);m&&i.push(me(`/requirements/configuration/${p}/path`,"configurationPointer",m)),a.has(f)?i.push(me(`/requirements/configuration/${p}/id`,"uniqueRequirement",`duplicates configuration requirement ${f}`)):a.set(f,{path:h,value:u.value,index:p})}let c=new Set,l=new Set;for(let[p,d]of s.entries()){let u=Ue(d),f=String(u.requirement),h=String(u.path),m=b1(h,u.value);m&&i.push(me(`/provisions/configuration/${p}/path`,"configurationPointer",m));let w=a.get(f);if(!w){i.push(me(`/provisions/configuration/${p}/requirement`,"configurationRequirement",`references unknown configuration requirement ${f}`));continue}c.has(f)&&i.push(me(`/provisions/configuration/${p}/requirement`,"uniqueProvision",`configuration requirement ${f} may have exactly one provision`)),c.add(f),h!==w.path&&i.push(me(`/provisions/configuration/${p}/path`,"configurationRequirement",`must equal /requirements/configuration/${w.index}/path`)),JSON.stringify(u.value)!==JSON.stringify(w.value)&&i.push(me(`/provisions/configuration/${p}/value`,"configurationRequirement",`must equal /requirements/configuration/${w.index}/value`));let b=`${h}\0${JSON.stringify(u.value)}`;l.has(b)&&i.push(me(`/provisions/configuration/${p}`,"uniqueContribution","duplicates another configuration path and value contribution")),l.add(b)}for(let[p,d]of a)c.has(p)||i.push(me(`/requirements/configuration/${d.index}`,"configurationProvision",`requires one provision linked by id ${p}`));return i}function b1(n,e){if(n===e1)return qL.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 r=[];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(i=>/\p{Cc}/u.test(i)))return"contains a disallowed object-key segment";r.push(s)}return/^x-[a-z0-9][a-z0-9-]*$/u.test(r[0])?void 0:"must be inside a top-level x-* extension namespace"}function TL(n){let e=Ue(n),t=Ue(e.requirements),r=Ue(t.capabilities),o=[];t.access!=="full_collection"&&o.push(me("/requirements/access","collectionAccess","must explicitly request full_collection; legacy or omitted access is not widened"));let s=Array.isArray(r.required)?r.required.map(String):[],a=(Array.isArray(r.optional)?r.optional.map(String):[]).find(w=>s.includes(w));a&&o.push(me("/requirements/capabilities/optional","disjoint",`must not repeat required capability ${a}`));let c=Ue(t.files),l=Array.isArray(c.required)?c.required.map(String):[],d=(Array.isArray(c.optional)?c.optional.map(String):[]).find(w=>l.includes(w));d&&o.push(me("/requirements/files/optional","disjoint",`must not repeat required file action ${d}`));let u=Ue(t.people),f=Array.isArray(u.required)?u.required.map(String):[],m=(Array.isArray(u.optional)?u.optional.map(String):[]).find(w=>f.includes(w));return m&&o.push(me("/requirements/people/optional","disjoint",`must not repeat required people permission ${m}`)),o}function ML(n){let e=Ue(n),t=Ue(e.requirements),r=Ue(t.capabilities),o=[];if(t.access!=="full_collection"&&o.push(me("/requirements/access","collectionAccess","must explicitly request full_collection; legacy or omitted access is not widened")),Object.keys(r).length===0)return o;let s=Array.isArray(r.required)?r.required.map(String):[],i=Array.isArray(r.optional)?r.optional.map(String):[],a=i.find(h=>s.includes(h));a&&o.push(me("/requirements/capabilities/optional","disjoint",`must not repeat required capability ${a}`));let c=new Set([...s,...i]),l=Ue(e.provisions);c.has("definitions.type-pack.apply")&&t.access!=="full_collection"&&o.push(me("/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(me("/requirements/capabilities/required","collectionSetupCapability","must require collection.setup.apply when bundled type packs are declared"));let p=Array.isArray(l.configuration)&&l.configuration.length>0,d=p||Array.isArray(l.type_packs)&&l.type_packs.length>0;p&&!s.includes("collection.setup.apply")&&o.push(me("/requirements/capabilities/required","collectionSetupCapability","must require collection.setup.apply when configuration provisions are declared")),c.has("collection.setup.apply")&&(t.access!=="full_collection"&&o.push(me("/requirements/access","collectionSetupAccess","must be full_collection for collection.setup.apply")),d||o.push(me("/provisions","collectionSetupProvision","must declare a configuration provision or type pack for collection.setup.apply"))),c.has("notifications.background-delivery")&&!Array.isArray(Ue(e.notifications).criteria)&&o.push(me("/notifications/criteria","notificationCapability","must be declared for notifications.background-delivery"));let u=Ue(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}`;c.has(m)!==f.has(h)&&o.push(me("/requirements/capabilities","fileCapability",`${m} and requirements.files.actions.${h} must be declared together`))}return o}function LL(n,e=!1){let t=Ue(n);if(t.distribution==="portable")return n;let r={...t};for(let o of["homepage","icon"])typeof r[o]=="string"&&(r[o]=w1(r[o],e));return Array.isArray(r.redirect_uris)&&(r.redirect_uris=r.redirect_uris.map(o=>typeof o=="string"?w1(o,e):o)),r}function w1(n,e){try{let t=new URL(n);return t.protocol==="http:"&&(e?nm(n):k1(t.hostname))&&(t.protocol="https:"),t.href}catch{return n}}function zs(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 nm(n){let e=/^http:\/\/[^/?#]+/.exec(n)?.[0];return zs(e)}function Uv(n,e){return n.protocol==="https:"||e&&n.protocol==="http:"&&k1(n.hostname)}function k1(n){return n==="localhost"||n==="127.0.0.1"||n==="[::1]"||n==="::1"}function rm(n){return{valid:!1,issues:n}}function me(n,e,t,r={}){return{path:n,keyword:e,message:t,params:r}}function Ue(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:{}}var im,Nv,bL,wL,qL,fd=I(()=>{hi();fi();RC();WC();qv();Yh();dd();im=524288,Nv=class extends Error{issues;constructor(e){super(`Invalid application manifest: ${AL(e)}`),this.issues=e,this.name="AppManifestValidationError"}},bL=DC,wL=KC;qL=["md","base"]});function Ho(n){return!1}function Ze(n){try{let e=new URL(n);return e.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(e.hostname)}catch{return!1}}function zv(n){return!1}var om=I(()=>{"use strict"});function Pi(n){return!1}function Go(n){return n==="lab"||n==="staging"||n==="production"}function ql(n){return n==="lab"}function Yo(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 At=I(()=>{"use strict";om()});function kt(n){return n.protocol==="https:"||n.protocol==="http:"?n.origin:`${n.protocol}//${n.host}`}function $v(n,e){if(typeof n!="string"||n.length>512)return null;let t;try{t=new URL(n)}catch{return null}if(t.username||t.password||t.search||t.hash||!["","/"].includes(t.pathname)||kt(t)!==n)return null;switch(t.protocol){case"https:":return"web";case"http:":return e==="native"?zs(n)?"native":null:Ze(n)?"web":null;case"capacitor:":return!t.port&&/^[a-z0-9.-]{1,253}$/.test(t.hostname)?"mobile":null;case"chrome-extension:":return/^[a-p]{32}$/.test(t.host)?"extension":null;case"moz-extension:":return jL.test(t.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{let e=new URL(n.href);if(e.protocol==="blob:"){let t=kt(new URL(e.pathname));return dt(t)?t:null}return kt(e)}catch{return null}}var jL,dt,tn=I(()=>{"use strict";fd();At();jL=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;dt=n=>$v(n)!==null});function P1(n,e){let t=S1.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")&&nn(),e.supersededDeclaredId!==void 0&&e.supersededDeclaredId!==n.id&&nn(),so({...n,id:e.id,name:e.name,storage:e.supersededDeclaredId===void 0?t:{...n.storage}})}function nn(){throw A("invalid_request","invalid application declaration","application_declaration")}function Bv(n,e=new Set,t=0,r={nodes:0,chars:0}){if((++r.nodes>524288||t>64)&&nn(),typeof n=="string")return r.chars+=n.length,r.chars>524288&&nn(),n;if(n===null||typeof n=="boolean")return n;if(typeof n=="number")return Number.isFinite(n)||nn(),n;(typeof n!="object"||e.has(n)||Object.getOwnPropertySymbols(n).length)&&nn(),e.add(n);try{if(Array.isArray(n))return(n.length>524288||Object.keys(n).length!==n.length)&&nn(),Object.freeze(Array.from({length:n.length},(s,i)=>{let a=Object.getOwnPropertyDescriptor(n,String(i));return(!a||!("value"in a))&&nn(),Bv(a.value,e,t+1,r)}));Object.getPrototypeOf(n)!==Object.prototype&&Object.getPrototypeOf(n)!==null&&nn();let o=Object.create(null);for(let s of Object.keys(n)){r.chars+=s.length;let i=Object.getOwnPropertyDescriptor(n,s);(r.chars>524288||!i||!("value"in i))&&nn(),o[s]=Bv(i.value,e,t+1,r)}return Object.freeze(o)}finally{e.delete(n)}}function sm(n){return JSON.parse(JSON.stringify(n.manifest))}function so(n){let e=Bv(n);(!e||Array.isArray(e)||Object.keys(e).some(m=>!["id","name","origin","environment","manifest","storage","installationKind"].includes(m)))&&nn();let{id:t,name:r,origin:o,environment:s,manifest:i}=e;(typeof t!="string"||!t||t.length>256||!/^[a-z0-9][a-z0-9._-]*$/.test(t)||t==="00000000-0000-0000-0000-000000000000"||typeof r!="string"||!r.trim()||new TextEncoder().encode(r).length>100||/[\u0000-\u001f\u007f]/.test(r)||typeof o!="string"||typeof s!="string"||!Go(s)||!i||Array.isArray(i)||typeof i!="object")&&nn(),Pi(s)&&!Yo(o)&&nn();let a=$v(o,i.platform==="native"?"native":void 0),c=e.installationKind??(a==="mobile"?"mobile":"app-runtime");(a===null||c!=="app-runtime"&&c!=="mobile"||a==="mobile"&&c!=="mobile"||(a==="extension"||a==="native")&&c!=="app-runtime")&&nn();let l=e.storage;l!==void 0&&(!l||Array.isArray(l)||typeof l!="object"||Object.keys(l).some(m=>!["joinDatabaseName","setupDatabaseName","unsyncedDatabaseName","applicationNamespace"].includes(m)))&&nn();let p=l,d=p?.applicationNamespace??t,u=typeof d=="string"&&d!==t?`namespace.${Pw(JSON.stringify([t,d]))}`:t,f={joinDatabaseName:p?.joinDatabaseName??`mdbase.${u}.native-collection-join.v1`,setupDatabaseName:p?.setupDatabaseName??`mdbase.${u}.native-model-setup.v1`,unsyncedDatabaseName:p?.unsyncedDatabaseName??`mdbase.${u}.unsynced.v1`,applicationNamespace:d};for(let m of Object.values(f))(typeof m!="string"||!m||m.length>256||/[\u0000-\u001f\u007f]/.test(m))&&nn();new Set([f.joinDatabaseName,f.setupDatabaseName,f.unsyncedDatabaseName]).size!==3&&nn();let h=Object.freeze({id:t,name:r,origin:o,environment:s,installationKind:c,manifest:i,storage:Object.freeze(f)});return S1.set(h,Object.freeze({...p})),h}var S1,Tl=I(()=>{"use strict";Qf();tn();ie();At();S1=new WeakMap});function hd(n){if(n!==null&&typeof n=="object"){for(let e of Object.values(n))hd(e);Object.freeze(n)}return n}function Jo(n){let e=ud(sm(n),{allowLocal:!0}),t=hd(e.manifest),r=t.requirements,o=io(r),s=hd(Rv(t,{})),i=Ev(r),a=hd(a1(s,i,void 0,o)),c=r.capabilities,l=c?.contract_version===2?Object.freeze({capabilityContractVersion:2,requiredNativeCapabilities:Object.freeze([...c.required])}):null,p=c?.contract_version===2&&[...c.required,...c.optional??[]].includes("offline.replica");return Object.freeze({contractVersion:e.contractVersion,manifest:t,semanticVersion:o,operations:s,...i?{files:hd(i)}:{},contracts:a,nativeCapabilities:l,privateDeviceDeclared:p})}var am=I(()=>{"use strict";dd();fd();Tl()});function x1(n,e){if(typeof n!="string"||!n.length)throw md();let t=new URL(n),r=e&&Ze(n);if(t.origin!==n||t.username||t.password||t.protocol!=="https:"&&!r)throw md();return n}function Cr(n){let{environment:e,release:t}=n;if(!Go(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(c=>!(c instanceof Uint8Array)||c.length!==32||c.every(l=>l===0))||!(t.policyPins instanceof Uint8Array)||!t.policyPins.length||t.policyPins.length>65536)throw md();let r=Pi(e),o=x1(t.cpOrigin,r),s=x1(t.logOrigin,r),i=n.appOrigin;if(r&&![o,s,i].every(Yo)||!dt(i))throw md();let a=Object.freeze({environment:e,appOrigin:i,cpOrigin:o,logOrigin:s,assetSha256:t.assetSha256,allowLoopbackHttp:ql(e)&&new URL(i).protocol==="http:"});return C1.add(a),a}function I1(n){return!!n&&typeof n=="object"&&C1.has(n)}var C1,md,Xo=I(()=>{"use strict";tn();At();C1=new WeakSet,md=()=>new Error("app environment: explicit authenticated build context required")});function $s(){return Object.freeze({...Fv,trustedRoots:Object.freeze(NL.map(O1)),policyPins:O1(DL)})}var Fv,NL,DL,O1,lm=I(()=>{Fv={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(Fv.source);Object.freeze(Fv);NL=Object.freeze(["d9f6e481aa47ae9e0373c8994fe6edb3131d8ac3cf3cbc1be58672a8543c932d"]),DL="8281825070a2bd532b5544dfb77617d4040ca6a25820d9f6e481aa47ae9e0373c8994fe6edb3131d8ac3cf3cbc1be58672a8543c932d818350c580fb092af10eb030605bd6e478e6f158206b587b1b32ba84b3d630868fe8e5396339f0c0ed2c59324a67824c1a2028040c5070a2bd532b5544dfb77617d4040ca6a2",O1=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 Wv(n){if(!n||typeof n!="object"||Array.isArray(n))throw ao();return n}function Hv(n){return n===null||typeof n=="string"||typeof n=="boolean"||typeof n=="number"?JSON.stringify(n):Array.isArray(n)?`[${n.map(Hv).join(",")}]`:`{${Object.entries(n).filter(([,t])=>t!==void 0).sort(([t],[r])=>t<r?-1:t>r?1:0).map(([t,r])=>`${JSON.stringify(t)}:${Hv(r)}`).join(",")}}`}async function pm(n){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(Hv(n))));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}function $L(n,e){let t=[[n,e]],r=0;for(;t.length;){if(++r>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 i=Object.keys(o);if(i.length!==Object.keys(s).length)return!1;for(let a of i){if(!Object.hasOwn(s,a))return!1;t.push([o[a],s[a]])}}return!0}async function dm(n){let e=n.declaration,t=n.signal,r=n.isCurrent,o=n.fetch??globalThis.fetch,s=e.manifest,i=so(e);function a(){try{if(!t.aborted&&n.signal===t&&n.declaration===e&&n.isCurrent===r&&e.id===i.id&&e.name===i.name&&e.origin===i.origin&&e.environment===i.environment&&e.manifest===s&&r.call(n)===!0&&!t.aborted)return}catch{}throw A("cancelled","Application registration fenced","application_registration_fenced")}a();let c,l;try{c=Cr({environment:i.environment,appOrigin:i.origin,release:$s()})}catch{throw a(),A("unavailable","SDK registration environment unavailable","application_registration_unavailable")}try{l=ud(sm(i),{allowLocal:!0}).manifest}catch{throw yd()}let p=i.environment==="local"?[]:l.installation_origins?.[i.environment]?.[i.installationKind]??[];if(l.name!==i.name||l.distribution==="portable"||new URL(l.homepage).origin!==i.origin&&!p.includes(i.origin)&&!("platform"in l&&l.platform==="native"&&i.installationKind==="app-runtime"&&zs(i.origin)))throw yd();let d=JSON.stringify({manifest:l}),u=`${c.cpOrigin}/v1/apps/register`,f=`mdbase.app.registration.v1.${encodeURIComponent(c.cpOrigin)}.${encodeURIComponent(l.id)}`,h=()=>{try{return globalThis.localStorage??null}catch{return null}},m=h()?await pm(l).catch(()=>null):null;a();let w=x=>{if(m)try{h()?.setItem(f,JSON.stringify({v:1,digest:m,declaredId:i.id,...x}))}catch{}};{let x=null;try{let P=h()?.getItem(f);x=P?Wv(JSON.parse(P)):null}catch{x=null}if(x&&m&&x.v===1&&x.digest===m&&x.declaredId===i.id&&typeof x.id=="string"&&Kv.test(x.id)&&x.id!==E1&&x.name===l.name&&typeof x.manifestDigest=="string"&&/^[0-9a-f]{64}$/.test(x.manifestDigest)&&(x.supersededDeclaredId===void 0||x.supersededDeclaredId===i.id))return Object.freeze({id:x.id,name:l.name,manifestDigest:x.manifestDigest,...x.supersededDeclaredId!==void 0?{supersededDeclaredId:i.id}:{}})}if(new TextEncoder().encode(d).length>im+32||typeof o!="function")throw yd();let b=new AbortController,g=()=>b.abort(),y=setTimeout(g,15e3);y.unref?.(),t.addEventListener("abort",g,{once:!0});function _(){if(a(),b.signal.aborted)throw cm()}async function v(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(),R=new Uint8Array(8192),O=0;try{for(;;){let E=await C.read();if(_(),E.done)break;if(O+E.value.length>R.length)return null;R.set(E.value,O),O+=E.value.length}return qs(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(R.subarray(0,O))))}catch(E){if(E instanceof oe)throw E;return null}finally{C.cancel().catch(()=>{})}}async function k(x){let P=new Uint8Array(2*im+8192),C=0,R=x.headers.get("content-length");if(R!==null&&/^(0|[1-9][0-9]*)$/.test(R)&&Number(R)>P.length)throw x.body?.cancel().catch(()=>{}),ao();if(!x.body)throw ao();let O=x.body.getReader();try{for(;;){let E=await O.read();try{if(_(),E.done)break;if(C+E.value.length>P.length)throw ao();P.set(E.value,C),C+=E.value.length}finally{E.value?.fill(0)}}try{return Wv(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(P.subarray(0,C))))}catch{throw ao()}}finally{P.fill(0),O.cancel().catch(()=>{}),O.releaseLock()}}async function S(x){let P=Wv(x.application),C=P.id,R=P.manifest_digest;if(typeof C!="string"||!Kv.test(C)||C===E1)throw ao();let O=Kv.test(i.id)&&C!==i.id,E=O?yd:ao;if(O&&R!==await pm(l).catch(()=>null))throw yd();if(_(),typeof R!="string"||!/^[0-9a-f]{64}$/.test(R)||P.name!==l.name||P.canonical_identity!==`bundle:${l.id}:sha256:${R}`||P.family_identity!==`bundle:${l.id}`||P.distribution!=="web")throw E();if(!P.application_declaration)throw A("upgrade_required","Canonical registration evidence unavailable","application_registration_unsupported");let j;try{j=ud(P.application_declaration,{allowLocal:!0}).manifest}catch{throw ao()}if(!$L(l,j))throw E();return _(),Object.freeze({id:C,name:l.name,manifestDigest:R,...O?{supersededDeclaredId:i.id}:{}})}try{_();try{n.onRequest?.()}catch{}for(let x=0;x<3;x++){_();let P;try{if(P=await o(u,{method:"POST",headers:{"content-type":"application/json"},body:d,signal:b.signal,credentials:"omit",redirect:"error",cache:"default",referrerPolicy:"no-referrer"}),_(),P.redirected||P.url&&P.url!==u)throw ao();if(!P.ok){if(zL.has(P.status))throw await P.body?.cancel().catch(()=>{}),cm();let R=await v(P);throw A("forbidden","Application registration refused",R?{reason:"application_registration_refused",details:{code:R.code,paths:[...R.paths]}}:"application_registration_refused")}let C=await S(await k(P));return w(C),C}catch(C){if(P?.body?.cancel().catch(()=>{}),_(),C instanceof oe&&C.reason!=="application_registration_unknown")throw C;if(x===2)throw cm();await new Promise((R,O)=>{let E=()=>{clearTimeout(j),b.signal.removeEventListener("abort",E);try{_(),R()}catch(B){O(B)}},j=setTimeout(E,x===0?250:1e3);j.unref?.(),b.signal.addEventListener("abort",E,{once:!0}),b.signal.aborted&&E()})}}throw cm()}finally{clearTimeout(y),t.removeEventListener("abort",g),b.abort()}}var Kv,E1,zL,yd,ao,cm,um=I(()=>{"use strict";fd();fd();Xo();ie();Tl();lm();$f();Kv=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,E1="00000000-0000-0000-0000-000000000000",zL=new Set([408,429,500,502,503,504]),yd=()=>A("invalid_request","Application registration binding mismatch","application_registration_binding"),ao=()=>A("unavailable","Application registration evidence invalid","application_registration_response"),cm=()=>A("outcome_unknown","Original application registration outcome unknown","application_registration_unknown")});function hm(n){return typeof n=="string"&&WL.includes(n)}var WL,Gv=I(()=>{"use strict";WL=["joining","opening_store","connecting_log","syncing","loading_snapshot","replaying","waiting_for_key","verifying_read","checking_setup"]});function D1(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:null}function z1(n,e,t){if(!/^[A-Za-z0-9_-]+$/.test(n))return!1;try{let r=atob(n.replaceAll("-","+").replaceAll("_","/"));return r.length===e&&(t===void 0||r.charCodeAt(0)===t)&&btoa(r).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")===n}catch{return!1}}function bm(n,e){let t=D1(n),r=D1(t?.native_completion);if(!r||!Object.hasOwn(r,"version")||r.version!==1||Object.keys(r).length!==N1.length+1||N1.some(i=>!Object.hasOwn(r,i)||typeof r[i]!="string"))throw jl();let o=r;for(let i of["account_id","authorization_request_id","application_id","application_installation_id","collection_id","grant_id"])if(!QL.test(o[i]))throw jl();if(!o.application_declaration_id||!/^[0-9a-f]{64}$/.test(o.application_manifest_digest)||!z1(o.grant_signing_public_key,65,4)||!z1(o.client_noise_public_key,32))throw jl();try{if(!dt(o.application_origin)||kt(new URL(o.application_origin))!==o.application_origin)throw jl()}catch{throw jl()}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(([i,a])=>o[i]!==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 jl();return Object.freeze({...o})}var N1,QL,jl,Yv=I(()=>{"use strict";tn();ie();N1=["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"],QL=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,jl=()=>A("unauthenticated","native completion does not match the original approved preparation")});function Jv(n,e,t,r,o,s){return bm({native_completion:n,collection_id:e.collectionId,grant_id:n?.grant_id,application_origin:o},{accountId:t,authorizationRequestId:e.authorizationRequestId,applicationId:r,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 $1=I(()=>{"use strict";Yv()});function sr(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 r=0;r<n.length;r++){let o=n.charCodeAt(r);if(o>=55296&&o<=56319){let s=n.charCodeAt(++r);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 Vs=I(()=>{"use strict"});function wm(n){let e=[n.account,n.installation,n.collection];if(e.some(t=>typeof t!="string"||!B1.test(t)))throw new it("invalid_scope");return`mdbase-app-${e.map(t=>t.toLowerCase()).join("-")}`}function Xv(n){let e=[n.account,n.installation];if(e.some(t=>typeof t!="string"||!B1.test(t)))throw new it("invalid_scope");return`mdbase-app-installation-${e.map(t=>t.toLowerCase()).join("-")}`}function vd(n,e,t){return wd(n,wm(e),t)}function _d(n,e,t){return wd(n,Xv(e),t)}function Ad(n){return typeof n=="string"&&n.length>0&&n.length<=64&&!/[^A-Za-z0-9_-]/.test(n)}function Fs(n){return typeof n=="string"&&n.length>0&&n.length<=256&&!/[\u0000-\u001f\u007f]/.test(n)}function V1(n){let e=F1({cpOrigin:n.cpOrigin,appId:n.appId});if(n.storageNamespace===void 0)return e;if(!Fs(n.storageNamespace))throw new it("invalid_scope");return`mdbase-app-sign-in-namespace-v1-${JSON.stringify([n.cpOrigin,n.appId,n.storageNamespace])}`}function F1(n){let e=new URL(n.cpOrigin);if(e.origin!==n.cpOrigin||e.username||e.password||!["https:","http:"].includes(e.protocol)||!Ad(n.appId))throw new it("invalid_scope");if(n.owner===void 0)return`mdbase-app-sign-in-v1-${n.appId}-${n.cpOrigin}`;if(!Fs(n.owner))throw new it("invalid_scope");return`mdbase-app-sign-in-v2-${JSON.stringify([n.cpOrigin,n.owner,n.appId])}`}function K1(n,e,t){if(e.storageNamespace!==void 0&&(!Fs(e.owner)||e.owner.startsWith("bundle:")))throw new it("invalid_scope");let r=F1(e),o=V1(e);return e.owner===void 0?wd(n,o,t):(async()=>{let s=await wd(n,o,t);try{let i=await wd(n,r,t);return{release:async()=>{await i.release(),await s.release()}}}catch(i){throw await s.release(),i}})()}function W1(n,e,t){try{return n.request(V1(e),{mode:"shared",signal:t},async()=>{})}catch(r){return Promise.reject(r)}}function wd(n,e,t){if(!n)return Promise.reject(new it("unavailable"));if(t?.aborted)return Promise.reject(new it("aborted"));let r,o=new Promise(d=>{r=d}),s,i,a=new Promise((d,u)=>{s=d,i=u}),c=!1,l=()=>{c=!0,i(new it("aborted"))};t?.addEventListener("abort",l,{once:!0});let p=Promise.resolve().then(()=>n.request(e,{mode:"exclusive",ifAvailable:!0},async d=>{if(t?.removeEventListener("abort",l),c||t?.aborted){i(new it("aborted"));return}if(!d){i(new it("busy"));return}s({release:()=>(r(),p)}),await o}));return p.catch(()=>{t?.removeEventListener("abort",l),i(new it("unavailable"))}),a}async function H1(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,r=Object.freeze({account:n.scope.account,installation:n.scope.installation,collection:n.scope.collection});wm(r);let o=await _d(n.locks,r,t),s;try{s=await vd(n.locks,r,t)}catch(h){throw await o.release(),h}let i={release:async()=>{await s.release(),await o.release()}},a;try{if(t?.aborted)throw new it("aborted");a=n.create(r)}catch{throw await i.release(),new it(t?.aborted?"aborted":"initialization_failed")}let c,l=Object.freeze({scope:Object.freeze({account:r.account,installation:r.installation}),isCurrent:()=>!c&&!t?.aborted}),p,d=new Promise((h,m)=>{p=()=>m(new it("aborted"))}),u=()=>c??=(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 it("shutdown_failed")}await i.release()})(),f=()=>{p(),u().catch(()=>{})};t?.addEventListener("abort",f,{once:!0});try{if(t?.aborted)throw new it("aborted");if(await Promise.race([Promise.resolve().then(()=>n.initialize(a,t,r,l)),d]),t?.aborted||c)throw new it("aborted");return{worker:a,scope:r,close:u}}catch{throw await u(),new it(t?.aborted?"aborted":"initialization_failed")}}var it,B1,Qo=I(()=>{"use strict";it=class extends Error{constructor(t){super(`app replica owner: ${t}`);this.reason=t;this.name="AppReplicaOwnerError"}reason},B1=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i});function J1(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 lt();return n}function G1(n){if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!=="encrypted,key,revision,version")throw lt();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>Y1+28)throw lt();return{version:1,revision:e.revision,key:J1(e.key),encrypted:new Uint8Array(e.encrypted)}}var Ul,vm,Y1,kd,lt,ZL,_m,X1=I(()=>{"use strict";At();tn();Qo();Ul="installation-sign-in",vm="original",Y1=128*1024,kd=class extends Error{constructor(t){super(`app installation storage ${t}; preserve storage and reopen`);this.reason=t}reason},lt=(n="unavailable")=>new kd(n),ZL=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]);_m=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 r=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}),o=null,s=null,i=null;try{if(!dt(r.origin))throw lt();{let l=r.cpOrigin,p=new URL(l),d=r.allowLoopbackHttp&&Ze(l);if(p.origin!==l||p.username||p.password||p.protocol!=="https:"&&!d)throw lt()}if(r.owner!==void 0&&!Fs(r.owner)||!["fresh","existing","open"].includes(r.mode)||!Ad(r.appId)||r.signal.aborted||Rt()!==r.origin||!globalThis.indexedDB||!globalThis.crypto?.subtle||typeof CryptoKey!="function")throw lt();let a=await K1(r.locks,r,r.signal);if(o=new n(r,a),o.check(),r.mode!=="existing"){s=t(),o.check(),o.bound(s);let l=J1(await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]));o.check(),i={version:1,revision:0,key:l,encrypted:await o.encrypt(l,0,s)},s.fill(0),s=null}o.db=await o.openDatabase(i),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 c={store:o,plaintext:s};return s=null,c}catch(a){throw await o?.close(),lt(a instanceof it&&a.reason==="busy"?"busy":"unavailable")}finally{s?.fill(0),i?.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 lt()}bound(e){if(!(e instanceof Uint8Array)||!e.length||e.length>Y1)throw lt()}aad(e){return new TextEncoder().encode(`${this.namespace}:${e}`)}async encrypt(e,t,r){this.check(),this.bound(r);let o=crypto.getRandomValues(new Uint8Array(12)),s=this.aad(t),i=new Uint8Array(r),a=null;try{a=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:o,additionalData:s},e,i)),this.check();let c=new Uint8Array(12+a.length);return c.set(o),c.set(a,12),c}finally{i.fill(0),a?.fill(0),o.fill(0),s.fill(0)}}async decrypt(e){this.check();let t=this.aad(e.revision),r=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:r,additionalData:t},e.key,o));try{return this.check(),this.bound(s),s}catch{throw s.fill(0),lt()}}finally{r.fill(0),o.fill(0),t.fill(0)}}openDatabase(e){return new Promise((t,r)=>{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}`,i=indexedDB.open(s,1),a=!1,c=!1,l=()=>{a=!0;try{i.transaction?.abort()}catch{}r(lt())},p=()=>this.options.signal.removeEventListener("abort",l);this.options.signal.addEventListener("abort",l,{once:!0}),i.onblocked=l,i.onupgradeneeded=()=>{try{if(this.check(),a||!e||i.result.objectStoreNames.length)throw lt();i.result.createObjectStore(Ul).add(e,vm),c=!0}catch{i.transaction?.abort()}},i.onerror=()=>{p(),r(lt())},i.onsuccess=()=>{p();try{if(this.check(),a||this.options.mode==="fresh"&&!c||i.result.objectStoreNames.length!==1||!i.result.objectStoreNames.contains(Ul))throw lt();t(i.result)}catch{i.result.close(),r(lt())}}})}readRecord(){return new Promise((e,t)=>{if(this.check(),!this.db)throw lt();let r=this.db.transaction(Ul,"readonly",{durability:"strict"}),o=null,s=()=>{try{r.abort()}catch{}},i=()=>this.options.signal.removeEventListener("abort",s);this.options.signal.addEventListener("abort",s,{once:!0}),r.onerror=r.onabort=()=>{i(),o?.encrypted.fill(0),t(lt())},r.oncomplete=()=>{i();try{if(this.check(),!o)throw lt();e(o)}catch{o?.encrypted.fill(0),t(lt())}};let a=r.objectStore(Ul).get(vm);a.onsuccess=()=>{try{this.check(),o=G1(a.result)}catch{s()}}})}async commit(e){let t=null;try{if(this.check(),!this.record||this.record.revision>=Number.MAX_SAFE_INTEGER)throw lt();let r=this.record;t={version:1,revision:r.revision+1,key:r.key,encrypted:await this.encrypt(r.key,r.revision+1,e)},this.check(),await new Promise((o,s)=>{if(this.check(),!this.db)throw lt();let i=this.db.transaction(Ul,"readwrite",{durability:"strict"}),a=()=>{try{i.abort()}catch{}},c=()=>this.options.signal.removeEventListener("abort",a);this.options.signal.addEventListener("abort",a,{once:!0}),i.onerror=i.onabort=()=>{c(),s(lt())},i.oncomplete=()=>{c();try{this.check(),o()}catch{s(lt())}};let l=i.objectStore(Ul),p=l.get(vm);p.onsuccess=()=>{let d=null;try{if(this.check(),d=G1(p.result),d.revision!==r.revision||!ZL(d.encrypted,r.encrypted))throw lt();l.put(t,vm)}catch{a()}finally{d?.encrypted.fill(0)}}}),this.check(),r.encrypted.fill(0),this.record=t,t=null}catch{throw await this.close(),lt()}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 ej(n,e){if(n!==400||!e||typeof e!="object"||Array.isArray(e))return!1;let{code:t,message:r}=e;return t==="invalid_request"&&typeof r=="string"&&r.length<=512&&/unrecognized key/i.test(r)&&r.includes("requested_private_device")}function ke(n){if(typeof n!="string"||!tj.test(n)||N(n).every(e=>e===0))throw T("response");return n}function mn(n,e){if(typeof n!="string"||!e.test(n))throw T("response");return n}function Te(n,e){if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!==e.split(",").sort().join())throw T("response");return n}function nj(n){if(typeof n!="string"||n.length>320||!/^[^\s@\u0000-\u001f\u007f]+@[^\s@\u0000-\u001f\u007f]+$/.test(n))throw T("response");return n}function Nl(n,e=!1){let[t,r,o,s]=e?["accountEmail","portalConfirmed","accountProvider","accountLogin"]:["account_email","account_selection_confirmed","account_provider","account_login"];return[t,r,o,s].some(i=>Object.hasOwn(n,i))?`,${t},${r}${Object.hasOwn(n,o)||Object.hasOwn(n,s)?`,${o},${s}`:""}`:""}function Am(n,e=!1){let t=Nl(n,e);if(!t)return{};let r=e?n.accountEmail:n.account_email,o=e?n.portalConfirmed:n.account_selection_confirmed,s=e?n.accountProvider:n.account_provider,i=e?n.accountLogin:n.account_login;if(o!==!0)throw T("response");if(t.includes(e?"accountProvider":"account_provider")){if(r!==null||s!=="github"||typeof i!="string"||!i.length||new TextEncoder().encode(i).byteLength>100||/[\s\u0000-\u001f\u007f]/.test(i))throw T("response");return{accountEmail:null,portalConfirmed:!0,accountProvider:"github",accountLogin:i}}return{accountEmail:nj(r),portalConfirmed:!0}}function rj(n){let{accountEmail:e,portalConfirmed:t,accountProvider:r,accountLogin:o,...s}=n;return s}function Q1(n,e){if(n.portalConfirmed&&(e.portalConfirmed!==!0||n.accountEmail!==e.accountEmail||n.accountProvider!==e.accountProvider||n.accountLogin!==e.accountLogin))throw T("binding")}function r_(n){return Object.hasOwn(n,"timer_consent")||Object.hasOwn(n,"timer_grants")?",timer_consent,timer_grants":""}function e_(n,e,t,r,o){if(!r_(n))return;if(![!0,!1,null].includes(n.timer_consent)||!Array.isArray(n.timer_grants)||n.timer_grants.length>1e3)throw T("response");let s=n.timer_grants.map(i=>{let a=Te(i,"grant_id,collection_id,declaration_digest"),c=ke(a.collection_id);if(!t.includes(c))throw T("response");return Object.freeze({grantId:ke(a.grant_id),collectionId:c,declarationDigest:mn(a.declaration_digest,/^[0-9a-f]{64}$/)})});if(new Set(s.map(i=>i.grantId)).size!==s.length||new Set(s.map(i=>i.collectionId)).size!==s.length||(n.timer_consent===!0?!r||!o||!s.some(i=>i.collectionId===o):s.length!==0)||new Set(s.map(i=>i.declarationDigest)).size>1)throw T("response");return n.timer_consent===null?void 0:Object.freeze({requestId:e,approved:n.timer_consent===!0,grants:Object.freeze(s.filter(i=>i.collectionId===o))})}function t_(n){let e=Te(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 T("response");return Object.freeze({grantId:ke(e.grantId),kind:e.kind,targetDigest:mn(e.targetDigest,/^[0-9a-f]{64}$/),channelId:e.channelId===null?null:ke(e.channelId),pending:e.pending})}function ij(n){let e=n&&typeof n=="object"&&!Array.isArray(n)?n.collections:void 0;return Array.isArray(e)&&e.length>0&&e.every(t=>!t||typeof t!="object"||!("mode"in t))}function n_(n){if(!Array.isArray(n)||n.length>1e3)throw T("response");let e=new Set;return Object.freeze(n.map(t=>{let r=c=>t&&typeof t=="object"&&c in t?`,${c}`:"",o=Te(t,`collection_id,display_name,role${r("availability")}${r("file_actions")}${r("mode")}`),s=ke(o.collection_id);if("mode"in o&&o.mode!=="cloud_copy"&&o.mode!=="private"||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 T("response");let i=wr(o.availability),a="file_actions"in o?i_(o.file_actions):null;return e.add(s),Object.freeze({collectionId:s,displayName:o.display_name,role:o.role,...i?{availability:i}:{},...a?{fileActions:a}:{},...o.mode==="private"?{mode:"private"}:{}})}))}function i_(n,e=km,t=!0){if(!Array.isArray(n)||n.length>km.length||!t&&!n.length||new Set(n).size!==n.length||n.some(r=>!e.includes(r)))throw T("response");return Object.freeze(km.filter(r=>n.includes(r)))}function Z1(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 T("binding");return e}function eI(n,e,t){return n===e||t!==null&&n===`${e}?collection_hint=${t}`?n:null}var tt,T,Qv,Zv,ar,tj,km,Dl,Sd=I(()=>{"use strict";$1();qo();ve();At();Vs();Xo();X1();Qo();nr();tt=class extends Error{constructor(t,r){super(`app installation sign-in: ${t}`);this.reason=t;this.server=r;this.name="AppInstallationSignInError"}reason;server},T=n=>new tt(n),Qv=new WeakSet,Zv=new WeakSet;ar=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),tj=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;km=["list","read","add","replace","move","delete"];Dl=class n{constructor(e,t,r){this.store=e;this.state=t;this.options=r;this.request=r.fetch??((o,s)=>globalThis.fetch(o,s)),this.parent=r.signal,this.parent.addEventListener("abort",this.onAbort,{once:!0}),this.check()}store;state;options;closed=!1;busy=!1;nativeAcknowledged=!1;closedPairing=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})}:{}}),r=null;try{if(!["lab","staging","production"].includes(t.environment)||!Ad(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 T("binding");let o=t.environmentSelection;if(t.requestedCreateCollections!==void 0&&typeof t.requestedCreateCollections!="boolean"||t.freshRequestedCreateCollections!==void 0&&typeof t.freshRequestedCreateCollections!="boolean"||t.freshRequestedPrivateDevice!==void 0&&typeof t.freshRequestedPrivateDevice!="boolean")throw T("binding");if(t.recoveryFor!==void 0){let i=Te(t.recoveryFor,"accountId,collectionId");if(ke(i.accountId),ke(i.collectionId),!t.owner||t.requestedCreateCollections===!0||t.freshRequestedCreateCollections===!0)throw T("binding")}if(o!==void 0&&(!I1(o)||o.environment!==t.environment||o.appOrigin!==t.origin||o.cpOrigin!==t.cpOrigin||t.allowLoopbackHttp===!0&&!o.allowLoopbackHttp))throw T("binding");r=await _m.open({...t,allowLoopbackHttp:o?.allowLoopbackHttp??t.allowLoopbackHttp},()=>{let i=crypto.getRandomValues(new Uint8Array(32));try{let a=`pair_${btoa(String.fromCharCode(...i)).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,...t.freshRequestedPrivateDevice===!0?{requestedPrivateDevice:!0}:{},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{i.fill(0)}});let s=this.decode(r.plaintext,t);return new n(r.store,s,t)}catch(o){throw await r?.store.close(),o instanceof tt?o:o instanceof kd&&o.reason==="busy"?T("open_in_another_tab"):T("recovery_required")}finally{r?.plaintext.fill(0)}}static decode(e,t){let r=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=r?.version===1,i=`${o},requestedCreateCollections,collectionIds,createCollections,consentRequest`,a=s?{...Te(r,o),version:3,renewal:null,requestedCreateCollections:!1,collectionIds:[],createCollections:!1,consentRequest:null}:r?.version===2?{...Te(r,i),version:3,renewal:null}:Te(r,`${i},renewal${Object.hasOwn(r,"collectionSelection")?",collectionSelection":""}${Object.hasOwn(r,"timerConsent")?",timerConsent":""}${Object.hasOwn(r,"timerChannel")?",timerChannel":""}${Object.hasOwn(r,"owner")?",owner":""}${Object.hasOwn(r,"collectionListing")?",collectionListing":""}${Object.hasOwn(r,"collectionRecoveries")?",collectionRecoveries":""}${Object.hasOwn(r,"recoveryFor")?",recoveryFor":""}${Object.hasOwn(r,"nativeAuthorization")?",nativeAuthorization":""}${Object.hasOwn(r,"nativeSelection")?",nativeSelection":""}${Object.hasOwn(r,"nativeGrants")?",nativeGrants":""}${Object.hasOwn(r,"requestedPrivateDevice")?",requestedPrivateDevice":""}${Object.hasOwn(r,"privateDeviceCollectionIds")?",privateDeviceCollectionIds":""}${Object.hasOwn(r,"requestSent")?",requestSent":""}`);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 T("recovery_required");let c=a;if(typeof c.requestedCreateCollections!="boolean"||typeof c.createCollections!="boolean"||t.requestedCreateCollections!==void 0&&t.requestedCreateCollections!==c.requestedCreateCollections)throw T("binding");if(c.collectionIds=this.collectionIds(c.collectionIds),c.requestedPrivateDevice!==void 0&&c.requestedPrivateDevice!==!0)throw T("recovery_required");if(c.privateDeviceCollectionIds!==void 0){let l=this.collectionIds(c.privateDeviceCollectionIds);if(!l.length||!c.token||l.some(p=>!c.collectionIds.includes(p)))throw T("recovery_required");c.privateDeviceCollectionIds=l}if(c.recoveryFor!==void 0){let l=Te(c.recoveryFor,"accountId,collectionId");ke(l.accountId),ke(l.collectionId)}if(c.recoveryFor===void 0!=(t.recoveryFor===void 0)||c.recoveryFor?.accountId!==t.recoveryFor?.accountId||c.recoveryFor?.collectionId!==t.recoveryFor?.collectionId||c.recoveryFor&&(c.requestedCreateCollections||c.createCollections||c.selection&&c.selection.accountId!==c.recoveryFor.accountId||c.token&&(c.nativeSelection?c.collectionIds.length!==0||c.nativeSelection.collectionId!==c.recoveryFor.collectionId:!n.recovered(c.recoveryFor.collectionId,c.collectionIds,c.privateDeviceCollectionIds??[],c.collectionSelection))))throw T("recovery_required");if(c.consentRequest!==null){let l=Te(c.consentRequest,`requestId,secret,requestedCreateCollections,challenge,completed,addedCollectionIds,approvedCreateCollections${Object.hasOwn(c.consentRequest,"requestedPrivateDevice")?",requestedPrivateDevice":""}${Nl(c.consentRequest,!0)}`);if(l.requestedPrivateDevice!==void 0&&l.requestedPrivateDevice!==!0||(Am(l,!0),ke(l.requestId),mn(l.secret,/^pair_[A-Za-z0-9_-]{43}$/),l.requestId===c.requestId||l.secret===c.secret||typeof l.requestedCreateCollections!="boolean"||typeof l.completed!="boolean"||typeof l.approvedCreateCollections!="boolean"||l.approvedCreateCollections&&!l.requestedCreateCollections)||(l.challenge!==null&&mn(l.challenge,/^[0-9a-f]{64}$/),this.collectionIds(l.addedCollectionIds),!c.token||!c.selection||l.completed&&l.challenge===null))throw T("recovery_required")}if(c.createCollections&&!c.token||c.collectionIds.length&&!c.token)throw T("recovery_required");if(c.collectionSelection!==void 0){let l=Te(c.collectionSelection,"requestId,selectedCollectionId,createdCollectionIds");if(ke(l.requestId),!c.token||!c.collectionIds.includes(ke(l.selectedCollectionId))||this.collectionIds(l.createdCollectionIds).some(p=>!c.collectionIds.includes(p)))throw T("recovery_required")}if(ke(c.requestId),ke(c.installationId),ke(c.deviceId),mn(c.secret,/^pair_[A-Za-z0-9_-]{43}$/),c.renewal!==null){let l=Te(c.renewal,"requestId,secret");if(ke(l.requestId),mn(l.secret,/^pair_[A-Za-z0-9_-]{43}$/),l.requestId===c.requestId||l.secret===c.secret)throw T("recovery_required")}if(c.requestSent!==void 0&&c.requestSent!==c.requestId)throw T("recovery_required");if(c.timerChannel!==void 0){if(!c.token||!c.selection)throw T("recovery_required");try{c.timerChannel=t_(c.timerChannel)}catch{throw T("recovery_required")}}if(c.timerConsent!==void 0){let l=Te(c.timerConsent,"requestId,approved,grants");if(ke(l.requestId),!c.token||!c.selection||typeof l.approved!="boolean"||!Array.isArray(l.grants)||l.grants.length>1)throw T("recovery_required");let p=l.grants.map(u=>{let f=Te(u,"grantId,collectionId,declarationDigest");return{grant_id:f.grantId,collection_id:f.collectionId,declaration_digest:f.declarationDigest}}),d=c.selection.portalConfirmed===!0||c.consentRequest?.portalConfirmed===!0;c.timerConsent=e_({timer_consent:l.approved,timer_grants:p},ke(l.requestId),c.collectionIds,d,p[0]?.collection_id)}if(c.selection!==null){let l=Te(c.selection,`accountId,connectorId,challenge,approvalMode${Nl(c.selection,!0)}`);if(ke(l.accountId),ke(l.connectorId),mn(l.challenge,/^[0-9a-f]{64}$/),l.approvalMode!=="password-ak1")throw T("response");Am(l,!0)}if(c.proof!==null&&this.proof(c.proof),c.token!==null&&mn(c.token,/^idev_[A-Za-z0-9_-]{43}$/),c.confirmed&&!c.selection||c.nativeStarted&&!c.confirmed||c.proof&&!c.nativeStarted||c.token&&!c.proof||c.collectionListing!==void 0&&(!c.token||!c.confirmed||!c.selection||!c.proof||n_(c.collectionListing).some(l=>!c.collectionIds.includes(l.collectionId))))throw T("recovery_required");if(c.collectionRecoveries!==void 0){if(!c.token||!c.confirmed||!c.selection||!c.proof||!c.collectionRecoveries||typeof c.collectionRecoveries!="object"||Array.isArray(c.collectionRecoveries))throw T("recovery_required");let l=Object.entries(c.collectionRecoveries);if(l.length>1e3||l.some(([p,d])=>!(c.collectionIds.includes(ke(p))||c.nativeGrants?.some(u=>u.collection_id===p))||d!==null&&!ke(d)))throw T("recovery_required")}if(c.nativeAuthorization){let l=Te(c.nativeAuthorization,"requestId,authorizationId,applicationId,manifestDigest");if(ke(l.requestId),ke(l.authorizationId),l.applicationId!==c.appId||!c.proof||!c.confirmed)throw T("recovery_required");mn(l.manifestDigest,/^[0-9a-f]{64}$/)}if(c.nativeSelection){let l=Te(c.nativeSelection,"requestId,authorizationRequestId,collectionId");if(ke(l.requestId),ke(l.authorizationRequestId),ke(l.collectionId),!c.token||!c.nativeAuthorization||l.requestId!==c.nativeAuthorization.requestId||l.authorizationRequestId!==c.nativeAuthorization.authorizationId)throw T("recovery_required")}if(c.nativeGrants&&(!c.token||!c.selection||!Array.isArray(c.nativeGrants)||c.nativeGrants.length>1e3||(c.nativeGrants=c.nativeGrants.map(l=>Jv(l,{requestId:c.requestId,authorizationRequestId:l.authorization_request_id,collectionId:l.collection_id},c.selection.accountId,c.appId,c.origin,l.application_manifest_digest)),new Set(c.nativeGrants.map(l=>l.collection_id)).size!==c.nativeGrants.length)))throw T("recovery_required");return c}modeConsented(e){return e.mode==="private"==(this.state.privateDeviceCollectionIds?.includes(e.collectionId)===!0)}static collectionIds(e){if(!Array.isArray(e)||e.length>1e3)throw T("response");let t=e.map(ke);if(new Set(t).size!==t.length)throw T("response");return t}static proof(e){let t=Te(e,"sign_pk,kem_pk,noise_pk,sig");return{sign_pk:mn(t.sign_pk,/^[0-9a-f]{64}$/),kem_pk:mn(t.kem_pk,/^[0-9a-f]{64}$/),noise_pk:mn(t.noise_pk,/^[0-9a-f]{64}$/),sig:mn(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 T("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(r=>r.authorization_request_id===e.nativeSelection.authorizationRequestId&&r.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,...e.privateDeviceCollectionIds?.length?{privateDeviceCollectionIds:Object.freeze([...e.privateDeviceCollectionIds])}:{}})}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(),T("recovery_required")}finally{t.fill(0)}}async exclusive(e){if(this.check(),this.busy)throw T("busy");this.busy=!0;try{return await e()}finally{this.busy=!1}}async json(e,t,r,o){this.check(),this.wrongAccountRequestId=null;let s=new AbortController,i=()=>s.abort(),a=setTimeout(i,15e3);this.lifetime.signal.addEventListener("abort",i,{once:!0});let c=null,l=null,p=!1,d=!1,u=new Uint8Array(o?.get||e.endsWith("/exchange")?1024*1024:64*1024),f=0;try{if(c=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}`}:{},...r===void 0?{}:{"content-type":"application/json"}},body:r===void 0?void 0:JSON.stringify(r),credentials:"omit",redirect:"error",cache:"default",referrerPolicy:"no-referrer",signal:s.signal}),this.check(),s.signal.aborted)throw T("outcome_unknown");let h=c.headers.get("content-length");if(h!==null&&/^(0|[1-9][0-9]*)$/.test(h)&&Number(h)>u.length)throw s.abort(),T("response");if(!c.body)throw T("response");for(l=c.body.getReader();;){let{done:w,value:b}=await l.read();try{if(this.check(),s.signal.aborted)throw T("outcome_unknown");if(w){p=!0;break}if(f+b.length>u.length)throw s.abort(),T("response");u.set(b,f),f+=b.length}finally{b?.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 T("response");if(!c.ok){let w=m.error;if(!o&&c.status===404&&(e==="/v1/pairing-requests"||e===`/v1/pairing-requests/${this.state.requestId}/exchange`||e===`/v1/pairing-requests/${this.state.requestId}/attest`)&&w&&typeof w=="object"&&!Array.isArray(w)&&(w.code==="installation_pairing_expired"||w.code==="installation_pairing_denied")){let y=w.code==="installation_pairing_expired"?"expired":"refused";throw this.closedPairing={requestId:this.state.requestId,reason:y},T(y)}let b=vr(c.status,m,c.headers),g=new tt(It(b)??"refused",b);throw e==="/v1/pairing-requests"&&ej(c.status,w)&&Zv.add(g),g}return{status:c.status,value:m}}catch(h){this.check();let m=h instanceof tt?h:T(o?.get&&!s.signal.aborted&&!(h instanceof DOMException&&h.name==="AbortError")?d?"response":!c||c.ok?"unavailable":"refused":"outcome_unknown");throw c&&!c.ok&&Qv.add(m),m}finally{u.fill(0),p||(l?.cancel()??c?.body?.cancel())?.catch(()=>{}),l?.releaseLock(),clearTimeout(a),this.lifetime.signal.removeEventListener("abort",i)}}start(e={}){let t;try{t=Z1(e)}catch(r){return Promise.reject(r)}return this.exclusive(()=>this.startRequest(t))}renewExpiredPairing(){return this.exclusive(async()=>{let e=this.state;if(e.token||this.closedPairing?.requestId!==e.requestId)throw T("recovery_required");let t=crypto.getRandomValues(new Uint8Array(32));try{let r=crypto.randomUUID(),o=`pair_${btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`;if(r===e.requestId||r===e.renewal?.requestId||o===e.secret)throw T("binding");let{requestSent:s,...i}=e,a=e.selection?rj(e.selection):e.selection;return await this.save({...i,selection:a,requestId:r,secret:o,renewal:{requestId:e.requestId,secret:e.secret}}),this.closedPairing=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 T("binding");if(this.closedPairing?.requestId===t.requestId)throw T(this.closedPairing.reason);let r;try{r=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.requestedPrivateDevice===!0?{requested_private_device:!0}:{},...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}:{}})}catch(a){if(t.requestedPrivateDevice!==!0||!(a instanceof tt)||!Zv.has(a))throw a;let{requestedPrivateDevice:c,...l}=t;return await this.save(l),await this.startRequest(e)}let{status:o,value:s}=r;if(o!==200&&o!==201)throw T("response");Te(s,`pairing_id,pairing_secret,verification_uri,expires_in,installation_device,app_id,app_origin,app_name${this.recoveryTargetKeys()}`),this.assertRecoveryTarget(s);let i=eI(s.verification_uri,`${t.cpOrigin}/pair/${t.requestId}`,e);if(s.pairing_id!==t.requestId||s.pairing_secret!==t.secret||i===null||s.installation_device!==!0||s.app_id!==t.appId||s.app_origin!==t.origin||s.app_name!==this.options.appName||!Number.isSafeInteger(s.expires_in)||s.expires_in<0||s.expires_in>600)throw T("response");return this.state.requestSent!==t.requestId&&await this.save({...this.state,requestSent:t.requestId}),Object.freeze({...this.view(),verificationUri:i})}recoveryTargetKeys(){return this.state.recoveryFor?",recovery_collection_id":""}assertRecoveryTarget(e){if(this.state.recoveryFor&&ke(e.recovery_collection_id)!==this.state.recoveryFor.collectionId)throw T("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 T("response");let r={accountId:ke(e.account_id),connectorId:ke(e.connector_id),challenge:mn(e.challenge,/^[0-9a-f]{64}$/),approvalMode:"password-ak1"};if(t.selection&&(r.accountId!==t.selection.accountId||r.connectorId!==t.selection.connectorId||r.challenge!==t.selection.challenge||r.approvalMode!==t.selection.approvalMode))throw T("binding");if(Object.assign(r,Am(e)),t.selection&&Q1(t.selection,r),t.recoveryFor&&r.accountId!==t.recoveryFor.accountId)throw e.status==="account_selected"&&!t.selection&&!t.confirmed&&!t.nativeStarted&&!t.proof&&!t.token?(this.wrongAccountRequestId=t.requestId,T("recovery_account_mismatch")):T("binding");return this.wrongAccountRequestId=null,r}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(Te(t,"status"),e!==202||this.state.selection&&!this.state.renewal)throw T("response");return this.view()}let r=`status,request_id,account_id,connector_id,device_id,installation_id,kind,challenge,approval_mode,app_id,app_origin,expires_at${Nl(t)}${this.recoveryTargetKeys()}`;if(t.status==="account_selected"||t.status==="awaiting_approval"){if(Te(t,r),e!==202||t.status==="awaiting_approval"&&!this.state.proof)throw T("response");let _=this.selected(t);return JSON.stringify(_)!==JSON.stringify(this.state.selection)&&await this.save({...this.state,selection:_}),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"),i=Object.hasOwn(t,"native_selection"),a=Object.hasOwn(t,"private_device_collection_ids");if(Te(t,`${r},connector,token,registration${o?",collection_ids,create_collections":""}${a?",private_device_collection_ids":""}${s?",selected_collection_id,created_collection_ids":""}${i?",native_selection":""}${r_(t)}`),e!==200||t.status!=="paired"||!this.state.confirmed||!this.state.proof)throw T("response");let c=this.selected(t),l=Te(t.connector,"id,name"),p=Te(t.registration,"device_id,sign_pk,kem_pk,noise_pk");if(l.id!==c.connectorId||l.name!==this.options.appName||p.device_id!==this.state.deviceId||p.sign_pk!==this.state.proof.sign_pk||p.kem_pk!==this.state.proof.kem_pk||p.noise_pk!==this.state.proof.noise_pk)throw T("binding");let d=o?n.collectionIds(t.collection_ids):[],u=a?n.collectionIds(t.private_device_collection_ids):[];if(u.length&&(!o||this.state.requestedPrivateDevice!==!0||u.some(_=>d.includes(_))))throw T("response");let f=n.collectionIds([...d,...u]),h=o?t.create_collections:!1;if(typeof h!="boolean"||h&&!this.state.requestedCreateCollections)throw T("response");let m=s?this.collectionSelection(t,f,this.state.requestId):void 0,w=i?this.parseNativeSelection(t.native_selection,this.state.requestId):void 0;if(i&&(!o||s||h||f.length!==0||t.timer_consent===!0))throw T("response");if(this.state.recoveryFor&&w&&w.collectionId!==this.state.recoveryFor.collectionId||this.state.recoveryFor&&!w&&(h||!n.recovered(this.state.recoveryFor.collectionId,f,u,m)))throw T("binding");if(t.timer_consent===!0&&!m)throw T("response");let b=!m&&u.length>0,g=e_(t,this.state.requestId,f,c.portalConfirmed===!0,m?.selectedCollectionId),y=mn(t.token,/^idev_[A-Za-z0-9_-]{43}$/);return await this.save({...this.state,selection:c,token:y,collectionIds:f,createCollections:h,privateDeviceCollectionIds:u.length?u:void 0,nativeSelection:w,...w||b?{collectionSelection:void 0}:m?{collectionSelection:m}:{},...g?{timerConsent:g}:{}}),this.view()})}static recovered(e,t,r,o){return t.length!==1||t[0]!==e?!1:r.length?r.length===1&&r[0]===e&&o===void 0:o?.selectedCollectionId===e&&o.createdCollectionIds.length===0}parseNativeSelection(e,t){let r=Te(e,"authorization_request_id,collection_id"),o=this.state.nativeAuthorization;if(!o||o.requestId!==t||ke(r.authorization_request_id)!==o.authorizationId)throw T("binding");return Object.freeze({requestId:t,authorizationRequestId:o.authorizationId,collectionId:ke(r.collection_id)})}pendingNativeSelection(){return this.check(),this.state.nativeSelection??null}nativeAuthorizationContext(e){this.check(),this.owned(e);let t=this.state,r=t.consentRequest&&!t.consentRequest.completed?t.consentRequest:null,o=r?.challenge??t.selection?.challenge,s=r?r.portalConfirmed:t.selection?.portalConfirmed;if(!t.proof||!t.confirmed||!s||!o||t.token&&!r)return null;let i=r?.requestId??t.requestId,a=t.nativeAuthorization;return Object.freeze({requestId:i,accountId:t.selection.accountId,appId:t.appId,challenge:o,...a?.requestId===i?{authorizationId:a.authorizationId}:{}})}attachNativeAuthorization(e,t,r){let o=Object.freeze({...t}),s=Object.freeze({...r}),i=e.isCurrent;return this.exclusive(async()=>{this.owned(e);let a=this.nativeAuthorizationContext(e);if(!a||e.isCurrent!==i||a.requestId!==o.requestId||a.challenge!==o.challenge||a.accountId!==o.accountId||s.applicationId!==a.appId||!/^[0-9a-f]{64}$/.test(s.manifestDigest)||(ke(s.authorizationId),a.authorizationId&&a.authorizationId!==s.authorizationId))throw T("binding");await this.save({...this.state,nativeAuthorization:{...s,requestId:a.requestId}});let c=a.requestId===this.state.requestId?this.state.secret:this.state.consentRequest.secret,{status:l,value:p}=await this.json(`/v1/pairing-requests/${a.requestId}/native-authorization`,!1,{authorization_request_id:s.authorizationId},{bearer:c});if(this.owned(e),e.isCurrent!==i)throw T("fenced");if(Te(p,"request_id,authorization_request_id,account_id"),l!==200||p.request_id!==a.requestId||p.authorization_request_id!==s.authorizationId||p.account_id!==a.accountId)throw T("binding")})}completeNativeAuthorization(e,t){let r=this.consentGuard(e);return this.exclusive(async()=>{r();let o=this.state,s=o.nativeSelection,i=o.nativeAuthorization;if(!this.nativeAcknowledged||!s||!i)throw T("binding");let a=Jv(t,s,o.selection.accountId,o.appId,o.origin,i.manifestDigest);await this.save({...o,nativeGrants:[...(o.nativeGrants??[]).filter(c=>c.collection_id!==s.collectionId),a]}),r()})}abandonNativeSelection(e){let t=e.isCurrent;return this.exclusive(async()=>{this.owned(e);let r=this.state,o=r.nativeSelection;if(!o||r.nativeGrants?.some(c=>c.authorization_request_id===o.authorizationRequestId&&c.collection_id===o.collectionId))return!1;if(r.recoveryFor)throw T("recovery_required");let{nativeSelection:s,nativeAuthorization:i,...a}=r;if(await this.save(a),this.owned(e),e.isCurrent!==t)throw T("fenced");return!0})}collectionSelection(e,t,r){let o=ke(e.selected_collection_id),s=n.collectionIds(e.created_collection_ids);if(!t.includes(o)||s.some(i=>!t.includes(i)))throw T("response");return Object.freeze({requestId:r,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,...e.requestedPrivateDevice===!0?{requestedPrivateDevice:!0}:{},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 T("fenced")}}async consentWindow(e,t){try{return await t()}catch(r){let o=r instanceof tt?r.server?.code:null;if((o==="installation_pairing_denied"||o==="installation_pairing_expired")&&r instanceof tt&&r.server?.status===404){let s=this.state.consentRequest;throw s&&!s.completed&&s.requestId===e&&await this.save({...this.state,consentRequest:null}),T(o==="installation_pairing_expired"?"expired":"refused")}throw r}}startCollectionConsent(e,t=!1,r={},o=!1){let s=this.consentGuard(e),i;try{i=Z1(r)}catch(c){return Promise.reject(c)}let a=async()=>{if(s(),typeof t!="boolean"||typeof o!="boolean")throw T("binding");let c=this.state.recoveryFor;if(c&&(i!==c.collectionId||t||o&&!(this.state.requestedPrivateDevice===!0&&this.state.privateDeviceCollectionIds?.includes(c.collectionId)===!0)))throw T("binding");let l=this.state.consentRequest;if(!l||l.completed){let b=crypto.getRandomValues(new Uint8Array(32));try{let g=`pair_${btoa(String.fromCharCode(...b)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`;l={requestId:crypto.randomUUID(),secret:g,requestedCreateCollections:t,challenge:null,completed:!1,addedCollectionIds:[],approvedCreateCollections:!1,...o?{requestedPrivateDevice:!0}:{}},await this.save({...this.state,consentRequest:l}),s()}finally{b.fill(0)}}else if(l.requestedCreateCollections!==t)throw T("binding");let p=this.state,d=p.token,u=l,f;try{f=await this.consentWindow(u.requestId,()=>this.json("/v1/pairing-requests",!1,{installation:{app_id:p.appId,request_id:u.requestId,pairing_secret:u.secret,installation_id:p.installationId,device_id:p.deviceId,kind:p.kind,requested_create_collections:u.requestedCreateCollections,...u.requestedPrivateDevice===!0?{requested_private_device:!0}:{},...p.recoveryFor?{recovery_collection_id:p.recoveryFor.collectionId}:{},reconsent:!0},...i?{collection_hint:i}:{}},{bearer:d}))}catch(b){if(u.requestedPrivateDevice!==!0||!(b instanceof tt)||!Zv.has(b))throw b;s();let{requestedPrivateDevice:g,...y}=u;return await this.save({...this.state,consentRequest:y}),s(),await a()}s();let{status:h,value:m}=f;Te(m,`pairing_id,pairing_secret,verification_uri,expires_in,installation_device,app_id,app_origin,app_name${this.recoveryTargetKeys()}`),this.assertRecoveryTarget(m);let w=null;if(h!==200&&h!==201||m.pairing_id!==l.requestId||m.pairing_secret!==l.secret||(w=eI(m.verification_uri,`${p.cpOrigin}/pair/${l.requestId}`,i))===null||m.installation_device!==!0||m.app_id!==p.appId||m.app_origin!==p.origin||m.app_name!==this.options.appName||!Number.isSafeInteger(m.expires_in)||m.expires_in<0||m.expires_in>600||d!==this.state.token)throw T("response");return Object.freeze({...this.collectionConsentView(),verificationUri:w})};return this.exclusive(async()=>{let c=this.state.consentRequest,l=c!==null&&!c.completed;try{return await a()}catch(p){if(l&&this.state.consentRequest===null&&p instanceof tt&&(p.reason==="refused"||p.reason==="expired"))return await a();throw p}})}exchangeCollectionConsent(e){let t=this.consentGuard(e);return this.exclusive(async()=>{t();let r=this.state.consentRequest,o=this.state;if(!r)throw T("binding");if(r.completed)return this.collectionConsentView();let{status:s,value:i}=await this.consentWindow(r.requestId,()=>this.json(`/v1/pairing-requests/${r.requestId}/exchange`,!1,void 0,{bearer:r.secret}));t();let a=Nl(i),c=`status,request_id,account_id,connector_id,device_id,installation_id,kind,challenge,approval_mode,app_id,app_origin,expires_at${a}${this.recoveryTargetKeys()}`,l=i.status==="scope_updated",p=l&&(Object.hasOwn(i,"selected_collection_id")||Object.hasOwn(i,"created_collection_ids")),d=l&&Object.hasOwn(i,"native_selection"),u=l?Object.hasOwn(i,"added_private_device_collection_ids")?"added_private_device_collection_ids":Object.hasOwn(i,"private_device_collection_ids")?"private_device_collection_ids":null:null;if(Te(i,`${c}${l?",added_collection_ids,approved_create_collections":""}${u?`,${u}`:""}${p?",selected_collection_id,created_collection_ids":""}${d?",native_selection":""}${l?r_(i):""}`),this.assertRecoveryTarget(i),!l&&(s!==202||i.status!=="awaiting_approval")||l&&s!==200||i.request_id!==r.requestId||i.account_id!==o.selection.accountId||i.connector_id!==o.selection.connectorId||i.device_id!==o.deviceId||i.installation_id!==o.installationId||i.kind!==o.kind||i.app_id!==o.appId||i.app_origin!==o.origin||i.approval_mode!==o.selection.approvalMode||!Number.isSafeInteger(i.expires_at)||i.expires_at<0)throw T("binding");let f=Am(i);if(r.portalConfirmed&&!a)throw T("response");Q1(r,f);let h=mn(i.challenge,/^[0-9a-f]{64}$/);if(r.challenge!==null&&r.challenge!==h)throw T("binding");if(!l)return(r.challenge===null||a&&!r.portalConfirmed)&&await this.save({...o,consentRequest:{...r,...f,challenge:h}}),t(),this.collectionConsentView();let m=n.collectionIds(i.added_collection_ids),w=u?n.collectionIds(i[u]):[];if(w.length&&(r.requestedPrivateDevice!==!0||w.some(P=>m.includes(P)||o.collectionIds.includes(P)&&!o.privateDeviceCollectionIds?.includes(P)))||m.some(P=>o.privateDeviceCollectionIds?.includes(P)))throw T("response");let b=n.collectionIds([...m,...w]),g=[...new Set([...o.privateDeviceCollectionIds??[],...w])];if(typeof i.approved_create_collections!="boolean"||i.approved_create_collections&&!r.requestedCreateCollections)throw T("response");let y=n.collectionIds([...new Set([...o.collectionIds,...b])]),_=p?this.collectionSelection(i,y,r.requestId):void 0,v=d?this.parseNativeSelection(i.native_selection,r.requestId):void 0;if(d&&(p||b.length!==0||i.approved_create_collections!==!1||i.timer_consent===!0)||i.timer_consent===!0&&!_)throw T("response");let k=_?[...new Set([...b,_.selectedCollectionId])]:b,S=e_(i,r.requestId,k,f.portalConfirmed===!0,_?.selectedCollectionId),x=v||!_&&w.length>0?void 0:_??o.collectionSelection;if(o.recoveryFor&&(d||i.approved_create_collections||!n.recovered(o.recoveryFor.collectionId,y,g,x)))throw T("binding");return await this.save({...o,collectionIds:y,privateDeviceCollectionIds:g.length?g:void 0,nativeSelection:v,collectionSelection:x,...S?{timerConsent:S}:{},createCollections:o.createCollections||i.approved_create_collections,consentRequest:{...r,...f,challenge:h,completed:!0,addedCollectionIds:b,approvedCreateCollections:i.approved_create_collections}}),t(),this.collectionConsentView()})}keptCollections(){return this.state.collectionListing===void 0?null:Object.freeze(n_(this.state.collectionListing).filter(e=>this.state.collectionIds.includes(e.collectionId)&&this.modeConsented(e)).map(e=>Object.freeze({...e,fileActions:Object.freeze([])})))}cachedApprovedCollections(e){this.consentGuard(e)();try{return this.keptCollections()}catch{return null}}listApprovedCollections(e){let t=this.consentGuard(e);return this.exclusive(async()=>{t();let r,o=this.options.freshRequestedPrivateDevice===!0&&(this.state.privateDeviceCollectionIds?.length??0)>0,s="/v1/next/collections?include=file_actions",i=f=>this.json(f,!1,void 0,{bearer:this.state.token,get:!0});try{r=await i(o?`${s},mode`:s),o&&r.status===200&&ij(r.value)&&(t(),r=await i(s))}catch(f){if(t(),f instanceof tt&&f.reason==="unavailable"&&!f.server&&!Qv.has(f)&&this.state.collectionListing!==void 0)return this.keptCollections();if(f instanceof tt&&(f.server||Qv.has(f))&&this.state.collectionListing!==void 0){let h={...this.state};delete h.collectionListing,await this.save(h),t()}throw f}t();let{status:a,value:c}=r;if(Te(c,"collections"),a!==200)throw T("response");let l=Object.freeze(n_(c.collections).filter(f=>this.modeConsented(f))),p=c.collections.filter(f=>this.state.collectionIds.includes(f.collection_id)).map(f=>{let h={...f};return delete h.file_actions,h}),d={...this.state};delete d.collectionListing;let u={...d,collectionListing:p};return await this.save(new TextEncoder().encode(JSON.stringify(u)).length<=128*1024?u:d),t(),l})}collectionRecoveries(){return this.check(),Object.freeze({...this.state.collectionRecoveries})}retireCollectionScope(e,t,r=null){let o=this.consentGuard(e);return this.exclusive(async()=>{if(o(),ke(t),!(this.state.collectionIds.includes(t)||this.state.nativeGrants?.some(s=>s.collection_id===t)))throw T("binding");if(r!==null){if(ke(r),this.state.collectionRecoveries?.[t]!==r)throw T("fenced")}else if(Object.hasOwn(this.state.collectionRecoveries??{},t))return;await this.saveRecovery(t,null),o()})}freshCollectionInstallation(e,t){let r=this.consentGuard(e);return this.exclusive(async()=>{if(r(),ke(t),!Object.hasOwn(this.state.collectionRecoveries??{},t))throw T("binding");let o=this.state.collectionRecoveries[t];if(o!==null)return o;let s=crypto.randomUUID();return await this.saveRecovery(t,s),r(),s})}async saveRecovery(e,t){let r={...this.state,collectionRecoveries:{...this.state.collectionRecoveries,[e]:t}};new TextEncoder().encode(JSON.stringify(r)).length>128*1024&&delete r.collectionListing,await this.save(r)}startFileAccess(e,t,r,o){let s=this.consentGuard(e),i;try{if(ke(t),i=i_([...r],km,!1),i.length!==r.length)throw T("binding")}catch{return Promise.reject(T("binding"))}return this.exclusive(async()=>{s();let a=crypto.getRandomValues(new Uint8Array(32));try{let c=crypto.randomUUID(),l=`pair_${btoa(String.fromCharCode(...a)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}`,p=this.state,d=p.token,{status:u,value:f}=await this.json("/v1/pairing-requests",!1,{installation:{app_id:p.appId,request_id:c,pairing_secret:l,installation_id:p.installationId,device_id:p.deviceId,kind:p.kind,requested_create_collections:!1,reconsent:!0,file_access:{collection_id:t,actions:[...i],reason:o}}},{bearer:d});s(),Te(f,"pairing_id,pairing_secret,verification_uri,expires_in,installation_device,app_id,app_origin,app_name");let h=`${p.cpOrigin}/pair/${c}`;if(u!==200&&u!==201||f.pairing_id!==c||f.pairing_secret!==l||f.verification_uri!==h||f.installation_device!==!0||f.app_id!==p.appId||f.app_origin!==p.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 T("response");return Object.freeze({requestId:c,secret:l,collectionId:t,actions:i,verificationUri:h,expiresAt:Date.now()+f.expires_in*1e3})}finally{a.fill(0)}})}exchangeFileAccess(e,t){let r=this.consentGuard(e);return this.exclusive(async()=>{r();let o=this.state,{status:s,value:i}=await this.json(`/v1/pairing-requests/${t.requestId}/exchange`,!1,void 0,{bearer:t.secret});if(r(),i.status==="pending"){if(Te(i,"status"),s!==202)throw T("response");return Object.freeze({state:"pending"})}if(i.status==="account_selected"||i.status==="awaiting_approval"){if(Te(i,`status,request_id,account_id,connector_id,device_id,installation_id,kind,challenge,approval_mode,app_id,app_origin,expires_at${Nl(i)}`),s!==202||i.request_id!==t.requestId||i.account_id!==o.selection?.accountId||i.installation_id!==o.installationId||i.device_id!==o.deviceId||i.app_id!==o.appId)throw T("binding");return Object.freeze({state:"pending"})}if(i.status==="declined"){if(Te(i,"status,request_id"),s!==200||i.request_id!==t.requestId)throw T("response");return Object.freeze({state:"declined"})}if(Te(i,"status,request_id,collection_id,file_actions"),s!==200||i.status!=="file_access_updated"||i.request_id!==t.requestId||i.collection_id!==t.collectionId)throw T("response");return Object.freeze({state:"granted",actions:i_(i.file_actions,t.actions,!1)})})}renameApprovedCollection(e,t,r){let o;try{ke(t),o=sr(r)}catch{return Promise.reject(T("binding"))}let s=this.consentGuard(e);return this.exclusive(async()=>{if(s(),!this.state.collectionIds.includes(t))throw T("refused");let{status:i,value:a}=await this.json(`/v1/next/collections/${t}/name`,!1,{display_name:o},{bearer:this.state.token,patch:!0});s();let c=Te(a,"collection_id,display_name");if(i!==200||c.collection_id!==t||c.display_name!==o)throw T("response");return Object.freeze({collectionId:t,displayName:o})})}deleteApprovedCollection(e,t,r){let o;try{ke(t),o=sr(r)}catch{return Promise.reject(T("binding"))}let s=this.consentGuard(e);return this.exclusive(async()=>{if(s(),!this.state.collectionIds.includes(t))throw T("refused");let{status:i,value:a}=await this.json(`/v1/next/collections/${t}`,!1,{confirm_name:o},{bearer:this.state.token,delete:!0});s();let c=Te(a,"collection_id,deleted");if(i!==200||c.collection_id!==t||c.deleted!==!0)throw T("response");return Object.freeze({collectionId:t,deleted:!0})})}signOutInstallation(){return this.exclusive(async()=>{let e=this.state.token;if(!e)throw T("binding");try{let{status:t,value:r}=await this.json("/v1/next/installation",!1,void 0,{bearer:e,delete:!0});if(t!==200||r.ok!==!0||r.revoked!==!0||!Number.isSafeInteger(r.collections)||r.collections<0||r.fence!=="closed"&&r.fence!=="committed_with_degraded_fence")throw T("response");return"revoked"}catch(t){if(t instanceof tt&&t.server?.status===401&&t.server.code==="invalid_connector")return"already_signed_out";throw t}})}requestSent(){return this.check(),!this.state.token&&this.state.requestSent===this.state.requestId}forgetSentRequest(){return this.exclusive(async()=>{if(this.state.token||this.state.requestSent===void 0)return;let{requestSent:e,...t}=this.state;await this.save(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 T("account_confirmation_required");if(this.state.confirmed||await this.save({...this.state,confirmed:!0}),this.check(),this.state.selection!==e)throw T("binding");return this.view()})}confirmSelectedAccount(e){return this.exclusive(async()=>{if(!this.state.selection||e!==this.state.selection.accountId)throw T("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 T("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 T("fenced")}prepareOriginalDevice(e){let t=e.isCurrent,r=()=>{try{return this.check(),this.owned(e),e.isCurrent===t}catch{return!1}};return this.exclusive(async()=>{if(!r())throw T("fenced");let o=this.state.proof?"existing":"fresh";if(this.state.nativeStarted||await this.save({...this.state,nativeStarted:!0}),!r())throw T("fenced");return Object.freeze({mode:o,pin:Object.freeze({...this.confirmedSelection(),isCurrent:r,installationOwned:r})})})}attest(e){let{runtime:t,custody:r,persistence:o,installation:s}=e,i=s.isCurrent,a=()=>{if(this.check(),this.owned(s),s.isCurrent!==i||!t.deviceCustodyCurrent(this.confirmedSelection(),r))throw T("fenced")};return this.exclusive(async()=>{if(a(),!this.state.nativeStarted)throw T("recovery_required");if(this.state.token)return this.view();if(!this.state.proof){await o.pending(new Uint8Array(r.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:ar(f.signPublicKey),kem_pk:ar(f.kemPublicKey),noise_pk:ar(f.noisePublicKey),sig:ar(u)})}),a()}finally{d.fill(0),u?.fill(0)}}let c=this.state.proof;if(c.sign_pk!==ar(r.signPublicKey)||c.kem_pk!==ar(r.kemPublicKey)||c.noise_pk!==ar(r.noisePublicKey))throw T("binding");let{status:l,value:p}=await this.json(`/v1/pairing-requests/${this.state.requestId}/attest`,!0,c);if(a(),Te(p,"ok"),l!==200||p.ok!==!0)throw T("response");return this.view()})}receipt(){let e=this.state,t=e.proof;if(this.check(),!e.token||!t||!e.selection)throw T("binding");let r=o=>Uint8Array.from(o.match(/../g),s=>parseInt(s,16));return Object.freeze({connectorId:e.selection.connectorId,deviceId:e.deviceId,installationId:e.installationId,signPublicKey:r(t.sign_pk),kemPublicKey:r(t.kem_pk),noisePublicKey:r(t.noise_pk)})}acknowledge(e){let{runtime:t,custody:r,persistence:o,installation:s}=e,i=s.isCurrent,a=()=>{if(this.check(),this.owned(s),s.isCurrent!==i||!t.deviceCustodyCurrent(this.confirmedSelection(),r))throw T("fenced")};return this.exclusive(async()=>{a();let c=this.receipt();if(ar(c.signPublicKey)!==ar(r.signPublicKey)||ar(c.kemPublicKey)!==ar(r.kemPublicKey)||ar(c.noisePublicKey)!==ar(r.noisePublicKey))throw T("binding");return await o.registered(c,{signal:this.lifetime.signal}),a(),t.acknowledgeDeviceRegistration(c),a(),this.nativeAcknowledged=!0,c})}originalTimerChannel(e){if(this.check(),this.receipt(),!this.state.timerConsent?.approved||!this.state.timerConsent.grants.some(r=>r.grantId===e))throw T("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&&t_(t).grantId!==e)throw T("binding");await this.save({...this.state,timerChannel:t===null?void 0:t_(t)}),this.originalTimerChannel(e)})}session(e){return this.receipt(),this.confirmedHostSession(e,this.state.environment)}confirmedHostSession(e,t){let r=this.confirmedSelection();if(t!==this.state.environment)throw T("binding");let o=new URL(e);if(o.origin!==e||o.protocol!=="https:"&&!!1||o.username||o.password)throw T("binding");return Object.freeze({...r,logOrigin:e,timerConsent:()=>(this.check(),this.state.timerConsent??null),connectorBearer:async({signal:s})=>{if(this.check(),s.aborted||!this.state.token)throw T("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 o_(n){return/^[0-9a-f]{64}$/.test(n)?Uint8Array.from(n.match(/../g).map(e=>parseInt(e,16))):null}function tI(n){if(!(n instanceof Map))return!1;let e=n.get(3);return e instanceof Map?e.get(0)==="unauthenticated"&&(e.get(1)==="nonce"||e.get(1)==="replay"):!1}var oj,Sm,nI=I(()=>{"use strict";oj="x-mdbase-next-nonce";Sm=class{constructor(e=Date.now){this.now=e}now;spares=[];take(){for(let e=this.spares.pop();e;e=this.spares.pop()){let t=this.now()-e.at;if(t>=0&&t<4e4)return e.nonce;e.nonce.fill(0)}return null}keep(e){let t=o_(e.get(oj)??"");if(t)for(this.spares.push({nonce:t,at:this.now()});this.spares.length>6;)this.spares.shift().nonce.fill(0)}}});function zl(n){if((typeof n!="number"||!Number.isSafeInteger(n))&&typeof n!="bigint")throw he("shape");let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw he("shape");return e}function xm(n,e){let t=zl(n);if(t>BigInt(e))throw he("shape");return Number(t)}function Ks(n){if(!(n instanceof Map))throw he("shape");return n}function Cm(n){let e=[];for(let[t,r]of n){if(typeof t!="number"||!Number.isSafeInteger(t)||t<0)throw he("shape");e.push([t,r])}return new Map(e.sort(([t],[r])=>t-r))}function Ws(n,e){if(!(n instanceof Uint8Array)||e!==void 0&&n.length!==e)throw he("shape");return n}function Im(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}function rI(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function iI(n){return btoa(String.fromCharCode(...n))}function a_(n,e){let t;try{t=new URL(n)}catch{throw he("binding")}if(t.username||t.password||t.pathname!=="/"||t.search||t.hash||t.protocol!=="https:"&&!(e&&Ze(n)))throw he("binding");return t.origin}function oI(n,e){let t=n.headers.get("content-length");return t!==null&&/^(0|[1-9][0-9]*)$/.test(t)&&Number(t)>e}function lj(n,e,t,r,o,s,i){let a=Pm.encode("mdbase/v1/ls-http"),c=Pm.encode(t),l=Pm.encode("/v1/rpc"),p=Pm.encode(o),d=Qe(p),u=Qe(s);p.fill(0);let f=new Uint8Array(1+a.length+c.length+1+l.length+1+16+96),h=0;for(let w of[Uint8Array.of(a.length),a,c,Uint8Array.of(0),l,Uint8Array.of(0),N(r),d,u,i])f.set(w,h),h+=w.length;let m=Qe(f);return f.fill(0),Object.freeze({endpoint:n,originalCallId:e,frame:s.slice(),token:o,method:t,path:"/v1/rpc",collection:r,nonce:i.slice(),bodyHash:u,tokenHash:d,digest:m})}var s_,Pd,sj,aj,Pm,On,he,$l,xd=I(()=>{"use strict";At();hi();Ye();ve();nr();nI();s_=16*1024*1024,Pd=9*1024*1024,sj=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"]),aj=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"]),Pm=new TextEncoder,On=class extends Error{constructor(t,r){super(`app log transport: ${t}`);this.reason=t;this.server=r;this.name="AppHttpLogError"}reason;server},he=n=>new On(n);$l=class{constructor(e,t={}){this.authority=e;try{if(this.endpointId=zl(e.endpoint),this.endpoint=this.endpointId,this.collection=e.collection,this.collectionBytes=N(this.collection),this.loopback=t.allowLoopbackHttp===!0,this.base=a_(e.origin,this.loopback),!Array.isArray(e.directOrigins)||e.directOrigins.length>32)throw he("binding");this.approved=new Set([this.base,...e.directOrigins.map(r=>a_(r,this.loopback))]),this.fetchImpl=t.fetch??globalThis.fetch,this.now=t.now??Date.now,this.spares=new Sm(this.now)}catch{throw he("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&&zl(this.authority.endpoint)===this.endpointId&&this.authority.collection===this.collection&&a_(this.authority.origin,this.loopback)===this.base}catch{return!1}}check(e){if(e.aborted||!this.isCurrent())throw he("fenced")}request(e){if(e.length>s_)throw he("shape");let t=Ks(we(e));if(t.get(0)!==0||typeof t.get(2)!="string")throw he("shape");let r=t.get(2),o=Ks(t.get(3));if(!sj.has(r)||!Im(Ws(o.get(0),16),this.collectionBytes))throw he("shape");return{id:zl(t.get(1)),method:r,params:o}}response(e,t){let r=Ks(we(e));if(r.get(0)!==1||zl(r.get(1))!==t||r.has(2)===r.has(3))throw he("shape");return r}async fetch(e,t,r,o){this.check(r);let s=new AbortController,i=()=>s.abort();r.addEventListener("abort",i,{once:!0});let a=setTimeout(i,o);a.unref?.();try{let c=this.fetchImpl,l=(t.method??"GET")==="GET"?"no-store":"default",p=await c(e,{...t,signal:s.signal,redirect:"error",credentials:"omit",cache:l,referrerPolicy:"no-referrer"});if(!this.isCurrent()||r.aborted)throw p.body?.cancel().catch(()=>{}),he("fenced");return this.withCleanup(p,()=>{clearTimeout(a),r.removeEventListener("abort",i)})}catch{throw clearTimeout(a),r.removeEventListener("abort",i),he(r.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,r,o){let s=new Uint8Array(Math.min(1024,t)),i=0,a=null;try{if(this.check(r),oI(e,t))throw he("integrity");if(!e.body)return s.subarray(0,0);for(a=e.body.getReader();;){let{done:c,value:l}=await a.read();try{if(this.check(r),c)break;if(i+l.length>t)throw he("integrity");if(i+l.length>s.length){let p=new Uint8Array(Math.min(t,Math.max(s.length*2,i+l.length)));p.set(s.subarray(0,i)),s.fill(0),s=p}s.set(l,i),i+=l.length,o(l.length)}finally{l?.fill(0)}}return s.subarray(0,i)}catch(c){throw s.fill(0),(a?.cancel()??e.body?.cancel())?.catch(()=>{}),c}finally{a?.releaseLock(),this.release(e)}}async refusal(e,t,r){let o;try{let i=await this.read(e,8192,t,r);try{o=Mo(i)}finally{i.fill(0)}}catch(i){if(i instanceof On&&i.reason==="fenced")return i;o=void 0}let s=vr(e.status,o,e.headers);return new On(It(s)??"unavailable",s)}async freshNonce(e,t){let r=await this.fetch(`${this.base}/v1/nonce`,{},e,15e3);if(!r.ok)throw await this.refusal(r,e,t);let o=await this.read(r,128,e,t);try{this.check(e);let s=o_(new TextDecoder("utf-8",{fatal:!0}).decode(o).trim());if(!s)throw he("shape");return s}finally{o.fill(0)}}async rpc(e,t,r,o,s,i=r,a=!0){this.check(o);let c=await this.authority.accessToken({signal:o});if(this.check(o),typeof c!="string"||!c||c.length>16*1024||/[\r\n]/.test(c))throw he("shape");let l=a?this.spares.take():null,p=l??await this.freshNonce(o,s);this.check(o);let d=lj(this.endpoint,i,t,this.collection,c,e,p);p.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 he("shape");let f=await this.fetch(`${this.base}/v1/rpc`,{method:"POST",headers:{authorization:`Bearer ${c}`,"content-type":"application/cbor","x-mdbase-nonce":rI(d.nonce),"x-mdbase-sig":rI(u)},body:e},o,15e3);if(this.spares.keep(f.headers),f.status===401&&this.authority.invalidateToken?.(c),!f.ok)throw await this.refusal(f,o,s);let h=await this.read(f,t==="append"?64*1024:s_,o,s),m;try{this.check(o),m=tI(this.response(h,r))}catch(w){throw h.fill(0),w}return l&&m?(h.fill(0),await this.rpc(e,t,r,o,s,i,!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 r=Ks(e),o=r.get(0),s=Ks(r.get(1)),i=r.get(2);if(typeof o!="string"||o.length>16*1024||typeof i!="number"||!Number.isSafeInteger(i))throw he("shape");let a;try{a=new URL(o)}catch{throw he("shape")}if(a.username||a.password||a.hash||!this.approved.has(a.origin))throw he("binding");let c=new Headers,l=new Set;if(s.size>32)throw he("shape");for(let[p,d]of s){if(typeof p!="string"||typeof d!="string")throw he("shape");let u=p.toLowerCase();if(!/^[a-z0-9!#$%&'*+.^_`|~-]+$/.test(u)||aj.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 he("shape");if(u==="x-amz-checksum-sha256"&&d!==iI(t))throw he("integrity");l.add(u),c.set(u,d)}if(i-this.now()<=5e3)throw he("unavailable");return{url:a.href,headers:c,expires:i}}timeout(e,t){let r=e.expires-this.now();if(r<=5e3)throw he("unavailable");return Math.min(r,3e4+Math.ceil(t/(128*1024))*1e3)}async upload(e,t,r){this.check(r);let o;try{o=await this.fetch(e.url,{method:"PUT",headers:e.headers,body:t},r,this.timeout(e,t.length))}catch(s){if(this.check(r),s instanceof On&&s.reason==="unavailable")return;throw s}try{if(this.check(r),o.ok||o.status===408||o.status===425||o.status===429||o.status>=500)return;throw he("unavailable")}finally{o.body?.cancel().catch(()=>{}),this.release(o)}}async download(e,t,r,o,s){let i=new Uint8Array(t),a=0,c=0;try{for(let l=0;l<32&&c<5;l++){this.check(o);let p=a,d=new Headers(e.headers);p>0&&d.set("range",`bytes=${p}-${t-1}`);let u;try{u=await this.fetch(e.url,{headers:d},o,this.timeout(e,t-p))}catch{this.check(o),c++;continue}let f=null;try{if(this.check(o),[401,403,404,410].includes(u.status))throw he("unavailable");if([408,425,429].includes(u.status)||u.status>=500){c++;continue}if(u.status!==(p===0?200:206)||oI(u,t-p)||(p>0?u.headers.get("content-range")!==`bytes ${p}-${t-1}/${t}`:u.headers.has("content-range"))||u.headers.has("content-encoding")&&u.headers.get("content-encoding")!=="identity")throw he("integrity");let h=u.headers.get("x-amz-checksum-sha256");if(h!==null&&h!==iI(r)||!u.body)throw he("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 he("integrity");i.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(!Im(Qe(i),r))throw he("integrity");return i}c=a>p?0:c+1}throw he("unavailable")}catch(l){throw i.fill(0),l}}async send(e,t){let r=null,o=null,s=null,i=null,a=null,c=++this.responseId,l=0;this.receiving.set(c,l);let p=d=>{l+=d,this.receiving.set(c,l)};try{if(this.check(t.signal),zl(e.endpoint)!==this.endpointId||!(e.frame instanceof Uint8Array)||e.frame.length>s_||e.sidecar!==void 0&&(!(e.sidecar instanceof Uint8Array)||e.sidecar.length>Pd))throw he("shape");r=e.frame.slice(),o=e.sidecar?.slice()??null;let d=this.request(r);if(o&&d.method!=="put_object")throw he("shape");if(d.method==="put_object"){let h=xm(d.params.get(3),Pd),m=Ws(d.params.get(4),32),w=d.params.get(5);if(h===0||o!==null&&(w!==void 0||o.length<=1024*1024)||o===null&&h>1024*1024)throw he("shape");let b=o??Ws(w);if(b.length!==h||!Im(Qe(b),m))throw he("integrity")}s=await this.rpc(r,d.method,d.id,t.signal,p),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=Ks(u.get(2)),m=h.get(0);if(m===0||m===2){if(h.has(1))throw he("shape");let v=s;return s=null,v}if(m!==1||!o)throw he("shape");let w=Ws(d.params.get(4),32),b=Ws(d.params.get(1),32);if(await this.upload(this.direct(h.get(1),w),o,t.signal),this.check(t.signal),this.commitId===d.id||this.commitId===0n)throw he("unavailable");let g=this.commitId--;a=ue(new Map([[0,0],[1,g],[2,"commit_object"],[3,new Map([[0,this.collectionBytes],[1,b]])]]));let y=await this.rpc(a,"commit_object",g,t.signal,p,d.id);try{this.check(t.signal);let v=this.response(y,g),k=v.get(2);if(v.has(3)||!(k instanceof Map)||k.size!==1||k.get(0)!==!0)throw he("unavailable")}finally{y.fill(0)}let _=new Map(h);return _.delete(1),_.set(0,0),u.set(2,Cm(_)),ue(Cm(u))}if(d.method==="get_object"){let h=Ks(u.get(2)),m=xm(h.get(2),Pd),w=Ws(h.get(3),32);if(m===0||h.has(0)===h.has(1))throw he("shape");let b=d.params.get(2),g=0,y=m;if(b!==void 0&&(!Array.isArray(b)||b.length!==2||(g=xm(b[0],Pd),y=xm(b[1],Pd),g>m||y>m-g)))throw he("shape");if(h.has(0)){let v=Ws(h.get(0));if(v.length!==y||y===m&&!Im(Qe(v),w))throw he("integrity");let k=s;return s=null,k}i=await this.download(this.direct(h.get(1),w),m,w,t.signal,p),this.check(t.signal);let _=new Map(h);return _.delete(1),_.set(0,i.subarray(g,g+y)),u.set(2,Cm(_)),ue(Cm(u))}let f=s;return s=null,f}catch(d){if(d instanceof On)throw d;if(t.signal.aborted||!this.isCurrent())throw he("fenced");let u=null;try{u=d.server}catch{}let f=pn(u)?It(u):null;throw f&&pn(u)?new On(f,u):he("unavailable")}finally{this.receiving.delete(c),r?.fill(0),o?.fill(0),s?.fill(0),i?.fill(0),a?.fill(0)}}}});function sI(n,e){let t;try{t=new URL(n)}catch{throw yt("binding")}if(t.username||t.password||t.pathname!=="/"||t.search||t.hash||t.protocol!=="https:"&&!(e&&Ze(n)))throw yt("binding");return t.origin}function aI(n){if(typeof n=="number"&&!Number.isSafeInteger(n))throw yt("binding");let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw yt("binding");return e}function cj(n){return[...n].map(e=>e.toString(16).padStart(2,"0")).join("")}function pj(n){if(!n||typeof n!="object"||Array.isArray(n))throw yt("response");return n}var lr,yt,l_,Bl,Cd=I(()=>{"use strict";At();ve();xd();nr();lr=class extends Error{constructor(t,r){super(`app CP authority: ${t}`);this.reason=t;this.server=r;this.name="AppCpAuthorityError"}reason;server},yt=n=>new lr(n),l_=n=>new lr(It(n)??"unavailable",n);Bl=class{constructor(e,t,r={}){this.runtime=e;this.session=t;this.tokenCache=r.tokenCache??null;try{this.endpoint=aI(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(N(o).every(i=>i===0))throw yt("binding");if(this.rawCpOrigin=t.cpOrigin,this.rawLogOrigin=t.logOrigin,this.cpOrigin=sI(this.rawCpOrigin,r.allowLoopbackHttp===!0),this.origin=sI(this.rawLogOrigin,r.allowLoopbackHttp===!0),this.directOrigins=Object.freeze([...t.directOrigins]),this.now=r.now??Date.now,this.fetchImpl=r.fetch??globalThis.fetch,this.transport=new $l(this,r),!this.scopeCurrent())throw yt("binding");e.bindCpConnector(t)}catch{throw yt("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&&aI(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(),yt("fenced");if(e.aborted)throw yt("fenced")}logTransport(){if(!this.isCurrent())throw yt("fenced");return this.transport}async signLogProof(e,t){if(this.check(t.signal),!this.authenticated)throw yt("fenced");return this.runtime.signLogHttp(e)}async json(e,t,r,o){this.check(o);let s=new AbortController,i=()=>s.abort();o.addEventListener("abort",i,{once:!0}),this.lifetime.signal.addEventListener("abort",i,{once:!0});let a=setTimeout(i,15e3);a.unref?.();let c=null,l=null,p=new Uint8Array(32*1024),d=0;try{let u=this.fetchImpl;if(c=await u(`${this.cpOrigin}${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,...r===void 0?{}:{"content-type":"application/json"}},body:r,signal:s.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(o),s.signal.aborted)throw yt("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(),c.ok?yt("unavailable"):l_(vr(c.status,void 0,c.headers));if(!c.body)throw c.ok?yt("response"):l_(vr(c.status,void 0,c.headers));for(l=c.body.getReader();;){let{done:h,value:m}=await l.read();try{if(this.check(o),s.signal.aborted)throw yt("unavailable");if(h)break;if(d+m.length>p.length)throw s.abort(),yt("response");p.set(m,d),d+=m.length}finally{m?.fill(0)}}if(!c.ok)throw l_(vr(c.status,Mo(p.subarray(0,d)),c.headers));return pj(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(p.subarray(0,d))))}catch(u){throw this.check(o),u instanceof lr?u:yt("unavailable")}finally{p.fill(0),(l?.cancel()??c?.body?.cancel())?.catch(()=>{}),l?.releaseLock(),clearTimeout(a),o.removeEventListener("abort",i),this.lifetime.signal.removeEventListener("abort",i)}}async accessToken(e){let t=null,r=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 c=await this.tokenCache.read(this.cacheKey(),this.now());if(this.check(e.signal),c)return this.token={value:c.value,expires:c.expires},this.authenticated=!0,c.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 yt("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(c=>parseInt(c,16))),r=this.runtime.signCpLogToken(t),this.check(e.signal),!(r instanceof Uint8Array)||r.length!==64))throw yt("response");let i=JSON.stringify({device_id:this.deviceId,challenge:s.challenge,sig:cj(r),capabilities:["collection_mode_switch_v2"]}),a=await this.json(`/v1/next/collections/${this.collection}/log-token`,o,i,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 yt("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 lr?o:yt(this.scopeCurrent()?"unavailable":"fenced")}finally{t?.fill(0),r?.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 c_(n,e){if(typeof n!="string"||!n.length||n.length%2||n.length>e*2||!/^[0-9a-f]+$/.test(n))throw Pe("response");return Uint8Array.from(n.match(/../g),t=>parseInt(t,16))}function p_(n){if(!n||typeof n!="object"||Array.isArray(n))throw Pe("response");return n}var Rn,Pe,dj,Om,lI,Vl,Id=I(()=>{"use strict";ve();At();Vs();nr();Rn=class extends Error{constructor(t,r=!1,o){super(`app cloud copy bootstrap: ${t}`);this.reason=t;this.retryable=r;this.server=o;this.name="AppCloudCopyBootstrapError"}reason;retryable;server},Pe=(n,e=!1)=>new Rn(n,e),dj=new Set([408,429,500,502,503,504]),Om=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]),lI=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join("");Vl=class{constructor(e,t,r,o,s={}){this.runtime=e;this.session=t;this.trust=r;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=Pi(r.environment),!1)throw Pe("binding");this.loopback=s.allowLoopbackHttp===!0||this.local;for(let c of[this.scope.accountId,this.scope.connectorId,this.scope.deviceId,this.scope.installationId,this.scope.collection])if(N(c).every(l=>l===0))throw Pe("binding");if(this.origin(this.scope.cpOrigin),this.origin(this.scope.logOrigin),r.schema!=="mdbn-app-trust/release/1"||!(["lab","staging","production"].includes(r.environment)||this.loopback&&r.environment==="test"||this.local)||r.cpOrigin!==this.scope.cpOrigin||r.logOrigin!==this.scope.logOrigin||!/^[0-9a-f]{64}$/.test(r.assetSha256)||r.source.repository!=="mdbase-dev/mdbase-connect"||!/^[0-9a-f]{40}$/.test(r.source.commit)||!r.source.version||r.source.version.length>64||!Array.isArray(r.trustedRoots)||r.trustedRoots.length<1||r.trustedRoots.length>64||!(r.policyPins instanceof Uint8Array)||!r.policyPins.length||r.policyPins.length>65536)throw Pe("binding");this.trustFields=Object.freeze({schema:r.schema,environment:r.environment,assetSha256:r.assetSha256,...r.source}),this.roots=Object.freeze(r.trustedRoots.map(c=>{if(!(c instanceof Uint8Array)||c.length!==32||c.every(l=>l===0))throw Pe("binding");return new Uint8Array(c)})),this.pins=new Uint8Array(r.policyPins);let i=s.displayName,a=i===void 0?void 0:sr(i);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:r.assetSha256,cpOrigin:this.scope.cpOrigin,logOrigin:this.scope.logOrigin}),this.request=s.fetch??globalThis.fetch,this.now=s.now??Date.now,!this.current()))throw Pe("binding")}catch{throw e.retireLog(),Pe("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&&!Yo(e))throw Pe("binding");let t=new URL(e);if(t.origin!==e||t.username||t.password||t.protocol!=="https:"&&!(this.loopback&&Ze(e)))throw Pe("binding");return t.origin}current(){try{let e=this.session,t=this.trust,r=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===r.schema&&t.environment===r.environment&&t.assetSha256===r.assetSha256&&t.source.repository===r.repository&&t.source.commit===r.commit&&t.source.version===r.version&&t.trustedRoots.length===this.roots.length&&t.trustedRoots.every((o,s)=>Om(o,this.roots[s]))&&Om(t.policyPins,this.pins)}catch{return!1}}check(e){if(e.aborted||!this.current())throw this.close(),Pe("fenced")}operationCopy(e){for(let t of["accountId","connectorId","deviceId","installationId","collection","purpose","cpOrigin","logOrigin","assetSha256","displayName"])if(e[t]!==this.operation[t])throw Pe("response");for(let t of["signPublicKey","kemPublicKey","noisePublicKey"])if(!(e[t]instanceof Uint8Array)||!Om(e[t],this.operation[t]))throw Pe("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 Pe("response");return Object.freeze({operation:this.operationCopy(e.operation),genesisItem:new Uint8Array(e.genesisItem),expectedGenesis:e.expectedGenesis})}async hash(e,t){let r=new TextEncoder().encode("mdbase/v1/chain"),o=new Uint8Array(1+r.length+e.length);o[0]=r.length,o.set(r,1),o.set(e,1+r.length);let s=new Uint8Array(await crypto.subtle.digest("SHA-256",o));return this.check(t),`sha256:${lI(s)}`}async json(e,t,r,o){this.check(o);let s=new AbortController,i=()=>s.abort(),a=setTimeout(i,15e3);a.unref?.(),o.addEventListener("abort",i,{once:!0}),this.lifetime.signal.addEventListener("abort",i,{once:!0});let c=new Uint8Array(1024*1024),l=0,p=null,d=null;try{let u=this.request;if(p=await u(`${this.scope.cpOrigin}${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,...r===void 0?{}:{"content-type":"application/json"}},body:r,signal:s.signal,redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer"}),this.check(o),s.signal.aborted)throw Pe("unavailable",!0);if(!p.ok){let h=await this.problem(p,o),m=It(h),w=!m&&dj.has(p.status);throw new Rn(m??(w?"unavailable":"refused"),w,h)}let f=p.headers.get("content-length");if(f!==null&&/^(0|[1-9][0-9]*)$/.test(f)&&Number(f)>c.length)throw s.abort(),Pe("response");if(!p.body)throw Pe("response");for(d=p.body.getReader();;){let{done:h,value:m}=await d.read();try{if(this.check(o),s.signal.aborted)throw Pe("unavailable",!0);if(h)break;if(l+m.length>c.length)throw s.abort(),Pe("response");c.set(m,l),l+=m.length}finally{m?.fill(0)}}try{return p_(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c.subarray(0,l))))}catch{throw Pe("response")}}catch(u){throw this.check(o),u instanceof Rn?u:Pe("unavailable",!0)}finally{c.fill(0),(d?.cancel()??p?.body?.cancel())?.catch(()=>{}),d?.releaseLock(),clearTimeout(a),o.removeEventListener("abort",i),this.lifetime.signal.removeEventListener("abort",i)}}async problem(e,t){let r=new Uint8Array(8192),o=0,s=e.body?.getReader();try{for(;s;){let{done:i,value:a}=await s.read();try{if(this.check(t),i)break;if(o+a.length>r.length){o=0;break}r.set(a,o),o+=a.length}finally{a?.fill(0)}}}catch{this.check(t),o=0}finally{s?.cancel().catch(()=>{}),s?.releaseLock()}try{return vr(e.status,o?Mo(r.subarray(0,o)):void 0,e.headers)}finally{r.fill(0)}}async challenge(e,t){for(let r=0;r<3;r++)try{return await this.json("/v1/next/devices/challenge",e,void 0,t)}catch(o){if(!(o instanceof Rn)||o.reason!=="unavailable"||!o.retryable||r===2)throw o;this.check(t),await new Promise((s,i)=>{let a=()=>{clearTimeout(l),t.removeEventListener("abort",c),this.lifetime.signal.removeEventListener("abort",c);try{this.check(t),s()}catch(p){i(p)}},c=()=>a(),l=setTimeout(a,r===0?250:1e3);l.unref?.(),t.addEventListener("abort",c,{once:!0}),this.lifetime.signal.addEventListener("abort",c,{once:!0}),(t.aborted||this.lifetime.signal.aborted)&&a()})}throw Pe("unavailable",!0)}async bootstrap(e){let{signal:t,reconcile:r}=e,o=Object.freeze({signal:t}),s=null,i=null;try{if(this.originalSignal??=t,t!==this.originalSignal||(this.check(t),this.attempted))throw Pe("fenced");this.attempted=!0;let a=await this.storageCallbacks.restore.call(this.persistence,o);if(this.check(t),a.state==="completed"){let w=this.copy(a.metadata);if(await this.hash(w.genesisItem,t)!==w.expectedGenesis)throw Pe("response");return this.completion=this.copy(w),w}if(a.state==="pending"){if(this.operationCopy(a.operation),r!=="explicit-unknown-outcome")throw Pe("outcome_unknown")}else if(a.state!=="none")throw Pe("response");await this.storageCallbacks.pending.call(this.persistence,this.operationCopy(this.operation),o),this.check(t);let c=await this.callbacks.bearer.call(this.session,o);if(this.check(t),typeof c!="string"||!c||c.length>16384||/[^\x21-\x7e]/.test(c))throw Pe("binding");let l=await this.challenge(c,t);if(s=c_(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 Pe("response");let p=this.scope.purpose==="create";if(i=p?this.runtime.signCloudCopyCreate(s):this.runtime.signCloudCopyJoin(s),this.check(t),i.length!==64)throw Pe("response");let d;try{d=await this.json(p?"/v1/next/collections/cloud-copy":`/v1/next/collections/${this.scope.collection}/devices`,c,JSON.stringify({device_id:this.scope.deviceId,capabilities:["collection_mode_switch_v2"],challenge:l.challenge,sig:lI(i),...p?{collection_id:this.scope.collection,...this.operation.displayName===void 0?{}:{display_name:this.operation.displayName}}:{}}),t)}catch(w){throw w instanceof Rn&&w.reason==="unavailable"?Pe("outcome_unknown"):w}if(d.collection_id!==this.scope.collection||d.log_url!==this.scope.logOrigin)throw Pe("response");if(p){let w=c_(d.root_public_key,32);if(d.state!=="cloud-copy"||d.owner_account!==this.scope.accountId||!this.roots.some(b=>Om(b,w)))throw Pe("response")}else if(typeof d.enrolled_at!="number"||!Number.isSafeInteger(d.enrolled_at)||d.enrolled_at<1)throw Pe("response");let u=p_(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 Pe("response");let f=p_(d.genesis);if(f.seq!==1)throw Pe("response");let h=c_(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 Rn?a:Pe("unavailable")}finally{s?.fill(0),i?.fill(0)}}adoptCollection(e,t){let{signal:r,replicaId:o,endpoint:s,opened:i,sqliteVersion:a,cloudCopyOptIn:c}=e;try{if(this.check(r),this.adopted||!this.completion||r!==this.originalSignal||c!==!0)throw Pe("binding");let l={replicaId:o,endpoint:s,opened:i,sqliteVersion:a,collection:this.scope.collection,deviceId:this.scope.deviceId,state:"cloud_copy",cloudCopyOptIn:!0,trustedRoots:this.roots.map(p=>new Uint8Array(p)),policyPins:new Uint8Array(this.pins),trustedSigners:[],expectedGenesis:this.completion.expectedGenesis};this.runtime.adoptDevice(l,t),this.adopted=!0,this.check(r)}catch(l){throw this.close(),l instanceof Rn?l:Pe("unavailable")}}close(){this.completion=null,this.lifetime.abort(),this.runtime.retireLog()}}});function pI(n){try{if(n instanceof ei)return n;if(n instanceof tt){if(n.reason==="outcome_unknown")return new ei("collection_delete_outcome_unknown");if(n.reason==="binding")return new ei("collection_delete_invalid");let e=To(n.server)?.code;if(e&&Object.hasOwn(cI,e))return new ei(cI[e]);if(n.reason==="refused"&&!n.server)return new ei("collection_delete_not_approved")}}catch{}return new ei("collection_delete_failed")}var ei,cI,dI=I(()=>{"use strict";Sd();nr();ei=class extends Error{constructor(t){super(`collection delete: ${t}`);this.code=t;this.name="AppCollectionDeleteError"}code},cI=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 uI(n){return typeof n=="string"&&/^[a-zA-Z0-9_-]{16,128}$/.test(n)}function u_(n,e){let t=()=>{throw new xe("application_worker_binding")};if(!Array.isArray(n)||n.length!==5||n[0]!==cr||n[1]!==e||!Number.isInteger(n[2])||n[2]<0||n[2]>Rm||n[2]===0&&n[3]!=="foreground"&&n[3]!=="approvalClosed"||n[2]!==0&&n[3]==="approvalClosed")return t();let r=n[3],o=n[4];["start","authorize","renewExpiredPairing","select","clearSelection","forget","refreshCollections","signOut","deleteCollection","requestFileAccess","pollFileAccess","openUnsynced","attachUnsynced","detachUnsynced","retireUnsynced","discardUnsynced","foreground","approvalClosed","cancelAuthorization","close","unlock"].includes(r)||t();let s=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;if(r==="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(i=>typeof i!="string"||!["list","read","add","replace","move","delete"].includes(i))||typeof o[2]!="string"||!o[2]||o[2].length>140)&&t(),Object.freeze([n[0],n[1],n[2],r,Object.freeze([o[0],Object.freeze([...o[1]]),o[2]])]);if(r==="unlock")return(!Array.isArray(o)||o.length!==3||typeof o[0]!="string"||!s.test(o[0])||o[0]==="00000000-0000-0000-0000-000000000000"||o[1]!=="password"&&o[1]!=="recoveryKey"||!(o[2]instanceof Uint8Array)||!o[2].length||o[2].length>d_)&&t(),Object.freeze([n[0],n[1],n[2],r,Object.freeze([o[0],o[1],o[2]])]);if(r==="pollFileAccess")(typeof o!="string"||!s.test(o))&&t();else if(r==="select"||r==="forget")(typeof o!="string"||!o||o.length>256||/[\u0000-\u001f\u007f]/.test(o))&&t();else{if(r==="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],r,Object.freeze([o[0],o[1]])]);if(r==="retireUnsynced")return(!Array.isArray(o)||o.length!==2||o.some(i=>typeof i!="string"||!s.test(i))||o[0]===o[1])&&t(),Object.freeze([n[0],n[1],n[2],r,Object.freeze([o[0],o[1]])]);r==="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():r==="foreground"?typeof o!="boolean"&&t():r==="approvalClosed"?o!==!0&&t():o!==null&&t()}return Object.freeze([...n])}var cr,Rm,d_,xe,Od=I(()=>{"use strict";cr="mdbn-application-worker/1",Rm=4294967295,d_=4096,xe=class extends Error{constructor(t){super("SDK application Worker unavailable");this.code=t;this.name="ApplicationWorkerError"}code}});function Em(n){let e=n.cpOrigin,t=n.signal,r=n.isCurrent,o=n.open,s=()=>{let f=!1;try{f=!t.aborted&&r()===!0}catch{}if(!f)throw new rn("application_popup_fenced")};s();let i;try{i=new URL(e)}catch{throw new rn("application_popup_binding")}let a=n.allowLoopbackHttp===!0&&Ze(e);if(i.origin!==e||i.username||i.password||i.search||i.hash||i.pathname!=="/"||i.protocol!=="https:"&&!a)throw new rn("application_popup_binding");let c;try{c=o()}catch{throw new rn("application_popup_unavailable")}if(c===null)throw new rn("application_popup_blocked");if(fI.has(c))throw new rn("application_popup_binding");fI.add(c);let l=!1,p=null,d=()=>{if(l){if(p)throw p;return}l=!0,t.removeEventListener("abort",u);try{c.close()}catch{throw p=new rn("application_popup_stop_failed"),p}},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||c.closed?.()===!0}catch{return!1}},focus(){if(s(),!l){try{c.focus?.()}catch{throw new rn("application_popup_unavailable")}s()}},navigate(f){if(s(),l)throw new rn("application_popup_fenced");let h;try{h=new URL(f)}catch{throw new rn("application_popup_binding")}if(h.origin!==e||h.username||h.password)throw new rn("application_popup_binding");try{c.navigate(h.href)}catch(m){throw m instanceof rn?m:new rn("application_popup_unavailable")}if(s(),l)throw new rn("application_popup_fenced")}})}function uj(){let n=0,e=0;try{let t=globalThis.window;n=Math.max(0,Math.round(t.screenX+(t.outerWidth-mI)/2)),e=Math.max(0,Math.round(t.screenY+(t.outerHeight-yI)/2))}catch{}return`popup,width=${mI},height=${yI},left=${Number.isFinite(n)?n:0},top=${Number.isFinite(e)?e:0}`}function qm(n,e,t,r=!1){return{cpOrigin:n,signal:e,isCurrent:t,allowLoopbackHttp:r,open(){let o=globalThis.window.open("about:blank","_blank",uj());if(!o)return null;let s=hI.get(o);if(s)return s;let i={navigate(a){if(o.closed)throw new rn("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 hI.set(o,i),i}}}function gI(n,e,t,r,o=!1){return{cpOrigin:n,signal:e,isCurrent:t,allowLoopbackHttp:o,open(){let s=null,i=a=>{Promise.resolve().then(()=>r.open(a)).catch(()=>{})};return{navigate(a){let c=new URL(a);r.returnUrl!==void 0&&c.searchParams.set("return_url",r.returnUrl),s=c.href,i(s)},focus(){s!==null&&i(s)},close(){s&&r.close&&Promise.resolve().then(()=>r.close()).catch(()=>{})}}}}}var rn,fI,hI,mI,yI,f_=I(()=>{"use strict";At();rn=class extends Error{constructor(t){super("application authorization popup unavailable");this.reason=t;this.name="ApplicationPortalError"}reason},fI=new WeakSet;hI=new WeakMap,mI=620,yI=760});function Hs(n,e=null){if(n instanceof He)return n;let t=n?.name??"",r=n instanceof Error?n.message:String(n),o=n?.resultCode,s=typeof o=="number"?o&255:null;return t==="QuotaExceededError"||/quota/i.test(r)||s===13?new He("Full",r,e):s===11||s===26||/malformed|not a database|SQLITE_CORRUPT|SQLITE_NOTADB/i.test(r)?new He("Corrupt",r,e):t==="NoModificationAllowedError"||s===5||s===6||/SQLITE_BUSY|SQLITE_LOCKED|NoModificationAllowed/i.test(r)?new He("Busy",r,e):s===1||s===19||s===20||s===25||/SQLITE_ERROR|SQLITE_CONSTRAINT|syntax/i.test(r)?new He("Sql",r,e):new He("Other",r,e)}function h_(n){if(typeof n=="bigint")return n;if(typeof n=="number"&&Number.isSafeInteger(n))return BigInt(n);throw new He("Other","SQLite integer is not losslessly represented")}var He,bI,wI,vI,_I,AI,fj,Tm,m_=I(()=>{"use strict";He=class extends Error{constructor(t,r,o=null){super(`${t}${o===null?"":`@${o}`}(${r})`);this.kind=t;this.detail=r;this.stmt=o;this.name="IndexError"}kind;detail;stmt},bI=1,wI=2,vI=3,_I=4,AI=5;fj="CREATE TABLE IF NOT EXISTS _mdbn_host(k TEXT PRIMARY KEY, v) WITHOUT ROWID",Tm=class n{constructor(e,t,r){this.sqlite3=e;this.db=t;this.info=r}sqlite3;db;info;cache=new Map;closed=!1;static open(e,t,r={}){try{let o=r.synchronous??"NORMAL";if(o!=="NORMAL"&&o!=="FULL")throw new He("Other","unsupported synchronous profile");if(r.pragmas!==!1&&(t.exec("PRAGMA locking_mode=EXCLUSIVE"),t.exec("PRAGMA journal_mode=WAL"),t.exec(`PRAGMA synchronous=${o}`)),r.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 He("Other","SQLite did not apply the requested storage profile");let s=t.selectValue("SELECT count(*) FROM sqlite_master WHERE name='_mdbn_host'")>0,i=t.selectValue("SELECT count(*) FROM sqlite_master");t.exec(fj);let a="Fresh";return s?a=t.selectValue("SELECT v FROM _mdbn_host WHERE k='clean'")===1?"Existing":"Unclean":i>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:r.quotaSuspect??!1})}catch(o){throw Hs(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((r,o)=>{let s=o+1;switch(r.kind){case"Null":e.bind(s,null);break;case"Integer":e.bind(s,r.value);break;case"Real":e.bind(s,r.value);break;case"Text":e.bind(s,r.value);break;case"Blob":e.bindAsBlob(s,r.value);break}})}column(e,t){let r=this.sqlite3.capi;switch(r.sqlite3_column_type(e.pointer,t)){case AI:return{kind:"Null"};case bI:{let o=r.sqlite3_column_int64(e.pointer,t);return{kind:"Integer",value:h_(o)}}case wI:return{kind:"Real",value:r.sqlite3_column_double(e.pointer,t)};case vI:return{kind:"Text",value:e.getString(t)};case _I:return{kind:"Blob",value:e.getBlob(t)??new Uint8Array(0)};default:return{kind:"Null"}}}run(e,t){if(this.closed)throw new He("Other","index closed");let r=this.sqlite3.capi,o=e.mode==="Transaction",s=[],i=0,a=0,c=13,l=p=>{if(t){if(!Number.isSafeInteger(p)||p<0||p>t.maxBytes-c)throw new He("Full","index reply byte budget exceeded");c+=p}};if(t&&([t.maxBytes,t.maxRows,t.maxValues,t.maxColumns].some(p=>!Number.isSafeInteger(p)||p<0)||t.maxBytes<c))throw new He("Full","invalid index reply budget");if(o)try{this.db.exec("BEGIN IMMEDIATE")}catch(p){throw Hs(p)}for(let p=0;p<e.stmts.length;p++){let d=e.stmts[p];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 He("Full","index reply column budget exceeded");l(24);let h=[];for(;u.step();){if(t&&++i>t.maxRows)throw new He("Full","index reply row budget exceeded");for(let m=0;m<f;m++){if(t){if(++a>t.maxValues)throw new He("Full","index reply value budget exceeded");let w=r.sqlite3_column_type(u.pointer,m);if(w===vI||w===_I)l(5),l(r.sqlite3_column_bytes(u.pointer,m));else if(w===bI||w===wI)l(9);else if(w===AI)l(1);else throw new He("Other","unknown SQLite value type")}h.push(this.column(u,m))}}s.push({columns:f,values:h,changes:h_(r.sqlite3_changes(this.db.pointer)),lastInsertRowid:h_(r.sqlite3_last_insert_rowid(this.db.pointer))})}finally{u.reset()}}catch(u){if(o)try{this.db.exec("ROLLBACK")}catch{}throw Hs(u,p)}}if(o)try{this.db.exec("COMMIT")}catch(p){try{this.db.exec("ROLLBACK")}catch{}throw Hs(p)}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 bj(n){let e=new y_(n);if(!e.take(8).every((i,a)=>i===SI[a]))throw Yt();let t=e.byte();if(t===1)throw e.done(),new He("Other","app database reset requires explicit recovery; automatic wipe refused");if(t!==0)throw Yt();let r=e.byte();if(r>1)throw Yt();let o=e.count(Hn.maxStatements,8),s=[];for(let i=0;i<o;i++){let a=e.text(Hn.maxSqlBytes),c=e.count(Hn.maxParameters,1),l=[];for(let p=0;p<c;p++)l.push(e.value());s.push({sql:a,params:l})}return e.done(),{mode:r===0?"Transaction":"Autocommit",stmts:s}}function wj(n,e){if(!Array.isArray(n)||n.length!==e)throw Yt();let t=new Mm(2);t.u32(n.length);let r=0;for(let o of n){if(!Number.isSafeInteger(o.columns)||o.columns<0||o.columns>Hn.maxColumns)throw Zo();if(!Array.isArray(o.values)||(o.columns===0?o.values.length!==0:o.values.length%o.columns!==0))throw Yt();if(r+=o.columns===0?0:o.values.length/o.columns,r>Hn.maxRows||o.values.length>Hn.maxValues)throw Zo();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 vj(n,e){let t=n instanceof He?n.kind:"Other",r={Sql:0,Corrupt:1,Full:2,Busy:3,Other:4},o=new Mm(3);o.byte(r[t]);let s=n instanceof He?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(PI.encode("app index operation failed; reopen and reconcile")),o.done()}function kI(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 Yt()}function xI(n,e){let t=!1,r=!1;return(o,s)=>{if(t)throw r=!0,n.fence(),Yt();t=!0,r=!1;try{let i=e();if(kI(i.memory,o,s),s>Hn.maxBytes)throw n.fence(),Zo();let a=n.run(new Uint8Array(i.memory.buffer,o,s).slice()),c=i.alloc(a.length);if(kI(i.memory,c,a.length),r||c===0||c<o+s&&o<c+a.length)throw Yt();return new Uint8Array(i.memory.buffer,c,a.length).set(a),BigInt(c)<<32n|BigInt(a.length)}catch(i){throw n.fence(),i}finally{t=!1}}}var SI,Hn,hj,mj,yj,Yt,Zo,gj,PI,y_,Mm,Lm,CI=I(()=>{"use strict";m_();SI=Uint8Array.of(77,68,66,73,68,88,0,1),Hn=Object.freeze({maxBytes:4*1024*1024,maxStatements:16384,maxValues:131072,maxRows:4096,maxColumns:100,maxSqlBytes:100*1024,maxParameters:100}),hj=-(1n<<63n),mj=(1n<<63n)-1n,yj=(1n<<64n)-1n,Yt=()=>new He("Other","invalid app index ABI"),Zo=()=>new He("Full","app index ABI budget exceeded"),gj=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}),PI=new TextEncoder,y_=class{constructor(e){this.bytes=e;if(e.length>Hn.maxBytes)throw Zo();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 Yt();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 r=this.u32();if(r>e)throw Zo();if(r>Math.floor((this.bytes.length-this.pos)/t))throw Yt();return r}data(e){return this.take(this.count(e,1))}text(e){return gj.decode(this.data(e))}value(){if(++this.values>Hn.maxValues)throw Zo();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 Yt();return{kind:"Real",value:t}}case 3:return{kind:"Text",value:this.text(Hn.maxBytes)};case 4:return{kind:"Blob",value:this.data(Hn.maxBytes).slice()};default:throw Yt()}}done(){if(this.pos!==this.bytes.length)throw Yt()}};Mm=class{parts=[];length=0;values=0;constructor(e){this.put(SI),this.byte(e)}put(e){if(e.length>Hn.maxBytes-this.length)throw Zo();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 Yt();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?hj:0n)||e>(t?mj:yj))throw Yt();let r=new Uint8Array(8),o=new DataView(r.buffer);t?o.setBigInt64(0,e,!0):o.setBigUint64(0,e,!0),this.put(r)}data(e){this.u32(e.length),this.put(e)}value(e){if(++this.values>Hn.maxValues)throw Zo();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 Yt();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(PI.encode(e.value));return;case"Blob":this.byte(4),this.data(e.value);return;default:throw Yt()}}done(){let e=new Uint8Array(this.length),t=0;for(let r of this.parts)e.set(r,t),t+=r.length;return e}};Lm=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 Yt();let r=bj(e);t=r.stmts.length;let o=Hn;return wj(this.index.run(r,o),t)}catch(r){return this.fence(),vj(r,t)}}}});function b_(n){let e=[n.account,n.installation,n.collection];if(e.some(r=>!_j.test(r)))throw new He("Other","invalid app storage scope");let t=`mdbase-app-${e.map(r=>r.toLowerCase()).join("-")}`;return{vfs:t,directory:`.${t}`}}async function II(n,e){let t=b_(e),r,o,s;try{r=await n.installOpfsSAHPoolVfs({name:t.vfs,directory:t.directory,initialCapacity:6}),r.isPaused?.()&&await r.unpauseVfs(),o=new r.OpfsSAHPoolDb("/app.db");let i=Tm.open(n,o,{synchronous:"FULL",verifyPragmas:!0});if(s=new g_(i),i.info.opened==="Unclean"){let a=s.run({mode:"Autocommit",stmts:[{sql:"PRAGMA quick_check",params:[]}]}),c=a[0]?.values;if(a.length!==1||c?.length!==1||c[0]?.kind!=="Text"||c[0].value!=="ok")throw s=void 0,i.close({markClean:!1}),o=void 0,new He("Corrupt","app database integrity check failed; recovery required")}return{index:s,pool:r}}catch(i){let a=!1;try{s?s.close():o?.close()}catch{a=!0}try{r?.pauseVfs?.()}catch{a=!0}let c=Hs(i);throw new He(a?"Other":c.kind,"app SQLite open failed; recovery required",c.stmt)}}var _j,g_,OI=I(()=>{"use strict";m_();_j=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;g_=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 He("Other","app database fenced or closed; reopen and reconcile");try{return t?this.inner.run(e,t):this.inner.run(e)}catch(r){this.fenced=!0;let o=Hs(r);throw new He(o.kind,"app SQLite operation failed; reopen and reconcile",o.stmt)}}reset(){throw new He("Other","app database reset requires explicit recovery; automatic wipe refused")}close(){this.closed||(this.closed=!0,this.inner.close({markClean:!this.fenced}))}}});function RI(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 Fl("binding");return async({scope:t,signal:r})=>{let o=Object.freeze({account:t.account,installation:t.installation,collection:t.collection});b_(o);let s=()=>{if(r.aborted||Object.entries(o).some(([y,_])=>t[y]!==_))throw Fl("fenced")};s();let i=globalThis.WorkerGlobalScope;if(typeof i!="function"||!(globalThis instanceof i))throw Fl("unsupported");let a=await e.loadWasm({signal:r});if(s(),!(a instanceof Uint8Array)||a.byteLength<1||a.byteLength>e.maxWasmBytes)throw Fl("binding");let c=new Uint8Array(a),l=new Uint8Array(await crypto.subtle.digest("SHA-256",c));if(s(),Array.from(l,y=>y.toString(16).padStart(2,"0")).join("")!==e.wasmSha256)throw Fl("binding");let p=await e.initialize({wasmBinary:c,print(){},printErr(){}});s();let d=await II(p,o),u=d.index,f=new Lm(u),h={import:y=>xI(f,y),fence:()=>f.fence(),get needsRecovery(){return f.needsRecovery}},m=y=>({kind:"Text",value:y}),w=Object.freeze({list(y){let[_]=u.run({mode:"Autocommit",stmts:[{sql:"SELECT v FROM _mdbn_host WHERE k >= 'w:' AND k < 'w;' ORDER BY k LIMIT 1024",params:[]}]}),v=[],k=0;for(let S of _?.values??[])if(S.kind==="Text"){if(k+=S.value.length,k>y)break;v.push(S.value)}return v},put(y,_){u.run({mode:"Autocommit",stmts:[{sql:"INSERT OR REPLACE INTO _mdbn_host(k, v) VALUES (?, ?)",params:[m(`w:${y}`),m(_)]}]})},remove(y){u.run({mode:"Autocommit",stmts:[{sql:"DELETE FROM _mdbn_host WHERE k = ?",params:[m(`w:${y}`)]}]})}}),b=null,g=()=>b??=Promise.resolve().then(async()=>{try{u.close(),await d.pool.pauseVfs()}catch{throw f.fence(),Fl("unavailable")}});return(r.aborted||Object.entries(o).some(([y,_])=>t[y]!==_))&&f.fence(),Object.freeze({sql:h,opened:{Fresh:"fresh",Existing:"existing",Unclean:"unclean"}[u.info.opened],sqliteVersion:u.info.sqliteVersion,ledger:w,close:g})}}var w_,Fl,EI=I(()=>{"use strict";OI();CI();w_=class extends Error{constructor(t){super(`app collection SQL: ${t}`);this.reason=t;this.name="AppCollectionSqlError"}reason},Fl=n=>new w_(n)});var lo,v_=I(()=>{"use strict";lo=Object.freeze({plaintextBytes:524288,operations:64,readbacks:128,pathCodeUnits:1024})});function se(n){throw new qn(n)}function En(n,e){return Object.keys(n).sort().join()===e}function __(n){return(!n||!En(n,"account,collection,installation")||Object.values(n).some(e=>typeof e!="string"||!A_.test(e)||e==="00000000-0000-0000-0000-000000000000"))&&se("binding"),Object.freeze({account:n.account,installation:n.installation,collection:n.collection})}function qI(n){for(let e of n){let t=e.charCodeAt(0);if(t<32||t===127)return!0}return n.includes("\\")}function Aj(n){(!Array.isArray(n)||n.length!==2)&&se("binding");let e=n.map(t=>((!t||typeof t!="object"||!En(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("/")||qI(t.path)||t.path.split("/").some(r=>!r||r==="."||r===".."))&&se("binding"),Object.freeze({kind:"resource_put",path:t.path,doc:t.doc,mustNotExist:!0})));return(e[0].path===e[1].path||Ii.encode(JSON.stringify(e)).byteLength>ti)&&se("binding"),Object.freeze(e)}function Ed(n){return typeof n=="string"&&n.length>0&&n.length<=lo.pathCodeUnits&&!n.startsWith("/")&&!qI(n)&&!n.split("/").some(e=>!e||e==="."||e==="..")}function Ys(n){let e=n;(!e||typeof e!="object"||!En(e,"assessmentDigest,ops,pack,readback")||!e.pack||typeof e.pack!="object"||!En(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"||!Gs.test(e.pack.digest)||typeof e.assessmentDigest!="string"||!Gs.test(e.assessmentDigest)||!Array.isArray(e.ops)||!e.ops.length||e.ops.length>lo.operations||!Array.isArray(e.readback)||!e.readback.length||e.readback.length>lo.readbacks)&&se("binding");let t=e.ops.map(i=>{(!i||typeof i!="object"||!Ed(i.path)||"baseRevision"in i&&(typeof i.baseRevision!="string"||!Gs.test(i.baseRevision)))&&se("binding");let a="baseRevision"in i?{baseRevision:i.baseRevision}:{};return i.kind==="resource_put"?((!En(i,"baseRevision"in i?"baseRevision,doc,kind,mustNotExist,path":"doc,kind,mustNotExist,path")||typeof i.doc!="string"||typeof i.mustNotExist!="boolean")&&se("binding"),Object.freeze({kind:i.kind,path:i.path,doc:i.doc,...a,mustNotExist:i.mustNotExist})):((i.kind!=="resource_delete"||!En(i,"baseRevision"in i?"baseRevision,kind,path":"kind,path"))&&se("binding"),Object.freeze({kind:i.kind,path:i.path,...a}))}),r=new Set,o=e.readback.map(i=>((!i||typeof i!="object"||!En(i,"doc,path")||!Ed(i.path)||i.doc!==null&&typeof i.doc!="string"||r.has(i.path))&&se("binding"),r.add(i.path),Object.freeze({path:i.path,doc:i.doc})));for(let i of t){let a=o.find(c=>c.path===i.path);(!a||a.doc!==(i.kind==="resource_put"?i.doc:null))&&se("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 Ii.encode(JSON.stringify(s)).byteLength>ti&&se("binding"),s}function $t(n){let e=n;(!e||typeof e!="object"||!En(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"||!Gs.test(e.assessmentDigest)||typeof e.provisionDigest!="string"||!Gs.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>lo.operations||!Array.isArray(e.resourceReadback)||!e.resourceReadback.length||e.resourceReadback.length+e.sources.length>lo.readbacks)&&se("binding"),Object.hasOwn(e,"planKind")&&(e.planKind!=="configuration-only"||e.packs.length!==0||!e.resourceOps.length||e.resourceOps.some(p=>!p||p.kind!=="resource_put"||!["mdbase.yaml","mdbase.provisions.yaml"].includes(p.path)))&&se("binding");let t=new Set,r=e.packs.map(p=>((!p||typeof p!="object"||!En(p,"digest,id,version")||typeof p.id!="string"||!p.id.length||p.id.length>150||t.has(p.id)||typeof p.version!="string"||!p.version.length||p.version.length>256||typeof p.digest!="string"||!Gs.test(p.digest))&&se("binding"),t.add(p.id),Object.freeze({...p}))),o=new Set,s=e.resourceReadback.map(p=>((!p||typeof p!="object"||!En(p,"doc,path")||!Ed(p.path)||o.has(p.path)||p.doc!==null&&typeof p.doc!="string")&&se("binding"),o.add(p.path),Object.freeze({...p}))),i=e.resourceOps.map(p=>{(!p||typeof p!="object"||!Ed(p.path))&&se("binding");let d=Object.hasOwn(p,"baseRevision");d&&(typeof p.baseRevision!="string"||!Gs.test(p.baseRevision))&&se("binding"),p.kind==="resource_put"?(!En(p,d?"baseRevision,doc,kind,mustNotExist,path":"doc,kind,mustNotExist,path")||typeof p.doc!="string"||typeof p.mustNotExist!="boolean"||(p.mustNotExist?d:!d))&&se("binding"):(p.kind!=="resource_delete"||!d||!En(p,"baseRevision,kind,path"))&&se("binding");let u=s.find(f=>f.path===p.path);return(!u||u.doc!==(p.kind==="resource_put"?p.doc:null))&&se("binding"),Object.freeze({...p})}),a=new Set,c=e.sources.map(p=>((!p||typeof p!="object"||!En(p,"document,id,path")||!Ed(p.path)||o.has(p.path)||typeof p.id!="string"||!A_.test(p.id)||p.id==="00000000-0000-0000-0000-000000000000"||a.has(p.id)||typeof p.document!="string"||!p.document.length)&&se("binding"),o.add(p.path),a.add(p.id),Object.freeze({...p}))),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(r),resourceOps:Object.freeze(i),resourceReadback:Object.freeze(s),sources:Object.freeze(c)});return Ii.encode(JSON.stringify(l)).byteLength>ti&&se("binding"),l}function Jt(n,e,t=0){t>8&&se("binding");let r=n;(!r||typeof r!="object"||r.version!==1&&r.version!==2&&r.version!==3&&r.version!==4||!En(r,r.version===1?"mutationId,ops,phase,scope,version":r.version===4?"mutationId,phase,plan,previous,scope,version":"mutationId,phase,plan,scope,version")||typeof r.mutationId!="string"||!A_.test(r.mutationId)||r.mutationId==="00000000-0000-0000-0000-000000000000"||!(Rd.includes(r.phase)||r.phase==="rejected"&&(r.version===3||r.version===4)))&&se("recovery_required");let o=__(r.scope);if(JSON.stringify(o)!==JSON.stringify(e)&&se("binding"),r.version===1)return Object.freeze({version:1,scope:o,mutationId:r.mutationId,ops:Aj(r.ops),phase:r.phase});if(r.version===4){let i=Jt(r.previous,e,t+1);i.phase!=="verified"&&se("recovery_required");for(let l=i;l.mutationId===r.mutationId&&se("binding"),l.version===4;)l=l.previous;let a=$t(r.plan);a.resourceOps.some(l=>l.kind!=="resource_put"||!l.mustNotExist&&!["mdbase.yaml","mdbase.lock.yaml","mdbase.provisions.yaml"].includes(l.path))&&se("binding");let c=Object.freeze({version:4,scope:o,mutationId:r.mutationId,plan:a,phase:r.phase,previous:i});return Ii.encode(JSON.stringify({...c,phase:"confirmed"})).byteLength>ti&&se("binding"),c}if(r.version===3){$t(r.plan).sourcePolicy!==void 0&&se("binding");let i=Object.freeze({version:3,scope:o,mutationId:r.mutationId,plan:$t(r.plan),phase:r.phase});return Ii.encode(JSON.stringify({...i,phase:"confirmed"})).byteLength>ti&&se("binding"),i}let s=Object.freeze({version:2,scope:o,mutationId:r.mutationId,plan:Ys(r.plan),phase:r.phase});return Ii.encode(JSON.stringify({...s,phase:"confirmed"})).byteLength>ti&&se("binding"),s}function jm(n){return n.version!==2&&se("recovery_required"),n}function kj(n,e,t){return t(),globalThis.indexedDB||se("recovery_required"),new Promise((r,o)=>{let s=indexedDB.open(n,1),i=!1,a=()=>{i=!0,e.removeEventListener("abort",a);try{s.transaction?.abort()}catch{}o(new qn("recovery_required"))};e.addEventListener("abort",a,{once:!0}),s.onupgradeneeded=()=>{try{t(),(i||s.result.objectStoreNames.length)&&se("recovery_required"),s.result.createObjectStore(Kl)}catch{a()}},s.onerror=s.onblocked=a,s.onsuccess=()=>{e.removeEventListener("abort",a);try{t(),(i||s.result.objectStoreNames.length!==1||!s.result.objectStoreNames.contains(Kl))&&se("recovery_required"),r(s.result)}catch{s.result.close(),o(new qn("recovery_required"))}}})}var Kl,Rd,A_,ti,Gs,Ii,qn,Wl,Js=I(()=>{"use strict";At();tn();v_();Kl="original-model-operation",Rd=["prepared","attempted","confirmed","verified"],A_=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,ti=lo.plaintextBytes,Gs=/^sha256:[0-9a-f]{64}$/,Ii=new TextEncoder,qn=class extends Error{constructor(t){super("Preserve the original collection setup operation.");this.reason=t}reason};Wl=class{constructor(e){this.owner=e;this.scope=__(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)))&&se("binding"),this.current=e.isCurrent,this.pins=JSON.stringify([e.databaseName,e.applicationNamespace,e.appOrigin,e.cpOrigin]);let t=new URL(e.appOrigin),r=new URL(e.cpOrigin);(!dt(e.appOrigin)||kt(t)!==e.appOrigin||r.origin!==e.cpOrigin||r.protocol!=="https:"&&!!1)&&se("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(__(this.owner.scope))===this.binding}catch{}t||(this.stopped=!0,se("fenced"))}async exclusive(e,t){this.check(e);let r=this.turn,o,s=new Promise(a=>{o=a});this.turn=r.then(()=>s);let i;try{await new Promise((c,l)=>{let p=()=>l(e.reason);e.addEventListener("abort",p,{once:!0}),r.then(()=>{e.removeEventListener("abort",p),c()})}),this.check(e),i=await kj(this.owner.databaseName,e,()=>this.check(e)),this.check(e);let a=await t(i);return this.check(e),a}finally{i?.close(),o()}}read(e,t){return this.check(t),new Promise((r,o)=>{let s=e.transaction(Kl,"readonly"),i=s.objectStore(Kl).get(this.namespace),a=()=>s.abort();t.addEventListener("abort",a,{once:!0}),s.onabort=s.onerror=()=>{t.removeEventListener("abort",a),o(new qn("recovery_required"))},s.oncomplete=()=>{t.removeEventListener("abort",a),r(i.result)}})}aad(e){return Ii.encode(JSON.stringify([this.namespace,1,e]))}async unwrap(e,t){if(this.check(t),e===void 0)return null;(!e||!En(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>ti+2048)&&se("recovery_required");let r;try{r=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(r));return(o?.version===2||o?.version===3||o?.version===4)&&r.byteLength>ti&&se("recovery_required"),Jt(o,this.scope)}catch(o){throw o instanceof qn||t.aborted?o:new qn("recovery_required")}finally{r?.fill(0)}}async commit(e,t,r,o){this.check(o);let s=(t?.revision??0)+1;Number.isSafeInteger(s)||se("fenced");let i=t?.key??await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),a=crypto.getRandomValues(new Uint8Array(12)),c=Ii.encode(JSON.stringify(r));c.byteLength>ti&&(c.fill(0),se("binding"));let l;try{l=await crypto.subtle.encrypt({name:"AES-GCM",iv:a,additionalData:this.aad(s)},i,c)}finally{c.fill(0)}this.check(o);try{await new Promise((p,d)=>{let u=e.transaction(Kl,"readwrite",{durability:"strict"}),f=()=>u.abort();o.addEventListener("abort",f,{once:!0}),u.onerror=u.onabort=()=>{o.removeEventListener("abort",f),d(new qn("outcome_unknown"))},u.oncomplete=()=>{o.removeEventListener("abort",f),p()};let h=u.objectStore(Kl),m=h.get(this.namespace);m.onsuccess=()=>{try{this.check(o);let w=m.result;if(w===void 0!=(t===void 0)||w&&w.revision!==t?.revision){u.abort();return}h.put({version:1,revision:s,key:i,iv:a,ciphertext:l},this.namespace)}catch{u.abort()}}})}catch(p){throw this.stopped=!0,p}return this.check(o),r}load(e){return this.exclusive(e,async t=>this.unwrap(await this.read(t,e),e))}prepare(e,t){let r=Ys(e);return Ii.encode(JSON.stringify({version:2,scope:this.scope,mutationId:this.scope.collection,plan:r,phase:"confirmed"})).byteLength>ti&&se("binding"),this.exclusive(t,async o=>{let s=await this.read(o,t),i=await this.unwrap(s,t);if(i){let c=jm(i);return JSON.stringify(c.plan)!==JSON.stringify(r)&&se("binding"),c}let a=jm(Jt({version:2,scope:this.scope,mutationId:crypto.randomUUID(),plan:r,phase:"prepared"},this.scope));return this.commit(o,s,a,t)})}prepareResources(e,t){let r=$t(e);return r.sourcePolicy!==void 0&&se("binding"),Ii.encode(JSON.stringify({version:3,scope:this.scope,mutationId:this.scope.collection,plan:r,phase:"confirmed"})).byteLength>ti&&se("binding"),this.exclusive(t,async o=>{let s=await this.read(o,t),i=await this.unwrap(s,t);if(i&&!(i.version===3&&i.phase==="rejected"))return i.version!==3&&se("recovery_required"),JSON.stringify(i.plan)!==JSON.stringify(r)&&se("binding"),i;let a=Jt({version:3,scope:this.scope,mutationId:crypto.randomUUID(),plan:r,phase:"prepared"},this.scope);return a.version!==3&&se("binding"),this.commit(o,s,a,t)})}prepareResourceRound(e,t,r){let o=$t(e);return this.exclusive(r,async s=>{let i=await this.read(s,r),a=await this.unwrap(i,r);a?.version===4&&a.phase==="rejected"&&(a=a.previous),(!a||a.mutationId!==t)&&se("binding"),a.phase!=="verified"&&se("recovery_required");let c=Jt({version:4,scope:this.scope,mutationId:crypto.randomUUID(),plan:o,phase:"prepared",previous:a},this.scope);return c.version!==4&&se("binding"),this.commit(s,i,c,r)})}advanceResource(e,t,r){return this.exclusive(r,async o=>{let s=await this.read(o,r),i=await this.unwrap(s,r);(!i||i.version!==3&&i.version!==4)&&se("recovery_required"),i.mutationId!==e&&se("binding"),i.phase==="rejected"&&se("recovery_required");let a=Rd.indexOf(i.phase),c=Rd.indexOf(t);if((c<a||c>a+1)&&se("recovery_required"),c===a)return i;let l=Jt({...i,phase:t},this.scope);return l.version!==3&&l.version!==4&&se("binding"),this.commit(o,s,l,r)})}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 r=>{let o=await this.read(r,t),s=await this.unwrap(o,t);if((!s||s.version!==3&&s.version!==4)&&se("recovery_required"),s.mutationId!==e&&se("binding"),s.phase==="rejected")return s;s.phase!=="attempted"&&se("recovery_required");let i=Jt({...s,phase:"rejected"},this.scope);return i.version!==3&&i.version!==4&&se("binding"),this.commit(r,o,i,t)})}advance(e,t,r){return this.exclusive(r,async o=>{let s=await this.read(o,r),i=await this.unwrap(s,r);i||se("recovery_required");let a=jm(i);a.mutationId!==e&&se("binding"),a.phase==="rejected"&&se("recovery_required");let c=Rd.indexOf(a.phase),l=Rd.indexOf(t);return(l<c||l>c+1)&&se("recovery_required"),l===c?a:this.commit(o,s,jm(Jt({...a,phase:t},this.scope)),r)})}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 TI(n){if(!n||typeof n!="object")return null;let e=n;if(typeof e.mutationId!="string"||!Sj.test(e.mutationId)||!Array.isArray(e.records)||!e.records.every(r=>typeof r=="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 Sj,MI=I(()=>{"use strict";Sj=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/});function Um(n){if(!n||typeof n!="object"||Array.isArray(n))throw Gn();let e=Object.getPrototypeOf(n);if(e!==Object.prototype&&e!==null)throw Gn();let t=Object.create(null);for(let r of Reflect.ownKeys(n)){if(typeof r!="string")throw Gn();let o=Object.getOwnPropertyDescriptor(n,r);if(!o||!("value"in o))throw Gn();o.enumerable&&(t[r]=o.value)}return t}function k_(n){if(typeof n!="string"||!n.trim()||Pj.encode(n).byteLength>4096)throw Gn();return n}function jI(n){let e=k_(n),t=new URL(e);if(!["http:","https:"].includes(t.protocol)||t.username||t.password)throw Gn();return e}function LI(n){let e=Um(n),t={issuer:jI(e.issuer),subject:k_(e.subject),name:k_(e.name)};if(e.account_id!==void 0){if(typeof e.account_id!="string"||!xj.test(e.account_id)||e.account_id==="00000000-0000-0000-0000-000000000000")throw Gn();t.account_id=e.account_id}return t}function Cj(n){if(!Array.isArray(n)||Object.getPrototypeOf(n)!==Array.prototype||n.length>1e3)throw Gn();for(let t of Reflect.ownKeys(n)){let r=Object.getOwnPropertyDescriptor(n,t);if(typeof t!="string"||!r||!("value"in r))throw Gn()}let e=[];for(let t=0;t<n.length;t++){let r=Object.getOwnPropertyDescriptor(n,String(t));if(!r||!("value"in r))throw Gn();e.push(r.value)}return e}function Hl(n,e){try{let t=Um(e);if(n==="identity"){let o=LI(t);return t.person_settings_url!==void 0&&(o.person_settings_url=jI(t.person_settings_url)),o}if(n!=="members")throw Gn();return{members:Cj(t.members).map(o=>{let s=Um(o),i=LI(s),a=s.role;if(a!=="owner"&&a!=="editor"&&a!=="viewer")throw Gn();return{...i,role:a}})}}catch{throw Gn()}}function UI(n,e){try{if(e instanceof oe)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 NI(n){let e=Um(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 Gn();return A(e.code,"people metadata request failed",e.reason)}function Nm(n,e){if(!e.peopleAuthority)throw A("upgrade_required","people metadata is unsupported","people_unsupported");return new gi(n,e.peopleAuthority)}var Gn,Pj,xj,qd=I(()=>{"use strict";ie();Sp();Gn=()=>A("unavailable","invalid people response","people_response"),Pj=new TextEncoder,xj=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/});function Or(n){if(!Xs(n)||Object.keys(n).some(r=>r!=="adopt"))throw ye("binding");if(n.adopt===void 0)return Object.freeze({});let e=n.adopt;if(!Xs(e)||Object.keys(e).length>256)throw ye("binding");let t={};for(let[r,o]of Object.entries(e)){if(!Oi(r)||typeof o!="string"||!Md.test(o))throw ye("binding");t[r]=o}return Object.freeze({adopt:Object.freeze(t)})}function Ij(n){if(!Xs(n)||!Td(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 ye("binding");let e=n.packs.map(o=>{if(!Xs(o)||!Td(o,"id,installedVersion,resources,status,version")||!Oi(o.id,150)||!Oi(o.version,128)||!["current","install","upgrade","downgrade","reconfigure","conflict"].includes(o.status)||!(o.installedVersion===null||Oi(o.installedVersion,128))||!Array.isArray(o.resources)||o.resources.length>1024)throw ye("binding");let s=o.resources.map(i=>{if(!Xs(i)||!Td(i,"action,installed,kind,mode,target",["currentDigest","reason"])||!Oi(i.target)||!Oi(i.kind,64)||i.mode!=="managed"&&i.mode!=="seed"||typeof i.installed!="boolean"||!["create","update","delete","adopt","preserve","conflict"].includes(i.action)||i.currentDigest!==void 0&&(typeof i.currentDigest!="string"||!Md.test(i.currentDigest))||i.reason!==void 0&&!Oi(i.reason,8192))throw ye("binding");return Object.freeze({...i})});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(!Xs(o)||!Td(o,"action,path,requirement",["value"])||!Oi(o.requirement,256)||!Oi(o.path,1024)||o.action!=="add"&&o.action!=="conflict"||!(o.value===void 0||o.value===null||["string","number","boolean"].includes(typeof o.value)))throw ye("binding");return Object.freeze({...o})}),r=n.staged.map(o=>{if(!Xs(o)||!Td(o,"document,path")||!Oi(o.path)||typeof o.document!="string"||o.document.length>512*1024)throw ye("binding");return Object.freeze({path:o.path,document:o.document})});return Object.freeze({packs:Object.freeze(e),configuration:Object.freeze(t),staged:Object.freeze(r)})}function Qs(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"||!Md.test(t.assessmentDigest))throw ye("binding");return Object.freeze({status:t.status,assessmentDigest:t.assessmentDigest,...e?{review:Ij(t.review)}:{}})}function DI(n){let e=Object.freeze({account:n.scope.account,installation:n.scope.installation,collection:n.scope.collection});if(Object.values(e).some(t=>!Gl.test(t)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/.test(t))||!Gl.test(n.generation))throw ye("binding");return{scope:e,generation:n.generation,binding:JSON.stringify([e.account,e.installation,e.collection])}}function Yl(n){try{return new TextEncoder().encode(JSON.stringify(n)).byteLength<=Oj}catch{return!1}}function zI(n,e,t){t=Object.freeze({...t});let r=DI(e),o=!1,s=null,i=null,a=0,c={},l=t.setupTurn,p=()=>{l?.owner===c&&(l.owner=null)},d=()=>{if(o||t.signal.aborted||t.isCurrent()!==!0)throw ye()},u=(m,w,b)=>{d();let g=[1,r.binding,r.generation,m,w,b];if(!Yl(g))throw ye("binding");n.postMessage(g)},f=()=>{if(!o){o=!0,p(),n.onmessage=n.onmessageerror=null;try{n.postMessage([1,r.binding,r.generation,0,"closed",null])}catch{}n.close()}},h=()=>{try{f()}finally{t.onProtocolFailure()}};return n.onmessageerror=h,n.onmessage=m=>{let w=m.data;try{if(d(),Array.isArray(w)&&w.length===6&&w[0]===1&&w[1]===r.binding&&w[2]===r.generation&&w[3]===0&&w[4]==="detach"&&w[5]===null){h();return}if(!Array.isArray(w)||w.length!==6||w[0]!==1||w[1]!==r.binding||w[2]!==r.generation||!Number.isInteger(w[3])||w[3]<1||w[3]>4294967295||!Tj.includes(w[4])||!Yl(w))throw ye("binding");let b=w[3],g=w[4],y=w[5];if(b<=a)throw ye("binding");if(a=b,Rj(g)){let k=null;try{let S=t.ledger?.()??null;if(!S)throw ye("recovery_required");if(g==="ledgerList"){if(y!==null)throw ye("binding");k=S.list(qj)}else if(g==="ledgerRemove"){if(typeof y!="string"||!Gl.test(y))throw ye("binding");S.remove(y)}else{if(!Array.isArray(y)||y.length!==2||typeof y[0]!="string"||!Gl.test(y[0])||typeof y[1]!="string"||y[1].length>Ej)throw ye("binding");S.put(y[0],y[1])}}catch(S){u(b,"error",S instanceof Rr?S.reason:"recovery_required");return}u(b,"result",k);return}if(s){u(b,"error","busy");return}if(l&&Mj(g)&&l.owner!==null&&l.owner!==c){u(b,"error","busy");return}let _=async()=>{d();let k=null;switch(g){case"resourcesAssess":case"resourcesApply":{let S=t.resourceSetup;if(!S)throw ye("recovery_required");if(g==="resourcesAssess"){let x=Array.isArray(y);if(x&&y.length!==2)throw ye("binding");k=x?Qs(await S.assess(y[0],t.signal,Or(y[1])),!0):Qs(await S.assess(y,t.signal))}else{if(!Array.isArray(y)||y.length!==2&&y.length!==3||typeof y[1]!="string"||!Md.test(y[1]))throw ye("binding");k=$t(y.length===3?await S.apply(y[0],y[1],t.signal,Or(y[2])):await S.apply(y[0],y[1],t.signal))}d();break}case"peopleIdentity":case"peopleMembers":{if(y!==null)throw ye("binding");let S=t.peopleAuthority;if(!S)throw A("upgrade_required","people metadata is unsupported","people_unsupported");let x=()=>{if(d(),S.collection!==r.scope.collection||S.isCurrent()!==!0)throw A("unauthenticated","people scope changed","people_fenced")};x();let P=Dm(g),C=await S.request(P,{signal:t.signal});if(x(),k=Hl(P,C),x(),!Yl([1,r.binding,r.generation,b,"result",k]))throw A("unavailable","invalid people response","people_response");break}case"load":if(y!==null)throw ye("binding");p(),k=await t.journal.load(t.signal);break;case"prepare":k=await t.journal.prepare(Ys(y),t.signal),d(),l&&(l.owner=c);break;case"prepareResources":k=await t.journal.prepareResources($t(y),t.signal),d(),l&&(l.owner=c);break;case"prepareResourceRound":if(!Array.isArray(y)||y.length!==2||typeof y[1]!="string")throw ye("binding");k=await t.journal.prepareResourceRound($t(y[0]),y[1],t.signal),d(),l&&(l.owner=c);break;case"assess":if(y!=="ready"&&y!=="setup_required")throw ye("binding");t.assess(y);break;case"foreground":if(typeof y!="boolean")throw ye("binding");t.foreground(y);break;case"recordResourceRejected":{if(typeof y!="string"||!Gl.test(y))throw ye("binding");let S=t.resourceSetup?.rejected;if(!S||await S(y,t.signal)!==!0)throw ye("recovery_required");d(),k=await t.journal.recordResourceRejected(y,t.signal),p();break}default:if(typeof y!="string"||!Gl.test(y))throw ye("binding");k=await t.journal[g](y,t.signal),(g==="recordVerified"||g==="recordResourceVerified")&&p()}d(),u(b,"result",k)},v=s=Promise.resolve().then(_).catch(k=>{if(!(o||t.signal.aborted))try{let S=Dm(g);u(b,"error",S?UI(S,k):k instanceof qn||k instanceof Rr?k.reason:"recovery_required")}catch{h()}});v.finally(()=>{s===v&&(s=null)}).catch(()=>{})}catch{h()}},n.start(),{close(){return i||(i=Promise.resolve().then(async()=>{f(),await s}),i)}}}function zm(n,e,t){t=Object.freeze({...t});let r=DI(e),o=!1,s=1,i=null,a=new Map,c=()=>{if(o||t.signal.aborted||t.isCurrent()!==!0)throw ye()},l=()=>{if(o)return;o=!0,t.signal.removeEventListener("abort",l),n.onmessage=n.onmessageerror=null;let _=i;i=null,_?.finish(void 0,ye(S_(_.action)?"fenced":"outcome_unknown"));for(let v of a.values())v(void 0,ye("fenced"));a.clear();try{n.postMessage([1,r.binding,r.generation,0,"detach",null])}catch{}try{n.close()}finally{t.onClose()}};t.signal.addEventListener("abort",l,{once:!0}),n.onmessageerror=l,n.onmessage=_=>{try{c();let v=_.data;if(!Array.isArray(v)||v.length!==6||v[0]!==1||v[1]!==r.binding||v[2]!==r.generation||!Yl(v))throw ye();if(v[3]===0&&v[4]==="closed"&&v[5]===null){l();return}let k=a.get(v[3]);if(k&&["result","error"].includes(v[4])){a.delete(v[3]),k(v[4]==="result"?v[5]:void 0,v[4]==="error"?ye(v[5]==="binding"?"binding":"recovery_required"):void 0);return}if(!i||v[3]!==i.id||!["result","error"].includes(v[4]))throw ye();let S=i,x=v[4]==="error"?Dm(S.action)&&v[5]!=="busy"?NI(v[5]):v[5]==="busy"?ye("busy"):ye(["binding","fenced","recovery_required","outcome_unknown"].includes(v[5])?v[5]:"recovery_required"):void 0;i=null,S.finish(v[4]==="result"?v[5]:void 0,x)}catch{l()}},n.start();let p=(_,v,k)=>{try{if(c(),k.aborted)throw ye();if(i)throw ye("busy");if(s>4294967295)throw l(),ye()}catch(x){return Promise.reject(x)}let S=s++;return new Promise((x,P)=>{let C=!1,R=()=>O(void 0,ye(S_(_)?"fenced":"outcome_unknown")),O=(E,j)=>{C||(C=!0,k.removeEventListener("abort",R),j?P(j):x(E))};i={id:S,action:_,finish:O},k.addEventListener("abort",R,{once:!0});try{let E=[1,r.binding,r.generation,S,_,v];if(!Yl(E))throw ye("binding");n.postMessage(E)}catch(E){i=null,O(void 0,E),l()}})},d=(_,v)=>{try{if(c(),s>4294967295)throw l(),ye()}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,r.binding,r.generation,k,_,v];if(!Yl(P))throw ye("binding");n.postMessage(P)}catch(P){a.delete(k),x(P)}})},u=Object.freeze({async list(){let _=await d("ledgerList",null);if(!Array.isArray(_))throw ye("recovery_required");return _.flatMap(v=>{try{let k=TI(JSON.parse(String(v)));return k?[k]:[]}catch{return[]}})},async put(_){await d("ledgerPut",[_.mutationId,JSON.stringify(_)])},async remove(_){await d("ledgerRemove",_)}}),f=(_,v)=>{let k=S_(_)?"fenced":"outcome_unknown";try{if(c(),v.aborted)throw ye()}catch{throw ye(k)}},h=async(_,v,k)=>{let S=await p(_,v,k);f(_,k);let x=Jt(S,r.scope);return f(_,k),x},m=async(_,v,k)=>{let S=await h(_,v,k);if(f(_,k),S.version!==2)throw ye("recovery_required");return S},w=async(_,v,k)=>{let S=await h(_,v,k);if(f(_,k),S.version!==3&&S.version!==4)throw ye("recovery_required");return S},b=Object.freeze({scope:r.scope,async load(_){let v=await p("load",null,_);f("load",_);let k=v===null?null:Jt(v,r.scope);return f("load",_),k},prepare:(_,v)=>m("prepare",Ys(_),v),recordAttempt:(_,v)=>m("recordAttempt",_,v),recordConfirmed:(_,v)=>m("recordConfirmed",_,v),recordVerified:(_,v)=>m("recordVerified",_,v),async prepareResources(_,v){let k=await w("prepareResources",$t(_),v);if(f("prepareResources",v),k.version!==3)throw ye("recovery_required");return k},async prepareResourceRound(_,v,k){let S=await w("prepareResourceRound",[$t(_),v],k);if(f("prepareResourceRound",k),S.version!==4)throw ye("recovery_required");return S},recordResourceAttempt:(_,v)=>w("recordResourceAttempt",_,v),recordResourceConfirmed:(_,v)=>w("recordResourceConfirmed",_,v),recordResourceVerified:(_,v)=>w("recordResourceVerified",_,v),recordResourceRejected:(_,v)=>w("recordResourceRejected",_,v)}),g=t.people===!0?Object.freeze({collection:r.scope.collection,isCurrent(){try{return c(),!0}catch{return!1}},async request(_,v={}){if(_!=="identity"&&_!=="members")throw A("invalid_request","invalid people resource");let k=_==="identity"?"peopleIdentity":"peopleMembers",S=v.signal??t.signal;try{let x=await p(k,null,S);f(k,S);let P=Hl(_,x);return f(k,S),P}catch(x){try{f(k,S)}catch{throw A("unauthenticated","people scope changed","people_fenced")}throw x instanceof Rr?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 p("resourcesAssess",S?[_,Or(k)]:_,v);f("resourcesAssess",v);let P=Qs(x,S);return f("resourcesAssess",v),P},async apply(_,v,k,S){if(!Md.test(v))throw ye("binding");let x=await p("resourcesApply",S===void 0?[_,v]:[_,v,Or(S)],k);f("resourcesApply",k);let P=$t(x);return f("resourcesApply",k),P}});return Object.freeze({journal:b,close:l,resourceSetup:y,ledger:u,...g?{peopleAuthority:g}:{},async assess(_,v){await p("assess",_,v),f("assess",v)},async setForeground(_,v){await p("foreground",_,v),f("foreground",v)}})}var Md,Xs,Oi,Td,Oj,Gl,Rr,ye,Rj,Ej,qj,Tj,Dm,S_,Mj,es=I(()=>{"use strict";Js();ie();MI();qd();Md=/^sha256:[0-9a-f]{64}$/,Xs=n=>!!n&&typeof n=="object"&&!Array.isArray(n)&&Object.getPrototypeOf(n)===Object.prototype,Oi=(n,e=4096)=>typeof n=="string"&&n.length>0&&n.length<=e;Td=(n,e,t=[])=>{let r=e.split(",");return r.every(o=>Object.hasOwn(n,o))&&Object.keys(n).every(o=>r.includes(o)||t.includes(o))};Oj=512*1024+8192,Gl=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,Rr=class extends Error{constructor(t){super(`app collection control: ${t}`);this.reason=t;this.name="AppCollectionControlError"}reason},ye=(n="fenced")=>new Rr(n);Rj=n=>n==="ledgerList"||n==="ledgerPut"||n==="ledgerRemove",Ej=16*1024,qj=448*1024,Tj=["load","prepare","prepareResources","prepareResourceRound","recordAttempt","recordConfirmed","recordVerified","recordResourceAttempt","recordResourceConfirmed","recordResourceVerified","recordResourceRejected","assess","foreground","peopleIdentity","peopleMembers","resourcesAssess","resourcesApply","ledgerList","ledgerPut","ledgerRemove"],Dm=n=>n==="peopleIdentity"?"identity":n==="peopleMembers"?"members":null,S_=n=>n==="load"||n==="assess"||n==="foreground"||n==="resourcesAssess"||n==="resourcesApply"||Dm(n)!==null,Mj=n=>n==="load"||n==="prepare"||n==="prepareResources"||n==="prepareResourceRound"||n.startsWith("record")});function Jl(n,e={}){return{description:"in-process",open(t,r){return new Promise((o,s)=>{let i;try{i=n.connect(e)}catch(c){s(A("unavailable",`runtime refused to connect: ${String(c)}`));return}let a=()=>{i.close(),s(A("cancelled","connect aborted"))};r?.addEventListener("abort",a,{once:!0}),i.onframe=c=>{r?.removeEventListener("abort",a),i.onframe=null,i.onclose=null,o({port:i,helloResponse:c})},i.onclose=c=>{r?.removeEventListener("abort",a),s(c??A("unavailable","runtime closed the session"))},i.send(t)})}}}var $m=I(()=>{"use strict";ie()});function P_(n){let e=[n.account,n.installation,n.collection];if(e.some(o=>typeof o!="string"||!Lj.test(o))||typeof n.isCurrent!="function")throw St();let t=JSON.stringify(e.map(o=>o.toLowerCase())),r=n.isCurrent.bind(n);return{binding:t,current:()=>{try{return r()===!0&&JSON.stringify([n.account,n.installation,n.collection].map(o=>o.toLowerCase()))===t}catch{return!1}}}}function VI(n,e,t,r,o){let s=P_(e),i=!1,a=()=>{if(!i){i=!0,n.onmessage=null,n.onmessageerror=null;try{n.postMessage([1,s.binding,"close"])}catch{}n.close(),r()}},c=()=>{if(i||!s.current())throw a(),St()};return n.onmessageerror=a,n.onmessage=l=>{try{c();let p=l.data;if(!Array.isArray(p)||p[0]!==1||p[1]!==s.binding)throw St();if(p.length===3&&p[2]==="close"){a();return}if(p.length===5&&jj.includes(p[2])){let u=p[2],f=p[3],h=p[4],m=$I(u);if(!o||!Number.isInteger(f)||f<1||f>4294967295||!(h instanceof Uint8Array)||!h.length||h.length>m)throw St();c(),o(u,f,h);return}if(p.length!==4||p[2]!=="frame"||!(p[3]instanceof Uint8Array)||p[3].length===0||p[3].length>Ro)throw St();let d=we(new Uint8Array(p[3]));c(),t(d)}catch{a()}},n.start(),{close:a,send(l){try{c();let p=ue(l);if(!p.length||p.length>Ro)throw St();c(),n.postMessage([1,s.binding,"frame",p],[p.buffer])}catch{throw a(),St()}},control(l,p,d){try{c();let u=$I(l);if(!Number.isInteger(p)||p<1||p>4294967295||!(d instanceof Uint8Array)||!d.length||d.length>u||!(d.buffer instanceof ArrayBuffer)||d.byteOffset!==0||d.byteLength!==d.buffer.byteLength)throw St();c(),n.postMessage([1,s.binding,l,p,d],[d.buffer])}catch{throw a(),St()}},current:c}}function Nj(n){if(!(n instanceof Map))return!1;let e=n;return e.get(0)===0&&Uj.has(e.get(2))}function Bm(n,e,t,r){if(!P_(t).current())throw St();let s;try{s=n.connect({collection:t.collection})}catch{throw e.close(),St()}let i;try{i=VI(e,t,c=>{if(s.send(c),r&&Nj(c))try{r(c.get(2))}catch{}},()=>s.close(),(c,l,p)=>{let d;try{if(c==="bases-request"&&typeof n.executeBases=="function")d=n.executeBases(s,p);else if((c==="bases-list-views-request"||c==="bases-read-view-source-request")&&typeof n.discoverBases=="function")d=n.discoverBases(s,c==="bases-list-views-request"?"list-views":"read-view-source",p);else throw St()}finally{p.fill(0)}try{i.current(),i.control(BI(c),l,d)}catch(u){throw d.byteLength&&d.fill(0),u}}),s.onframe=c=>{try{i.send(c)}catch{}},s.onclose=()=>i.close()}catch{throw s.close(),e.close(),St()}let a=Object.freeze({async assess(c,l,p){if(l.throwIfAborted(),i.current(),!n.setupResources)throw St();let d=p===void 0?n.setupResources(s,"assess",c):n.setupResources(s,"assess",c,void 0,p);return i.current(),l.throwIfAborted(),d},async apply(c,l,p,d){if(p.throwIfAborted(),i.current(),!n.setupResources)throw St();let u=d===void 0?n.setupResources(s,"apply",c,l):n.setupResources(s,"apply",c,l,d);return i.current(),p.throwIfAborted(),u},async rejected(c,l){if(l.throwIfAborted(),i.current(),!n.resourceRejected)return!1;let p=n.resourceRejected(s,c);return i.current(),l.throwIfAborted(),p}});return{close:()=>i.close(),resourceSetup:a}}function Vm(n,e){let t=P_(e),r=!1,o=!1,s,i=null,a=[],c=()=>A("cancelled","Bases read cancelled"),l=1;return{description:"app-local",close(){o=!0,s?s.close():n.close()},async open(p,d){if(r)throw St();if(!t.current()||d?.aborted||o)throw n.close(),St();r=!0;let u,f=s=VI(n,e,w=>u?.onframe?.(w),()=>{let w=i;i=null;let b=a.splice(0);w?.finish(void 0,c());for(let g of b)g.finish(void 0,c());u?.onclose?.(St())},(w,b,g)=>{if(!i||w!==i.response||b!==i.id)throw g.fill(0),St();let y=i;i=null,y.finish(g),h()});function h(){if(i||a.length===0)return;let w=a.shift();i=w;try{if(f.current(),i!==w){h();return}if(l>4294967295)throw f.close(),St();w.id=l++,f.control(w.kind,w.id,w.request)}catch(b){i===w&&(i=null),w.finish(void 0,b),h()}}let m=(w,b,g)=>{try{if(f.current(),g?.aborted)throw c();if(!(b instanceof Uint8Array)||!b.length||b.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(_){return Promise.reject(_)}let y=new Uint8Array(b);return new Promise((_,v)=>{let k=!1,S=(C,R)=>{if(i!==x&&y.byteLength&&y.fill(0),k){C?.byteLength&&C.fill(0);return}k=!0,g?.removeEventListener("abort",P),R!==void 0?v(R):_(C)},x={kind:w,request:y,response:BI(w),finish:S},P=()=>{let C=a.indexOf(x);C!==-1&&a.splice(C,1),i===x&&x.id===void 0&&(i=null),S(void 0,c())};a.push(x),g?.addEventListener("abort",P,{once:!0}),h()})};u={onframe:null,onclose:null,send:w=>f.send(w),close:()=>f.close(),readAppBases:(w,b)=>m("bases-request",w,b),readAppBasesDiscovery(w,b,g){return w!=="list-views"&&w!=="read-view-source"?Promise.reject(A("invalid_request","unknown native Bases read")):m(w==="list-views"?"bases-list-views-request":"bases-read-view-source-request",b,g)}};try{if(d?.aborted||o)throw St();return await Jl({connect:()=>u}).open(p,d)}catch{throw f.close(),St()}}}}var Lj,St,jj,BI,$I,Uj,Fm=I(()=>{"use strict";Ye();ie();$m();up();Lj=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/iu,St=()=>A("unavailable","app local facade unavailable; reopen and reconcile");jj=["bases-request","bases-response","bases-list-views-request","bases-list-views-response","bases-read-view-source-request","bases-read-view-source-response"],BI=n=>n==="bases-request"?"bases-response":n==="bases-list-views-request"?"bases-list-views-response":"bases-read-view-source-response",$I=n=>n.endsWith("request")?128*1024:n==="bases-response"?Ro:1024*1024;Uj=new Set(["submit","resolve_hold","open_upload","upload_chunk","commit_upload","abort_upload","fetch_file","read_file","ack_chunks"])});var Xl,x_=I(()=>{"use strict";Ye();ie();ve();Xl=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 r=null,o=null,s=t?.(()=>{if(!o)throw A("unavailable","runtime imports called before initialization");return o})??{},i=new TextDecoder,a={host_app_sql:(p,d)=>0n,host_now_ms:()=>Date.now(),host_local_date:(p,d,u,f)=>{try{let h=i.decode(new Uint8Array(r.buffer,d,u)),m=new Intl.DateTimeFormat("en-CA",{timeZone:h,year:"numeric",month:"2-digit",day:"2-digit"}).format(p);return/^\d{4}-\d{2}-\d{2}$/.test(m)?(new Uint8Array(r.buffer,f,10).set(new TextEncoder().encode(m)),10):0}catch{return 0}},host_default_zone:(p,d)=>{let u=new TextEncoder().encode(Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"),f=Math.min(u.length,d);return new Uint8Array(r.buffer,p,f).set(u.subarray(0,f)),f},host_random:(p,d)=>{let u=new Uint8Array(r.buffer,p,d);for(let f=0;f<d;f+=65536)globalThis.crypto.getRandomValues(u.subarray(f,f+65536))}},{instance:c}=await WebAssembly.instantiate(e,{env:{...a,...s}}),l=c.exports;return o=l,r=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),r=Number(e&0xffffffffn);if(r===0)return new Uint8Array(0);let o=new Uint8Array(this.x.memory.buffer,t,r).slice();return this.x.dealloc(t,r),o}info(){let e=we(this.takeOut(this.x.rt_info())),t=r=>{let[o,s]=r;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 r=e.queryExecutionProfile,o;if(r!==void 0){if(r!=="memory_constrained"&&r!=="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=r==="memory_constrained"?0:1}let s=Nn(new Map([[0,N(e.collection)],[1,N(e.replicaId)],[2,N(e.deviceId)],[3,e.mode==="local_only"?0:1],[4,e.signSecretKey],[5,e.kemSecretKey],[6,e.e2e??!1]])),i;try{let a=this.put(s);i=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(i.length)throw A("unavailable",`runtime failed to open: ${new TextDecoder().decode(i)}`);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,r=!1,o=[],s={onframe:null,onclose:null,send:i=>{if(r)throw A("unavailable","port closed");let a=ue(i);if(t===null){let c=e.grant&&e.clientKey?new Uint8Array([...N(e.grant),...e.clientKey]):new Uint8Array(0),l=we(this.takeOut(this.x.rt_hello(...this.put(c),...this.put(a)))),p=BigInt(l[0]),d=we(l[1]);queueMicrotask(()=>{s.onframe?.(d),p===0n&&s.end()}),p!==0n&&(t=p,this.ports.set(p,s),this.flush());return}this.x.rt_frame(t,...this.put(a)),this.flush()},close:()=>{r||(r=!0,t!==null&&(this.ports.delete(t),this.x.rt_close(t)),s.onclose?.())},deliver:i=>s.onframe?s.onframe(i):o.push(i),end:()=>{r||(r=!0,t!==null&&this.ports.delete(t),s.onclose?.())}};return s}sessionForPort(e){for(let[t,r]of this.ports)if(r===e)return t;return null}flush(){let e=this.takeOut(this.x.rt_poll());if(!e.length)return;let t=we(e),r=new Set(t.filter(o=>o[1]===null).map(o=>BigInt(o[0])));for(let o of t){let[s,i]=o,a=this.ports.get(BigInt(s));if(a)if(i===null)a.end();else{let c=we(i);if(r.has(BigInt(s))){if(c instanceof Map){let l=c;l.get(0)===2&&l.get(1)==="closed"&&a.deliver(c)}}else queueMicrotask(()=>a.deliver(c))}}}dispose(){this.timer&&clearInterval(this.timer);for(let e of[...this.ports.values()])e.close()}}});function Zs(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 Km(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}function KI(n){try{return n.server}catch{return null}}function Kj(n){try{return n.reason}catch{return null}}function Ld(n,e=globalThis.navigator?.onLine){let t=KI(n);if(pn(t)){let r=t.retryAfterMs;return t.status===429?{kind:"rate_limited",retryAfterMs:r}:t.status>=500?{kind:"server_busy",retryAfterMs:r}:t.status===401||t.status===403?{kind:"auth"}:null}return Kj(n)!=="unavailable"?null:e===!1?{kind:"offline"}:{kind:"unreachable"}}var FI,Dj,zj,$j,Bj,Pt,Vj,Fj,ea,Wm=I(()=>{"use strict";hi();Ye();ve();nr();FI=16*1024*1024,Dj=9*1024*1024,zj=64,$j=64*1024*1024,Bj=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};Vj=new Set(["read","head","subscribe","get_object","has_objects","put_object","get_snapshot"]),Fj=6;ea=class{constructor(e,t,r){this.runtime=e;this.transport=t;try{if(this.endpoint=Zs(r.endpoint),this.collection=N(r.collection),Zs(t.endpoint)!==this.endpoint||!Km(N(t.collection),this.collection))throw new Error}catch{throw new Pt("invalid_binding")}if(this.rounds=r.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(Zs(this.transport.endpoint)!==this.endpoint||!Km(N(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>zj)throw new Pt("invalid_call");let t=0,r=new Set,o=[];try{for(let s of e){if(Zs(s.endpoint)!==this.endpoint||!(s.frame instanceof Uint8Array)||s.frame.length>FI||s.sidecar!==void 0&&(!(s.sidecar instanceof Uint8Array)||s.sidecar.length>Dj))throw new Pt("invalid_call");if(t+=s.frame.length+(s.sidecar?.length??0),t>$j)throw new Pt("invalid_call");let i=we(s.frame);if(!(i instanceof Map))throw new Pt("invalid_call");let a=i;if(a.size!==4||a.get(0)!==0||!Bj.has(a.get(2)))throw new Pt("invalid_call");let c=Zs(a.get(1));if(r.has(c))throw new Pt("invalid_call");r.add(c);let l=a.get(3),p=l instanceof Map?l.get(0):void 0;if(!(p instanceof Uint8Array)||!Km(p,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||Zs(u.get(3))!==BigInt(s.sidecar.length)||u.has(5)||!(f instanceof Uint8Array)||!Km(f,Qe(s.sidecar)))throw new Pt("invalid_call")}let d=a.get(2)==="read"?{after:Zs(l.get(1)),control:l.get(3)===1}:void 0;o.push({id:c,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 r=[];try{for(let o=0;o<t.length;){if(!this.current())return{quiet:!0};let s=o+1,i=l=>Vj.has(t[l].method);if(i(o))for(;s<t.length&&s-o<Fj&&i(s);)s++;let a=t.slice(o,s);o=s;let c=a.map(l=>this.transport.send(l.call,{signal:this.abort.signal}).then(p=>({reply:p,error:null}),p=>({reply:null,error:p})));r.push(...c);for(let[l,p]of a.entries()){let{reply:d,error:u}=await c[l];if(d===null){if(!this.current())return{quiet:!0};let f=KI(u);if(pn(f)){let m=It(f);m&&(this.problem=f),(m||f.status===403&&f.code==="forbidden")&&(this.terminal??=f)}let h=Ld(u);h&&(this.health=h),this.runtime.logNoResponse(p.id);continue}try{if(!this.current())return{quiet:!0};if(!(d instanceof Uint8Array)||d.length>FI){this.runtime.logNoResponse(p.id);continue}if(this.runtime.acceptLogReply(p.id,d)!==!0)this.runtime.logNoResponse(p.id);else if(this.problem=null,this.health=null,p.read){let f=p.read.control?1:0;p.read.after>this.readAfter[f]&&(this.readAfter[f]=p.read.after,this.readAdvances++)}}finally{d instanceof Uint8Array&&d.fill(0)}}}}finally{for(let o of await Promise.all(r))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(()=>{})}}});function jd(n,e,t=0,r={nodes:0}){if(t>32||++r.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(i=>jd(i,e,t+1,r));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[i,a]of o){if(typeof i!="string"||s.has(i))throw A("invalid_request","invalid resource DATA");s.set(i,jd(a,e,t+1,r))}return e?s:Object.fromEntries(s)}function WI(n){if(!(n instanceof Uint8Array)||n.length===0||n.length>64*1024)throw L();return new Uint8Array(n)}function Yn(n){if((typeof n!="number"||!Number.isSafeInteger(n))&&typeof n!="bigint")throw L();let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw L();return e}function on(n){if(!(n instanceof Uint8Array)||n.length!==32)throw L();return n}var ts,Mt,L,HI,Ql,Hm=I(()=>{"use strict";Ye();ve();ie();x_();Zt();Wm();es();Js();ts=class extends Error{reason="account_key_proof_unavailable";constructor(){super("this app runtime cannot prove an account-key request"),this.name="AppAccountKeyProofUnavailableError"}},Mt=class extends Error{reason="strict_device_approval";constructor(){super("this account uses strict device approval; add this device from your desktop"),this.name="AppStrictDeviceApprovalError"}},L=()=>A("unavailable","app runtime unavailable; reopen and reconcile");HI=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]);Ql=class n extends Xl{constructor(t,r){super(t);this.sqlBinding=r}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,r){if(r.needsRecovery)throw L();return this.instantiateApp(t,r)}static async createDevice(t){return this.instantiateApp(t,null)}static async instantiateApp(t,r){let o={sql:r,exports:null,run:null},s=await this.load(t,a=>(o.exports=a,o.run=r?.import(a)??null,{host_app_sql:(c,l)=>o.run?.(c,l)??0n})),i=["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)||i.some(a=>typeof s[a]!="function"))throw L();return new n(s,o)}open(t){throw L()}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(),L()}}openAppConsuming(t){let r=null;try{if(this.attempted||this.deviceAttempted||!this.sql||this.sql.needsRecovery)throw L();this.attempted=!0;let o=Yn(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 L();let s=t.state==="e2e"?0:t.state==="cloud_copy"?1:-1,i=t.opened==="fresh"?0:t.opened==="existing"?1:t.opened==="unclean"?2:-1;if(s<0||i<0||typeof t.cloudCopyOptIn!="boolean"||s===1!==t.cloudCopyOptIn||(r=Nn(new Map([[0,3],[1,N(t.collection)],[2,N(t.replicaId)],[3,N(t.deviceId)],[4,o],[5,t.trustedRoots.map(on)],[6,t.trustedSigners.map(N)],[7,Pu(t.expectedGenesis)],[8,s],[9,t.cloudCopyOptIn],[10,on(t.signSecretKey)],[11,on(t.kemSecretKey)],[12,i],[13,t.sqliteVersion],[16,WI(t.policyPins)]])),r.length>64*1024)||this.guard(()=>this.takeOut(this.app.rt_app_open(...this.put(r)))).length)throw L();this.collection=t.collection,this.deviceId=t.deviceId,this.endpoint=o,this.active=!0,this.markOpened()}catch{throw this.retireLog(),this.fail(),L()}finally{r?.fill(0),t.signSecretKey?.fill(0),t.kemSecretKey?.fill(0)}}openUnsyncedConsuming(t){let r=null;try{if(this.attempted||this.deviceAttempted||!this.sql||this.sql.needsRecovery||typeof this.app.rt_app_open_local!="function"||(this.attempted=!0,!Number.isSafeInteger(t.sqliteVersion)||t.sqliteVersion<0||t.sqliteVersion>4294967295))throw L();let o=t.opened==="fresh"?0:t.opened==="existing"?1:t.opened==="unclean"?2:-1;if(o<0||(r=Nn(new Map([[0,1],[1,N(t.collection)],[2,N(t.replicaId)],[3,N(t.deviceId)],[12,o],[13,t.sqliteVersion]])),this.guard(()=>this.takeOut(this.app.rt_app_open_local(...this.put(r)))).length))throw L();this.collection=t.collection,this.deviceId=t.deviceId,this.active=!0,this.markOpened()}catch{throw this.fail(),L()}finally{r?.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 L();let r=super.connect(t),o=r.send.bind(r),s=r.close.bind(r);return r.send=i=>this.guard(()=>o(i)),r.close=()=>this.guard(()=>s()),r}executeBases(t,r){return this.readBases(t,r,"execute")}discoverBases(t,r,o){if(r!=="list-views"&&r!=="read-view-source")throw L();return this.readBases(t,o,r)}readBases(t,r,o){let s=this.sessionForPort(t),i=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 i!="function")throw L();if(!(r instanceof Uint8Array)||!r.length||r.length>128*1024)throw A("invalid_request","Bases request bytes exceed bound");let a=new Uint8Array(r);try{let c=this.guard(()=>{let l=Yn(i.call(this.app,s,...this.put(a))),p=Number(l&0xffffffffn);if(!p||p>(o==="execute"?16:1)*1024*1024)throw L();return this.takeOut(l)});if(!this.active||this.retired||this.sql.needsRecovery||this.sessionForPort(t)!==s)throw c.fill(0),L();return c}finally{a.fill(0)}}setupResources(t,r,o,s,i){let a=this.sessionForPort(t),c=this.app.rt_app_resources;if(!this.active||this.retired||!this.sql||this.sql.needsRecovery||a===null||typeof c!="function")throw A("unavailable","resource setup unsupported","resource_setup_unsupported");if(r!=="assess"&&r!=="apply"||r==="apply"&&(typeof s!="string"||!/^sha256:[0-9a-f]{64}$/.test(s)))throw L();let l=i!==void 0,p=[1,r==="apply"?1:0,jd(o,!0),s??null];l&&p.push(jd(Or(i),!0));let d=ue(p);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=Yn(c.call(this.app,a,...this.put(d))),w=Number(m&0xffffffffn);if(!w||w>512*1024)throw L();return this.takeOut(m)}),!this.active||this.retired||this.sql.needsRecovery||this.sessionForPort(t)!==a)throw L();let f=this.guard(()=>we(u));if(!Array.isArray(f)||f.length!==3||f[0]!==1||typeof f[1]!="boolean")throw L();if(f[1]===!1)throw A("unavailable","resource setup unavailable","resource_setup_unavailable");let h=jd(f[2],!1);return r==="assess"?Qs(h,l):$t(h)}finally{d.fill(0),u?.fill(0)}}resourceRejected(t,r){let o=null;try{let s=this.sessionForPort(t),i=this.app.rt_app_receipt_rejected;return!this.active||this.retired||s===null||typeof i!="function"||!/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/.test(r)?!1:(o=N(r),this.guard(()=>i.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,r,o){let s=null,i=null;try{let a=this.sessionForPort(t),c=r.collection,l=r.deviceId;if(!this.active||this.retired||a===null||c!==this.collection||r.isCurrent()!==!0||!(o instanceof Uint8Array)||o.length>64*1024)return null;s=new Uint8Array(o),i=N(l);let p=this.guard(()=>this.takeOut(this.app.rt_app_verify_handover(a,...this.put(i),...this.put(s))));if(p.length===0||this.sessionForPort(t)!==a||r.isCurrent()!==!0||r.collection!==c||r.deviceId!==l)return null;let d=this.guard(()=>Uu.dec(we(p)));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),i?.fill(0)}}bindCpConnector(t){let r=null;try{if(!this.active||this.retired||this.pump||this.cpPin||t.isCurrent()!==!0||t.deviceId!==this.deviceId||t.collection!==this.collection)throw L();let o=t.connectorId;if(r=N(o),r.every(s=>s===0)||this.guard(()=>this.app.rt_app_cp_bind_connector(...this.put(r)))!==1)throw L();this.connectorId=o,this.cpPin=t}catch{throw L()}finally{r?.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 L();let r=we(t);if(!(r instanceof Map))throw L();let o=r;if(o.size!==4||[0,1,2,3].some(i=>!o.has(i)))throw L();let s=i=>{let a=o.get(i);if(!(a instanceof Uint8Array)||a.length!==32||a.every(c=>c===0))throw L();return new Uint8Array(a)};return{m:o,identity:Object.freeze({signPublicKey:s(0),kemPublicKey:s(1),noisePublicKey:s(2)})}}openDeviceConsuming(t){let r=null;try{if(this.deviceAttempted||this.attempted||this.retired)throw L();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 L();let s=[this.connectorId,this.deviceId,this.installationId].map(N);if(s.some(l=>l.every(p=>p===0)))throw L();let i=t.opened;if(i.mode!=="fresh"&&i.mode!=="existing"||i.mode==="existing"&&(!(i.envelope instanceof Uint8Array)||!i.envelope.length||i.envelope.length>1024))throw L();r=Nn(new Map([[0,1],[1,s[0]],[2,s[1]],[3,s[2]],[4,i.mode==="fresh"?0:1],[5,on(t.signSecretKey)],[6,on(t.kemSecretKey)],[7,i.mode==="fresh"?new Uint8Array:new Uint8Array(i.envelope)]]));let a=this.guard(()=>this.takeOut(this.app.rt_app_device_open(...this.put(r))));if(!a.length||!this.deviceCurrent())throw L();let c=this.guard(()=>{let{m:l,identity:p}=this.publicResult(a),d=l.get(3);if(!(d instanceof Uint8Array)||!d.length||d.length>1024)throw L();return{...p,envelope:new Uint8Array(d)}});return this.publicIdentity={signPublicKey:new Uint8Array(c.signPublicKey),kemPublicKey:new Uint8Array(c.kemPublicKey),noisePublicKey:new Uint8Array(c.noisePublicKey)},this.noiseEnvelope=new Uint8Array(c.envelope),Object.freeze(c)}catch{throw this.retireLog(),L()}finally{r?.fill(0),t.signSecretKey?.fill(0),t.kemSecretKey?.fill(0)}}deviceCustodyCurrent(t,r){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&&r.envelope instanceof Uint8Array&&r.envelope.length===this.noiseEnvelope.length&&r.envelope.every((o,s)=>o===this.noiseEnvelope[s])&&["signPublicKey","kemPublicKey","noisePublicKey"].every(o=>r[o]instanceof Uint8Array&&r[o].length===32&&r[o].every((s,i)=>s===this.publicIdentity[o][i]))}catch{return!1}}acknowledgeDeviceRegistration(t){let r=null;try{if(!this.deviceCurrent()||this.active||this.deviceRegistered||!this.publicIdentity||t.connectorId!==this.connectorId||t.deviceId!==this.deviceId||t.installationId!==this.installationId)throw L();for(let o of["signPublicKey","kemPublicKey","noisePublicKey"])if(on(t[o]).some((s,i)=>s!==this.publicIdentity[o][i]))throw L();if(r=Nn(new Map([[0,N(t.connectorId)],[1,N(t.deviceId)],[2,N(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(r)))!==1||!this.deviceCurrent())throw L();this.deviceRegistered=!0}catch{throw this.retireLog(),L()}finally{r?.fill(0)}}prepareCloudCopyCollection(t){let r=null;try{if(t.approvalMode==="strict")throw new Mt;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 L();let o=N(t.collection);if(o.every(s=>s===0)||(r=Nn(new Map([[0,o],[1,t.purpose==="create"?0:1]])),this.guard(()=>this.app.rt_app_cloud_copy_pin(...this.put(r)))!==1||!this.cloudCopyCollectionCurrent(t)))throw L()}catch(o){throw this.retireLog(),o instanceof Mt?o:L()}finally{r?.fill(0)}}cloudCopyCollectionCurrent(t){try{let r=this.cloudSource;return this.deviceCurrent()&&!this.active&&this.deviceRegistered&&r!==null&&(!t||t===r)&&r.isCurrent===this.cloudCallback&&r.isCurrent()===!0&&r.connectorId===this.connectorId&&r.deviceId===this.deviceId&&r.installationId===this.installationId&&r.collection===this.cloudCollection&&r.purpose===this.cloudPurpose&&r.approvalMode==="password-ak1"}catch{return!1}}signCloudCopyCreate(t){return this.signCloudCopy(t,"create")}signCloudCopyJoin(t){return this.signCloudCopy(t,"join")}signCloudCopy(t,r){let o=null,s=null;try{if(this.cloudIssued||!this.cloudCopyCollectionCurrent()||this.cloudPurpose!==r||(this.cloudIssued=!0,o=new Uint8Array(on(t)),s=this.guard(()=>this.takeOut(r==="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 L();return s}catch{throw s?.fill(0),this.retireLog(),L()}finally{o?.fill(0)}}preparePrivateCollection(t,r){let o=null,s=null;try{if(t.approvalMode==="strict")throw new Mt;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 L();let i=N(t.collection);if(i.every(a=>a===0))throw L();if(r.mode==="fresh"){if(o=Nn(new Map([[0,i],[1,t.purpose==="create"?0:1]])),this.guard(()=>this.app.rt_app_private_collection_pin(...this.put(o)))!==1)throw L()}else if(r.mode==="existing"){let a=r.marker,c=this.publicIdentity;if(t.purpose!=="enrol"||!c||a.collection!==t.collection||a.connectorId!==this.connectorId||a.deviceId!==this.deviceId||a.installationId!==this.installationId||typeof a.acknowledged!="boolean")throw L();for(let p of["signPublicKey","kemPublicKey","noisePublicKey"])if(!HI(on(a[p]),c[p]))throw L();let l=new Uint8Array(on(a.sasCommitment));if(l.every(p=>p===0)||(s=l,o=Nn(new Map([[0,1],[1,i],[2,N(a.connectorId)],[3,N(a.deviceId)],[4,N(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 L()}else throw L();if(!this.privateCollectionCurrent())throw L();if(t.purpose==="enrol"){let a=this.guard(()=>this.takeOut(this.app.rt_app_private_enrol_commitment()));if(a.length!==32||a.every(c=>c===0)||s!==null&&!HI(a,s))throw L();this.sasCommitment=new Uint8Array(a)}}catch(i){throw this.retireLog(),i instanceof Mt?i:L()}finally{o?.fill(0)}}registeredDeviceReceipt(){if(!this.deviceCurrent()||!this.deviceRegistered||!this.publicIdentity)throw L();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 L();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 r=this.privateSource;return this.deviceCurrent()&&!this.active&&this.deviceRegistered&&r!==null&&r.isCurrent()===!0&&r.connectorId===this.connectorId&&r.deviceId===this.deviceId&&r.installationId===this.installationId&&r.collection===this.prospectiveCollection&&r.purpose===this.privatePurpose&&r.approvalMode==="password-ak1"}catch{return!1}}signPrivateCreate(t){let r=null;try{if(!this.privateCollectionCurrent()||this.privatePurpose!=="create")throw L();r=new Uint8Array(on(t));let o=this.guard(()=>this.takeOut(this.app.rt_app_private_create_sign(...this.put(r))));if(o.length!==64||!this.privateCollectionCurrent())throw L();return o}catch{throw this.retireLog(),L()}finally{r?.fill(0)}}signPrivateDeviceEnrol(t){let r=null;try{if(!this.privateCollectionCurrent()||this.privatePurpose!=="enrol"||!this.sasCommitment||this.privateEnrolAcknowledged)throw L();r=new Uint8Array(on(t));let o=this.guard(()=>this.takeOut(this.app.rt_app_private_device_enrol_sign(...this.put(r))));if(o.length!==64||!this.privateCollectionCurrent())throw L();return Object.freeze({signature:o,sasCommitment:new Uint8Array(this.sasCommitment)})}catch{throw this.retireLog(),L()}finally{r?.fill(0)}}adoptDevice(t,r){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 L();let s=WI(t.policyPins);if(r){if(this.sql||r.needsRecovery||!this.sqlBinding.exports)throw L();this.sqlBinding.sql=r,this.sqlBinding.run=r.import(this.sqlBinding.exports)}if(!this.sql||this.sql.needsRecovery)throw L();this.attempted=!0;let i=Yn(t.endpoint),a=t.state==="e2e"?0:t.state==="cloud_copy"?1:-1,c=t.opened==="fresh"?0:t.opened==="existing"?1:t.opened==="unclean"?2:-1;if(a<0||c<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=Nn(new Map([[0,4],[1,N(t.collection)],[2,N(t.replicaId)],[3,N(t.deviceId)],[4,i],[5,t.trustedRoots.map(on)],[6,t.trustedSigners.map(N)],[7,Pu(t.expectedGenesis)],[8,a],[9,t.cloudCopyOptIn],[10,null],[11,null],[12,c],[13,t.sqliteVersion],[14,N(this.connectorId)],[15,N(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 L();this.collection=t.collection,this.endpoint=i,this.active=!0,this.markOpened()}catch{throw this.retireLog(),this.fail(),L()}finally{o?.fill(0)}}signCpEnrol(t){let r=null;try{if(!this.deviceCurrent()||!this.publicIdentity||this.active||this.pump)throw this.retireLog(),L();r=new Uint8Array(on(t));let o=this.guard(()=>this.takeOut(this.app.rt_app_cp_enrol_sign(...this.put(r))));if(!this.deviceCurrent())throw this.retireLog(),L();if(!o.length)throw L();let{m:s,identity:i}=this.guard(()=>this.publicResult(o)),a=s.get(3);if(!(a instanceof Uint8Array)||a.length!==64||["signPublicKey","kemPublicKey","noisePublicKey"].some(c=>i[c].some((l,p)=>l!==this.publicIdentity[c][p])))throw L();return Object.freeze({...i,signature:new Uint8Array(a)})}catch{throw this.retireLog(),L()}finally{r?.fill(0)}}signCpLogToken(t){let r=null;try{if(!this.active||this.retired||!this.cpPin)throw L();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(),L();r=new Uint8Array(on(t));let i=this.guard(()=>this.takeOut(this.app.rt_app_cp_log_token_sign(...this.put(r))));if(i.length!==64)throw i.fill(0),L();return i}catch{throw L()}finally{r?.fill(0)}}bindLogTransport(t){try{if(!this.active||this.retired||this.pump||this.endpoint===null||this.collection===null||t.isCurrent()!==!0||Yn(t.endpoint)!==this.endpoint||t.collection!==this.collection)throw L()}catch{throw L()}let r=N(this.collection);if(this.guard(()=>this.app.rt_app_log_bind(this.endpoint,...this.put(r)))!==1)throw L();if(this.logGeneration=this.guard(()=>Yn(this.app.rt_app_log_generation())),this.logGeneration===0n)throw this.retireLog(),L();return this.pump=new ea(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,r){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 r!="string"||r.length===0||r.length>16*1024||/[^\x21-\x7e]/.test(r))return null;let s=new TextEncoder().encode(r);o=new Uint8Array(32+s.length),o.set(t,0),o.set(s,32),s.fill(0);let i=this.logGeneration,a=this.guard(()=>this.takeOut(this.app.rt_app_log_hello_sign(i,...this.put(o))));return a.length!==64?(a.fill(0),null):a}catch{return null}finally{o?.fill(0)}}async reconnectLogTransport(t){let r=this.pump,o=this.logGeneration,s=()=>this.active&&!this.retired&&this.pump===r&&r!==null&&this.transport===t&&t.isCurrent()===!0&&Yn(t.endpoint)===this.endpoint&&t.collection===this.collection;try{if(!s()||(await r.drainForAuthenticatedReconnect(),!s()))throw L();this.pump=null,this.transport=null;let i=N(this.collection);try{if(this.guard(()=>this.app.rt_app_log_reconnect(this.endpoint,...this.put(i)))!==1)throw L()}finally{i.fill(0)}if(this.logGeneration=this.guard(()=>Yn(this.app.rt_app_log_generation())),this.logGeneration<=o||!t.isCurrent()||this.retired||!this.active)throw L();return this.pump=new ea(this,t,{endpoint:this.endpoint,collection:this.collection}),this.transport=t,this.pump}catch{throw this.retireLog(),L()}}signLogHttp(t){let r=null;try{if(!this.active||!this.pump||!this.transport||this.logGeneration===0n||this.endpoint===null||t.path!=="/v1/rpc"||t.collection!==this.collection||Yn(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 L();r=Nn(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,Yn(t.originalCallId),...this.put(r))));if(o.length!==64)throw o.fill(0),L();return o}catch{throw L()}finally{r?.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 r=we(t);if(!Array.isArray(r)||r.length>64)throw L();return r.map(o=>{if(!(o instanceof Map))throw L();let s=o,i=s.get(0),a=s.get(1),c=s.get(2);if(Yn(i)!==this.endpoint||!(a instanceof Uint8Array)||c!==void 0&&!(c instanceof Uint8Array))throw L();return{endpoint:i,frame:a,...c!==void 0?{sidecar:c}:{}}})})}acceptLogReply(t,r){return!this.active||this.retired?!1:this.guard(()=>this.app.rt_app_log_reply(Yn(t),...this.put(r))===1)}logNoResponse(t){this.active&&!this.retired&&this.guard(()=>this.app.rt_app_log_no_response(Yn(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 r=this.transport;return r.isCurrent()!==!0||Yn(r.endpoint)!==this.endpoint||r.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 r=we(t);if(!(r instanceof Map))throw L();let o=r;if(o.size!==2||!o.has(0)||!o.has(1))throw L();let s=o.get(0),i=o.get(1);if(s===0||s===1){if(i!==null)throw L();return Object.freeze({state:s===0?"pending":"keyed"})}if(s!==2||typeof i!="string"||!["not_private","not_ready","not_enrolled","not_authorized","device_missing","enrolment_mismatch","not_keyed","no_wrap","inconsistent","failed","outcome_unknown"].includes(i))throw L();return Object.freeze({state:"refused",reason:i})}unlockAccountKeyConsuming(t,r){try{if(t.approvalMode==="strict")throw new Mt;if(!this.accountKeyCurrent(t))throw L();on(r);let o=this.guard(()=>this.accountKeyState(this.takeOut(this.app.rt_app_account_key_unlock(...this.put(r)))));if(!this.accountKeyCurrent(t))throw L();return o}catch(o){throw this.retireLog(),o instanceof Mt?o:L()}finally{r instanceof Uint8Array&&r.fill(0)}}setupAccountKeyDeviceConsuming(t,r){try{if(t.approvalMode==="strict")throw new Mt;if(!this.accountKeyCurrent(t))throw L();on(r);let o=this.guard(()=>this.accountKeyState(this.takeOut(this.app.rt_app_account_key_device_setup(...this.put(r)))));if(!this.accountKeyCurrent(t))throw L();return o.state==="refused"?o:Object.freeze({state:o.state==="keyed"?"recovery_keyed":"recovery_pending"})}catch(o){throw this.retireLog(),o instanceof Mt?o:L()}finally{r instanceof Uint8Array&&r.fill(0)}}get supportsAccountKeyFetchProof(){return typeof this.app.rt_app_account_key_fetch_sign=="function"}signAccountKeyFetch(t,r,o){let s=this.app.rt_app_account_key_fetch_sign;if(typeof s!="function")throw new ts;let i=null,a=null;try{if(t.approvalMode==="strict")throw new Mt;if(!this.accountKeyCurrent(t)||(a=N(r),a.every(l=>l===0)))throw L();i=Nn(new Map([[0,new Uint8Array(on(o))],[1,a]]));let c=this.guard(()=>this.takeOut(s(...this.put(i))));if(c.length!==64||!this.accountKeyCurrent(t))throw c.fill(0),L();return c}catch(c){throw this.retireLog(),c instanceof Mt?c:L()}finally{i?.fill(0),a?.fill(0)}}accountKeyStatus(t){try{if(!this.accountKeyCurrent(t))throw L();let r=this.guard(()=>this.accountKeyState(this.takeOut(this.app.rt_app_account_key_status())));if(!this.accountKeyCurrent(t))throw L();return r}catch{throw this.retireLog(),L()}}observations(){if(!this.active||this.retired)throw L();return this.guard(()=>{let t=we(this.takeOut(this.app.rt_app_observations()));if(!(t instanceof Map))throw L();let r=t;for(let o of[1,2,3,4])if(typeof r.get(o)!="boolean")throw L();return{status:Wi.dec(r.get(0)),keyringRebuilding:r.get(1),keyringRebuildFailed:r.get(2),snapshotInstallAvailable:r.get(3),requiresReopen:r.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()}}});function Xm(n){let e=n.manifest.requirements.files;return e?Object.freeze({required:Object.freeze([...n.files?.actions??[]]),optional:Object.freeze([...e.optional??[]])}):null}function Qm(n,e){return n.collections.find(t=>t.collectionId===e)?.fileActions??[]}function nO(n,e){let t=r=>n.required.includes(r)||n.optional.includes(r)&&e().includes(r);return Object.freeze({allows:t,check(r){if(!t(r))throw tO(r,n.optional.includes(r))}})}function rO(n,e,t,r){let o=e?.files,s=t?.reason;if(!Array.isArray(o)||!o.length||o.some(a=>!tU.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 i=[];for(let a of o)if(!n?.required.includes(a)){if(!n?.optional.includes(a))throw tO(a,!1);r.includes(a)||i.push(a)}return Object.freeze(i)}function iO(n,e,t){let r=n.grant?.actions??[...new Set([...e?.required??[],...t])];return Object.freeze({status:"granted",actions:Object.freeze([...r])})}function rU(n,e){return new Promise(t=>{let r=0,o=a=>{clearInterval(i),n.removeEventListener("abort",s),t(a)},s=()=>o(!1),i=setInterval(()=>{e.closed?o(!0):++r>=3&&o(!1)},500);n.addEventListener("abort",s,{once:!0})})}async function oO(n,e,t){let r=i=>{try{e.close()}catch{}return i},o;try{o=await n.start()}catch(i){if(t.aborted)return r(Jm);throw i}let s=o.fileAccess?.requestId;for(let i=!1;;){let a=n.native().fileAccess;if(!s||a?.requestId!==s)return r(Jm);if(a.state==="granted")return r(n.granted());if(a.state==="declined")return r(nU);if(a.state==="expired"||i||t.aborted||(i=await rU(t,e),t.aborted))return r(Jm);await n.poll(s).catch(()=>{})}}var tU,tO,Jm,nU,Zm=I(()=>{"use strict";ie();tU=["list","read","add","replace","move","delete"];tO=(n,e)=>e?A("forbidden",`File action ${n} needs requestAccess first`,"access_required"):A("forbidden",`File action ${n} is not declared`,"access_undeclared");Jm=Object.freeze({status:"cancelled"}),nU=Object.freeze({status:"declined"})});async function dO(n,e){try{return Object.freeze({outcome:"applied",snapshot:await n})}catch(t){if(X(t,"conflict")&&t.reason==="setup_changed")return Object.freeze({outcome:"changed",snapshot:e()});if(X(t,"outcome_unknown"))return Object.freeze({outcome:"unknown",snapshot:e()});throw t}}function cU(n){return n==="contract"?{key:"contract",the:"the shared format for this app's notes",bare:"shared format for this app's notes",many:"shared formats for this app's notes"}:n==="type"?{key:"type",the:"the note type for this app",bare:"note type for this app",many:"note types for this app"}:n==="schema"?{key:"schema",the:"the set of checks for this app's note properties",bare:"set of checks for this app's note properties",many:"sets of checks for this app's note properties"}:{key:"other",the:"the setup item this app needs",bare:"setup item this app needs",many:"setup items this app needs"}}function iy(n){if(n===void 0)return Object.freeze([]);if(!Array.isArray(n)||n.length>sU)throw new TypeError("setup records: at most 32 { path, document } entries");let e=new Set,t=new TextEncoder,r=0;return Object.freeze(n.map(o=>{let s=o?.path,i=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 i!="string"||!i.length||(r+=t.encode(i).length+t.encode(s).length)>aU)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:i})}))}function uO(n,e){return n.status!=="current"||n.refusal||e.facets.contracts.assessment?.status!=="setup_required"?n:Object.freeze({...n,status:"conflict",summary:pO,refusal:Object.freeze({code:"setup_unresolved",message:pO})})}function Nd(n,e){let t=n.review,r=n.status==="current"?"current":n.status==="conflict"?"conflict":"setup",o=[],s={},i=new Set(t.staged.map(w=>w.path)),a=new Map,c=0,l=!1,p=(w,b,g,y,_,v=1)=>{c+=v,_&&(l=!0);let k=a.get(w);k?(k.count+=v,k.targets.includes(g)||k.targets.push(g)):a.set(w,{kind:b,targets:[g],count:v,message:y})};for(let w of t.packs)for(let b of w.resources){let g=cU(b.kind),y=`T${g.the.slice(1)}`,_=b.kind==="contract"?", so other apps can work with them":"",v=k=>k===1?g.the:`${k} ${g.many}`;switch(b.action){case"create":p(`resource:create:${g.key}`,"create",b.target,k=>`Add ${v(k)}${_}.`,!1);break;case"update":p(`resource:update:${g.key}`,"update",b.target,k=>`Update ${v(k)}.`,!0);break;case"delete":p(`resource:delete:${g.key}`,"delete",b.target,k=>`Remove ${v(k)}, which this app no longer uses.`,!0);break;case"adopt":i.has(b.target)?p(`resource:adopt-replace:${g.key}`,"adopt",b.target,k=>k===1?`Replace ${g.the} with this app's version. Yours isn't kept.`:`Replace ${k} ${g.many} with this app's versions. Yours aren't kept.`,!0):p(`resource:adopt-match:${g.key}`,"adopt",b.target,k=>k===1?`Use your existing ${g.bare}, which already matches this app's.`:`Use your ${k} existing ${g.many}, which already match this app's.`,!1);break;case"preserve":case"conflict":{if(b.action==="preserve"&&b.reason===void 0)break;let k=b.mode==="seed",S=b.currentDigest!==void 0;S&&(s[b.target]=b.currentDigest),o.push({target:b.target,...S?{adoptable:{digest:b.currentDigest}}:{},message:S&&k?`Your ${g.bare} has changes that can't be combined with the version this app needs. You can replace it with this app's version.`:S&&b.installed?`${y} was changed after this app set it up. You can replace it with this app's version.`:S?`This collection already has a ${g.bare} that differs from the one this app needs. You can replace it with this app's version.`:b.installed?`${y} was changed after this app set it up, so it can't be updated automatically.`:`${y} can't be set up automatically.`});break}default:break}}for(let w of t.configuration){let b=dU(w.path);if(w.action==="add")if(b==="include")p("setting:include","setting",b,()=>"Include this app's files when reading the collection.",!0);else if(b==="record extensions"&&typeof w.value=="string"){let g=w.value.replace(/^\./,"");p(`setting:ext:${g}`,"setting",b,()=>`Read .${g} files as notes in this collection.`,!0)}else p("setting:other","setting",b,g=>g===1?"Adjust a collection setting this app needs.":`Adjust ${g} collection settings this app needs.`,!0);else o.push({target:b,message:"A collection setting differs from what this app needs, so it can't be changed automatically."})}let d=r==="current"?[]:e.records.map(w=>Object.freeze({path:w.path,action:w.free?"create":"skip"}));for(let w of d)w.action==="create"&&p(`record:${w.path}`,"record",w.path,()=>`Create the starter note "${lU(w.path)}".`,!1);if(e.promoted){let w=e.promoted;p("record:existing-files","record","Existing files",()=>`Recognize ${w} existing ${w===1?"file":"files"} as notes, preserving their contents.`,!0,1)}r==="setup"&&a.size===0&&o.length===0&&p("update:setup-record","update","Setup record",()=>"Update this collection's record of this app's setup. Your notes and note types stay as they are.",!0);let u=[...a.values()].map(w=>({kind:w.kind,target:w.targets.join(", "),message:w.message(w.count)}));r==="current"&&o.length&&(r="conflict");let f=(e.newer?.major.length??0)>0||t.packs.some(w=>w.installedVersion&&Ms(w.installedVersion,w.version)==="installed_newer_major"),h;r!=="current"&&!e.canManage?h={code:"setup_forbidden",message:"This app doesn't have permission to set up this collection."}:f?h={code:"installed_newer",message:"A newer version of this app set up this collection. Update the app to continue."}:o.length?h={code:"setup_conflict",message:o.length===Object.keys(s).length?`${o.length===1?"One item differs":`${o.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."}:d.some(w=>w.action==="create")&&!e.canCreateRecords&&(h={code:"setup_records_forbidden",message:"This app doesn't have permission to create notes in this collection."});let m=r==="current"?"Everything this app needs is already set up.":h?h.message:`This app will make ${pU(c,"change")} to this collection.${l?"":" Nothing already in it is changed."}`;return Object.freeze({status:r,canApply:r==="setup"&&h===void 0,digest:n.assessmentDigest,summary:m,changes:Object.freeze(u.map(w=>Object.freeze(w))),conflicts:Object.freeze(o.map(w=>Object.freeze(w))),adoptable:Object.freeze(s),packs:Object.freeze([...t.packs.map(w=>Object.freeze({id:w.id,version:w.version,status:w.status,...w.installedVersion?{installedVersion:w.installedVersion,relation:Ms(w.installedVersion,w.version)}:{}})),...(e.newer?.kept??[]).map(w=>Object.freeze({id:w.id,version:w.version,status:"current",installedVersion:w.installedVersion,relation:"installed_newer"}))]),staged:t.staged,records:Object.freeze(d),...h?{refusal:Object.freeze(h)}:{}})}var sU,aU,lU,pU,dU,pO,oy=I(()=>{"use strict";ie();Gf();sU=32,aU=256*1024,lU=n=>(n.split("/").pop()??n).replace(/\.(md|ya?ml|json)$/i,"");pU=(n,e,t=`${e}s`)=>`${n} ${n===1?e:t}`,dU=n=>(n.split("/").filter(Boolean).pop()??n).replace(/[_-]+/g," ");pO="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 L_(n){let e=typeof n=="number"&&Number.isInteger(n)&&n>=1e3&&n<=4999?n:null;return Object.freeze({closeCode:e,closeClass:e===null?"unknown":hU[e]??"other"})}function bO(n){try{let e=fe(n,"relayCloseCode");if(e!==void 0)return L_(e)}catch{}}var hU,j_=I(()=>{"use strict";vn();hU={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 wO(){throw A("unavailable","SDK release trust unavailable: package authenticated LAB or production inputs","application_release_trust_unavailable")}var vO=I(()=>{"use strict";ie()});function U_(n){return n instanceof Uint8Array||ArrayBuffer.isView(n)&&n.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in n&&n.BYTES_PER_ELEMENT===1}function ay(n,e=""){if(typeof n!="boolean")throw new TypeError(sy(e)+"expected boolean, got type="+typeof n);return n}function ta(n,e=""){if(typeof n!="number")throw new TypeError(sy(e)+"expected number, got "+typeof n);if(!Number.isSafeInteger(n)||n<0)throw new RangeError(sy(e)+"expected integer >= 0, got "+n);return n}function Et(n,e,t=""){if(U_(n)&&(e===void 0||n.length===e))return n;e!==void 0&&ta(e,"length");let r=U_(n),o=e!==void 0?` of length ${e}`:"",s=r?`length=${n.length}`:`type=${typeof n}`,i=sy(t)+"expected Uint8Array"+o+", got "+s;throw r?new RangeError(i):new TypeError(i)}function N_(n,e=!0){if(n.destroyed)throw new Error("hash was destroyed");if(e&&n.finished)throw new Error("digest() was already called")}function AO(n,e){Et(n,void 0,"output");let t=e.outputLen;if(!(n.length>=t))throw new RangeError('"output" expected length >= '+t)}function Ei(n){return new Uint32Array(n.buffer,n.byteOffset,Math.floor(n.byteLength/4))}function dr(...n){for(let e=0;e<n.length;e++)n[e].fill(0)}function mU(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function yU(n){return n<<24&4278190080|n<<8&16711680|n>>>8&65280|n>>>24&255}function gU(n){for(let e=0;e<n.length;e++)n[e]=yU(n[e]);return n}function bU(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 kO(n,e){if(bU(n,e)&&n.byteOffset<e.byteOffset)throw new Error("complex overlap of input and output is not supported")}function SO(n,e){return _O(n,"defaults"),_O(e,"opts"),Object.assign(n,e)}function PO(n,e){if(n=Et(n),e=Et(e),n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r++)t|=n[r]^e[r];return t===0}function xO(n,e,t){let r=e,o=t||(()=>[]),s=(a,c)=>r(c,...o(a)).update(a).digest(),i=r(new Uint8Array(n),...o(new Uint8Array(0)));return s.outputLen=i.outputLen,s.blockLen=i.blockLen,s.create=(a,...c)=>r(a,...c),s}function Dd(n,e,t=!0){if(e===void 0)return new Uint8Array(n);if(Et(e,n,"output"),t&&!zd(e))throw new Error("invalid output, must be aligned");return e}function CO(n,e,t){ta(n),ta(e),ay(t);let r=new Uint8Array(16),o=mU(r);return o.setBigUint64(0,BigInt(e),t),o.setBigUint64(8,BigInt(n),t),r}function zd(n){return n.byteOffset%4===0}function ec(n){return Uint8Array.from(Et(n))}var sy,_O,Er,ur,D_,ly=I(()=>{/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */sy=n=>n?`"${n}" `:"";_O=(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;ur=Er?n=>n:gU;D_=(n,e)=>{function t(r,...o){if(Et(r,void 0,"key"),n.nonceLength!==void 0){let d=o[0];Et(d,n.varSizeNonce?void 0:n.nonceLength,"nonce")}let s=n.tagLength,i=n.nonceLength!==void 0?1:0;if(!n.withAAD){for(let d=i;d<o.length;d++)if(U_(o[d]))throw new Error("AAD not supported")}n.withAAD&&o[i]!==void 0&&Et(o[i],void 0,"AAD");let a=e(r,...o),c=(d,u)=>{if(u!==void 0){if(d!==2)throw new Error("cipher output not supported");Et(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,Et(d,void 0,"data"),c(a.encrypt.length,u),a.encrypt(d,u)},decrypt(d,u){if(Et(d,void 0,"data"),s&&d.length<s)throw new Error('"ciphertext" expected length >= tagLength='+s);return c(a.decrypt.length,u),a.decrypt(d,u)}}}return Object.assign(t,n),t}});function $e(n,e){return n<<e|n>>>32-e}function AU(n,e,t,r,o,s,i,a){let c=o.length,l=new Uint8Array($d),p=Ei(l),d=Er&&zd(o)&&zd(s),u=d?Ei(o):IO,f=d?Ei(s):IO;if(!Er){for(let h=0;h<c;i++){if(n(e,t,r,p,i,a),ur(p),i>=z_)throw new Error("arx: counter overflow");let m=Math.min($d,c-h);for(let w=0,b;w<m;w++)b=h+w,s[b]=o[b]^l[w];h+=m}return}for(let h=0;h<c;i++){if(n(e,t,r,p,i,a),i>=z_)throw new Error("arx: counter overflow");let m=Math.min($d,c-h);if(d&&m===$d){let w=h/4;if(h%4!==0)throw new Error("arx: invalid block position");for(let b=0,g;b<_U;b++)g=w+b,f[g]=u[g]^p[b];h+=$d;continue}for(let w=0,b;w<m;w++)b=h+w,s[b]=o[b]^l[w];h+=m}}function $_(n,e){let{allowShortKeys:t,extendNonceFn:r,counterLength:o,counterRight:s,rounds:i}=SO({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof n!="function")throw new Error("core must be a function");return ta(o),ta(i),ay(s),ay(t),(a,c,l,p,d=0)=>{Et(a,void 0,"key"),Et(c,void 0,"nonce"),Et(l,void 0,"data");let u=l.length,f=p!==void 0;if(p=Dd(u,p,!1),f&&kO(l,p),ta(d),d<0||d>=z_)throw new Error("arx: counter overflow");let h=[],m=a.length,w,b;if(m===32)h.push(w=ec(a)),b=vU;else if(m===16&&t)w=new Uint8Array(32),w.set(a),w.set(a,16),b=wU,h.push(w);else throw Et(a,32,"arx key"),new Error("invalid key size");(!Er||!zd(c))&&h.push(c=ec(c));let g=Ei(w);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");let v=c.subarray(0,16);if(Er)r(b,g,Ei(v),g);else{let k=ur(Uint32Array.from(b));r(k,g,Ei(v),g),dr(k),ur(g)}c=c.subarray(16)}else Er||ur(g);let y=16-o;if(y!==c.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){let v=new Uint8Array(12);v.set(c,s?0:12-c.length),c=v,h.push(c)}let _=ur(Ei(c));try{return AU(n,b,g,_,l,p,d,i),p}finally{dr(...h)}}}var OO,wU,vU,$d,_U,z_,IO,RO=I(()=>{ly();OO=n=>Uint8Array.from(n.split(""),e=>e.charCodeAt(0)),wU=ur(Ei(OO("expand 16-byte k"))),vU=ur(Ei(OO("expand 32-byte k")));$d=64,_U=16,z_=2**32-1,IO=Uint32Array.of()});function sn(n,e){return n[e++]&255|(n[e++]&255)<<8}var B_,EO,qO=I(()=>{ly();B_=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=ec(Et(e,32,"key"));let t=sn(e,0),r=sn(e,2),o=sn(e,4),s=sn(e,6),i=sn(e,8),a=sn(e,10),c=sn(e,12),l=sn(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|r<<3)&8191,this.r[2]=(r>>>10|o<<6)&7939,this.r[3]=(o>>>7|s<<9)&8191,this.r[4]=(s>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let p=0;p<8;p++)this.pad[p]=sn(e,16+2*p)}process(e,t,r=!1){let o=r?0:2048,{h:s,r:i}=this,a=i[0],c=i[1],l=i[2],p=i[3],d=i[4],u=i[5],f=i[6],h=i[7],m=i[8],w=i[9],b=sn(e,t+0),g=sn(e,t+2),y=sn(e,t+4),_=sn(e,t+6),v=sn(e,t+8),k=sn(e,t+10),S=sn(e,t+12),x=sn(e,t+14),P=s[0]+(b&8191),C=s[1]+((b>>>13|g<<3)&8191),R=s[2]+((g>>>10|y<<6)&8191),O=s[3]+((y>>>7|_<<9)&8191),E=s[4]+((_>>>4|v<<12)&8191),j=s[5]+(v>>>1&8191),B=s[6]+((v>>>14|k<<2)&8191),D=s[7]+((k>>>11|S<<5)&8191),J=s[8]+((S>>>8|x<<8)&8191),V=s[9]+(x>>>5|o),U=0,ce=U+P*a+C*(5*w)+R*(5*m)+O*(5*h)+E*(5*f);U=ce>>>13,ce&=8191,ce+=j*(5*u)+B*(5*d)+D*(5*p)+J*(5*l)+V*(5*c),U+=ce>>>13,ce&=8191;let ee=U+P*c+C*a+R*(5*w)+O*(5*m)+E*(5*h);U=ee>>>13,ee&=8191,ee+=j*(5*f)+B*(5*u)+D*(5*d)+J*(5*p)+V*(5*l),U+=ee>>>13,ee&=8191;let te=U+P*l+C*c+R*a+O*(5*w)+E*(5*m);U=te>>>13,te&=8191,te+=j*(5*h)+B*(5*f)+D*(5*u)+J*(5*d)+V*(5*p),U+=te>>>13,te&=8191;let Ce=U+P*p+C*l+R*c+O*a+E*(5*w);U=Ce>>>13,Ce&=8191,Ce+=j*(5*m)+B*(5*h)+D*(5*f)+J*(5*u)+V*(5*d),U+=Ce>>>13,Ce&=8191;let et=U+P*d+C*p+R*l+O*c+E*a;U=et>>>13,et&=8191,et+=j*(5*w)+B*(5*m)+D*(5*h)+J*(5*f)+V*(5*u),U+=et>>>13,et&=8191;let $=U+P*u+C*d+R*p+O*l+E*c;U=$>>>13,$&=8191,$+=j*a+B*(5*w)+D*(5*m)+J*(5*h)+V*(5*f),U+=$>>>13,$&=8191;let Y=U+P*f+C*u+R*d+O*p+E*l;U=Y>>>13,Y&=8191,Y+=j*c+B*a+D*(5*w)+J*(5*m)+V*(5*h),U+=Y>>>13,Y&=8191;let K=U+P*h+C*f+R*u+O*d+E*p;U=K>>>13,K&=8191,K+=j*l+B*c+D*a+J*(5*w)+V*(5*m),U+=K>>>13,K&=8191;let Z=U+P*m+C*h+R*f+O*u+E*d;U=Z>>>13,Z&=8191,Z+=j*p+B*l+D*c+J*a+V*(5*w),U+=Z>>>13,Z&=8191;let _e=U+P*w+C*m+R*h+O*f+E*u;U=_e>>>13,_e&=8191,_e+=j*d+B*p+D*l+J*c+V*a,U+=_e>>>13,_e&=8191,U=(U<<2)+U|0,U=U+ce|0,ce=U&8191,U=U>>>13,ee+=U,s[0]=ce,s[1]=ee,s[2]=te,s[3]=Ce,s[4]=et,s[5]=$,s[6]=Y,s[7]=K,s[8]=Z,s[9]=_e}finalize(){let{h:e,pad:t}=this,r=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,r[0]=e[0]+5,o=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+o,o=r[a]>>>13,r[a]&=8191;r[9]-=8192;let s=(o^1)-1;for(let a=0;a<10;a++)r[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|r[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 i=e[0]+t[0];e[0]=i&65535;for(let a=1;a<8;a++)i=(e[a]+t[a]|0)+(i>>>16)|0,e[a]=i&65535;dr(r)}update(e){N_(this),Et(e),e=ec(e);let{buffer:t,blockLen:r}=this,o=e.length;for(let s=0;s<o;){let i=Math.min(r-this.pos,o-s);if(i===r){for(;r<=o-s;s+=r)this.process(e,s);continue}t.set(e.subarray(s,s+i),this.pos),this.pos+=i,s+=i,this.pos===r&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,dr(this.h,this.r,this.buffer,this.pad)}digestInto(e){N_(this),AO(e,this),this.finished=!0;let{buffer:t,h:r}=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 i=0;i<8;i++)e[s++]=r[i]>>>0,e[s++]=r[i]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}},EO=xO(32,n=>new B_(n))});function V_(n,e,t,r,o,s=20){let i=n[0],a=n[1],c=n[2],l=n[3],p=e[0],d=e[1],u=e[2],f=e[3],h=e[4],m=e[5],w=e[6],b=e[7],g=o,y=t[0],_=t[1],v=t[2],k=i,S=a,x=c,P=l,C=p,R=d,O=u,E=f,j=h,B=m,D=w,J=b,V=g,U=y,ce=_,ee=v;for(let Ce=0;Ce<s;Ce+=2)k=k+C|0,V=$e(V^k,16),j=j+V|0,C=$e(C^j,12),k=k+C|0,V=$e(V^k,8),j=j+V|0,C=$e(C^j,7),S=S+R|0,U=$e(U^S,16),B=B+U|0,R=$e(R^B,12),S=S+R|0,U=$e(U^S,8),B=B+U|0,R=$e(R^B,7),x=x+O|0,ce=$e(ce^x,16),D=D+ce|0,O=$e(O^D,12),x=x+O|0,ce=$e(ce^x,8),D=D+ce|0,O=$e(O^D,7),P=P+E|0,ee=$e(ee^P,16),J=J+ee|0,E=$e(E^J,12),P=P+E|0,ee=$e(ee^P,8),J=J+ee|0,E=$e(E^J,7),k=k+R|0,ee=$e(ee^k,16),D=D+ee|0,R=$e(R^D,12),k=k+R|0,ee=$e(ee^k,8),D=D+ee|0,R=$e(R^D,7),S=S+O|0,V=$e(V^S,16),J=J+V|0,O=$e(O^J,12),S=S+O|0,V=$e(V^S,8),J=J+V|0,O=$e(O^J,7),x=x+E|0,U=$e(U^x,16),j=j+U|0,E=$e(E^j,12),x=x+E|0,U=$e(U^x,8),j=j+U|0,E=$e(E^j,7),P=P+C|0,ce=$e(ce^P,16),B=B+ce|0,C=$e(C^B,12),P=P+C|0,ce=$e(ce^P,8),B=B+ce|0,C=$e(C^B,7);let te=0;r[te++]=i+k|0,r[te++]=a+S|0,r[te++]=c+x|0,r[te++]=l+P|0,r[te++]=p+C|0,r[te++]=d+R|0,r[te++]=u+O|0,r[te++]=f+E|0,r[te++]=h+j|0,r[te++]=m+B|0,r[te++]=w+D|0,r[te++]=b+J|0,r[te++]=g+V|0,r[te++]=y+U|0,r[te++]=_+ce|0,r[te++]=v+ee|0}function kU(n,e,t,r){let o=Er?n:ur(n.slice(0,4)),s=Er?e:ur(e.slice(0,8)),i=Er?t:ur(t.slice(0,4)),a=new Uint32Array(16);V_(o,s,i.subarray(1),a,i[0]);let c=0;r[c++]=a[0]-o[0]|0,r[c++]=a[1]-o[1]|0,r[c++]=a[2]-o[2]|0,r[c++]=a[3]-o[3]|0,r[c++]=a[12]-i[0]|0,r[c++]=a[13]-i[1]|0,r[c++]=a[14]-i[2]|0,r[c++]=a[15]-i[3]|0,ur(r),Er||dr(o,s,i),dr(a)}function MO(n,e,t,r,o){o!==void 0&&Et(o,void 0,"AAD");let s=n(e,t,CU),i=CO(r.length,o?o.length:0,!0),a=EO.create(s);o&&TO(a,o),TO(a,r),a.update(i);let c=a.digest();return dr(s,i),c}var SU,PU,xU,TO,CU,LO,F_,K_,W_=I(()=>{RO();qO();ly();SU=$_(V_,{counterRight:!1,counterLength:4,allowShortKeys:!1}),PU=$_(V_,{counterRight:!1,counterLength:8,extendNonceFn:kU,allowShortKeys:!1}),xU=new Uint8Array(16),TO=(n,e)=>{n.update(e);let t=e.length%16;t&&n.update(xU.subarray(t))},CU=new Uint8Array(32);LO=n=>(e,t,r)=>({encrypt(s,i){let a=s.length;i=Dd(a+16,i,!1),i.set(s);let c=i.subarray(0,-16);n(e,t,c,c,1);let l=MO(n,e,t,c,r);return i.set(l,a),dr(l),i},decrypt(s,i){i=Dd(s.length-16,i,!1);let a=s.subarray(0,-16),c=s.subarray(-16),l=MO(n,e,t,a,r);if(!PO(c,l))throw dr(l),new Error("invalid tag");return i.set(s.subarray(0,-16)),n(e,t,i,i,1),dr(l),i}}),F_=D_({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},LO(SU)),K_=D_({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},LO(PU))});function py(n,e,t=()=>{}){if(!Array.isArray(n))throw new TypeError(`"${e}" expected array, got type=${typeof n}`);for(let r=0;r<n.length;r++)t(n[r],`${e}[${r}]`);return n}function rs(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 na(n,e){if(typeof n!="function")throw new TypeError(`"${e}" is invalid: expected function, got ${typeof n}`);return n}function co(n,e=""){if(typeof n!="boolean")throw new TypeError(IU(e)+"expected boolean, got type="+typeof n);return n}function OU(n){if(typeof n=="bigint"){if(!is(n))throw new RangeError("positive bigint expected, got "+n)}else H_(n);return n}function tc(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 DO(n){if(typeof n!="string")throw new TypeError("hex string expected, got "+typeof n);return n===""?cy:BigInt("0x"+n)}function dy(n){return DO(Ta(n))}function po(n){return DO(Ta(os(ft(n)).reverse()))}function Y_(n,e){if(Sn(e),e===0)throw new Error("zero output length is invalid");n=OU(n);let t=e*2,r=n.toString(16);if(r.length>t)throw new RangeError("number is too large");return Xu(r.padStart(t,"0"))}function uy(n,e){return Y_(n,e).reverse()}function os(n){return Uint8Array.from(Xt(n))}function is(n){return typeof n=="bigint"&&cy<=n}function J_(n,e,t){return is(n)&&is(e)&&is(t)&&e<=n&&n<t}function ra(n,e,t,r){if(!J_(e,t,r))throw new RangeError("expected valid "+n+": "+t+" <= n < "+r+", got "+e)}function X_(n){if(n<cy)throw new Error("expected non-negative bigint, got "+n);return n===cy?0:n.toString(2).length}function qi(n,e={},t={},r="object"){rs(n,r),rs(e,"fields"),rs(t,"optFields");function o(i,a,c){let l=r==="object"?`param "${String(i)}"`:`"${r}.${String(i)}"`,p=n[i];if(!Object.hasOwn(n,i)&&(c?p!==void 0:a!=="function"))throw new TypeError(`${l} is invalid: expected own property`);if(c&&p===void 0)return;let d=typeof p;if(d!==a||p===null)throw new TypeError(`${l} is invalid: expected ${a}, got ${d}`)}let s=(i,a)=>Object.entries(i).forEach(([c,l])=>o(c,l,a));s(e,!1),s(t,!0)}var Xt,H_,UO,G_,NO,Bd,Vd,cy,jO,IU,zO,Fd=I(()=>{fi();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Xt=(n,e,t)=>ft(n,e,t),H_=Sn;UO=Ta,G_=(...n)=>Ib(...n),NO=n=>Xu(n),Bd=Yu,Vd=n=>Xk(n),cy=BigInt(0),jO=BigInt(1),IU=n=>n?`"${n}" `:"";zO=n=>(tc(n,"n"),(jO<<BigInt(n))-jO)});function ct(n,e){if(e<=Qt)throw new Error("mod: expected positive modulus, got "+e);let t=n%e;return t>=Qt?t:e+t}function MU(n,e,t){if(t<=ht)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<Qt)throw new Error("invalid exponent, negatives unsupported");if(e===Qt)return ht;if(e===ht)return n;let r=n%t;if(r<Qt&&(r+=t),e<TU){let a=ht;for(;e>Qt;)e&ht&&(a=a*r%t),r=r*r%t,e>>=ht;return a}let o=[];for(;e>Qt;)o.push(Number(e&qU)),e>>=Q_;let s=new Array(16);s[0]=ht,s[1]=r;for(let a=2;a<16;a++)s[a]=s[a-1]*r%t;let i=s[o[o.length-1]];for(let a=o.length-2;a>=0;a--){i=i*i%t,i=i*i%t,i=i*i%t,i=i*i%t;let c=o[a];c!==0&&(i=i*s[c]%t)}return i}function qr(n,e,t){if(t<=ht)throw new Error("pow2: expected modulus > 1, got "+t);if(e<Qt)throw new Error("pow2: expected non-negative exponent, got "+e);let r=n;for(;e-- >Qt;)r*=r,r%=t;return r}function $O(n,e){if(n===Qt)throw new Error("invert: expected non-zero number");if(e<=ht)throw new Error("invert: expected modulus > 1, got "+e);let t=ct(n,e),r=e,o=Qt,s=ht;for(;t!==Qt;){let a=r/t,c=r-t*a,l=o-s*a;r=t,t=c,o=s,s=l}if(r!==ht)throw new Error("invert: does not exist");return ct(o,e)}function Z_(n,e,t){let r=n;if(!r.eql(r.sqr(e),t))throw new Error("Cannot find square root")}function eA(n,e){if((n&ht)===Qt)throw new Error(e+": expected odd modulus, got "+n)}function HO(n,e){let t=n,r=(t.ORDER+ht)/Q_,o=t.pow(e,r);return Z_(t,o,e),o}function LU(n,e){let t=n,r=(t.ORDER-FO)/KO,o=t.mul(e,ia),s=t.pow(o,r),i=t.mul(e,s),a=t.mul(t.mul(i,ia),s),c=t.mul(i,t.sub(a,t.ONE));return Z_(t,c,e),c}function jU(n){let e=my(n),t=GO(n),r=t(e,e.neg(e.ONE)),o=t(e,r),s=t(e,e.neg(r)),i=(n+RU)/WO;return((a,c)=>{let l=a,p=l.pow(c,i),d=l.mul(p,r),u=l.mul(p,o),f=l.mul(p,s),h=l.eql(l.sqr(d),c),m=l.eql(l.sqr(u),c);p=l.cmov(p,d,h),d=l.cmov(f,u,m);let w=l.eql(l.sqr(d),c),b=l.cmov(p,d,w);return Z_(l,b,c),b})}function GO(n){if(n<VO)throw new Error("sqrt is not defined for small field");eA(n,"tonelliShanks");let e=n-ht,t=0;for(;e%ia===Qt;)e/=ia,t++;let r=ia,o=my(n);for(;Kd(o,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return HO;let s=o.pow(r,e),i=(e+ht)/ia;return function(c,l){let p=c;if(p.is0(l))return l;if(Kd(p,l)!==1)throw new Error("Cannot find square root");let d=t,u=p.mul(p.ONE,s),f=p.pow(l,e),h=p.pow(l,i);for(;!p.eql(f,p.ONE);){if(p.is0(f))throw new Error("Cannot find square root: probably non-prime P");let m=1,w=p.sqr(f);for(;!p.eql(w,p.ONE);)if(m++,w=p.sqr(w),m===d)throw new Error("Cannot find square root");let b=ht<<BigInt(d-m-1),g=p.pow(u,b);d=m,u=p.sqr(g),f=p.mul(f,u),h=p.mul(h,g)}return h}}function UU(n){return eA(n,"Fp.sqrt"),n%Q_===VO?HO:n%KO===FO?LU:n%WO===EU?jU(n):GO(n)}function nc(n){if(rs(n,"field"),typeof n.ORDER!="bigint")throw new TypeError('param "ORDER" is invalid: expected bigint, got '+typeof n.ORDER);tc(n.BYTES,"BYTES"),tc(n.BITS,"BITS");for(let e of NU)na(n[e],"field."+e);if(n.BYTES<1||n.BITS<1)throw new Error("invalid field: expected BYTES/BITS > 0");if(n.ORDER<=ht)throw new Error("invalid field: expected ORDER > 1, got "+n.ORDER);return n}function hy(n,e,t=!1){nc(n),py(e,"nums"),co(t,"passZero");let r=n,o=new Array(e.length).fill(t?r.ZERO:void 0),s=e.reduce((a,c,l)=>r.is0(c)?a:(o[l]=a,r.mul(a,c)),r.ONE),i=r.inv(s);return e.reduceRight((a,c,l)=>r.is0(c)?a:(o[l]=r.mul(a,o[l]),r.mul(a,c)),i),o}function Kd(n,e){nc(n);let t=n;eA(t.ORDER,"FpLegendre");let r=(t.ORDER-ht)/ia,o=t.pow(e,r),s=t.eql(o,t.ONE),i=t.eql(o,t.ZERO),a=t.eql(o,t.neg(t.ONE));if(!s&&!i&&!a)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function DU(n,e){if(e!==void 0&&H_(e),n<=Qt)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=X_(n);if(e!==void 0&&e<t)throw new Error(`invalid n length: expected nBitLength (${e}) >= bitLen(n) (${t})`);let r=e!==void 0?e:t,o=Math.ceil(r/8);return{nBitLength:r,nByteLength:o}}function my(n,e={}){return Object.freeze(fy.prototype),new fy(n,e)}var Qt,ht,ia,VO,Q_,FO,RU,KO,EU,qU,WO,TU,YO,NU,BO,fy,Wd=I(()=>{Fd();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */Qt=BigInt(0),ht=BigInt(1),ia=BigInt(2),VO=BigInt(3),Q_=BigInt(4),FO=BigInt(5),RU=BigInt(7),KO=BigInt(8),EU=BigInt(9),qU=BigInt(15),WO=BigInt(16),TU=BigInt("0x10000000000000000");YO=(n,e)=>(ct(n,e)&ht)===ht,NU=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];BO=new WeakMap,fy=class{ORDER;BITS;BYTES;isLE;ZERO=Qt;ONE=ht;_lengths;_mod;constructor(e,t={}){if(e<=ht)throw new Error("invalid field: expected ORDER > 1, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=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}=DU(e,r);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 ct(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new TypeError("invalid field element: expected bigint, got "+typeof e);return Qt<=e&&e<this.ORDER}is0(e){return e===Qt}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ht)===ht}neg(e){return ct(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return ct(e*e,this.ORDER)}add(e,t){return ct(e+t,this.ORDER)}sub(e,t){return ct(e-t,this.ORDER)}mul(e,t){return ct(e*t,this.ORDER)}pow(e,t){return MU(e,t,this.ORDER)}div(e,t){return ct(e*$O(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 $O(e,this.ORDER)}sqrt(e){let t=BO.get(this);return t||BO.set(this,t=UU(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?uy(e,this.BYTES):Y_(e,this.BYTES)}fromBytes(e,t=!1){Xt(e);let{_lengths:r,BYTES:o,isLE:s,ORDER:i,_mod:a}=this;if(r){if(e.length<1||!r.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+r+" 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 c=s?po(e):dy(e);if(a&&(c=ct(c,i)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return hy(this,e,!0)}cmov(e,t,r){return co(r,"condition"),r?t:e}}});function Gd(n){let e=n;if(typeof e!="function")throw new TypeError('"Point" expected constructor, got type='+typeof n);na(e.fromAffine,"Point.fromAffine"),na(e.fromBytes,"Point.fromBytes"),na(e.fromHex,"Point.fromHex"),rs(e.BASE,"Point.BASE"),rs(e.ZERO,"Point.ZERO"),nc(e.Fp),nc(e.Fn)}function ZO(n,e){Gd(n),eR(e,n);let t=hy(n.Fp,e.map(r=>r.Z));return e.map((r,o)=>n.fromAffine(r.toAffine(t[o])))}function BU(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 VU(n,e){let t=n*(4*e+128);if(t>XO)throw new Error("invalid window size: table would need ~"+Math.ceil(t/2**20)+" MiB, max "+XO/2**20+" MiB")}function FU(n,e){if(n!==void 0){na(n,"randomBytes");try{let t=n(e);if(!Bd(t)||t.length!==e)return}catch{return}return n}}function eR(n,e){py(n,"points"),n.forEach((t,r)=>{if(!(t instanceof e))throw new Error("invalid point at index "+r)})}function KU(n,e,t){if(!Array.isArray(n))throw new Error("array of scalars expected");n.forEach((r,o)=>{if(!(t===void 0?e.isValid(r):is(r)&&r<t))throw new Error("invalid scalar at index "+o)})}function nA(n){return tR.get(n)||1}function WU(n,e){let t=n.double(),r=[n];for(let o=1;o<e;o++)r.push(r[o-1].add(t));return r}function HU(n,e){let t=2**e,r=t/2,o=BigInt(t-1),s=[];for(;n>rA;){let i=0;n&Hd&&(i=Number(n&o),i>=r&&(i-=t),n-=BigInt(i)),s.push(i),n>>=Hd}return s}function GU(n,e,t){let r=2**e,o=r/2,s=BigInt(r-1),i=BigInt(e),a=[];for(let c=0;c<t;c++){let l=Number(n&s);n>>=i,l>o&&(l-=r,n+=Hd),a.push(l)}if(n!==rA)throw new Error("invalid wnaf");return a}function YU(n,e,t){let r=0;for(let s of t)r=Math.max(r,s.length);let o=n;for(let s=r-1;s>=0;s--){s!==r-1&&(o=o.double());for(let i=0;i<t.length;i++){let a=t[i][s];if(a){let c=e[i][Math.abs(a)-1>>1];o=o.add(a<0?c.negate():c)}}}return o}function JU(n,e,t,r=!1){if(Gd(n),eR(e,n),co(r,"allowOversized"),KU(t,n.Fn,r?n.Fn.ORDER**zU:void 0),e.length!==t.length)throw new Error("arrays of points and scalars must have equal length");let o=e.map(i=>WU(i,4)),s=t.map(i=>HU(i,4));return YU(n.ZERO,o,s)}function QO(n,e,t){if(e){if(e.ORDER!==n)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return nc(e),e}else return my(n,{isLE:t})}function nR(n,e,t={},r){if(n!=="weierstrass"&&n!=="edwards")throw new Error('expected curve type "weierstrass" or "edwards"');if(r===void 0&&(r=n==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${n} CURVE object`);qi(t);for(let c of["p","n","h"]){let l=e[c];if(!(is(l)&&l!==rA))throw new Error(`CURVE.${c} must be positive bigint`)}let o=QO(e.p,t.Fp,r),s=QO(e.n,t.Fn,r),a=["Gx","Gy","a",n==="weierstrass"?"b":"d"];for(let c of a)if(!o.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:o,Fn:s}}function gy(n,e){return function(r){let o=n(r);return{secretKey:o,publicKey:e(o)}}}var rA,Hd,zU,tA,JO,$U,XO,tR,yy,iA=I(()=>{Fd();Wd();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */rA=BigInt(0),Hd=BigInt(1),zU=BigInt(4),tA=16,JO=128,$U=5,XO=2**31;tR=new WeakMap;yy=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){Gd(e),this.randomBytes=FU(t,tA),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,r){let o=Math.ceil(r/t)+1,s=2**(t-1),i=[],a=e;for(let c=0;c<o;c++){let l=a;for(let p=0;p<s;p++)i.push(l),l=l.add(a);a=i[i.length-1].double()}return{W:t,bits:r,windows:o,comp:i}}wnafCachedCT(e,t){let{W:r,windows:o,comp:s}=e,i=2**(r-1),a=GU(t,r,o),c=this.ZERO,l=this.BASE;for(let p=0;p<o;p++){let d=a[p],u=p*i,f=Math.abs(d)-1,h=s[u];for(let w=1;w<i;w++)h=w===f?s[u+w]:h;let m=h.negate();d===0?l=l.add(s[u]):c=c.add(d<0?m:h)}return{p:c,f:l}}getWnafPrecomputes(e,t,r,o){let s=this.wnafPrecomputes.get(t),i=s?.find(a=>a.W===e&&a.bits===r);return i||(i=this.buildWnafTable(t,e,r),typeof o=="function"&&(i={...i,comp:o(i.comp)}),s||(s=[],this.wnafPrecomputes.set(t,s)),s.push(i)),i}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),!J_(t,Hd,this.Point.Fn.ORDER))throw new Error("invalid scalar")}runCT(e,t,r,o){let s=nA(e);return s===1?this.fixedWindowCT(e,t,r):this.wnafCachedCT(this.getWnafPrecomputes(s,e,r,o),t)}mulCT(e,t,r){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,r)}mulCTBlinded(e,t,r){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw new Error("randomBytes is required for scalar blinding");let o=this.Point.Fn.BITS+JO,s=this.randomBytes(tA);if(!Bd(s)||s.length!==tA)throw new Error("randomBytes returned invalid byte array");s[0]=s[0]&63|128;let i=t+dy(s)*this.Point.Fn.ORDER;return this.runCT(e,i,o,r)}fixedWindowCT(e,t,r){let o=$U,s=1<<o,i=zO(o),a=new Array(s);a[0]=this.ZERO;for(let p=1;p<s;p++)a[p]=a[p-1].add(e);let c=Math.ceil(r/o),l=this.ZERO;for(let p=c-1;p>=0;p--){if(p!==c-1)for(let f=0;f<o;f++)l=l.double();let d=Number(t>>BigInt(p*o)&i),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===Hd?!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,r,o){return this.shouldBlind(e,r)?this.mulCTBlinded(e,t,o):this.mulCT(e,t,o)}mulUnsafe(e,t,r){if(this.assertPoint(e),!is(t))throw new Error("invalid scalar");let o=nA(e);if(o===1||t>=this.Point.Fn.ORDER)return JU(this.Point,[e],[t],!0);let s=this.getWnafPrecomputes(o,e,this.bits,r);return this.wnafCachedCT(s,t).p}setWindowSize(e,t){this.assertPoint(e),BU(t,this.bits);let r=Math.ceil((this.bits+JO)/t)+1;VU(r*2**(t-1),this.Point.Fp.BYTES),tR.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return nA(e)!==1}}});function QU(n,e,t,r){let o=n.sqr(t),s=n.sqr(r),i=n.add(n.mul(e.a,o),s),a=n.add(n.ONE,n.mul(e.d,n.mul(o,s)));return n.eql(i,a)}function iR(n,e={}){qi(e,{},{},"extraOpts");let t=e,r=nR("edwards",n,t,t.FpFnLE),{Fp:o,Fn:s}=r,i=r.CURVE,{h:a}=i;if(Kd(o,i.a)!==1)throw new Error("edwards: CURVE.a must be a square in Fp for complete addition formulas");if(Kd(o,i.d)!==-1)throw new Error("edwards: CURVE.d must be a non-square in Fp for complete addition formulas");qi(t,{},{uvRatio:"function",randomBytes:"function"});let c=t.randomBytes===void 0?Vd:t.randomBytes,l=vy<<BigInt(o.BYTES*8)-wy;function p(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:by}}}:t.uvRatio;if(!QU(o,i,i.Gx,i.Gy))throw new Error("bad curve params: generator point");let u=o.eql(i.a,o.neg(o.ONE))?g=>o.neg(g):o.eql(i.a,o.ONE)?g=>g:g=>o.mul(i.a,g);function f(g,y,_=!1){let v=_?wy:by;return ra("coordinate "+g,y,v,l),y}function h(g){if(!(g instanceof m))throw new Error("EdwardsPoint expected")}class m{static BASE=new m(i.Gx,i.Gy,o.ONE,o.mul(i.Gx,i.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",_),this.Z=f("z",v,!0),this.T=f("t",k),Object.freeze(this)}static CURVE(){return i}static fromAffine(y){if(y instanceof m)throw new Error("extended point not allowed");let{x:_,y:v}=y||{};return f("x",_),f("y",v),new m(_,v,o.ONE,o.mul(_,v))}static fromBytes(y,_=!1){let v=o.BYTES,{a:k,d:S}=i;y=os(Xt(y,v,"point")),co(_,"zip215");let x=os(y),P=y[v-1];x[v-1]=P&-129;let C=po(x),R=_?l:o.ORDER;ra("point.y",C,by,R);let O=o.sqr(C),E=o.sub(O,o.ONE),j=o.sub(o.mulN(S,O),k),{isValid:B,value:D}=d(E,j);if(!B)throw new Error("bad point: invalid y coordinate");let J=p(D),V=(P&128)!==0;if(!_&&o.is0(D)&&V)throw new Error("bad point: x=0 and x_0=1");return V!==J&&(D=o.neg(D)),m.fromAffine({x:D,y:C})}static fromHex(y,_=!1){return m.fromBytes(NO(y),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=6,_=!0){return b.setWindowSize(this,y),_||this.multiply(vy),this}assertValidity(){let y=this,{a:_,d:v}=i;if(y.is0())throw new Error("bad point: ZERO");let{X:k,Y:S,Z:x,T:P}=y,C=o.sqr(k),R=o.sqr(S),O=o.sqr(x),E=o.sqr(O),j=o.mul(C,_),B=o.mul(o.add(j,R),O),D=o.add(E,o.mul(v,o.mul(C,R)));if(!o.eql(B,D))throw new Error("bad point: equation left != right (1)");let J=o.mul(k,S),V=o.mul(x,P);if(!o.eql(J,V))throw new Error("bad point: equation left != right (2)")}equals(y){h(y);let{X:_,Y:v,Z:k}=this,{X:S,Y:x,Z:P}=y,C=o.mul(_,P),R=o.mul(S,k),O=o.mul(v,P),E=o.mul(x,k);return o.eql(C,R)&&o.eql(O,E)}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:_,Z:v}=this,k=o.sqr(y),S=o.sqr(_),x=o.mul(o.sqr(v),vy),P=u(k),C=o.addN(y,_),R=o.sub(o.subN(o.sqr(C),k),S),O=o.addN(P,S),E=o.subN(O,x),j=o.subN(P,S),B=o.mul(R,E),D=o.mul(O,j),J=o.mul(R,j),V=o.mul(E,O);return new m(B,D,V,J)}add(y){h(y);let{d:_}=i,{X:v,Y:k,Z:S,T:x}=this,{X:P,Y:C,Z:R,T:O}=y,E=o.mul(v,P),j=o.mul(k,C),B=o.mul(o.mulN(x,_),O),D=o.mul(S,R),J=o.sub(o.subN(o.mulN(o.addN(v,k),o.addN(P,C)),E),j),V=o.subN(D,B),U=o.addN(D,B),ce=o.sub(j,u(E)),ee=o.mul(J,V),te=o.mul(U,ce),Ce=o.mul(J,ce),et=o.mul(V,U);return new m(ee,te,et,Ce)}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:_,f:v}=b.mulSecret(this,y,a,w);return w([_,v])[0]}multiplyUnsafe(y){if(!s.isValid(y))throw new RangeError("invalid scalar: expected 0 <= sc < curve.n");return y===by?m.ZERO:this.is0()||y===wy?this:b.mulUnsafe(this,y,w)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return b.mulUnsafe(this,i.n).is0()}toAffine(y){let _=this,v=y;if(v!=null&&typeof v!="bigint")throw new TypeError('"invertedZ" expected bigint, got type='+typeof v);let{X:k,Y:S,Z:x}=_,P=_.is0();v==null&&(v=P?o.create(rR):o.inv(x));let C=o.mul(k,v),R=o.mul(S,v),O=o.mul(x,v);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:R}}clearCofactor(){return a===wy?this:a===vy?this.double():a===XU?this.double().double():a===rR?this.double().double().double():this.multiplyUnsafe(a)}toBytes(){let{x:y,y:_}=this.toAffine(),v=o.toBytes(_);return v[v.length-1]|=p(y)?128:0,v}toHex(){return UO(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}let w=g=>ZO(m,g),b=new yy(m,c);return b.bits>=6&&m.BASE.precompute(6),Object.freeze(m.prototype),Object.freeze(m),m}function oR(n,e,t={}){if(Gd(n),typeof e!="function")throw new Error('"hash" function param is required');let r=e,o=t;qi(o,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",zip215:"boolean",mapToCurve:"function",toMontgomery:"function",toMontgomerySecret:"function"});let{prehash:s}=o,{BASE:i,Fp:a,Fn:c}=n,l=r.outputLen,p=2*a.BYTES;if(l!==void 0&&(tc(l,"hash.outputLen"),l!==p))throw new Error(`hash.outputLen must be ${p}, got ${l}`);let d=o.randomBytes===void 0?Vd:o.randomBytes,u=o.toMontgomery,f=o.toMontgomerySecret,h=o.adjustScalarBytes===void 0?j=>j:o.adjustScalarBytes,m=o.domain===void 0?(j,B,D)=>{if(co(D,"phflag"),B.length||D)throw new Error("Contexts/pre-hash are not supported");return j}:o.domain;function w(j){return c.create(po(j))}function b(j){let B=P.secretKey;Xt(j,P.secretKey,"secretKey");let D=Xt(r(j),2*B,"hashedSecretKey"),J=h(D.slice(0,B)),V=D.slice(B,2*B),U=w(J);return{head:J,prefix:V,scalar:U}}function g(j){let{head:B,prefix:D,scalar:J}=b(j),V=i.multiply(J),U=V.toBytes();return{head:B,prefix:D,scalar:J,point:V,pointBytes:U}}function y(j){return g(j).pointBytes}function _(j=Uint8Array.of(),...B){let D=G_(...B);return w(r(m(D,Xt(j,void 0,"context"),!!s)))}function v(j,B,D={}){qi(D,{},{},"options"),j=os(Xt(j,void 0,"message")),s&&(j=s(j));let{prefix:J,scalar:V,pointBytes:U}=g(B),ce=_(D.context,J,j),ee=i.multiply(ce).toBytes(),te=_(D.context,ee,U,j),Ce=c.create(ce+te*V);if(!c.isValid(Ce))throw new Error("sign failed: invalid s");let et=G_(ee,c.toBytes(Ce));return Xt(et,P.signature,"result")}let k={zip215:o.zip215};function S(j,B,D,J=k){qi(J);let{context:V}=J,U=J.zip215===void 0?!!k.zip215:J.zip215,ce=P.signature;j=Xt(j,ce,"signature"),B=Xt(B,void 0,"message"),D=Xt(D,P.publicKey,"publicKey"),U!==void 0&&co(U,"zip215"),s&&(B=s(B));let ee=ce/2,te=j.subarray(0,ee),Ce=po(j.subarray(ee,ce)),et,$,Y;try{et=n.fromBytes(D,U),$=n.fromBytes(te,U),Y=i.multiplyUnsafe(Ce)}catch{return!1}if(!U&&et.isSmallOrder())return!1;let K=_(V,te,D,B);return $.add(et.multiplyUnsafe(K)).subtract(Y).clearCofactor().is0()}let x=a.BYTES,P={secretKey:x,publicKey:x,signature:2*x,seed:x};function C(j){return j=j===void 0?d(P.seed):j,Xt(j,P.seed,"seed")}function R(j){return Bd(j)&&j.length===P.secretKey}function O(j,B){try{return!!n.fromBytes(j,B===void 0?k.zip215:B)}catch{return!1}}let E={getExtendedPublicKey:g,randomSecretKey:C,isValidSecretKey:R,isValidPublicKey:O,toMontgomery(j){if(u===void 0)throw new Error("Montgomery conversion is not supported for this curve");return u(n.fromBytes(j))},toMontgomerySecret(j){if(f===void 0)throw new Error("Montgomery conversion is not supported for this curve");return f(j)}};return Object.freeze(P),Object.freeze(E),Object.freeze({keygen:gy(C,y),getPublicKey:y,sign:v,verify:S,utils:E,Point:n,lengths:P})}var by,wy,vy,XU,rR,sR=I(()=>{Fd();iA();Wd();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */by=BigInt(0),wy=BigInt(1),vy=BigInt(2),XU=BigInt(4),rR=BigInt(8)});function aR(n,e){return n+e-(e>>Tr<<Tr)}function ZU(n){let e=BigInt(6)*n;return(t,r,o)=>{let s=r+o,a=((e+o-r)*t+r)%n;return{x_2:a,x_3:s-a}}}function eN(n){return qi(n,{P:"bigint",type:"string",adjustScalarBytes:"function",powPminus2:"function"},{randomBytes:"function",scalarMultBase:"function"}),Object.freeze({...n})}function lR(n){let e=eN(n),{P:t,type:r,adjustScalarBytes:o,powPminus2:s,randomBytes:i}=e,a=e.scalarMultBase,c=r==="x25519";if(!c&&r!=="x448")throw new Error("invalid type");let l=i===void 0?Vd:i,p=c?255:448,d=ZU(t),u=c?32:56,f=BigInt(c?9:5),h=BigInt(c?121665:39081),m=c?_y**BigInt(254):_y**BigInt(447),w=c?BigInt(8)*(_y**BigInt(251)-Tr):BigInt(4)*(_y**BigInt(445)-Tr),b=m+w+Tr,g=D=>ct(D,t),y=_(f);function _(D){return uy(g(D),u)}function v(D){let J=os(Xt(D,u,"uCoordinate"));return c&&(J[31]&=127),g(po(J))}function k(D){return po(o(os(Xt(D,u,"scalar"))))}let S=new Set(c?[oa,Tr,t-Tr,BigInt("325606250916557431795983626356110631294008115727848805560023387167927233504"),BigInt("39382357235489614581723060781553021112529911719440698176882885853963445705823")]:[oa,Tr,t-Tr]);function x(D,J){let V=v(J);if(S.has(V))throw new Error("invalid private or public key received");let U=O(V,k(D));if(U===oa)throw new Error("invalid private or public key received");return _(U)}function P(D){if(a===void 0)return x(D,y);let J=k(D);ra("scalar",J,m,b);let V=g(a(J));if(V===oa)throw new Error("invalid private or public key received");return _(V)}let C=P,R=x;function O(D,J){ra("u",D,oa,t),ra("scalar",J,m,b);let V=J,U=D,ce=Tr,ee=oa,te=D,Ce=Tr,et=V^V>>Tr;for(let K=BigInt(p-1);K>=oa;K--){let Z=aR(t,et>>K);({x_2:ce,x_3:te}=d(Z,ce,te)),{x_2:ee,x_3:Ce}=d(Z,ee,Ce);let _e=ce+ee,re=g(_e*_e),ne=ce-ee,Ke=g(ne*ne),Ve=re-Ke,Ft=te+Ce,Re=te-Ce,nt=g(Re*_e),ci=g(Ft*ne),yo=nt+ci,go=nt-ci;te=g(yo*yo),Ce=g(U*g(go*go)),ce=g(re*Ke),ee=g(Ve*(re+g(h*Ve)))}let $=aR(t,V);({x_2:ce,x_3:te}=d($,ce,te)),{x_2:ee,x_3:Ce}=d($,ee,Ce);let Y=s(ee);return g(ce*Y)}let E={secretKey:u,publicKey:u,seed:u},j=D=>(D=D===void 0?l(u):D,Xt(D,E.seed,"seed"),D),B={randomSecretKey:j};return Object.freeze(E),Object.freeze(B),Object.freeze({keygen:gy(j,C),getSharedSecret:R,getPublicKey:C,scalarMult:x,scalarMultBase:P,utils:B,GuBytes:y.slice(),lengths:E})}var oa,Tr,_y,cR=I(()=>{Fd();iA();Wd();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */oa=BigInt(0),Tr=BigInt(1),_y=BigInt(2)});function hR(n){let e=BigInt(10),t=BigInt(20),r=BigInt(40),o=BigInt(80),s=Ay,a=n*n%s*n%s,c=qr(a,dR,s)*a%s,l=qr(c,oA,s)*n%s,p=qr(l,nN,s)*l%s,d=qr(p,e,s)*p%s,u=qr(d,t,s)*d%s,f=qr(u,r,s)*u%s,h=qr(f,o,s)*f%s,m=qr(h,o,s)*f%s,w=qr(m,e,s)*p%s;return{pow_p_5_8:qr(w,dR,s)*n%s,b2:a}}function sA(n){return n[0]&=248,n[31]&=127,n[31]|=64,n}function oN(n,e){let t=Ay,r=ct(e*e*e,t),o=ct(r*r*e,t),s=hR(n*o).pow_p_5_8,i=ct(n*r*s,t),a=ct(e*i*i,t),c=i,l=ct(i*uR,t),p=a===n,d=a===ct(-n,t),u=a===ct(-n*uR,t);return p&&(i=c),(d||u)&&(i=l),YO(i,t)&&(i=ct(-i,t)),{isValid:p||d,value:i}}function sN(n){let{y:e}=n;return fR.toBytes(fR.div(oA+e,oA-e))}function aN(n){let e=Yd.Fp.BYTES;return ft(n,e),sA(Mb(n.subarray(0,e))).subarray(0,e)}function lN(n){return oR(Yd,Mb,Object.assign({adjustScalarBytes:sA,toMontgomery:sN,toMontgomerySecret:aN,zip215:!0},n))}var pR,oA,dR,tN,nN,rN,Ay,iN,uR,Yd,fR,Jd,ni,ky=I(()=>{hi();fi();sR();Wd();cR();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */pR=BigInt(0),oA=BigInt(1),dR=BigInt(2),tN=BigInt(3),nN=BigInt(5),rN=BigInt(8),Ay=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),iN={p:Ay,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:rN,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};uR=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");Yd=iR(iN,{uvRatio:oN}),fR=Yd.Fp;Jd=lN({}),ni=(()=>{let n=Ay,e=t=>{let{pow_p_5_8:r,b2:o}=hR(t);return ct(qr(r,tN,n)*o,n)};return lR({P:n,type:"x25519",powPminus2:e,adjustScalarBytes:sA,scalarMultBase:t=>{let r=ct(t,Yd.Fn.ORDER);if(r===pR)return pR;let o=Yd.BASE.multiply(r);return ct((o.Z+o.Y)*e(ct(o.Z-o.Y,n)),n)}})})()});var Sy,sa,aA=I(()=>{fi();Sy=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(ip(e),ft(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 r=this.blockLen,o=new Uint8Array(r);o.set(t.length>r?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),at(o)}update(e){return Hi(this),this.iHash.update(e),this}digestInto(e){Hi(this),qa(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:r,finished:o,destroyed:s,blockLen:i,outputLen:a,canXOF:c}=this;return e=e,e.finished=o,e.destroyed=s,e.blockLen=i,e.outputLen=a,e.canXOF=c,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},sa=(()=>{let n=((e,t,r)=>new Sy(e,t).update(r).digest());return n.create=(e,t)=>new Sy(e,t),n})()});function xy(n){return"dh"in n?n:{publicKey:n.publicKey,dh:e=>aa(n.secretKey,e)}}async function yR(n,e){let t;try{t=await n.dh(e)}catch(r){throw r instanceof gt?r:new gt("invalid public key")}return AR(t)}function sc(){let n=ni.utils.randomSecretKey();return{secretKey:n,publicKey:ni.getPublicKey(n)}}function _R(n){return{secretKey:n,publicKey:ni.getPublicKey(n)}}function Xd(...n){let e=0;for(let o of n)e+=o.length;let t=new Uint8Array(e),r=0;for(let o of n)t.set(o,r),r+=o.length;return t}function AR(n){let e=0;for(let t of n)e|=t;if(e===0)throw new gt("invalid public key (all-zero shared secret)");return n}function aa(n,e){let t;try{t=ni.getSharedSecret(n,e)}catch{throw new gt("invalid public key")}return AR(t)}function gR(n,e){let t=sa(Qe,n,e),r=sa(Qe,t,Uint8Array.of(1)),o=sa(Qe,t,Xd(r,Uint8Array.of(2)));return[r,o]}function bR(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[r,o]of[["collection",n],["target device",t]])if(o.length!==16)throw new gt(`${r} ID must be 16 bytes`);if(e&&e.length!==16)throw new gt("grant ID must be 16 bytes");return Xd(cN,n,e??pN,t)}var wR,Mr,mR,vR,rc,lA,Py,gt,ic,Cy,oc,Iy,cN,pN,la=I(()=>{"use strict";W_();ky();aA();hi();wR="Noise_IK_25519_ChaChaPoly_SHA256",Mr=32,mR=32,vR=65535,rc=16,lA=vR-rc,Py=2**30;gt=class extends Error{constructor(e){super(e),this.name="NoiseError"}},ic=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>=Py)throw new gt("session message limit reached");let r=F_(this.k,bR(this.n),e).encrypt(t);return this.n++,r}decrypt(e,t){if(!this.k)return t;if(this.n>=Py)throw new gt("session message limit reached");let r;try{r=F_(this.k,bR(this.n),e).decrypt(t)}catch{throw new gt("decryption failed")}return this.n++,r}},Cy=class{ck;h;cs=new ic;constructor(e){let t=new TextEncoder().encode(e);t.length<=mR?(this.h=new Uint8Array(mR),this.h.set(t)):this.h=Qe(t),this.ck=this.h}mixKey(e){let[t,r]=gR(this.ck,e);this.ck=t,this.cs=new ic(r)}mixHash(e){this.h=Qe(Xd(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]=gR(this.ck,new Uint8Array(0));return[new ic(e),new ic(t)]}},oc=class{constructor(e){this.opts=e;if(e.remoteStatic.length!==Mr)throw new gt("remote static key must be 32 bytes");this.e=e.ephemeral??sc(),this.ss.mixHash(e.prologue),this.ss.mixHash(e.remoteStatic)}opts;ss=new Cy(wR);e;state="start";async writeMessage1(e){if(this.state!=="start")throw new gt("handshake out of order");this.state="sent";let t=xy(this.opts.staticKey),r=this.ss;r.mixHash(this.e.publicKey),r.mixKey(aa(this.e.secretKey,this.opts.remoteStatic));let o=r.encryptAndHash(t.publicKey);r.mixKey(await yR(t,this.opts.remoteStatic));let s=r.encryptAndHash(e),i=Xd(this.e.publicKey,o,s);if(i.length>vR)throw new gt("handshake message too large");return i}async readMessage2(e){if(this.state!=="sent")throw new gt("handshake out of order");if(e.length<Mr+rc)throw new gt("handshake message too short");this.state="done";let t=this.ss,r=e.subarray(0,Mr);t.mixHash(r),t.mixKey(aa(this.e.secretKey,r)),t.mixKey(await yR(xy(this.opts.staticKey),r));let o=t.decryptAndHash(e.subarray(Mr)),[s,i]=t.split();return{payload:o,transport:{send:s,recv:i,handshakeHash:t.h,remoteStatic:this.opts.remoteStatic}}}},Iy=class{constructor(e){this.opts=e;this.e=e.ephemeral??sc(),this.ss.mixHash(e.prologue),this.ss.mixHash(e.staticKey.publicKey)}opts;ss=new Cy(wR);e;rs=null;re=null;state="start";readMessage1(e){if(this.state!=="start")throw new gt("handshake out of order");if(this.state="done",e.length<Mr+Mr+rc+rc)throw new gt("handshake message too short");let t=this.ss,r=e.subarray(0,Mr).slice();t.mixHash(r),t.mixKey(aa(this.opts.staticKey.secretKey,r));let o=t.decryptAndHash(e.subarray(Mr,Mr+Mr+rc));t.mixKey(aa(this.opts.staticKey.secretKey,o));let s=t.decryptAndHash(e.subarray(Mr+Mr+rc));return this.re=r,this.rs=o,this.state="read",{remoteStatic:o,payload:s}}writeMessage2(e){if(this.state!=="read"||!this.re||!this.rs)throw new gt("handshake out of order");this.state="done";let t=this.ss;t.mixHash(this.e.publicKey),t.mixKey(aa(this.e.secretKey,this.re)),t.mixKey(aa(this.e.secretKey,this.rs));let r=t.encryptAndHash(e),[o,s]=t.split();return{message:Xd(this.e.publicKey,r),transport:{send:s,recv:o,handshakeHash:t.h,remoteStatic:this.rs}}}},cN=new TextEncoder().encode("mdbase/v1/client"),pN=new Uint8Array(16)});function dN(n,e,t){return new Promise((r,o)=>{let s=()=>o(A("cancelled","connect aborted"));t?.addEventListener("abort",s,{once:!0}),n.onmessage=i=>{t?.removeEventListener("abort",s),n.onmessage=a=>{e.push(a)},r(i)},n.onclose=i=>{t?.removeEventListener("abort",s),o(i??A("unavailable","connection closed during the handshake"))}})}function pA(n,e,t=cA,r=[]){let o=new Uint8Array(0),s=!1,i=setTimeout(()=>l(),t);i.unref?.();let a={ondata:null,onclose:null,write(p){if(s)throw A("unavailable","connection closed");for(let d=0;d<p.length;d+=lA){if(e.send.count>=Py-1)throw l(),A("unavailable","session message limit reached; reconnecting");n.send(e.send.encrypt(o,p.subarray(d,d+lA)))}},close(){s||(s=!0,clearTimeout(i),n.close())}},c=p=>{if(s)return;let d;try{d=e.recv.decrypt(o,p)}catch{l(A("unavailable","transport message failed authentication","noise"));return}a.ondata?.(d)};if(n.onmessage=c,n.onclose=p=>l(p),r.length){let p=r.splice(0);queueMicrotask(()=>p.forEach(c))}function l(p){s||(s=!0,clearTimeout(i),n.close(),a.onclose?.(p))}return a}function Mi(n){return{description:n.description,async open(e,t){let r=()=>A("cancelled","connect aborted");if(t?.aborted)throw r();let o=await n.target(t);if(t?.aborted)throw r();let s=await o.openCarrier(t);if(t?.aborted)throw s.close(),r();try{let i=new oc({prologue:o.prologue,staticKey:n.staticKey,remoteStatic:o.remoteStatic}),a=[],c=dN(s,a,t);c.catch(()=>{}),o.preamble&&s.send(o.preamble);let l=await i.writeMessage1(n.firstPayload?n.firstPayload(e):ue(e));if(t?.aborted)throw r();s.send(l);let{payload:p,transport:d}=await i.readMessage2(await c),u=we(p);return{port:af(pA(s,d,n.lifetimeMs,a)),helloResponse:u,...o.device?{device:o.device}:{}}}catch(i){throw s.close(),X(i)?i:i instanceof gt?A("unauthenticated",`handshake failed: ${i.message}`,"noise"):A("unavailable",`handshake failed: ${String(i)}`)}}}}function ac(n,e=uN,t){return new Promise((r,o)=>{let s;try{s=e(n)}catch(d){o(X(d)?d:A("unavailable",`cannot open ${n}: ${String(d)}`));return}s.binaryType="arraybuffer";let i=!1,a=null,c=null,l={get onmessage(){return a},set onmessage(d){a=d},get onclose(){return c},set onclose(d){c=d},send(d){s.send(d)},close(){try{s.close(1e3)}catch{}}},p=()=>{s.close(),o(A("cancelled","connect aborted"))};t?.addEventListener("abort",p,{once:!0}),s.onopen=()=>{i=!0,t?.removeEventListener("abort",p),r(l)},s.onmessage=d=>{let u=d.data;u instanceof ArrayBuffer?a?.(new Uint8Array(u)):ArrayBuffer.isView(u)&&a?.(new Uint8Array(u.buffer,u.byteOffset,u.byteLength))},s.onerror=()=>{},s.onclose=d=>{let u=fN(d.code,d.reason);i?c?.(u):(t?.removeEventListener("abort",p),o(u??A("unavailable",`cannot connect to ${n}`)))}})}function fN(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 kR(n){let e=new Uint8Array(0),t={onmessage:null,onclose:null,send(r){if(r.length>65535)throw A("too_large","Noise message over 65535 bytes");let o=new Uint8Array(2+r.length);o[0]=r.length>>8,o[1]=r.length&255,o.set(r,2),n.write(o)},close(){n.close()}};return n.ondata=r=>{let o=new Uint8Array(e.length+r.length);o.set(e),o.set(r,e.length);let s=0;for(;o.length-s>=2;){let i=o[s]<<8|o[s+1];if(o.length-s-2<i)break;t.onmessage?.(o.slice(s+2,s+2+i)),s+=2+i}e=o.slice(s)},n.onclose=r=>t.onclose?.(r?A("unavailable",r.message):void 0),t}var cA,uN,lc=I(()=>{"use strict";Ye();ie();la();up();cA=1440*60*1e3;uN=n=>{let e=globalThis.WebSocket;if(!e)throw A("unavailable","no WebSocket implementation; pass webSocket");return new e(n)}});function yN(n){return typeof n=="string"&&Object.hasOwn(SR,n)?SR[n]:4e3}function ca(n,e){let t=typeof e=="string"&&mN.has(e)?e:void 0,r=L_(n),o={relayCloseCode:r.closeCode,relayCloseClass:r.closeClass},s=(i,a,c,l)=>A(i,a,{reason:c,details:o,...l===void 0?{}:{retryAfterMs:l}});switch(r.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.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${r.closeCode===null?"":` (${r.closeCode})`}`,"relay_closed")}}function gN(n){let e=globalThis.WebSocket;if(!e)throw A("unavailable","no WebSocket implementation; pass webSocket");return new e(n)}function cc(n,e,t=gN,r){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,i)=>{let a;try{a=t(n)}catch(w){i(A("unavailable",`cannot open ${n}: ${String(w)}`));return}a.binaryType="arraybuffer";let c=!1,l,p=new Uint8Array(0),d=null,u=null,f={get onmessage(){return d},set onmessage(w){d=w},get onclose(){return u},set onclose(w){u=w,w&&l&&w(l)},send(w){if(l)throw l;if(w.length>65535)throw A("too_large","Noise message over 65535 bytes");let b=new Uint8Array(4+w.length);new DataView(b.buffer).setUint32(0,w.length),b.set(w,4),a.send(b)},close(){try{a.close(1e3)}catch{}}},h=w=>{l||(l=w,c?u?.(w):(r?.removeEventListener("abort",m),i(w)))},m=()=>{a.close(),h(A("cancelled","connect aborted"))};r?.addEventListener("abort",m,{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:ut(e.devicePublicKey)}))},a.onmessage=w=>{if(l)return;let b=w.data;if(typeof b=="string"){let v;try{v=JSON.parse(b)}catch{return}v.type==="pipe_opened"&&!c?(c=!0,r?.removeEventListener("abort",m),s(f)):v.type==="pipe_close"&&(h(ca(yN(v.reason),v.reason)),a.close());return}if(!c)return;let g=b instanceof ArrayBuffer?new Uint8Array(b):ArrayBuffer.isView(b)?new Uint8Array(b.buffer,b.byteOffset,b.byteLength):null;if(!g)return;if(g.length>hN){a.close(),h(A("too_large","relay frame over the limit"));return}let y=new Uint8Array(p.length+g.length);y.set(p),y.set(g,p.length);let _=0;for(;y.length-_>=4;){let v=new DataView(y.buffer,y.byteOffset+_,4).getUint32(0);if(v>65535){a.close(),h(A("internal","relay sent an oversized Noise message"));return}if(y.length-_-4<v)break;d?.(y.slice(_+4,_+4+v)),_+=4+v}p=y.slice(_)},a.onerror=()=>{},a.onclose=w=>h(ca(w.code,w.reason))}):Promise.reject(A("invalid_request","relay pipes require a grant","grant_required"))}var hN,mN,SR,Qd=I(()=>{"use strict";om();ie();j_();Ye();hN=65539,mN=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(" ")),SR=Object.assign(Object.create(null),{unauthenticated:4401,grant_inactive:4403,grant_revoked_on_device:4403,grant_pending_approval:4403,unknown_grant:4403,connector_offline:4404,connector_busy:4429})});function uA(n){let e=new Uint8Array(0),t=!1,r,o=null,s=null,i=[],a=0,c={get onmessage(){return o},set onmessage(d){for(o=d;d&&!t&&i.length&&o===d;){let u=i.shift();a-=u.length,d(u)}},get onclose(){return s},set onclose(d){s=d,d&&t&&r&&d(r)},send(d){if(t)throw A("unavailable","relay pipe closed");if(d.length>dA)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,i.length=0,a=0,n.close())}},l=(d,u)=>{t||(t=!0,e=new Uint8Array(0),i.length=0,a=0,r=ca(d,u),n.close(),s?.(r))},p=d=>{if(!t){if(o)return o(d);if(i.length>=bN||a+d.length>wN)return l(4e3,"invalid_frame");i.push(d),a+=d.length}};return n.onmessage=d=>{if(t)return;if(d.length>PR)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>dA)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,p(m),t)return}e=u.slice(f),e.length>PR&&l(4e3,"invalid_frame")},n.onclose=d=>l(d?.code,d?.reason),c}async function xR(n){try{return await n()}catch(e){if(X(e))throw e;if(e?.code==="not_authorized")throw A("unauthenticated","Connect authorization is missing","not_authorized");let r=e?.cause;throw typeof r?.code=="number"?ca(r.code,typeof r.reason=="string"?r.reason:void 0):A("unavailable","the relay pipe could not be opened","relay_unavailable")}}function Zd(n,e){let t=n.targets.filter(o=>Oy.test(o.device)&&/^[0-9a-f]{64}$/.test(o.noise_pk)&&!!o.relay_collection&&Oy.test(o.relay_collection)),r=o=>(o.online===!0?0:o.online===void 0?1:2)*2+(o.device===e?0:1);return t.map((o,s)=>({target:o,index:s,rank:r(o)})).sort((o,s)=>o.rank-s.rank||o.index-s.index).map(({target:o})=>o)}function fA(n,e){let t=Zd(n,e),r=t.filter(o=>o.online===!0);return r.length?r:t.slice(0,1)}function hA(n,e){return!e?.aborted&&X(n)&&(n.code==="unavailable"||n.code==="rate_limited")}function CR(n){let e=n.collection,t=n.next,r=n.staticKey;if(!Oy.test(e))throw A("invalid_request","collection must be a UUID");let o=t.route.bind(t),s=t.openPipe.bind(t),i=`next-relay:${e}`,a=null;return pf({description:i,open:async(c,l)=>{if(l?.aborted)throw A("cancelled","connect aborted");let p=await xR(()=>o(e,l?{signal:l}:{}));if(l?.aborted)throw A("cancelled","connect aborted");if(p.collection.toLowerCase()!==e.toLowerCase()||!Oy.test(p.grant))throw A("unauthenticated","the route does not match this collection's grant","route_mismatch");let d=wr(p.availability);if(d?.state==="unavailable")throw Vn(d.reason);let u=fA(p,a);if(!u.length)throw A("unavailable",p.reason==="no_device_registered"?"this collection has no device set up to serve it":"no device of this collection is online",p.reason??"no_device_online");let f;for(let h of u){let m=Object.freeze({...h}),w=m.noise_pk,b=new Uint8Array(32);for(let y=0;y<32;y++)b[y]=parseInt(w.slice(2*y,2*y+2),16);let g=Mi({description:i,staticKey:r,target:async()=>({prologue:Ti(N(m.relay_collection),N(p.grant),N(m.device)),remoteStatic:b,device:m.device,openCarrier:async y=>{let _=await xR(()=>s(e,m,y?{signal:y}:{}));return uA(_)}})});try{let y=await g.open(c,l);return a=y.device??null,y}catch(y){if(!hA(y,l))throw y;a===m.device&&(a=null),f??=y}}throw f},get target(){return a}})}var dA,PR,bN,wN,Oy,mA=I(()=>{"use strict";ve();qo();ie();la();lc();Qd();hp();dA=65535,PR=4+dA,bN=16,wN=1<<20,Oy=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i});function IR(n,e){let t=()=>A("unauthenticated","people scope changed","people_fenced"),r={collection:n,isCurrent:()=>e.holds(n),async request(o,s={}){if(o!=="identity"&&o!=="members")throw A("invalid_request","invalid people resource");for(let i=0;;i++){if(s.signal?.throwIfAborted(),!r.isCurrent())throw t();let a=await e.accessToken(n,i>0),{status:c,body:l}=await AN(e,`/v1/authorities/${n}/${o}`,a,s.signal);if(!r.isCurrent())throw t();if(!(c===401&&i===0)){if(c===401)throw A("unauthenticated","people credential is no longer current","people_fenced");if(c===403){let p=l?.error?.code;throw p==="approval_required"?Vn("approval_required"):A("forbidden","people access was refused",o==="members"&&p==="insufficient_access"?"people_permission_declined":"people_access")}if(c===404)throw A("upgrade_required","people metadata is unsupported","people_unsupported");if(c!==200||!l)throw yA();return l}}}};return r}async function AN(n,e,t,r){let o=new AbortController,s=()=>o.abort();r?.addEventListener("abort",s,{once:!0});let i=setTimeout(s,_N);i.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"}),c=await a.text();if(c.length>vN)throw yA();let l=null;try{let p=JSON.parse(c);p&&typeof p=="object"&&!Array.isArray(p)&&(l=p)}catch{l=null}return{status:a.status,body:l}}catch(a){throw r?.aborted?A("cancelled","request cancelled"):a instanceof oe?a:yA()}finally{clearTimeout(i),r?.removeEventListener("abort",s)}}var vN,_N,yA,OR=I(()=>{"use strict";qo();ie();vN=1024*1024,_N=15e3,yA=()=>A("unavailable","people metadata is unavailable","people_response")});function wA(n){if(!/^sha256:[a-f0-9]{64}$/.test(n))throw Li();return Uint8Array.from(n.slice(7).match(/../g),e=>parseInt(e,16))}function gA(n){if(!(n instanceof Map)||[...n.keys()].some(e=>typeof e!="number"))throw Li();return n}function Ry(n,e){if(!(n instanceof Uint8Array)||n.length!==e)throw Li();return n.slice()}function bA(n){if(n instanceof vt)return n.value;if(n instanceof Map){if([...n.keys()].some(e=>typeof e!="string"))throw Li();return Object.fromEntries([...n].map(([e,t])=>[e,bA(t)]))}if(Array.isArray(n))return n.map(bA);if(n===null||["string","boolean","number"].includes(typeof n))return n;throw Li()}async function eu(n,e,t,r){let o=ue(new Map([[0,1],[1,e],...t].sort(([i],[a])=>Number(i)-Number(a)))),s;try{s=await n.declaredSetup(o,r);let i=gA(we(s));if(i.get(0)!==1)throw Li();let a=i.get(1),c=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(i.size!==c.length||c.some(f=>!i.has(f)))throw Li();if(a==="cancelled")return{kind:a};if(a==="receipt")return{kind:a,receipt:kn.dec(i.get(3))};let l=Ry(i.get(2),16);if(a==="pending")return{kind:a,ticket:l};if(a!=="review"||!["ready","setup_required","incompatible"].includes(i.get(3))||typeof i.get(8)!="string")throw Li();let p=gA(i.get(9)),d=i.get(10);if(!(p instanceof Map)||p.size!==2||![p.get(0),p.get(1)].every(f=>Number.isSafeInteger(f)&&Number(f)>=0&&Number(f)<=256)||!Array.isArray(d)||d.length>32)throw Li();let u=d.map(f=>{let h=gA(f);if(h.size!==2||typeof h.get(0)!="string"||!["create","skip"].includes(h.get(1)))throw Li();return Object.freeze({path:h.get(0),action:h.get(1)})});return{kind:a,ticket:l,revision:Ry(i.get(4),32),declaration:RR(Ry(i.get(7),32)),application:i.get(8),promoted:p.get(0),retained:p.get(1),records:Object.freeze(u),assessment:Qs({status:i.get(3)==="ready"?"current":i.get(3)==="incompatible"?"conflict":"provision",assessmentDigest:"sha256:"+RR(Ry(i.get(5),32)),review:bA(i.get(6))},!0)}}finally{o.fill(0),s?.fill(0)}}var Li,RR,ER=I(()=>{"use strict";Ye();ie();es();Zt();Li=()=>A("internal","Invalid Native setup reply.","declared_setup_codec"),RR=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join("")});function kN(n){return new Promise((e,t)=>{if(n?.aborted)return t(A("cancelled","Setup cancelled."));let r=()=>{clearTimeout(o),t(A("cancelled","Setup cancelled."))},o=setTimeout(()=>{n?.removeEventListener("abort",r),e()},100);n?.addEventListener("abort",r,{once:!0})})}function qR(n){let{client:e,journal:t}=n,r=n.operations.includes("assess_collection_setup")&&n.operations.includes("apply_collection_setup"),o=new WeakMap,s=new WeakSet,i=!1,a;async function c(b){if(i)throw A("rate_limited","A setup operation is already running.");i=!0;try{return a&&(await a,a=void 0),await b()}finally{i=!1}}async function l(b,g){if(b||await e.readyForRead(g),await n.assertCurrent(),g?.aborted)throw A("cancelled","Setup cancelled.");if(b&&(b.closed||e.currentSession()!==b))throw ss()}async function p(b,g){try{await eu(b,"cancel",[[2,g]],AbortSignal.timeout(1e3))}catch{}}async function d(b={}){await l(void 0,b.signal);let g=await e.readyForRead(b.signal);await l(g,b.signal);let y=await pm(n.manifest);await l(g,b.signal);let _=Or(b.adopt===void 0?{}:{adopt:b.adopt}),v=iy(b.records),k=[];_.adopt&&Object.keys(_.adopt).length&&k.push([3,new Map(Object.entries(_.adopt).map(([x,P])=>[x,wA(P)]))]),v.length&&k.push([4,v.map(x=>new Map([[0,x.path],[1,x.document]]))]);let S;try{let x=await eu(g,"assess",k,b.signal);await l(g,b.signal);for(let P=0;x.kind==="pending";P++){if(S=x.ticket,P>=512)throw tu();await kN(b.signal),await l(g,b.signal),x=await eu(g,"poll",[[2,S]],b.signal),await l(g,b.signal)}if(x.kind!=="review")throw tu();if(S=x.ticket,x.declaration!==y||x.application!==n.manifest?.id)throw ss();if(x.records.length!==v.length||x.records.some((P,C)=>P.path!==v[C].path))throw tu();return{s:g,review:x,options:{records:v,..._.adopt?{adopt:Object.freeze({..._.adopt})}:{}}}}catch(x){throw S&&await p(g,S),x}}async function u(b){await l(void 0,b);let g=await t.load();if(await l(void 0,b),!g)return;let y;try{y=await e.receipt(g,{signal:b})}catch(_){throw pa(g,_)}if(await l(void 0,b),y.mutation!==g||y.state!=="confirmed"&&y.state!=="rejected")throw pa(g);await t.clear(g)}function f(b,g){return Nd(g.assessment,{canManage:!0,canCreateRecords:b.hello.grant.capabilities.includes("records.create"),records:g.records.map(y=>({path:y.path,free:y.action==="create"})),...g.promoted?{promoted:g.promoted}:{}})}let h=(b,g)=>JSON.stringify([b.status,b.canApply,b.summary,b.changes,b.conflicts,b.adoptable,b.packs,b.staged,b.records,b.refusal??null,g.promoted,g.retained]);async function m(b){if(await l(void 0,b.signal),!r){if(n.operations.includes("apply_collection_setup")||n.operations.includes("assess_collection_setup"))throw tu();let k=Nd({status:"current",assessmentDigest:`sha256:${"0".repeat(64)}`,review:{configuration:[],packs:[],staged:[]}},{canManage:!1,canCreateRecords:!1,records:[]});return s.add(k),k}await u(b.signal);let{s:g,review:y,options:_}=await d(b),v=f(g,y);return o.set(v,{session:g,review:y,options:_,consumed:!1}),v}return Object.freeze({assess(b={}){return c(async()=>{let g=await m(b),y=o.get(g);return y&&(a=p(y.session,y.review.ticket),await l(y.session,b.signal)),g.status==="current"?"ready":g.refusal?.code==="installed_newer"?"incompatible":"setup_required"})},plan(b={}){return c(()=>m(b))},async apply(b,g={}){return c(async()=>{if(s.has(b))return await l(void 0,g.signal),"ready";let y=o.get(b);if(!y)throw new TypeError("setup.apply needs the original plan returned by setup.plan");if(y.consumed)throw ss();if(b.refusal)throw A(b.refusal.code==="setup_conflict"?"conflict":b.refusal.code==="installed_newer"?"upgrade_required":"forbidden",b.refusal.message,b.refusal.code);if(b.status==="current"){await l(y.session,g.signal);let _=await d({signal:g.signal});if(await p(_.s,_.review.ticket),_.review.assessment.status!=="current")throw ss();return"ready"}y.consumed=!0;for(let _=0;;_++){let v=crypto.randomUUID(),k;try{k=await t.begin(v)}catch(P){throw pa(v,P)}if(k!==v)throw pa(k);let S=!1,x=!1;try{await l(y.session,g.signal),S=!0;let P=await eu(y.session,"apply",[[2,y.review.ticket],[3,N(v)],[4,y.review.revision],[5,wA(y.review.assessment.assessmentDigest)]],g.signal);if(await n.assertCurrent(),P.kind!=="receipt"||P.receipt.mutation!==v)throw pa(v);let C=P.receipt.state==="pending"?await e.awaitReceipt(v,{timeoutMs:3e4,signal:g.signal}):P.receipt;if(await n.assertCurrent(),C.mutation!==v||C.state!=="confirmed"&&C.state!=="rejected")throw pa(v);if(x=!0,await t.clear(v),C.state==="rejected"||(C.conflicts?.length??0)>0||C.status!==void 0&&C.status!=="applied")throw ss(v,C.problem);let R=await d({signal:g.signal});if(R.review.assessment.status!=="current")throw tu();return await p(R.s,R.review.ticket),"ready"}catch(P){if(!S||x||ja(P)&&P.code!=="outcome_unknown"){if(await t.clear(v),!x&&(ja(P)?P.code==="not_found"||P.code==="conflict":!S&&X(P,"conflict")&&P.reason==="setup_changed")){if(_)throw ss(v,P);let R=await d({...y.options,signal:g.signal});try{if(await l(R.s,g.signal),R.review.assessment.status!=="provision"||h(f(R.s,R.review),R.review)!==h(b,y.review))throw ss(v,P)}catch(O){throw await p(R.s,R.review.ticket),O}y={...y,session:R.s,review:R.review};continue}throw new oe((X(P)?P:ss()).toProblem(),{mutationId:v,cause:P})}throw pa(v,P)}}})}})}var ss,pa,tu,TR=I(()=>{"use strict";ie();ve();Ua();es();oy();um();ER();ss=(n,e)=>new oe(A("conflict","This collection changed since setup was reviewed. Review it again.","setup_changed").toProblem(),{...n?{mutationId:n}:{},...e?{cause:e}:{}}),pa=(n,e)=>new oe(A("outcome_unknown","Reconcile the original setup before trying again.","setup_outcome_unknown").toProblem(),{mutationId:n,...e?{cause:e}:{}}),tu=()=>A("unavailable","Native setup is unavailable.","resource_setup_unavailable")});function LR(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 r(){let s=await n.grant();await n.assertCurrent(s);let i=await n.store();if(!i.getSetupAttempt||!i.putSetupAttemptIfAbsent||!i.deleteSetupAttempt)throw t();return{grant:s,store:i}}async function o(s,i){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},i.refreshKey,s.slice(12)));let c=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a)),l=Array.from(i.noisePublicKey,p=>p.toString(16).padStart(2,"0")).join("");if(c.version!==1||!MR.test(c.mid)||c.noise!==l||Object.keys(c).sort().join(",")!=="mid,noise,version")throw t();return await n.assertCurrent(i),c.mid}catch{throw t()}finally{a?.fill(0)}}return{async load(){let{grant:s,store:i}=await r(),a=await i.getSetupAttempt(s.collection);return await n.assertCurrent(s),a?o(a,s):void 0},async begin(s){if(!MR.test(s))throw t();let{grant:i,store:a}=await r(),c=crypto.getRandomValues(new Uint8Array(12)),l=new TextEncoder().encode(JSON.stringify({version:1,mid:s,noise:Array.from(i.noisePublicKey,u=>u.toString(16).padStart(2,"0")).join("")})),p;try{p=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:c,additionalData:e},i.refreshKey,l))}finally{l.fill(0)}await n.assertCurrent(i);let d=await a.putSetupAttemptIfAbsent(i.collection,new Uint8Array([...c,...p]));return o(d,i)},async clear(s){let{grant:i,store:a}=await r(),c=await a.getSetupAttempt(i.collection);c&&await o(c,i)===s&&(await n.assertCurrent(i),await a.deleteSetupAttempt(i.collection,c))}}}var MR,jR=I(()=>{"use strict";ie();MR=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/});function nu(){throw A("unauthenticated","the stored grant belongs to another app","grant_storage")}function UR(n,e,t={}){let r=globalThis.indexedDB;if(!r)throw A("unavailable","IndexedDB is not available here","grant_storage");let o=t.owner;if(o!==void 0&&!Fs(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}`,i=h=>h===void 0||o===void 0||h.owner===o?h:nu(),a=h=>o===void 0||h===void 0||h.owner===o,c=h=>o===void 0?h:{...h,owner:o},l=null,p=()=>l??=new Promise((h,m)=>{let w=r.open(s,2);w.onupgradeneeded=()=>{for(let b of[vA,da,pc])w.result.objectStoreNames.contains(b)||w.result.createObjectStore(b)},w.onsuccess=()=>{w.result.onversionchange=()=>{w.result.close(),l=null},h(w.result)},w.onerror=()=>{l=null,m(A("unavailable","grant storage could not be opened","grant_storage"))}}),d=async(h,m,w)=>{let b=await p();return new Promise((g,y)=>{let _=b.transaction([...h],m,{durability:"strict"}),v,k=!1;_.oncomplete=()=>k?g(v):y(A("unavailable","grant storage returned no result","grant_storage")),_.onabort=_.onerror=()=>y(A("unavailable","grant storage transaction failed","grant_storage"));try{w(_,S=>{v=S,k=!0})}catch{try{_.abort()}catch{}}})},u=(h,m,w)=>d([h],m,(b,g)=>w(b.objectStore(h),g)),f=(h,m)=>u(h,"readonly",(w,b)=>{let g=w.get(m);g.onsuccess=()=>b(g.result)});return{getSetupAttempt:async h=>i(await f(pc,h))?.bytes,putSetupAttemptIfAbsent:async(h,m)=>i(await u(pc,"readwrite",(w,b)=>{let g=w.get(h);g.onsuccess=()=>{if(g.result!==void 0)return b(g.result);let y=c({bytes:m.slice()});w.add(y,h).onsuccess=()=>b(y)}})).bytes,deleteSetupAttempt:async(h,m)=>{await u(pc,"readwrite",(b,g)=>{let y=b.get(h);y.onsuccess=()=>{if(!a(y.result))return g("refused");let _=y.result?.bytes;if(!_||_.length!==m.length||!_.every((v,k)=>v===m[k]))return g("done");b.delete(h).onsuccess=()=>g("done")}})==="refused"&&nu()},getIdentity:async()=>i(await f(vA,"installation")),putIdentityIfAbsent:async h=>i(await u(vA,"readwrite",(m,w)=>{let b=m.get("installation");b.onsuccess=()=>{if(b.result!==void 0)return w(b.result);let g=c(h);m.add(g,"installation").onsuccess=()=>w(g)}})),getGrant:async h=>i(await f(da,h)),listGrants:async()=>(await u(da,"readonly",(h,m)=>{let w=h.getAll();w.onsuccess=()=>m(w.result)})).map(h=>i(h)),putGrant:async h=>{await u(da,"readwrite",(w,b)=>{let g=w.get(h.collection);g.onsuccess=()=>{if(!a(g.result))return b("refused");w.put(c(h),h.collection).onsuccess=()=>b("done")}})==="refused"&&nu()},deleteGrant:async h=>{await u(da,"readwrite",(w,b)=>{let g=w.get(h);g.onsuccess=()=>{if(!a(g.result))return b("refused");w.delete(h).onsuccess=()=>b("done")}})==="refused"&&nu()},clearGrants:async()=>{await d([da,pc],"readwrite",(m,w)=>{let b=!1,g=2,y=()=>{--g===0&&w(b?"refused":"done")};for(let _ of[da,pc]){let v=m.objectStore(_);if(o===void 0){v.clear().onsuccess=y;continue}let k=v.openCursor();k.onsuccess=()=>{let S=k.result;if(!S)return y();a(S.value)?S.delete():b=!0,S.continue()}}})==="refused"&&nu()}}}var vA,da,pc,NR=I(()=>{"use strict";Qo();ie();vA="identity",da="grants",pc="native-setup-attempts"});var FR={};Ca(FR,{MdbaseAppGrants:()=>SA,deliverAppGrantCallback:()=>IN,mergeCollectionEntries:()=>RN});function xN(n){try{let e=Uint8Array.from(atob(n.replaceAll("-","+").replaceAll("_","/")),t=>t.charCodeAt(0));return e.length===32&&Tn(e)===n}catch{return!1}}function IN(n){let e=globalThis.BroadcastChannel;if(!e)throw A("unavailable","BroadcastChannel is not available","authorization_callback");let t=new e(VR);t.postMessage({type:"callback",url:String(n)}),t.close()}function ON(){return{subscribe(n){let e=globalThis.BroadcastChannel;if(!e)throw A("unavailable","BroadcastChannel is not available","authorization_callback");let t=new e(VR);return t.onmessage=r=>{let o=r.data;o?.type==="callback"&&typeof o.url=="string"&&n(o.url)},()=>t.close()}}}function RN(n,e){let t=new Map;for(let r of n)t.set(r.collectionId,Object.freeze({collectionId:r.collectionId,displayName:r.displayName,kind:"cloud_copy",availability:r.availability??Object.freeze({state:"available"}),role:r.role}));for(let r of e)t.has(r.collectionId)||t.set(r.collectionId,Object.freeze({collectionId:r.collectionId,displayName:r.displayName,kind:"private",availability:r.availability,role:r.role}));return[...t.values()].sort((r,o)=>r.displayName.localeCompare(o.displayName)||r.collectionId.localeCompare(o.collectionId))}async function kA(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 r=0n;for(let s of t.subarray(32))r=r<<8n|BigInt(s);if(r<=DR/2n)return t;let o=DR-r;for(let s=63;s>=32;s--)t[s]=Number(o&0xffn),o>>=8n;return t}async function EN(n,e,t,r){let o=Math.floor(Date.now()/1e3),s=crypto.randomUUID(),i=[m1,jv,"POST",e,await BR(t),await BR(r),o,s].join(`
130
- `);return{[pd.version]:String(jv),[pd.timestamp]:String(o),[pd.nonce]:s,[pd.signature]:Tn(await kA(n,new TextEncoder().encode(i)))}}async function _A(n,e){let t=await crypto.subtle.generateKey({name:e,namedCurve:"P-256"},!1,n);return{privateKey:t.privateKey,publicKey:Tn(new Uint8Array(await crypto.subtle.exportKey("raw",t.publicKey)))}}async function qN(){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 TN(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 MN(n,e){let t=new AbortController,r=()=>t.abort(),o=setTimeout(r,e);return o.unref?.(),n?.addEventListener("abort",r,{once:!0}),n?.aborted&&t.abort(),{signal:t.signal,done:()=>{clearTimeout(o),n?.removeEventListener("abort",r)}}}async function LN(n,e){let t=globalThis.navigator?.locks;if(t)return t.request(n,{mode:"exclusive"},e);let r=qy.get(n)??Promise.resolve(),o,s=new Promise(i=>{o=i});qy.set(n,s),await r;try{return await e()}finally{o(),qy.get(n)===s&&qy.delete(n)}}var SN,VR,as,PN,DR,CN,Tn,Ey,zR,$R,BR,Ty,ua,AA,ji,qy,SA,KR=I(()=>{"use strict";dd();Xo();Tl();Qf();am();vO();um();ve();qo();ie();vn();mA();la();lc();hp();Qd();Sp();OR();TR();jR();Db();NR();Yv();SN=new Set(["owner","editor","viewer"]),VR="mdbase.app-grant.v1",as=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,PN=15e3;DR=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),CN=new TextEncoder().encode("mdbase-next client noise key v1\0");Tn=n=>{let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")},Ey=n=>crypto.getRandomValues(new Uint8Array(n)),zR=n=>{let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n),e},$R=(...n)=>{let e=new Uint8Array(n.reduce((r,o)=>r+o.length,0)),t=0;for(let r of n)e.set(r,t),t+=r.length;return e};BR=async n=>Tn(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n))));Ty=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]),ua=(n,e)=>!!e&&n.collection===e.collection&&n.owner===e.owner&&Ty(n.noisePublicKey,e.noisePublicKey),AA=(n,e)=>ua(n,e)&&Ty(n.refresh,e.refresh),ji=()=>A("cancelled","the stored grant changed during this operation"),qy=new Map;SA=class{constructor(e){this.options=e;this.declaration=so(e.declaration),this.cpOrigin=Cr({environment:this.declaration.environment,appOrigin:this.declaration.origin,release:wO()}).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??ON(),this.storeValue=e.store??null}options;declaration;cpOrigin;redirect;fetcher;callbacks;storeValue;registration=null;tokens=new Map;routeProbe;refreshing=new Map;forgotten=new Set;epoch=0;register(){let e=this.registration??=dm({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??=bx(Jo(this.declaration).manifest.id,Xf(this.declaration))}async store(){if(this.storeValue)return this.storeValue;let e=this.owner();return this.storeValue=UR(this.cpOrigin,(await this.register()).id,{owner:e})}async identity(){let e=await this.store(),t=await e.getIdentity();if(t)return t;let r=await _A(["sign"],"ECDSA");return e.putIdentityIfAbsent({version:1,privateKey:r.privateKey,publicKey:r.publicKey})}async request(e,t,r){let o=MN(r,PN);try{let s;try{s=await this.fetcher(`${this.cpOrigin}${e}`,{...t,redirect:"error",credentials:"omit",signal:o.signal})}catch{throw r?.aborted?A("cancelled","request cancelled"):A("unavailable","cannot reach the control plane","control_unreachable")}let i=null;try{let a=await s.json();a&&typeof a=="object"&&!Array.isArray(a)&&(i=a)}catch{i=null}return{status:s.status,body:i}}finally{o.done()}}async authorize(e){e=Object.freeze({...e});let t=await this.prepareAuthorization(e).catch(r=>{throw e.popup.close(),r});try{e.popup.navigate(t.authorizationUri);let{collectionId:r}=await t.finish(e);return{collectionId:r}}finally{t.cancel();try{e.popup.close()}catch{}}}async prepareAuthorization(e={}){if(e=Object.freeze({...e}),e.collection!==void 0&&!as.test(e.collection))throw A("invalid_request","collection must be a UUID");if(e.expectedAccountId!==void 0&&(!as.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)||!xN(e.authorizationNonce)))throw A("invalid_request","invalid original challenge","authorization_binding");let t=new AbortController,r=e.signal?AbortSignal.any([e.signal,t.signal]):t.signal,o=this.epoch,s=()=>{if(r.aborted)throw A("cancelled","authorization fenced","authorization_cancelled");if(o!==this.epoch)throw ji()};s();let i=await this.register(),a=Jo(this.declaration),c=await this.identity(),l=await _A(["deriveBits"],"ECDH"),p=await _A(["sign"],"ECDSA"),d=await qN(),u=Tn(Ey(32)),f=Tn(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(u)))),h=Tn(Ey(24)),m=crypto.randomUUID(),w=new Date,b={protocol_version:oo,authorization_id:m,application_id:i.id,application_declaration_id:String(a.manifest.id),application_manifest_digest:i.manifestDigest,application_installation_id:await p1(c.publicKey),installation_signing_public_key:c.publicKey,grant_agreement_public_key:l.publicKey,grant_signing_public_key:p.publicKey,flow:"authorization_code",authorization_nonce:e.authorizationNonce??Tn(Ey(32)),issued_at:w.toISOString(),expires_at:new Date(w.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:b,signature:Tn(await kA(c.privateKey,d1(b)))},y=$R(CN,zR(16),N(m),zR(32),d.publicKey),_={public_key:Tn(d.publicKey),signature:Tn(await kA(p.privateKey,y))};s();let v=await this.request("/oauth/authorization_request",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:i.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(_)})},r);s();let k=v.body?.authorization_uri;if(v.status!==200||v.body?.authorization_id!==m||typeof k!="string"||!k.startsWith(`${this.cpOrigin}/oauth/authorize?`))throw A("unavailable",`authorization could not be started (${v.status})`,"authorization_start");let S=null,x=this.awaitCallback(h,{navigate(){},close(){},get closed(){return S?.closed===!0}},{popup:{navigate(){},close(){}},signal:r,timeoutMs:e.timeoutMs});x.catch(()=>{});let P=!1;return Object.freeze({applicationId:i.id,manifestDigest:i.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 R=()=>t.abort();C.signal?.addEventListener("abort",R,{once:!0}),C.signal?.aborted&&t.abort();try{s();let O=C.collection??e.collection;if(O!==void 0&&!as.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 E=await x;s();let j=await this.request("/oauth/token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:E,client_id:i.id,redirect_uri:this.redirect.href,code_verifier:u})},r);s();let B=e.expectedAccountId?bm(j.body,{accountId:e.expectedAccountId,authorizationRequestId:m,applicationId:i.id,declarationId:b.application_declaration_id,manifestDigest:i.manifestDigest,applicationInstallationId:b.application_installation_id,applicationOrigin:this.redirect.origin,collectionId:O,grantSigningPublicKey:p.publicKey,clientNoisePublicKey:Tn(d.publicKey)}):void 0,D=await this.saveTokens(j,{noise:d,signing:p.privateKey,collection:O,check:s});return s(),{collectionId:D,...B?{nativeCompletion:B}:{}}}finally{C.signal?.removeEventListener("abort",R),t.abort()}}})}awaitCallback(e,t,r){let o=Math.min(Math.max(r.timeoutMs??6e5,1e3),18e5);return new Promise((s,i)=>{let a=null,c=f=>{p(),clearTimeout(d),clearInterval(u),r.signal?.removeEventListener("abort",l),f()},l=()=>c(()=>i(A("cancelled","authorization cancelled","authorization_cancelled"))),p=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 c(()=>i(A("forbidden","access was not approved","authorization_denied")));let w=h.searchParams.get("code");if(!w)return c(()=>i(A("unavailable","the authorization callback has no code","authorization_callback")));c(()=>s(w))}),d=setTimeout(()=>c(()=>i(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&&c(()=>i(A("cancelled","the authorization window was closed","authorization_cancelled")))},500);r.signal?.addEventListener("abort",l,{once:!0}),r.signal?.aborted&&l()})}async saveTokens(e,t){let r=e.body;if(e.status!==200||!r)throw e.status===400&&r&&typeof r.error=="string"&&r.error==="invalid_grant"?A("unauthenticated","the grant is no longer valid","grant_invalid"):e.status===400?Vn("sync_required"):A("unavailable",`token request failed (${e.status})`,"token_error");let o=r.access_token,s=r.refresh_token,i=r.collection_id,a=r.expires_in,c=r.refresh_expires_in;if(typeof o!="string"||typeof s!="string"||typeof i!="string"||!as.test(i)||typeof a!="number"||!(a>0)||typeof c!="number"||!(c>0))throw A("unavailable","invalid token response","token_response");let l=i.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 p=t.previous?.refreshKey??await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),d=Ey(12),u=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:d,additionalData:this.aad(l)},p,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:p,refresh:$R(d,u),refreshExpiresAt:Date.now()+c*1e3,...h?{signingPrivateKey:h}:{},...t.previous?.owner?{owner:t.previous.owner}:{}},w=this.epoch;return await this.withLock(l,"commit",async()=>{let b=await this.store();if(w!==this.epoch||t.previous&&!AA(t.previous,await b.getGrant(l)))throw ji();t.check?.(),await b.putGrant(m);let g=await b.getGrant(l);if(!g||!Ty(m.noisePublicKey,g.noisePublicKey)||!Ty(m.refresh,g.refresh))throw ji();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 r=await this.heldGrant(e),o=this.tokens.get(e);if(!t&&o&&ua(r,o)&&o.expiresAt-Date.now()>6e4)return o.access;let s=this.refreshing.get(e);if(s&&AA(r,s.grant)){let c=await s.work;return await this.assertCurrent(r),c}let i=this.withLock(e,"refresh",async()=>{let c=await this.assertCurrent(r);return this.refresh(e,c)}),a={grant:r,work:i};this.refreshing.set(e,a);try{let c=await i;return await this.assertCurrent(r),c}finally{this.refreshing.get(e)===a&&this.refreshing.delete(e)}}withLock(e,t,r){return LN(`mdbase.app-grant.${t}:${JSON.stringify([this.cpOrigin,this.owner(),e])}`,r)}async heldGrant(e){let t=await(await this.store()).getGrant(e);if(!t)throw Vn("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(!ua(e,t))throw ji();return t}async refresh(e,t){if(t.refreshExpiresAt<=Date.now())throw Vn("sync_required");let r;try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:t.refresh.slice(0,12),additionalData:this.aad(e)},t.refreshKey,t.refresh.slice(12));r=new TextDecoder().decode(c)}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:r,client_id:o.id}),i=t.signingPrivateKey?await EN(t.signingPrivateKey,"/oauth/token",s.toString(),r):{},a=await this.request("/oauth/token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...i},body:s});try{await this.saveTokens(a,{previous:t})}catch(c){throw X(c,"unauthenticated")&&c.reason==="grant_invalid"&&await this.withLock(e,"commit",async()=>{let l=await this.store();if(!AA(t,await l.getGrant(e)))throw ji();await l.deleteGrant(e),this.forgotten.add(e);let p=this.tokens.get(e);p&&ua(t,p)&&this.tokens.delete(e)}),c}return a.body.access_token}async route(e,t){for(let r=0;;r++){let o=await this.accessToken(e,r>0),s=await this.request(`/v1/next/collections/${encodeURIComponent(e)}/route`,{headers:{authorization:`Bearer ${o}`}},t);if(s.status===401&&r===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 i=s.body;if(typeof i.collection!="string"||i.collection.toLowerCase()!==e||!Array.isArray(i.targets))throw A("unauthenticated","the route does not match this collection's grant","route_mismatch");let c=wr(i.availability)??(Zd(i,null).length?{state:"available"}:{state:"unavailable",reason:i.reason==="no_device_registered"?"no_device_registered":"device_offline"});return{token:o,route:i,availability:c}}}async verifiedStoredNativeGrant(e){let t=await this.register(),r=await(await this.store()).getGrant(e.collection_id);return!!r&&e.application_id===t.id&&e.application_origin===this.declaration.origin&&r.owner===this.owner()&&Tn(r.noisePublicKey)===e.client_noise_public_key}async collections(e={}){let t=await(await this.store()).listGrants(),r=[];for(let s of t)(e.bindings===void 0||e.bindings.some(i=>i.collection_id===s.collection&&i.application_origin===this.declaration.origin&&Tn(s.noisePublicKey)===i.client_noise_public_key))&&r.push(s);let o=new Set(r.map(s=>s.collection));for(let s of r){let i;try{i=await this.accessToken(s.collection)}catch(l){if(X(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 ${i}`}},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!==i||!ua(s,l))throw ji();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 c=[];for(let l of a.body.collections){let p=typeof l.collection=="string"?l.collection.toLowerCase():"";if(!as.test(p)||c.some(f=>f.collectionId===p))continue;let d=wr(l.availability);if(l.state!=="synced_e2e"&&!d)continue;let u=o.has(p)?d??{state:"opening"}:{state:"unavailable",reason:"sync_required"};c.push(Object.freeze({collectionId:p,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:SN.has(l.role)?l.role:null}))}return c}return[]}async availability(e,t={}){let r=e.toLowerCase(),o=this.routeProbe={};try{let{token:s,route:i,availability:a}=await this.route(r,t.signal),c=this.tokens.get(r);return a.state==="available"&&!t.signal?.aborted&&c?.access===s&&(o.ready={credentials:c,route:i,until:performance.now()+3e3,signal:t.signal}),a}catch(s){let i=X(s)?fe(s.details,"availability"):void 0;if(typeof i=="string")return wr({state:"unavailable",reason:i});throw s}}async waitForAvailable(e,t={}){let r=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 i=await this.availability(e,t.signal?{signal:t.signal}:{});if((!s||i.state!==s.state||i.state==="unavailable"&&s.state==="unavailable"&&i.reason!==s.reason)&&t.onAvailability?.(i),s=i,i.state==="available"||i.state==="unavailable"&&(i.reason==="sync_required"||i.reason==="access_removed"))return i;let a=r-Date.now();if(a<=0)return i;await new Promise(c=>{let l=setTimeout(p,Math.min(o,a));function p(){clearTimeout(l),t.signal?.removeEventListener("abort",p),c()}t.signal?.addEventListener("abort",p,{once:!0})})}}connector(e){let t=e.toLowerCase();if(!as.test(t))throw A("invalid_request","collection must be a UUID");let r=null,o=this.options.webSocket,s;return pf({description:`app-grant:${t}`,open:async(i,a)=>{let c=s===void 0?this.routeProbe?.ready:void 0;this.routeProbe=void 0;let l=await(s??=this.heldGrant(t));if(await this.assertCurrent(l),a?.aborted)throw A("cancelled","connect aborted");let{token:p,route:d,availability:u}=c&&!c.signal?.aborted&&performance.now()<c.until&&c.credentials===this.tokens.get(t)&&ua(l,c.credentials)&&c.credentials.expiresAt>Date.now()?{token:c.credentials.access,route:c.route,availability:{state:"available"}}:await this.route(t,a);if(await this.assertCurrent(l),a?.aborted)throw A("cancelled","connect aborted");if(u.state==="unavailable")throw Vn(u.reason);if(!as.test(d.grant))throw A("unauthenticated","the route names no grant","route_mismatch");let f=fA(d,r);if(!f.length)throw Vn("device_offline");let h;for(let m of f){await this.assertCurrent(l);let w=new Uint8Array(32);for(let y=0;y<32;y++)w[y]=parseInt(m.noise_pk.slice(2*y,2*y+2),16);let b=Mi({description:`app-grant:${t}`,staticKey:TN(l),target:async()=>({prologue:Ti(N(m.relay_collection),N(d.grant),N(m.device)),remoteStatic:w,device:m.device,openCarrier:async y=>{await this.assertCurrent(l);let _=await cc(m.url,{accessToken:p,collection:m.relay_collection,grant:d.grant,device:m.device,devicePublicKey:w},o,y);try{return await this.assertCurrent(l),_}catch(v){throw _.close(),v}}})}),g;try{g=await b.open(i,a)}catch(y){if(!hA(y,a))throw y;r===m.device&&(r=null),h??=y;continue}try{await this.assertCurrent(l)}catch(y){throw g.port.close(),y}return PS(g.port,l),r=g.device??null,g}throw h},get target(){return r}})}people(e,t){let r=e.toLowerCase();if(!as.test(r))throw A("invalid_request","collection must be a UUID");return new gi(t,IR(r,{cpOrigin:this.cpOrigin,fetch:this.fetcher,accessToken:(o,s)=>this.accessToken(o,s),holds:o=>!this.forgotten.has(o)}))}setup(e){let t=Jo(this.declaration),r,o=async()=>{let i=e.currentSession(),a=i&&CS(i);if(!a||a.collection!==e.collection||(r??=a,!ua(r,a)))throw ji();return r};return qR({assertCurrent:async()=>this.assertCurrent(await o()),journal:LR({store:()=>this.store(),grant:o,assertCurrent:i=>this.assertCurrent(i),aad:this.aad(e.collection)}),client:e,manifest:t.manifest,operations:t.operations})}async forget(e,t={}){let r=e.toLowerCase(),o=t.expectedNoisePublicKey;await this.withLock(r,"commit",async()=>{let s=await this.store(),i=await s.getGrant(r);if(o!==void 0&&i&&Tn(i.noisePublicKey)!==o)throw ji();await s.deleteGrant(r),this.forgotten.add(r),this.tokens.delete(r),this.routeProbe=void 0})}async forgetAllGrants(){this.routeProbe=void 0,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 r=async(o,s)=>o.length?this.withLock(o[0],"commit",()=>r(o.slice(1),s)):s();await r(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 HR(n){let e=0,t=0;try{let r=n?.records.status.pending;e=typeof r=="number"&&r>0?r:0}catch{e=0}try{t=n?.records.ledger?.getSnapshot().pending.length??0}catch{t=0}return Math.max(e,t)}function GR(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 YR=I(()=>{"use strict";ie()});function JR(){return new Promise(n=>{let e;try{e=indexedDB.open(IA,1)}catch{n(null);return}e.onupgradeneeded=()=>{try{e.result.createObjectStore(uc)}catch{}},e.onsuccess=()=>{let t=e.result;t.onversionchange=()=>t.close(),n(t.objectStoreNames.contains(uc)?t:(t.close(),null))},e.onerror=e.onblocked=()=>n(null)})}function CA(n,e){return JR().then(t=>new Promise(r=>{if(!t){r(null);return}let o=null;try{let s=t.transaction(uc,n),i=e(s.objectStore(uc));i&&(i.onsuccess=()=>{o=i.result??null}),s.oncomplete=()=>{t.close(),r(o)},s.onerror=s.onabort=()=>{t.close(),r(null)}}catch{t.close(),r(null)}}))}function XR(){return typeof indexedDB>"u"?null:Object.freeze({async read(n,e){let t=await CA("readonly",r=>r.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 CA("readwrite",t=>t.put({value:e.value,expires:e.expires},n)).catch(()=>null)},async drop(n){await CA("readwrite",e=>e.delete(n)).catch(()=>null)}})}async function QR(n){let{cpOrigin:e,connectorId:t,deviceId:r}=n;if(!t||!r)return!0;let o=await JR();return o?new Promise(s=>{try{let i=o.transaction(uc,"readwrite"),a=i.objectStore(uc).openCursor();a.onsuccess=()=>{let c=a.result;if(c){if(typeof c.key=="string"){let l=c.key.split(" ");l.length===5&&l[0]===e&&l[2]===t&&l[3]===r&&c.delete()}c.continue()}},i.oncomplete=()=>{o.close(),s(!0)},i.onerror=i.onabort=()=>{o.close(),s(!1)}}catch{o.close(),s(!1)}}):!1}var IA,uc,OA=I(()=>{"use strict";IA="mdbase.app.log-token.v1",uc="tokens"});function fa(n,e){return new Promise((t,r)=>{if(e.aborted){r(e.reason);return}let o=()=>{clearTimeout(s),r(e.reason)},s=setTimeout(()=>{e.removeEventListener("abort",o),t()},n);e.addEventListener("abort",o,{once:!0})})}var jy=I(()=>{"use strict"});function ZN(n,e){let t=new URL(n);if(t.protocol==="https:")return`wss://${t.host}`;if(e&&Ze(n))return`ws://${t.host}`;throw new Error("app log push: origin")}function t8(n){let e=n.get(3);if(!(e instanceof Map))return null;let t=e.get(0),r=e.get(1);return{code:typeof t=="string"?t:"unavailable",reason:typeof r=="string"?r:""}}var BN,VN,FN,KN,WN,HN,GN,YN,JN,XN,QN,e8,ZR,Uy,e2=I(()=>{"use strict";At();Ye();ve();BN=4401,VN=4403,FN=4410,KN=3e4,WN=1e4,HN=6e4,GN=6e4,YN=15e3,JN=4,XN=64*1024,QN=1024*1024;e8=n=>[...n].map(e=>e.toString(16).padStart(2,"0")).join(""),ZR=(n,e,t)=>ue(new Map([[0,0],[1,n],[2,e],[3,t]]));Uy=class{constructor(e,t,r={}){this.source=e;this.events=t;this.base=ZN(e.origin,r.allowLoopbackHttp===!0),this.collectionBytes=N(e.collection);let o=r.WebSocket??globalThis.WebSocket;if(typeof o!="function")throw new Error("app log push: no WebSocket");this.Ws=o,this.random=r.random??Math.random,this.now=r.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 r=this.socket;if(this.socket=null,r){r.onopen=r.onmessage=r.onclose=r.onerror=null;try{r.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(GN,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,r;try{let i=this.life.signal;if(e=await this.source.accessToken({signal:i}),t=await this.source.nonce({signal:i}),this.paused||!this.available||!this.source.isCurrent())return;if(r=this.source.signHello(t,e),!r){++this.unsigned>=JN?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=${e8(t)}`)}catch{this.schedule();return}o.binaryType="arraybuffer",this.socket=o;let s=ZR(1,"hello",new Map([[0,[1,0]],[1,e],[2,N(this.source.deviceId)],[3,r]]));r.fill(0),t.fill(0),o.onopen=()=>{try{o.send(s)}catch{this.lost(o,1006)}},o.onmessage=i=>this.message(o,i.data),o.onclose=i=>this.lost(o,i.code),o.onerror=()=>{},this.opening=setTimeout(()=>{this.opening=null,this.lost(o,1006)},YN)}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>QN){this.lost(e,1009);return}let r=new Uint8Array(t),o;try{let a=we(r);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(r),o.get(1)==="closed"){let a=o.get(2),c=a instanceof Map?a.get(1):null;this.end(c==="gone"?"gone":c==="revoked"?"revoked":"forbidden")}return}if(o.get(0)!==1)return;let s=o.get(1),i=t8(o);if(s===1){if(i){this.refused(e,i);return}try{e.send(ZR(2,"subscribe",new Map([[0,this.collectionBytes],[1,0],[2,XN]])))}catch{this.lost(e,1006)}return}if(s===2){if(i){this.refused(e,i);return}let a=o.get(2);if(!(a instanceof Map)){this.lost(e,1007);return}let c=a.get(0),l=a.get(1);this.startPing(e),this.setLive(!0),(typeof c=="number"||typeof c=="bigint")&&l instanceof Uint8Array&&l.length===32&&this.deliver(ue(new Map([[0,2],[1,"head"],[2,new Map([[0,this.collectionBytes],[1,c],[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)},WN)}},KN)}lost(e,t){if(e!==this.socket)return;let r=this.isLive&&this.now()-this.liveSince>=HN;if(this.drop(1e3,"lost"),t===VN){this.end("forbidden");return}if(t===FN){this.end("gone");return}if(r&&(this.attempts=0),t===BN){this.token&&this.source.invalidateToken?.(this.token),this.token=null,this.attempts=0,this.schedule(!0);return}this.schedule()}}});function t2(n){if(!n||typeof n!="object"||Array.isArray(n))throw ri();return n}function n2(n){if(typeof n=="number"&&!Number.isSafeInteger(n))throw ri();let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw ri();return e}var ri,fc,RA=I(()=>{"use strict";At();ve();ie();ri=()=>A("unavailable","people metadata is unavailable","people_response");fc=class{constructor(e,t={}){this.session=e;this.rawOrigin=e.cpOrigin;let r=new URL(this.rawOrigin);if(r.username||r.password||r.pathname!=="/"||r.search||r.hash||r.protocol!=="https:"&&!(t.allowLoopbackHttp===!0&&Ze(e.cpOrigin)))throw A("invalid_request","invalid people CP origin","people_binding");this.cpOrigin=r.origin,this.collection=e.collection,this.connector=e.connectorId,this.device=e.deviceId,this.ep=n2(e.endpoint);for(let o of[this.collection,this.connector,this.device])if(N(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&&n2(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 r=new AbortController,o=()=>r.abort();t.signal?.addEventListener("abort",o,{once:!0}),this.lifetime.signal.addEventListener("abort",o,{once:!0});let s=setTimeout(o,15e3);s.unref?.();let i=new Uint8Array(1024*1024),a=0,c,l;try{let p=await this.session.connectorBearer({signal:r.signal});if(this.check(t.signal),r.signal.aborted)throw ri();if(typeof p!="string"||!/^(idev_|ct_)/.test(p)||p.length>16*1024||/[^\x21-\x7e]/.test(p))throw A("unauthenticated","invalid people credential","people_binding");let d=this.fetchImpl;if(c=await d(`${this.cpOrigin}/v1/authorities/${this.collection}/${e}?device_id=${this.device}`,{method:"GET",headers:{authorization:`Bearer ${p}`},signal:r.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(t.signal),r.signal.aborted)throw ri();let u=c.headers.get("content-length");if(u!==null&&/^(0|[1-9][0-9]*)$/.test(u)&&Number(u)>i.length||!c.body)throw ri();for(l=c.body.getReader();;){let{done:h,value:m}=await l.read();try{if(this.check(t.signal),r.signal.aborted)throw ri();if(h)break;if(a+m.length>i.length)throw ri();i.set(m,a),a+=m.length}finally{m?.fill(0)}}let f=t2(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i.subarray(0,a))));if(this.check(t.signal),c.status===401)throw A("unauthenticated","people credential is no longer current","people_fenced");if(c.status===403){let h=t2(f.error);throw A("forbidden","people access was refused",e==="members"&&h.code==="people_permission_declined"?"people_permission_declined":"people_access")}if(c.status===404)throw A("upgrade_required","people metadata is unsupported","people_unsupported");if(!c.ok)throw ri();return f}catch(p){throw this.check(t.signal),p instanceof oe?p:ri()}finally{r.abort(),i.fill(0),(l?.cancel()??c?.body?.cancel())?.catch(()=>{}),l?.releaseLock(),clearTimeout(s),t.signal?.removeEventListener("abort",o),this.lifetime.signal.removeEventListener("abort",o)}}close(){this.lifetime.abort()}}});function Ny(n,e){if(typeof n!="string"||!e.test(n))throw ge("invalid_request","timer_input");return encodeURIComponent(n)}function ls(n,e){if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!==e.split(",").sort().join())throw ge("invalid_request","timer_input");return n}function r2(n){let e=ls(n,"id,fire_at");if(Ny(e.id,EA),typeof e.fire_at!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(e.fire_at)||!Number.isFinite(Date.parse(e.fire_at)))throw ge("invalid_request","timer_input");return{id:e.id,fire_at:e.fire_at}}function qA(n){if(typeof n!="string"||!n.length||n.length>100)throw ge("invalid_request","timer_input")}function r8(n,e,t){let r=`${n}/${Ny(t[0],n8)}`;if(e==="list"&&t.length===1)return{path:r,method:"GET",write:!1};if(e==="put"&&t.length===3){let o=ls(t[2],"criterion_id,fire_at");return qA(o.criterion_id),r2({id:t[1],fire_at:o.fire_at}),{path:`${r}/${Ny(t[1],EA)}`,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 ge("invalid_request","timer_input");return{path:`${r}/${Ny(t[1],EA)}${o===void 0?"":`?generation=${o}`}`,method:"DELETE",write:!0}}if((e==="reconcile"||e==="reconcileWithReceipt")&&t.length===2){let o=ls(t[1],`criterion_id,timers${e==="reconcileWithReceipt"?",recovery":""}`);if(qA(o.criterion_id),!Array.isArray(o.timers)||o.timers.length>1e4)throw ge("invalid_request","timer_input");let s=o.timers.map(r2);if(new Set(s.map(i=>i.id)).size!==s.length)throw ge("invalid_request","timer_input");if(e==="reconcileWithReceipt"){let i=ls(o.recovery,"protocol_version,operation_id,expected_revision");if(i.protocol_version!==1||typeof i.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(i.operation_id)||!Number.isSafeInteger(i.expected_revision)||i.expected_revision<0||i.expected_revision>=Number.MAX_SAFE_INTEGER)throw ge("invalid_request","timer_input")}return{path:`${r}/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:`${r}/operations/${t[1]}`,method:"GET",write:!1};throw ge("invalid_request","timer_input")}function o2(n,e){let t=i2(e.scope),r=e.generation,o=`/v1/next/collections/${e.scope.collection}/background-grants/${e.grantId}/timers`,s=!1,i=0,a=null,c=null,l=()=>{if(s||e.signal.aborted||!e.isCurrent())throw ge("unauthenticated","timer_fenced")},p=()=>{if(c)return c;s=!0,e.signal.removeEventListener("abort",d),a?.ctrl.abort();try{n.postMessage([1,t,r,"close"])}finally{n.removeEventListener("message",u),n.close()}return c=Promise.resolve().then(async()=>{await a?.work})},d=()=>{p()},u=f=>{let h=f.data;if(!Array.isArray(h)||h[0]!==1||h[1]!==t||h[2]!==r){p();return}if(h.length===4&&h[3]==="close"){p();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]<=i||a||typeof h[4]!="string"||!Array.isArray(h[5])){p();return}let m=h[3],w=h[4],b=h[5],g=new AbortController;i=m;let y=!1,_=w!=="list"&&w!=="lookupOperation",v=Promise.resolve().then(async()=>{let k=setTimeout(()=>g.abort(),1e4),S,x,P=new Uint8Array(ru),C=0,R=()=>{x?.cancel().catch(()=>{})};g.signal.addEventListener("abort",R,{once:!0});try{l(),g.signal.throwIfAborted();let O=o.slice(0,-7)+"/notifications/channels",E,j,B=null;if(w==="vapid"&&b.length===0){if(!e.journal)throw ge("upgrade_required","native_timer_channel_journal_unavailable");e.journal.read(),E={path:"/v1/notifications/vapid-public-key",method:"GET",write:!1}}else if(w==="registerChannel"&&b.length===1){if(!e.journal)throw ge("upgrade_required","native_timer_channel_journal_unavailable");let ee=b[0],te=ls(ee,`kind,criteria,${ee?.kind==="web_push"?"subscription":"token"}`);if(!["web_push","fcm"].includes(te.kind)||!Array.isArray(te.criteria)||!te.criteria.length||te.criteria.length>100||(te.criteria.forEach(qA),new Set(te.criteria).size!==te.criteria.length))throw ge("invalid_request","timer_input");let Ce;if(te.kind==="fcm"){if(typeof te.token!="string"||te.token.length<16||te.token.length>4096||/[\s\u0000-\u001f\u007f]/.test(te.token))throw ge("invalid_request","timer_input");Ce={transport:"fcm",token:te.token}}else{let K=ls(te.subscription,"endpoint,expirationTime,keys"),Z=ls(K.keys,"p256dh,auth");if(typeof K.endpoint!="string"||K.endpoint.length>2048||typeof Z.p256dh!="string"||typeof Z.auth!="string"||!/^[A-Za-z0-9_-]{87}$/.test(Z.p256dh)||!/^[A-Za-z0-9_-]{22}$/.test(Z.auth))throw ge("invalid_request","timer_input");let _e;try{_e=new URL(K.endpoint)}catch{throw ge("invalid_request","timer_input")}if(_e.protocol!=="https:"||_e.username||_e.password||_e.hash||_e.href!==K.endpoint||K.expirationTime!==null&&(!Number.isFinite(K.expirationTime)||K.expirationTime<0))throw ge("invalid_request","timer_input");Ce={subscription:K}}E={path:O,method:"POST",write:!0,body:{installation_id:e.scope.installation,criteria:[...te.criteria].sort(),...Ce}};let et=new TextEncoder().encode(JSON.stringify(E.body)),$;try{$=[...new Uint8Array(await crypto.subtle.digest("SHA-256",et))].map(K=>K.toString(16).padStart(2,"0")).join("")}finally{et.fill(0)}l(),g.signal.throwIfAborted();let Y=e.journal.read();if(B=Y,Y?.pending)throw ge("outcome_unknown","timer_channel_reapproval_required");j={grantId:e.grantId,kind:te.kind,targetDigest:$,channelId:Y?.channelId??null,pending:"register"}}else if(w==="unregisterChannel"&&b.length===1&&["web_push","fcm"].includes(b[0])){if(!e.journal)throw ge("upgrade_required","native_timer_channel_journal_unavailable");let ee=e.journal.read();if(B=ee,!ee){n.postMessage([1,t,r,m,!0,void 0]);return}if(ee.pending==="register")throw ge("outcome_unknown","timer_channel_reapproval_required");if(ee.kind!==b[0]||!ee.channelId)throw ge("invalid_request","timer_channel_kind");j={...ee,pending:"delete"},E={path:`${O}/${ee.channelId}`,method:"DELETE",write:!0}}else E=r8(o,w,b);_=E.write;let D=E.body===void 0?void 0:JSON.stringify(E.body);if(D&&new TextEncoder().encode(D).length>ru)throw ge("invalid_request","timer_input");let J=await e.bearer();if(l(),g.signal.throwIfAborted(),typeof J!="string"||!/^(idev_|ct_)[A-Za-z0-9_-]{43}$/.test(J))throw ge("unauthenticated","timer_credential");j&&(await e.journal.write(j),l(),g.signal.throwIfAborted()),y=_;let V=e.fetch;if(S=await V(`${e.cpOrigin}${E.path}`,{method:E.method,body:D,headers:{authorization:`Bearer ${J}`,...D===void 0?{}:{"content-type":"application/json"}},credentials:"omit",redirect:"error",cache:E.method==="GET"?"no-store":"default",referrerPolicy:"no-referrer",signal:g.signal}),l(),g.signal.throwIfAborted(),S.redirected)throw ge("unavailable","timer_response");if(w==="unregisterChannel"&&S.status===204){await e.journal.write(null),l(),g.signal.throwIfAborted(),n.postMessage([1,t,r,m,!0,void 0]);return}if(S.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json"||!S.body)throw ge("unavailable","timer_response");let U=S.headers.get("content-length");if(U&&/^\d+$/.test(U)&&Number(U)>ru)throw ge("unavailable","timer_response");for(x=S.body.getReader();;){let ee=await x.read();try{if(l(),g.signal.throwIfAborted(),ee.done)break;if(C+ee.value.length>ru)throw ge("unavailable","timer_response");P.set(ee.value,C),C+=ee.value.length}finally{ee.value?.fill(0)}}let ce=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(P.subarray(0,C)));if(w==="unregisterChannel"&&S.status===404&&ce?.error?.code==="channel_not_found"){await e.journal.write(null),l(),g.signal.throwIfAborted(),n.postMessage([1,t,r,m,!0,void 0]);return}if(!S.ok){let ee=!!j&&S.status===503&&typeof ce?.error?.code=="string";throw S.status>=500&&!ee?ge("unavailable","timer_http"):ce?.error?.operation_outcome==="unknown"?ge("outcome_unknown","timer_write_unknown"):(j&&(await e.journal.write(B),l(),g.signal.throwIfAborted()),y=!1,ee?ge("unavailable","timer_http"):A(S.status===401||S.status===403?"unauthenticated":S.status===409?"conflict":S.status===404?"upgrade_required":S.status===429?"rate_limited":"invalid_request","Timer request was refused.","timer_refused"))}if(l(),g.signal.throwIfAborted(),w==="registerChannel"){if(typeof ce?.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(ce.channel_id))throw ge("unavailable","timer_channel_response");await e.journal.write({...j,channelId:ce.channel_id,pending:null}),l(),g.signal.throwIfAborted(),n.postMessage([1,t,r,m,!0,{channelId:ce.channel_id,installationId:e.scope.installation,criteria:E.body.criteria}])}else n.postMessage([1,t,r,m,!0,ce])}catch(O){let E=y?ge("outcome_unknown","timer_write_unknown"):O instanceof oe?O:ge(g.signal.aborted?"cancelled":"unavailable","timer_request");s||n.postMessage([1,t,r,m,!1,E.code,E.reason])}finally{clearTimeout(k),g.signal.removeEventListener("abort",R),P.fill(0),(x?.cancel()??S?.body?.cancel())?.catch(()=>{}),x?.releaseLock(),a?.id===m&&(a=null)}});a={id:m,ctrl:g,work:v}};n.addEventListener("message",u),n.start(),e.signal.addEventListener("abort",d,{once:!0});try{l()}catch(f){throw p(),f}return Object.freeze({close:p})}function s2(n,e,t){let r=i2(e.scope),o=e.generation,s=!1,i=0,a=null,c=()=>{if(s)return;s=!0,t.signal.removeEventListener("abort",c);let y=a;a=null,y?.signal?.removeEventListener("abort",y.abort),y?.reject(ge(y.write?"outcome_unknown":"cancelled","timer_port_closed"));try{n.postMessage([1,r,o,"close"])}finally{n.removeEventListener("message",l),n.close(),t.onClose()}},l=y=>{let _=y.data;if(!Array.isArray(_)||_[0]!==1||_[1]!==r||_[2]!==o){c();return}if(_.length===4&&_[3]==="close"){c();return}let v=a;if(!v||_[3]!==v.id||!(_.length===6&&_[4]===!0||_.length===7&&_[4]===!1&&typeof _[5]=="string"&&vo(_[5]))){c();return}a=null,v.signal?.removeEventListener("abort",v.abort),_[4]?v.resolve(_[5]):v.reject(A(_[5],"Timer request could not complete.",typeof _[6]=="string"?_[6]:void 0))},p=(y,_,v,k=!1)=>{if(s||t.signal.aborted||v.signal?.aborted)return Promise.reject(ge("cancelled","timer_port_closed"));if(a||d&&!k)return Promise.reject(ge("unavailable","timer_port_busy"));if(i>=Number.MAX_SAFE_INTEGER)return c(),Promise.reject(ge("unavailable","timer_port_closed"));let S=++i,x=y!=="list"&&y!=="lookupOperation"&&y!=="vapid";return new Promise((P,C)=>{let R=()=>{try{n.postMessage([1,r,o,S,"cancel"])}catch{c()}C(ge(x?"outcome_unknown":"cancelled","timer_request_cancelled"))};a={id:S,write:x,resolve:P,reject:C,abort:R,signal:v.signal},v.signal?.addEventListener("abort",R,{once:!0});try{if(new TextEncoder().encode(JSON.stringify(_)).length>ru)throw ge("invalid_request","timer_input");n.postMessage([1,r,o,S,y,_])}catch(O){a=null,v.signal?.removeEventListener("abort",R),C(O)}})},d=!1,u=()=>{if(s||t.signal.aborted)throw ge("cancelled","timer_port_closed")},f=y=>{if(!y?.length||y.length>100||y.some(_=>typeof _!="string"||!_.length||_.length>100)||new Set(y).size!==y.length)throw ge("invalid_request","timer_channel_criteria_required");return[...y].sort()},h=(y,_)=>{let v=ls(y,"channelId,installationId,criteria");if(typeof v.channelId!="string"||v.installationId!==e.scope.installation||JSON.stringify(v.criteria)!==JSON.stringify(_))throw ge("outcome_unknown","timer_channel_response");return{channelId:v.channelId,installationId:e.scope.installation,criteria:[..._]}},m=async(y,_)=>{if(u(),y.signal?.throwIfAborted(),d||a)throw ge("unavailable","timer_port_busy");d=!0;try{return await _()}finally{d=!1}},w=y=>m(y,async()=>{let _=f(y.criteria);if(y.installationId!==void 0&&y.installationId!==e.scope.installation)throw ge("invalid_request","timer_channel_installation");let v=y.serviceWorker;if(!v?.pushManager||typeof v.pushManager.getSubscription!="function"||typeof v.pushManager.subscribe!="function")throw ge("invalid_request","timer_push_platform");let k=await p("vapid",[],y,!0);if(u(),y.signal?.throwIfAborted(),typeof k.public_key!="string"||!/^[A-Za-z0-9_-]{87}$/.test(k.public_key))throw ge("unavailable","timer_vapid_response");let S=atob(k.public_key.replace(/-/g,"+").replace(/_/g,"/")),x=Uint8Array.from(S,R=>R.charCodeAt(0));if(x.length!==65||x[0]!==4||btoa(S).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")!==k.public_key)throw ge("unavailable","timer_vapid_response");let P=await v.pushManager.getSubscription();if(u(),y.signal?.throwIfAborted(),P){let R=P.options.applicationServerKey;if(!R||R.byteLength!==x.length||new Uint8Array(R).some((O,E)=>O!==x[E]))throw ge("invalid_request","timer_push_key_changed")}if(!P&&(P=await v.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:x}),s||t.signal.aborted||y.signal?.aborted))throw await P.unsubscribe(),ge("cancelled","timer_port_closed");let C=P.toJSON();return h(await p("registerChannel",[{kind:"web_push",criteria:_,subscription:{endpoint:C.endpoint,expirationTime:C.expirationTime??null,keys:C.keys}}],y,!0),_)}),b=y=>m(y,async()=>{let _=f(y.criteria);if(y.installationId!==void 0&&y.installationId!==e.scope.installation)throw ge("invalid_request","timer_channel_installation");return{...h(await p("registerChannel",[{kind:"fcm",criteria:_,token:y.token}],y,!0),_),transport:"fcm"}}),g=(y,_)=>m(_,async()=>{if(await p("unregisterChannel",["web_push"],_,!0),u(),_.signal?.throwIfAborted(),y){let v=await y.pushManager.getSubscription();u(),_.signal?.throwIfAborted(),v&&await v.unsubscribe(),u(),_.signal?.throwIfAborted()}});return n.addEventListener("message",l),n.start(),t.signal.addEventListener("abort",c,{once:!0}),t.signal.aborted&&c(),Object.freeze({list:(y,_)=>p("list",[y],_),put:(y,_,v,k)=>p("put",[y,_,v],k),cancel:(y,_,v,k)=>p("cancel",[y,_,v],k),reconcile:(y,_,v)=>p("reconcile",[y,_],v),reconcileWithReceipt:(y,_,v)=>p("reconcileWithReceipt",[y,_],v),lookupOperation:(y,_,v)=>p("lookupOperation",[y,_],v),registerWebPush:w,unregisterWebPush:g,registerFcm:b,unregisterFcm:y=>m(y,async()=>{await p("unregisterChannel",["fcm"],y,!0)}),close:c})}var n8,EA,ru,ge,i2,TA=I(()=>{"use strict";ie();n8=/^[A-Za-z0-9._-]{1,64}$/,EA=/^[A-Za-z0-9._:-]{1,128}$/,ru=2*1024*1024,ge=(n,e)=>A(n,"Timer request could not complete.",e),i2=n=>JSON.stringify([n.account,n.installation,n.collection])});function hc(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 Dy(n){let e=n.incidents.find(s=>s.kind==="waiting_for_key");if(!e)return null;let t={through:n.confirmedThrough,head:n.headKnown},r=s=>fe(e.details,s),o=r("reason");typeof o=="string"&&/^[a-z_]{1,32}$/.test(o)&&(t.key=o);for(let s of["position","at"]){let i=r(s);typeof i=="number"&&(t[s]=i)}return t}function l2(n){if(hc(n)!=="waiting_for_key")return!1;let e=Dy(n)?.key;return e==="reading"||e==="no_grant"}var a2,c2=I(()=>{"use strict";vn();a2=15e4});var zy,MA,Ge,LA,i8,$y,jA=I(()=>{"use strict";Ye();ve();Vs();zy=264*1024+256,MA=264*1024,Ge=()=>new Error("app cloud copy outcome unavailable; preserve storage and reopen"),LA=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]),i8=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),$y=class{constructor(e,t,r,o,s){this.source=e;this.store=o;this.key=r;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 i=e.displayName;if(this.displayName=i===void 0?void 0:sr(i),this.displayName!==void 0&&e.purpose!=="create"||i!==this.displayName)throw Ge();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(N);if(a.some(c=>c.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(c=>{if(!(c instanceof Uint8Array)||c.length!==32||c.every(l=>l===0))throw Ge();return new Uint8Array(c)})),t.connectorId!==e.connectorId||t.deviceId!==e.deviceId||t.installationId!==e.installationId)||typeof globalThis.CryptoKey!="function"||!(r instanceof CryptoKey)||r.type!=="secret"||r.extractable||r.algorithm.name!=="AES-GCM"||r.algorithm.length!==256||r.usages.length!==2||!r.usages.includes("encrypt")||!r.usages.includes("decrypt"))throw Ge();this.aad=ue(["mdbase/v1/app-cloud-copy-outcome-platform",...a,e.purpose,e.cpOrigin,e.logOrigin,e.assetSha256,...this.keys]),this.check(this.lifetime)}catch{throw Ge()}}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,r])=>this.source[t]!==r))throw Ge()}catch{throw Ge()}}operation(e){if(e){if(e.displayName!==this.displayName)throw Ge();for(let t of Object.keys(this.fields))if(e[t]!==this.fields[t])throw Ge();for(let[t,r]of["signPublicKey","kemPublicKey","noisePublicKey"].entries())if(!(e[r]instanceof Uint8Array)||!LA(e[r],this.keys[t]))throw Ge()}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 Ge();return Object.freeze({operation:t,genesisItem:new Uint8Array(e.genesisItem),expectedGenesis:e.expectedGenesis})}async hashChecked(e,t){let r=new TextEncoder().encode("mdbase/v1/chain"),o=new Uint8Array(1+r.length+e.genesisItem.length);o[0]=r.length,o.set(r,1),o.set(e.genesisItem,1+r.length);let s=new Uint8Array(await crypto.subtle.digest("SHA-256",o));if(this.check(t),e.expectedGenesis!==`sha256:${i8(s)}`)throw Ge()}async read(e){let t=null;try{this.check(e);let r=await this.io.read.call(this.store,Object.freeze({signal:e}));if(this.check(e),r===null){if(this.mode!=="fresh")throw Ge();return null}if(!(r instanceof Uint8Array)||!r.length||r.length>zy)throw Ge();let o=new Uint8Array(r),s=we(o);if(!(s instanceof Map))throw Ge();let i=s;if(i.size!==3||i.get(0)!==1)throw Ge();let a=i.get(1),c=i.get(2);if(!(a instanceof Uint8Array)||a.length!==12||!(c instanceof Uint8Array)||c.length<16||c.length>MA+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(c))),this.check(e),t.length>MA))throw Ge();let l=we(t);if(!(l instanceof Map))throw Ge();let p=l,d=p.get(0)===1&&p.size===3;if(!d&&!(p.get(0)===2&&p.size===4)||(d?null:p.get(3))!==(this.displayName??null))throw Ge();let u=p.get(1);if(!Array.isArray(u)||u.length!==3||u.some((m,w)=>!(m instanceof Uint8Array)||!LA(m,this.keys[w])))throw Ge();let f=p.get(2),h=null;if(f!==null){if(!Array.isArray(f)||f.length!==2||!(f[0]instanceof Uint8Array)||typeof f[1]!="string")throw Ge();h=this.metadata({operation:this.operation(),genesisItem:f[0],expectedGenesis:f[1]}),await this.hashChecked(h,e)}return{encrypted:o,metadata:h}}catch{throw Ge()}finally{t?.fill(0)}}async write(e,t,r){let o=null,s=null;try{if(this.check(r),o=ue(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>MA)throw Ge();let i=crypto.getRandomValues(new Uint8Array(12)),a=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:i,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(o)));if(this.check(r),s=ue(new Map([[0,1],[1,i],[2,a]])),s.length>zy)throw Ge();let c=await this.io.cas.call(this.store,t,s,Object.freeze({signal:r}));if(this.check(r),c!==!0)throw Ge()}catch{throw Ge()}finally{o?.fill(0),s?.fill(0)}}async restore(e){let{signal:t}=e,r=await this.read(t);return this.check(t),r===null?Object.freeze({state:"none"}):r.metadata===null?Object.freeze({state:"pending",operation:this.operation()}):Object.freeze({state:"completed",metadata:this.metadata(r.metadata)})}async pending(e,t){let{signal:r}=t;this.check(r),this.operation(e);let o=await this.read(r);this.check(r),!o&&await this.write(null,null,r)}async completed(e,t){let{signal:r}=t;this.check(r);let o=this.metadata(e);await this.hashChecked(o,r);let s=await this.read(r);if(this.check(r),!s)throw Ge();if(s.metadata){if(!LA(s.metadata.genesisItem,o.genesisItem)||s.metadata.expectedGenesis!==o.expectedGenesis)throw Ge();return}await this.write(o,s.encrypted,r)}close(){this.closed=!0,this.key=null}}});function NA(n){if(!(n instanceof Uint8Array)||!n.length||n.length>zy)throw yn();return new Uint8Array(n)}var By,UA,yn,o8,Vy,p2=I(()=>{"use strict";tn();ve();jA();By="public-outcome",UA="operation",yn=()=>new Error("app cloud copy outcome store unavailable; preserve storage and reopen"),o8=(n,e)=>n===null||e===null?n===e:n.length===e.length&&n.every((t,r)=>t===e[r]);Vy=class n{constructor(e,t,r){this.source=e;this.origin=t;this.lifetime=r;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,r])=>this.source[t]!==r))throw yn()}catch{throw yn()}}static async open(e){let{source:t,origin:r,mode:o,signal:s}=e,i=null;try{i=new n(t,r,s);let a=[i.fields.accountId,i.fields.connectorId,i.fields.deviceId,i.fields.installationId,i.fields.collection].map(l=>{if(N(l).every(p=>p===0))throw yn();return l.toLowerCase()});if(!dt(r)||!["fresh","existing"].includes(o)||!["create","join"].includes(i.fields.purpose)||!/^[0-9a-f]{64}$/.test(i.fields.assetSha256)||!globalThis.indexedDB)throw yn();i.check(s),i.db=await i.openDatabase(`mdbase.app.cloud-copy-outcome.v1.${a.join(".")}.${i.fields.purpose}`,o),i.db.onversionchange=()=>i.close(),i.check(s);let c=await i.read(Object.freeze({signal:s}));try{if(o==="fresh"!=(c===null))throw yn();i.check(s)}finally{c?.fill(0)}return i}catch{throw i?.close(),yn()}}openDatabase(e,t){return new Promise((r,o)=>{this.check(this.lifetime);let s=indexedDB.open(e,1),i=!1,a=!1,c=()=>{i=!0,o(yn())},l=()=>this.lifetime.removeEventListener("abort",c);this.lifetime.addEventListener("abort",c,{once:!0}),s.onblocked=c,s.onupgradeneeded=()=>{try{if(this.check(this.lifetime),i||t!=="fresh"||s.result.objectStoreNames.length!==0)throw yn();s.result.createObjectStore(By),a=!0}catch{s.transaction?.abort()}},s.onerror=()=>{l(),o(yn())},s.onsuccess=()=>{l();try{if(this.check(this.lifetime),i||t==="fresh"&&!a||s.result.objectStoreNames.length!==1||!s.result.objectStoreNames.contains(By))throw yn();r(s.result)}catch{s.result.close(),o(yn())}}})}async read(e){let{signal:t}=e;this.check(t);let r=await this.transaction("readonly",t,null,null);return this.check(t),r}async compareAndSet(e,t,r){let{signal:o}=r;this.check(o);let s=e===null?null:NA(e),i=NA(t);try{let a=await this.transaction("readwrite",o,s,i);return this.check(o),a===!0}finally{s?.fill(0),i.fill(0)}}transaction(e,t,r,o){return new Promise((s,i)=>{if(this.check(t),!this.db)throw yn();let a=this.db.transaction(By,e,{durability:"strict"}),c=a.objectStore(By),l=null,p=!1,d=()=>{p=!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),i(yn())},a.oncomplete=()=>{u();try{if(this.check(t),p)throw yn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),i(yn())}};let f=c.get(UA);f.onsuccess=()=>{let h=null;try{this.check(t),h=f.result===void 0?null:NA(f.result),e==="readonly"?(l=h,h=null):(l=o8(h,r),l===!0&&o!==null&&(r===null?c.add(new Uint8Array(o),UA):c.put(new Uint8Array(o),UA)))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db?.close(),this.db=null)}}});function $A(n,e){if(typeof n!="string"||!n.length||n.length>e*2||n.length%2||!/^[0-9a-f]+$/.test(n))throw ot("response");return Uint8Array.from(n.match(/../g).map(t=>parseInt(t,16)))}function BA(n){if(!n||typeof n!="object"||Array.isArray(n))throw ot("response");return n}var ha,ot,DA,zA,Fy,VA=I(()=>{"use strict";At();ve();Vs();ha=class extends Error{constructor(t){super(`app private bootstrap: ${t}`);this.reason=t;this.name="AppPrivateBootstrapError"}reason},ot=n=>new ha(n),DA=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),zA=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]);Fy=class{constructor(e,t,r,o={}){this.runtime=e;this.session=t;this.persistence=r;this.options=o;try{let s=o.displayName;if(this.displayName=s===void 0?void 0:sr(s),this.displayName!==void 0&&t.purpose!=="create")throw ot("binding");this.scope=Object.freeze({connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId,collection:t.collection,purpose:t.purpose,accountId:t.accountId,cpOrigin:t.cpOrigin,logOrigin:t.logOrigin});for(let i of[this.scope.connectorId,this.scope.deviceId,this.scope.installationId,this.scope.collection,this.scope.accountId])if(N(i).every(a=>a===0))throw ot("binding");if(this.origin(this.scope.cpOrigin),this.origin(this.scope.logOrigin),!(t.rootPublicKey instanceof Uint8Array)||t.rootPublicKey.length!==32||t.rootPublicKey.every(i=>i===0)||(this.root=new Uint8Array(t.rootPublicKey),this.fetchImpl=o.fetch??globalThis.fetch,this.now=o.now??Date.now,this.marker=this.scope.purpose==="enrol"?e.privateEnrolMarker():null,!this.current()))throw ot("binding")}catch{throw e.retireLog(),ot("binding")}}runtime;session;persistence;options;attempted=!1;lifetime=new AbortController;scope;root;marker;fetchImpl;now;displayName;origin(e){let t=new URL(e);if(t.username||t.password||t.pathname!=="/"||t.search||t.hash||t.protocol!=="https:"&&!(this.options.allowLoopbackHttp===!0&&Ze(e)))throw ot("binding");return t.origin}current(){try{return!this.lifetime.signal.aborted&&this.runtime.privateCollectionCurrent(this.session)&&this.session.isCurrent()===!0&&this.session.approvalMode==="password-ak1"&&zA(this.session.rootPublicKey,this.root)&&Object.entries(this.scope).every(([e,t])=>this.session[e]===t)}catch{return!1}}markerCopy(){let e=this.marker;if(!e)throw ot("binding");return Object.freeze({...e,sasCommitment:new Uint8Array(e.sasCommitment),signPublicKey:new Uint8Array(e.signPublicKey),kemPublicKey:new Uint8Array(e.kemPublicKey),noisePublicKey:new Uint8Array(e.noisePublicKey)})}check(e){if(!this.current()||e.aborted)throw this.close(),ot("fenced")}async json(e,t,r,o){this.check(o);let s=new AbortController,i=()=>s.abort(),a=setTimeout(i,15e3);a.unref?.(),o.addEventListener("abort",i,{once:!0}),this.lifetime.signal.addEventListener("abort",i,{once:!0});let c=new Uint8Array(1024*1024),l=0,p=null,d=null;try{let u=this.fetchImpl;if(d=await u(`${this.origin(this.scope.cpOrigin)}${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,...r===void 0?{}:{"content-type":"application/json"}},body:r,signal:s.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(o),s.signal.aborted||!d.ok)throw ot("unavailable");let f=d.headers.get("content-length");if(f!==null&&/^(0|[1-9][0-9]*)$/.test(f)&&Number(f)>c.length)throw s.abort(),ot("response");if(!d.body)throw ot("response");for(p=d.body.getReader();;){let{done:h,value:m}=await p.read();try{if(this.check(o),s.signal.aborted)throw ot("unavailable");if(h)break;if(l+m.length>c.length)throw s.abort(),ot("response");c.set(m,l),l+=m.length}finally{m?.fill(0)}}return BA(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c.subarray(0,l))))}catch(u){throw this.check(o),u instanceof ha?u:ot("unavailable")}finally{c.fill(0),(p?.cancel()??d?.body?.cancel())?.catch(()=>{}),p?.releaseLock(),clearTimeout(a),o.removeEventListener("abort",i),this.lifetime.signal.removeEventListener("abort",i)}}copy(e){if(e.displayName!==this.displayName||e.collection!==this.scope.collection||e.deviceId!==this.scope.deviceId||e.logOrigin!==this.scope.logOrigin||!zA(e.rootPublicKey,this.root)||!(e.genesisItem instanceof Uint8Array)||!e.genesisItem.length||e.genesisItem.length>256*1024||e.expectedGenesis.length!==71||!/^sha256:[0-9a-f]{64}$/.test(e.expectedGenesis)||e.approval!==(this.scope.purpose==="create"?"creator":"pending"))throw ot("response");return Object.freeze({collection:e.collection,deviceId:e.deviceId,logOrigin:e.logOrigin,expectedGenesis:e.expectedGenesis,approval:e.approval,...this.displayName===void 0?{}:{displayName:this.displayName},rootPublicKey:new Uint8Array(e.rootPublicKey),genesisItem:new Uint8Array(e.genesisItem)})}async bootstrap(e){let t=null,r=null;try{if(this.check(e.signal),this.attempted)throw ot("fenced");this.attempted=!0;let o=await this.persistence.restoredCompletion(e);if(this.check(e.signal),o){let w=this.copy(o);return this.marker&&!this.marker.acknowledged&&(await this.persistence.privateEnrolAcknowledged(this.markerCopy(),e),this.check(e.signal)),w}if(this.marker?.acknowledged)throw ot("response");this.marker?await this.persistence.privateEnrolPending(this.markerCopy(),e):await this.persistence.pendingCreate({...this.runtime.registeredDeviceReceipt(),collection:this.scope.collection,...this.displayName===void 0?{}:{displayName:this.displayName}},e),this.check(e.signal);let s=await this.session.connectorBearer(e);if(this.check(e.signal),typeof s!="string"||!s||s.length>16384||/[^\x21-\x7e]/.test(s))throw ot("binding");let i=await this.json("/v1/next/devices/challenge",s,void 0,e.signal);if(this.check(e.signal),t=$A(i.challenge,32),t.length!==32||typeof i.expires_at!="number"||!Number.isSafeInteger(i.expires_at)||i.expires_at-this.now()<=5e3||i.expires_at-this.now()>16*6e4)throw ot("response");let a=this.scope.purpose==="enrol";r=a?this.runtime.signPrivateDeviceEnrol(t).signature:this.runtime.signPrivateCreate(t),this.check(e.signal);let c=await this.json(a?`/v1/next/collections/${this.scope.collection}/private/devices`:"/v1/next/collections/private",s,JSON.stringify({device_id:this.scope.deviceId,capabilities:["collection_mode_switch_v2"],challenge:i.challenge,sig:DA(r),...a?{sas_commit:DA(this.marker.sasCommitment)}:{collection_id:this.scope.collection,...this.displayName===void 0?{}:{display_name:this.displayName}}}),e.signal);if(this.check(e.signal),c.collection_id!==this.scope.collection||this.origin(c.log_url)!==this.origin(this.scope.logOrigin))throw ot("response");if(a){if(c.approval!=="pending"||typeof c.enrolled_at!="number"||!Number.isSafeInteger(c.enrolled_at)||c.enrolled_at<1)throw ot("response")}else if(c.state!=="private"||c.owner_account!==this.scope.accountId||!zA($A(c.root_public_key,32),this.root))throw ot("response");let l=BA(c.device);if(l.device_id!==this.scope.deviceId||typeof l.token!="string"||!l.token.length||l.token.length>16384||/[^\x21-\x7e]/.test(l.token)||typeof l.expires_at!="number"||!Number.isSafeInteger(l.expires_at)||l.expires_at-this.now()<=5e3||l.expires_at-this.now()>16*6e4)throw ot("response");let p=BA(c.genesis);if(p.seq!==1)throw ot("response");let d=$A(p.item,256*1024),u=new TextEncoder().encode("mdbase/v1/chain"),f=new Uint8Array(1+u.length+d.length);f[0]=u.length,f.set(u,1),f.set(d,1+u.length);let h=new Uint8Array(await crypto.subtle.digest("SHA-256",f));this.check(e.signal);let m=this.copy({collection:this.scope.collection,deviceId:this.scope.deviceId,logOrigin:this.scope.logOrigin,rootPublicKey:this.root,genesisItem:d,expectedGenesis:`sha256:${DA(h)}`,approval:a?"pending":"creator",...this.displayName===void 0?{}:{displayName:this.displayName}});return await this.persistence.completed(this.copy(m),e),this.check(e.signal),this.marker&&(await this.persistence.privateEnrolAcknowledged(this.markerCopy(),e),this.check(e.signal)),m}catch(o){throw this.close(),o instanceof ha?o:ot("unavailable")}finally{t?.fill(0),r?.fill(0)}}close(){this.lifetime.abort(),this.runtime.retireLog()}}});var Ky,FA,Oe,ma,s8,Wy,KA=I(()=>{"use strict";At();Ye();ve();Vs();Ky=264*1024,FA=Ky+256,Oe=()=>new Error("app private bootstrap custody unavailable; preserve storage and reopen"),ma=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]),s8=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),Wy=class{constructor(e,t,r,o,s,i={}){this.source=e;this.key=r;this.store=o;this.noise=s;try{let a=i.displayName;if(this.displayName=a===void 0?void 0:sr(a),this.displayName!==void 0&&e.purpose!=="create")throw Oe();this.pins=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});let c=[this.pins.accountId,this.pins.connectorId,this.pins.deviceId,this.pins.installationId,this.pins.collection].map(N);if(c.some(l=>l.every(p=>p===0))||!["create","enrol"].includes(this.pins.purpose))throw Oe();for(let l of[e.cpOrigin,e.logOrigin]){let p=new URL(l);if(!(i.allowLoopbackHttp===!0&&Ze(l))&&p.protocol!=="https:"||p.origin!==l||p.username||p.password)throw Oe()}if(!(e.rootPublicKey instanceof Uint8Array)||e.rootPublicKey.length!==32||e.rootPublicKey.every(l=>l===0)||(this.root=new Uint8Array(e.rootPublicKey),this.keys=[t.signPublicKey,t.kemPublicKey,t.noisePublicKey].map(l=>{if(!(l instanceof Uint8Array)||l.length!==32||l.every(p=>p===0))throw Oe();return new Uint8Array(l)}),this.checkReceipt(t),r.type!=="secret"||r.extractable||r.algorithm.name!=="AES-GCM"||r.algorithm.length!==256||!r.usages.includes("encrypt")||!r.usages.includes("decrypt")))throw Oe();this.aad=ue(["mdbase/v1/app-private-bootstrap-platform",...c,this.pins.purpose,e.cpOrigin,e.logOrigin,this.root]),this.check(new AbortController().signal)}catch{throw Oe()}}source;key;store;noise;pins;root;keys;aad;displayName;check(e){try{if(e.aborted||this.source.isCurrent()!==!0||this.source.approvalMode!=="password-ak1"||!ma(this.source.rootPublicKey,this.root)||Object.entries(this.pins).some(([t,r])=>this.source[t]!==r))throw Oe()}catch{throw Oe()}}checkReceipt(e){if(e.connectorId!==this.pins.connectorId||e.deviceId!==this.pins.deviceId||e.installationId!==this.pins.installationId||[e.signPublicKey,e.kemPublicKey,e.noisePublicKey].some((r,o)=>!(r instanceof Uint8Array)||r.length!==32||r.every(s=>s===0)||!ma(r,this.keys[o])))throw Oe()}commit(e){if(this.checkReceipt(e),this.pins.purpose!=="enrol"||e.collection!==this.pins.collection||typeof e.acknowledged!="boolean"||!(e.sasCommitment instanceof Uint8Array)||e.sasCommitment.length!==32||e.sasCommitment.every(t=>t===0))throw Oe();return new Uint8Array(e.sasCommitment)}markerCopy(e,t){return Object.freeze({connectorId:this.pins.connectorId,deviceId:this.pins.deviceId,installationId:this.pins.installationId,collection:this.pins.collection,signPublicKey:new Uint8Array(this.keys[0]),kemPublicKey:new Uint8Array(this.keys[1]),noisePublicKey:new Uint8Array(this.keys[2]),sasCommitment:new Uint8Array(t),acknowledged:e.acknowledged})}copy(e){if(e.displayName!==this.displayName||e.collection!==this.pins.collection||e.deviceId!==this.pins.deviceId||e.logOrigin!==this.pins.logOrigin||!(e.rootPublicKey instanceof Uint8Array)||!ma(e.rootPublicKey,this.root)||!(e.genesisItem instanceof Uint8Array)||!e.genesisItem.length||e.genesisItem.length>256*1024||!/^sha256:[0-9a-f]{64}$/.test(e.expectedGenesis)||e.approval!==(this.pins.purpose==="create"?"creator":"pending"))throw Oe();return Object.freeze({collection:this.pins.collection,deviceId:this.pins.deviceId,logOrigin:this.pins.logOrigin,rootPublicKey:new Uint8Array(this.root),genesisItem:new Uint8Array(e.genesisItem),expectedGenesis:e.expectedGenesis,approval:e.approval,...this.displayName===void 0?{}:{displayName:this.displayName}})}async hashChecked(e,t){let r=new TextEncoder().encode("mdbase/v1/chain"),o=new Uint8Array(1+r.length+e.genesisItem.length);o[0]=r.length,o.set(r,1),o.set(e.genesisItem,1+r.length);let s=new Uint8Array(await crypto.subtle.digest("SHA-256",o));if(this.check(t),e.expectedGenesis!==`sha256:${s8(s)}`)throw Oe()}async read(e){let t=null;try{this.check(e.signal);let r=await this.store.read(e);if(this.check(e.signal),r===null)return null;if(!(r instanceof Uint8Array)||!r.length||r.length>FA)throw Oe();let o=new Uint8Array(r),s=we(o);if(!(s instanceof Map))throw Oe();let i=s;if(i.size!==3||i.get(0)!==1)throw Oe();let a=i.get(1),c=i.get(2);if(!(a instanceof Uint8Array)||a.length!==12||!(c instanceof Uint8Array)||c.length<16||c.length>Ky+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(c))),this.check(e.signal),t.length>Ky))throw Oe();let l=we(t);if(!(l instanceof Map))throw Oe();let p=l,d=p.get(0)===1&&p.size===4;if(!d&&!(p.get(0)===2&&p.size===5)||(d?null:p.get(4))!==(this.displayName??null))throw Oe();let u=p.get(1);if(!Array.isArray(u)||u.length!==3||u.some((w,b)=>!(w instanceof Uint8Array)||!ma(w,this.keys[b])))throw Oe();let f=p.get(2);if(this.pins.purpose==="create"?f!==null:!(f instanceof Uint8Array)||f.length!==32||f.every(w=>w===0))throw Oe();let h=p.get(3),m=null;if(h!==null){if(!Array.isArray(h)||h.length!==2||!(h[0]instanceof Uint8Array)||typeof h[1]!="string")throw Oe();m=this.copy({...this.pins,rootPublicKey:this.root,genesisItem:h[0],expectedGenesis:h[1],approval:this.pins.purpose==="create"?"creator":"pending",...this.displayName===void 0?{}:{displayName:this.displayName}}),await this.hashChecked(m,e.signal)}return{encrypted:o,value:{commit:f===null?null:new Uint8Array(f),metadata:m}}}catch{throw Oe()}finally{t?.fill(0)}}async write(e,t,r){let o=null,s=null;try{if(this.check(r.signal),o=ue(new Map([[0,2],[1,this.keys.map(l=>new Uint8Array(l))],[2,e.commit],[3,e.metadata===null?null:[e.metadata.genesisItem,e.metadata.expectedGenesis]],[4,this.displayName??null]])),o.length>Ky)throw Oe();let i=crypto.getRandomValues(new Uint8Array(12)),a=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:i,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(o)));this.check(r.signal),s=ue(new Map([[0,1],[1,i],[2,a]]));let c=await this.store.compareAndSet(t,s,r);if(this.check(r.signal),c!==!0)throw Oe()}catch{throw Oe()}finally{o?.fill(0),s?.fill(0)}}async pendingCreate(e,t){if(this.check(t.signal),this.checkReceipt(e),this.pins.purpose!=="create"||e.collection!==this.pins.collection||e.displayName!==this.displayName)throw Oe();let r=await this.read(t);this.check(t.signal),!r&&await this.write({commit:null,metadata:null},null,t)}async privateEnrolPending(e,t){this.check(t.signal);let r=this.commit(e),o=this.markerCopy(e,r);if(o.acknowledged)throw Oe();let s=await this.read(t);if(this.check(t.signal),s&&!ma(s.value.commit,r))throw Oe();try{await this.noise.privateEnrolPending(o,t),this.check(t.signal)}catch{throw Oe()}s||await this.write({commit:r,metadata:null},null,t)}async completed(e,t){this.check(t.signal);let r=this.copy(e);await this.hashChecked(r,t.signal);let o=await this.read(t);if(this.check(t.signal),!o)throw Oe();if(o.value.metadata){if(!ma(o.value.metadata.genesisItem,r.genesisItem)||o.value.metadata.expectedGenesis!==r.expectedGenesis)throw Oe();return}await this.write({...o.value,metadata:r},o.encrypted,t)}async privateEnrolAcknowledged(e,t){this.check(t.signal);let r=this.commit(e),o=this.markerCopy(e,r),s=await this.read(t);if(this.check(t.signal),!s?.value.metadata||!ma(s.value.commit,r))throw Oe();try{await this.noise.privateEnrolAcknowledged(o,t),this.check(t.signal)}catch{throw Oe()}}async restoredCompletion(e){let t=await this.read(e);return this.check(e.signal),t?.value.metadata?this.copy(t.value.metadata):null}}});function HA(n){if(!(n instanceof Uint8Array)||!n.length||n.length>FA)throw gn();return new Uint8Array(n)}var Hy,d2,gn,WA,Gy,u2=I(()=>{"use strict";tn();ve();KA();Hy="public-outcome",d2="operation",gn=()=>new Error("app private bootstrap store unavailable"),WA=(n,e)=>n===null||e===null?n===e:n.length===e.length&&n.every((t,r)=>t===e[r]);Gy=class n{constructor(e,t,r,o,s){this.db=e;this.source=t;this.pins=r;this.root=o;this.origin=s;e.onversionchange=()=>this.close()}db;source;pins;root;origin;closed=!1;static async open(e){try{return await this.openChecked(e)}catch{throw gn()}}static async openChecked(e){let{source:t,signal:r}=e,o=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}),s=[o.accountId,o.connectorId,o.deviceId,o.installationId,o.collection];for(let d of s)if(N(d).every(u=>u===0))throw gn();if(!(t.rootPublicKey instanceof Uint8Array)||t.rootPublicKey.length!==32||t.rootPublicKey.every(d=>d===0))throw gn();let i=new Uint8Array(t.rootPublicKey);if(!dt(e.origin)||Rt()!==e.origin||!["fresh","existing"].includes(e.mode)||!["create","enrol"].includes(o.purpose)||!globalThis.indexedDB)throw gn();let a=()=>{try{return!r.aborted&&t.isCurrent()===!0&&t.approvalMode==="password-ak1"&&t.rootPublicKey instanceof Uint8Array&&WA(t.rootPublicKey,i)&&Object.entries(o).every(([d,u])=>t[d]===u)}catch{return!1}};if(!a())throw gn();let c=`mdbase.app.private-bootstrap.v1.${s.map(d=>d.toLowerCase()).join(".")}.${o.purpose}`,l=await new Promise((d,u)=>{let f=indexedDB.open(c,1),h=!1,m=()=>{h=!0,u(gn())},w=()=>r.removeEventListener("abort",m);r.addEventListener("abort",m,{once:!0}),f.onblocked=m,f.onupgradeneeded=()=>{if(h||!a()||e.mode!=="fresh"||f.result.objectStoreNames.length!==0){f.transaction?.abort();return}f.result.createObjectStore(Hy)},f.onerror=()=>{w(),u(gn())},f.onsuccess=()=>{if(w(),h||!a()||f.result.objectStoreNames.length!==1||!f.result.objectStoreNames.contains(Hy)){f.result.close(),u(gn());return}d(f.result)}}),p=new n(l,t,o,i,e.origin);try{let d=await p.read({signal:r});if(e.mode==="fresh"!=(d===null))throw gn();return d?.fill(0),p.check(r),p}catch{throw p.close(),gn()}}check(e){try{if(this.closed||e.aborted||Rt()!==this.origin||this.source.isCurrent()!==!0||this.source.approvalMode!=="password-ak1"||!(this.source.rootPublicKey instanceof Uint8Array)||!WA(this.source.rootPublicKey,this.root)||Object.entries(this.pins).some(([t,r])=>this.source[t]!==r))throw gn()}catch{throw gn()}}async read(e){this.check(e.signal);let t=await this.transaction("readonly",e.signal,null,null);return this.check(e.signal),t}async compareAndSet(e,t,r){this.check(r.signal);let o=null,s=null;try{o=e===null?null:HA(e),s=HA(t);let i=await this.transaction("readwrite",r.signal,o,s);return this.check(r.signal),i===!0}finally{o?.fill(0),s?.fill(0)}}transaction(e,t,r,o){return new Promise((s,i)=>{this.check(t);let a=this.db.transaction(Hy,e,{durability:"strict"}),c=a.objectStore(Hy),l=null,p=!1,d=()=>{p=!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),i(gn())},a.oncomplete=()=>{u();try{if(this.check(t),p)throw gn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),i(gn())}};let f=c.get(d2);f.onsuccess=()=>{let h=null;try{this.check(t),h=f.result===void 0?null:HA(f.result),e==="readonly"?(l=h,h=null):(l=WA(h,r),l===!0&&o!==null&&c.put(new Uint8Array(o),d2))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db.close())}}});var f2,h2=I(()=>{f2=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9])});function cs(n,e,t,r,o,s){let i=o[s],a=o[s+1],c=H[2*n],l=H[2*n+1],p=H[2*e],d=H[2*e+1],u=H[2*t],f=H[2*t+1],h=H[2*r],m=H[2*r+1],w=np(c,p,i);l=rp(w,l,d,a),c=w|0;let b=m^l,g=h^c;m=Nk(b,g),h=Dk(b,g),{h:f,l:u}=er(f,u,m,h),b=d^f,g=p^u,d=di(b,g,24),p=ui(b,g,24),H[2*n]=c,H[2*n+1]=l,H[2*e]=p,H[2*e+1]=d,H[2*t]=u,H[2*t+1]=f,H[2*r]=h,H[2*r+1]=m}function ps(n,e,t,r,o,s){let i=o[s],a=o[s+1],c=H[2*n],l=H[2*n+1],p=H[2*e],d=H[2*e+1],u=H[2*t],f=H[2*t+1],h=H[2*r],m=H[2*r+1],w=np(c,p,i);l=rp(w,l,d,a),c=w|0;let b=m^l,g=h^c;m=di(b,g,16),h=ui(b,g,16),{h:f,l:u}=er(f,u,m,h),b=d^f,g=p^u,d=_s(b,g,63),p=As(b,g,63),H[2*n]=c,H[2*n+1]=l,H[2*e]=p,H[2*e+1]=d,H[2*t]=u,H[2*t+1]=f,H[2*r]=h,H[2*r+1]=m}function a8(n,e={},t,r,o){if(Sn(t),n<=0||n>t)throw new Error('"dkLen" must be 1..'+t+", got "+n);let{key:s,salt:i,personalization:a}=e;if(s!==void 0&&(s.length<1||s.length>t))throw new Error('"key" expected to be undefined or of length=1..'+t);i!==void 0&&ft(i,r,"salt"),a!==void 0&&ft(a,o,"personalization")}var Bt,H,GA,YA,mc,m2=I(()=>{h2();Gu();fi();Bt=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),H=new Uint32Array(32);GA=class{buffer;buffer32;finished=!1;destroyed=!1;length=0;pos=0;blockLen;outputLen;canXOF=!1;constructor(e,t){Sn(e),Sn(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=So(this.buffer)}update(e){Hi(this),ft(e);let{blockLen:t,buffer:r,buffer32:o}=this,s=e.length,i=e.byteOffset,a=e.buffer;for(let c=0;c<s;){this.pos===t&&(Nr(o),this.compress(o,0,!1),Nr(o),this.pos=0);let l=Math.min(t-this.pos,s-c),p=i+c;if(l===t&&!(p%4)&&c+l<s){let d=new Uint32Array(a,p,Math.floor((s-c)/4));Nr(d);for(let u=0;c+t<s;u+=o.length,c+=t)this.length+=t,this.compress(d,u,!1);Nr(d);continue}r.set(c===0&&l===s?e:e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){if(Hi(this),qa(e,this),e.byteOffset&3)throw new RangeError('"output" expected 4-byte aligned byteOffset, got '+e.byteOffset);let{pos:t,buffer32:r}=this;this.finished=!0,this.buffer.fill(0,t),Nr(r),this.compress(r,0,!0),Nr(r);let o=this.get(),s=e===this.buffer?r:So(e),i=Math.floor(this.outputLen/4);for(let p=0;p<i;p++)s[p]=en(o[p]);let a=this.outputLen%4;if(!a)return;let c=i*4,l=o[i];for(let p=0;p<a;p++)e[c+p]=l>>>8*p}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){let{buffer:t,length:r,finished:o,destroyed:s,outputLen:i,pos:a}=this;return e||=new this.constructor({dkLen:i}),e.set(...this.get()),e.buffer.set(t),e.destroyed=s,e.finished=o,e.length=r,e.pos=a,e.outputLen=i,e}clone(){return this._cloneInto()}},YA=class extends GA{v0l=Bt[0]|0;v0h=Bt[1]|0;v1l=Bt[2]|0;v1h=Bt[3]|0;v2l=Bt[4]|0;v2h=Bt[5]|0;v3l=Bt[6]|0;v3h=Bt[7]|0;v4l=Bt[8]|0;v4h=Bt[9]|0;v5l=Bt[10]|0;v5h=Bt[11]|0;v6l=Bt[12]|0;v6h=Bt[13]|0;v7l=Bt[14]|0;v7h=Bt[15]|0;constructor(e={}){e=sp({},e);let t=e.dkLen===void 0?64:e.dkLen;super(128,t),a8(t,e,64,16,16);let{key:r,personalization:o,salt:s}=e,i=0;if(r!==void 0&&(ft(r,void 0,"key"),i=r.length),this.v0l^=this.outputLen|i<<8|65536|1<<24,s!==void 0){ft(s,void 0,"salt");let a=So(xb(s));this.v4l^=en(a[0]),this.v4h^=en(a[1]),this.v5l^=en(a[2]),this.v5h^=en(a[3])}if(o!==void 0){ft(o,void 0,"personalization");let a=So(xb(o));this.v6l^=en(a[0]),this.v6h^=en(a[1]),this.v7l^=en(a[2]),this.v7h^=en(a[3])}if(r!==void 0){let a=new Uint8Array(this.blockLen);a.set(r),this.update(a),at(a)}}get(){let{v0l:e,v0h:t,v1l:r,v1h:o,v2l:s,v2h:i,v3l:a,v3h:c,v4l:l,v4h:p,v5l:d,v5h:u,v6l:f,v6h:h,v7l:m,v7h:w}=this;return[e,t,r,o,s,i,a,c,l,p,d,u,f,h,m,w]}set(e,t,r,o,s,i,a,c,l,p,d,u,f,h,m,w){this.v0l=e|0,this.v0h=t|0,this.v1l=r|0,this.v1h=o|0,this.v2l=s|0,this.v2h=i|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=p|0,this.v5l=d|0,this.v5h=u|0,this.v6l=f|0,this.v6h=h|0,this.v7l=m|0,this.v7h=w|0}compress(e,t,r){let{v0l:o,v0h:s,v1l:i,v1h:a,v2l:c,v2h:l,v3l:p,v3h:d,v4l:u,v4h:f,v5l:h,v5h:m,v6l:w,v6h:b,v7l:g,v7h:y}=this;H[0]=o,H[1]=s,H[2]=i,H[3]=a,H[4]=c,H[5]=l,H[6]=p,H[7]=d,H[8]=u,H[9]=f,H[10]=h,H[11]=m,H[12]=w,H[13]=b,H[14]=g,H[15]=y,H.set(Bt,16);let _=Ab(this.length),v=_b(this.length);H[24]=Bt[8]^_,H[25]=Bt[9]^v,r&&(H[28]=~H[28],H[29]=~H[29]);let k=0,S=f2;for(let x=0;x<12;x++)cs(0,4,8,12,e,t+2*S[k++]),ps(0,4,8,12,e,t+2*S[k++]),cs(1,5,9,13,e,t+2*S[k++]),ps(1,5,9,13,e,t+2*S[k++]),cs(2,6,10,14,e,t+2*S[k++]),ps(2,6,10,14,e,t+2*S[k++]),cs(3,7,11,15,e,t+2*S[k++]),ps(3,7,11,15,e,t+2*S[k++]),cs(0,5,10,15,e,t+2*S[k++]),ps(0,5,10,15,e,t+2*S[k++]),cs(1,6,11,12,e,t+2*S[k++]),ps(1,6,11,12,e,t+2*S[k++]),cs(2,7,8,13,e,t+2*S[k++]),ps(2,7,8,13,e,t+2*S[k++]),cs(3,4,9,14,e,t+2*S[k++]),ps(3,4,9,14,e,t+2*S[k++]);this.v0l^=H[0]^H[16],this.v0h^=H[1]^H[17],this.v1l^=H[2]^H[18],this.v1h^=H[3]^H[19],this.v2l^=H[4]^H[20],this.v2h^=H[5]^H[21],this.v3l^=H[6]^H[22],this.v3h^=H[7]^H[23],this.v4l^=H[8]^H[24],this.v4h^=H[9]^H[25],this.v5l^=H[10]^H[26],this.v5h^=H[11]^H[27],this.v6l^=H[12]^H[28],this.v6h^=H[13]^H[29],this.v7l^=H[14]^H[30],this.v7h^=H[15]^H[31],at(H)}destroy(){this.destroyed=!0,at(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},mc=ap(n=>new YA(n))});function ds(n,e,t,r){let o=Lt[2*n],s=Lt[2*n+1],i=Lt[2*e],a=Lt[2*e+1],c=Lt[2*t],l=Lt[2*t+1],p=Lt[2*r],d=Lt[2*r+1],u=0,f=0,h=0,m=0,w=0;u=Math.imul(o,i),f=((o>>>0)*(i>>>0)-(u>>>0))/4294967296+.5|0,h=(o>>>0)+(i>>>0)+(u<<1>>>0),s=s+a+(f<<1|u>>>31)+(h/4294967296|0)|0,o=h|0,m=d^s,w=p^o,d=w,p=m,u=Math.imul(c,p),f=((c>>>0)*(p>>>0)-(u>>>0))/4294967296+.5|0,h=(c>>>0)+(p>>>0)+(u<<1>>>0),l=l+d+(f<<1|u>>>31)+(h/4294967296|0)|0,c=h|0,m=a^l,w=i^c,a=m>>>24|w<<8,i=m<<8|w>>>24,u=Math.imul(o,i),f=((o>>>0)*(i>>>0)-(u>>>0))/4294967296+.5|0,h=(o>>>0)+(i>>>0)+(u<<1>>>0),s=s+a+(f<<1|u>>>31)+(h/4294967296|0)|0,o=h|0,m=d^s,w=p^o,d=m>>>16|w<<16,p=m<<16|w>>>16,u=Math.imul(c,p),f=((c>>>0)*(p>>>0)-(u>>>0))/4294967296+.5|0,h=(c>>>0)+(p>>>0)+(u<<1>>>0),l=l+d+(f<<1|u>>>31)+(h/4294967296|0)|0,c=h|0,m=a^l,w=i^c,a=m<<1|w>>>31,i=m>>>31|w<<1,Lt[2*n]=o,Lt[2*n+1]=s,Lt[2*e]=i,Lt[2*e+1]=a,Lt[2*t]=c,Lt[2*t+1]=l,Lt[2*r]=p,Lt[2*r+1]=d}function g2(n,e,t,r,o,s,i,a,c,l,p,d,u,f,h,m){ds(n,o,c,u),ds(e,s,l,f),ds(t,i,p,h),ds(r,a,d,m),ds(n,s,p,m),ds(e,i,d,u),ds(t,a,c,f),ds(r,o,l,h)}function iu(n,e,t,r,o){if(o)for(let s=0;s<256;s++){let i=n[e+s]^n[t+s];Lt[s]=i,n[r+s]^=i}else for(let s=0;s<256;s++){let i=n[e+s]^n[t+s];Lt[s]=i,n[r+s]=i}for(let s=0;s<128;s+=16)g2(s,s+1,s+2,s+3,s+4,s+5,s+6,s+7,s+8,s+9,s+10,s+11,s+12,s+13,s+14,s+15);for(let s=0;s<16;s+=2)g2(s,s+1,s+16,s+17,s+32,s+33,s+48,s+49,s+64,s+65,s+80,s+81,s+96,s+97,s+112,s+113);for(let s=0;s<256;s++)n[r+s]^=Lt[s];at(Lt)}function JA(n,e){let t=op(n),r=new Uint32Array(1),o=op(r);if(r[0]=en(e),e<=64)return mc.create({dkLen:e}).update(o).update(t).digest();let s=new Uint8Array(e),i=mc.create({}).update(o).update(t).digest(),a=0;for(s.set(i.subarray(0,32)),a+=32;e-a>64;a+=32){let c=mc.create({}).update(i);c.digestInto(i),c.destroy(),s.set(i.subarray(0,32),a)}return s.set(mc(i,{dkLen:e-a}),a),at(i,r),s}function l8(n,e,t,r,o,s,i=!1){let a;n===0?e===0?a=o-1:i?a=e*r+o-1:a=e*r+(o==0?-1:0):i?a=t-r+o-1:a=t-r+(o==0?-1:0);let c=n!==0&&e!==ou-1?(e+1)*r:0,l=Math.imul(s,s),p=((s>>>0)*(s>>>0)-(l>>>0))/4294967296+.5|0,d=Math.imul(a,p),u=((a>>>0)*(p>>>0)-(d>>>0))/4294967296+.5|0,f=a-1-u;return(c+f)%t}function us(n){return Number.isSafeInteger(n)&&n>=0&&n<c8}function d8(n={}){n=sp({},n);let e={t:3,m:b2,p:1,version:19,dkLen:32,maxmem:p8,asyncTick:10};for(let[l,p]of Object.entries(n))p!==void 0&&(e[l]=p);let{dkLen:t,p:r,m:o,t:s,version:i,onProgress:a,asyncTick:c}=e;if(!us(t)||t<4)throw new Error('"dkLen" must be 4..');if(!us(r)||r<1||r>=Math.pow(2,24))throw new Error('"p" must be 1..2^24');if(!us(o))throw new Error('"m" must be 0..2^32');if(!us(s)||s<1)throw new Error('"t" (iterations) must be 1..2^32');if(a!==void 0&&typeof a!="function")throw new Error('"onProgress" must be a function');if(Sn(c,"asyncTick"),!us(o)||o<8*r)throw new Error('"m" (memory) must be at least 8*p bytes');if(i!==16&&i!==19)throw new Error('"version" must be 0x10 or 0x13, got '+i);return e}function u8(n,e,t,r){let o=[],s=new Uint32Array(1),i=op(s),a,c,l=!1,p=(d,u)=>(typeof d=="string"&&o.push(u),u);try{let d=p(n,Qu(n,"password")),u=p(e,Qu(e,"salt"));if(!us(d.length))throw new Error('"password" must be less of length 1..4Gb');if(!us(u.length)||u.length<8)throw new Error('"salt" must be of length 8..4Gb');if(!Object.values(Yy).includes(t))throw new Error('"type" was invalid');let{p:f,dkLen:h,m,t:w,version:b,key:g,personalization:y,maxmem:_,onProgress:v,asyncTick:k}=d8(r),S=g;g=p(S,y2(S,"key"));let x=y;y=p(x,y2(x,"personalization")),a=mc.create();for(let P of[f,h,m,w,b,t])s[0]=en(P),a.update(i);for(let P of[d,u,g,y])s[0]=en(P.length),a.update(i).update(P);return c=new Uint32Array(18),a.digestInto(op(c)),l=!0,{H0:c,p:f,dkLen:h,m,t:w,version:b,maxmem:_,onProgress:v,asyncTick:k}}finally{a&&a.destroy(),at(s,...o),!l&&c&&at(c)}}function f8(n,e,t,r){let{H0:o,p:s,dkLen:i,m:a,t:c,version:l,maxmem:p,onProgress:d,asyncTick:u}=u8(n,e,t,r);try{let f=s,h=4*s*Math.floor(a/(ou*s)),m=Math.floor(h/s),w=Math.floor(m/ou),b=h*1024;if(!us(p))throw new Error('"maxmem" expected <2**32, got '+p);if(b>p)throw new Error('"maxmem" limit was hit: memUsed(mP*1024)='+b+", maxmem="+p);let g=new Uint32Array(b/4);for(let _=0;_<s;_++){let v=256*m*_;o[17]=en(_),o[16]=en(0),g.set(Nr(So(JA(o,1024))),v),o[16]=en(1),g.set(Nr(So(JA(o,1024))),v+256)}let y=()=>{};if(d){let _=c*ou*s*w-2*s,v=Math.max(Math.floor(_/1e4),1),k=0;y=()=>{k++,d&&(!(k%v)||k===_)&&d(k/_)}}return{type:t,mP:h,p:s,t:c,version:l,B:g,laneLen:m,lanes:f,segmentLen:w,dkLen:i,perBlock:y,asyncTick:u}}finally{at(o)}}function h8(n,e,t,r){let o=new Uint32Array(256);for(let i=0;i<e;i++)for(let a=0;a<256;a++)o[a]^=n[256*(t*i+t-1)+a];let s=JA(Nr(o),r);return at(n,o),s}function*m8(n,e){let{type:t,mP:r,p:o,t:s,version:i,B:a,laneLen:c,lanes:l,segmentLen:p,perBlock:d}=n;e[262]=r,e[264]=s,e[266]=t;for(let u=0;u<s;u++){let f=u!==0&&i===19;e[256]=u;for(let h=0;h<ou;h++){e[260]=h;let m=t==Yy.Argon2i||t==Yy.Argon2id&&u===0&&h<2;for(let w=0;w<o;w++){e[258]=w,e[268]=0;let b=0;u===0&&h===0&&(b=2,m&&(e[268]++,iu(e,256,2*256,0,!1),iu(e,0,2*256,0,!1)));let g=w*c+h*p+b;for(let y=b;y<p;y++,g++){d();let _=g%c?g-1:g+c-1,v,k;if(m){let C=y%128;C===0&&(e[268]++,iu(e,256,2*256,0,!1),iu(e,0,2*256,0,!1)),v=e[2*C],k=e[2*C+1]}else{let C=256*_;v=a[C],k=a[C+1]}let S=u===0&&h===0?w:k%l,x=l8(u,h,c,p,y,v,S==w),P=c*S+x;iu(a,256*_,256*P,g*256,f),yield}}}}at(e)}async function y8(n,e,t,r){let o=f8(e,t,n,r),s=new Uint32Array(3*256),i=m8(o,s),a=()=>at(s,o.B),c=Date.now();for(;!i.next().done;){let l=Date.now()-c;l>=0&&l<o.asyncTick||(await Jk(a),c=Date.now())}return h8(o.B,o.p,o.laneLen,o.dkLen)}var Yy,ou,y2,Lt,c8,b2,p8,w2,v2=I(()=>{m2();fi();Yy={Argon2d:0,Argon2i:1,Argon2id:2},ou=4,y2=(n,e="")=>n===void 0?Uint8Array.of():Qu(n,e),Lt=new Uint32Array(256);c8=Math.pow(2,32),b2=1024**2,p8=b2*1024;w2=(n,e,t={})=>y8(Yy.Argon2id,n,e,t)});function b8(n,e,t,r=32,o){ip(n),Sn(r,"length"),ft(e,void 0,"prk");let s=n.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(r>255*s)throw new Error("Length must be <= 255*HashLen");let i=Math.ceil(r/s);if(t===void 0?t=g8:ft(t,void 0,"info"),!i)return o&&at(e),new Uint8Array;let a=o&&i===1?e:new Uint8Array(i*s),{iHash:c,oHash:l}=sa.create(n,e),p=o?e:new Uint8Array(s),d=i>1?o?.iHash||n.create():void 0;for(let f=0;f<i-1;f++){su[0]=f+1;let h=c._cloneInto(d);f&&h.update(p),h.update(t).update(su).digestInto(p),l._cloneInto(d).update(p).digestInto(p),a.set(p,s*f)}if(su[0]=i,i>1&&c.update(p),c.update(t).update(su).digestInto(p),l.update(p).digestInto(p),a.set(p,s*(i-1)),c.destroy(),l.destroy(),d?.destroy(),p!==a&&at(p),at(su),r===a.length)return a;let u=a.slice(0,r);return at(a),u}var su,g8,Jy,_2=I(()=>{aA();fi();su=Uint8Array.of(0),g8=Uint8Array.of();Jy=(n,e,t,r,o)=>{ip(n),t===void 0&&(t=new Uint8Array(n.outputLen));let s=sa.create(n,t).update(e);return b8(n,s.digest(),r,o,s)}});function ga(n,e){let t=yc.encode(n);if(t.length>255)throw De("internal","domain tag longer than 255 bytes");return Qe(ZA(Uint8Array.of(t.length),t,e))}function ZA(...n){let e=0;for(let o of n)e+=o.length;let t=new Uint8Array(e),r=0;for(let o of n)t.set(o,r),r+=o.length;return t}function e0(n,e){if(n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r++)t|=n[r]^e[r];return t===0}function bt(...n){for(let e of n)e.fill(0)}function Jn(n){if(!w8.test(n))throw De("internal","not a UUID");let e=n.replace(/-/g,"").toLowerCase(),t=new Uint8Array(16);for(let r=0;r<16;r++)t[r]=parseInt(e.slice(r*2,r*2+2),16);return t}function v8(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function k2(n=Xy){let e=n(ii);if(e.length!==ii)throw De("internal","entropy returned the wrong length");return e}function S2(n){return ga("mdbase/v1/recovery-key-check",n).subarray(0,A2)}function P2(n){if(n.length!==ii)throw De("internal","recovery secret is 32 bytes");let e=ZA(n,S2(n)),t="",r=0,o=0;for(let s of e){for(r=r<<8|s,o+=8;o>=5;)t+=XA[r>>>o-5&31],o-=5;r&=(1<<o)-1}return o>0&&(t+=XA[r<<5-o&31]),bt(e),[QA,...t.match(/.{1,5}/g)].join("-")}function lu(n){if(typeof n!="string"||n.length>4096)throw De("invalid_recovery_key","Not a recovery key.","wrong_length");let e=n.toUpperCase().replace(/[\s-]/g,"").replace(/O/g,"0").replace(/[IL]/g,"1");if(!e.startsWith(QA))throw De("invalid_recovery_key","A recovery key starts with MDB1.","wrong_prefix");if(e=e.slice(QA.length),e.length!==_8)throw De("invalid_recovery_key","A recovery key has 55 characters after MDB1.","wrong_length");let t=new Uint8Array(ii+A2),r=0,o=0,s=0;for(let c of e){let l=XA.indexOf(c);if(l<0)throw De("invalid_recovery_key","A recovery key uses only Crockford base32 characters.","bad_character");r=r<<5|l,o+=5,o>=8&&(s<t.length&&(t[s++]=r>>>o-8&255),o-=8),r&=(1<<o)-1}if(s!==t.length||r!==0)throw De("invalid_recovery_key","Not a recovery key.","bad_character");let i=t.slice(0,ii),a=e0(S2(i),t.subarray(ii));if(bt(t),!a)throw bt(i),De("invalid_recovery_key","The recovery key has a typo (check failed).","checksum");return i}function x2(n,e){if(n.length!==ii)throw De("internal","recovery secret is 32 bytes");let t=Jn(e),r=Jy(Qe,n,t,yc.encode("mdbase/v1/recovery-sign"),32),o=Jy(Qe,n,t,yc.encode("mdbase/v1/recovery-kem"),32),s=Jd.getPublicKey(r),i=ni.getPublicKey(o);return{device:v8(ga("mdbase/v1/recovery-id",ZA(t,s)).subarray(0,16)),signSeed:r,signPk:s,kemSk:o,kemPk:i,noisePk:new Uint8Array(32)}}function C2(n,e){return Jd.sign(e,n.signSeed)}function I2(n){bt(n.signSeed,n.kemSk)}function O2(n,e){if(n.length!==ii)throw De("internal","recovery secret is 32 bytes");let t=Jy(Qe,n,Jn(e),yc.encode("mdbase/v1/account-key-proof"),32);return{seed:t,pk:Jd.getPublicKey(t)}}function A8(n,e,t){if(!Number.isSafeInteger(t)||t<0)throw De("internal","expected_version");return ga("mdbase/v1/account-key-rewrap",ue([Jn(n),Qe(e),t]))}function R2(n,e,t,r){return Jd.sign(A8(e,t,r),n.seed)}function cu(n){return ga("mdbase/v1/account-key-id",n)}function O8(n){if(!(ya(n.mKib)&&ya(n.t)&&ya(n.p)&&n.mKib>=P8&&n.mKib<=q2&&n.t>=x8&&n.t<=C8&&n.p>=1&&n.p<=I8&&n.mKib>=8*n.p&&n.salt instanceof Uint8Array&&n.salt.length===16))throw De("params","Unsupported key derivation parameters.")}function T2(n){return[E2,n.mKib,n.t,n.p,n.salt]}function R8(n){if(!Array.isArray(n)||n.length!==5)throw De("encoding","Not an account key bundle.");let[e,t,r,o,s]=n;if(!ya(e)||!ya(t)||!ya(r)||!ya(o)||!(s instanceof Uint8Array)||s.length!==16)throw De("encoding","Not an account key bundle.");if(e!==E2||t>4294967295||r>4294967295||o>4294967295)throw De("params","Unsupported key derivation parameters.");return{mKib:t,t:r,p:o,salt:s}}function n0(n){return ue(Tg([[0,t0],[1,T2(n.kdf)],[2,n.nonce],[3,n.ct],[4,n.keyId]]))}function M2(n){if(!(n instanceof Uint8Array)||n.length>k8)throw De("encoding","Not an account key bundle.");let e;try{e=we(n)}catch{throw De("encoding","Not an account key bundle.")}if(!(e instanceof Map)||e.size!==5||[...e.keys()].join()!=="0,1,2,3,4")throw De("encoding","Not an account key bundle.");let t=e,r=t.get(2),o=t.get(3),s=t.get(4);if(t.get(0)!==t0||!(r instanceof Uint8Array)||r.length!==24||!(o instanceof Uint8Array)||o.length!==48||!(s instanceof Uint8Array)||s.length!==32)throw De("encoding","Not an account key bundle.");let i={kdf:R8(t.get(1)),nonce:r,ct:o,keyId:s};if(!Mg(n0(i),n))throw De("encoding","Not an account key bundle.");return i}function L2(n){if(typeof n!="string")throw De("weak_password","The password is required.","too_short");if(yc.encode(n).length>au)throw De("weak_password","The password is too long.","too_long");let e=n.normalize("NFKC"),t=yc.encode(e);if(t.length>au)throw De("weak_password","The password is too long.","too_long");if([...e].length<gc)throw bt(t),De("weak_password",`The password needs at least ${gc} characters.`,"too_short");return t}function ba(n){bt(L2(n))}async function j2(n,e,t,r){O8(e);let o=L2(n);try{let s=await t(o,e.salt,{mKib:e.mKib,t:e.t,p:e.p},r);if(!(s instanceof Uint8Array)||s.length!==32)throw De("internal","The KDF runner returned the wrong length.");return s}finally{bt(o)}}function U2(n,e,t){return ga("mdbase/v1/account-key-bundle",ue([t0,Jn(n),e,T2(t)]))}async function Zy(n,e,t,r={}){if(n.length!==ii)throw De("internal","recovery secret is 32 bytes");ba(e);let o=r.entropy??Xy,s=r.kdf??{...S8,salt:o(16)},i=r.nonce??o(24);if(i.length!==24)throw De("internal","nonce is 24 bytes");let a=cu(n),c=await j2(e,s,r.argon2id??Qy,r.signal);try{let l=K_(c,i,U2(t,a,s)).encrypt(n);return{kdf:s,nonce:i,ct:l,keyId:a}}finally{bt(c)}}async function N2(n,e,t,r={}){let o=await j2(e,n.kdf,r.argon2id??Qy,r.signal),s;try{s=K_(o,n.nonce,U2(t,n.keyId,n.kdf)).decrypt(n.ct)}catch{throw De("wrong_secret","Wrong password.")}finally{bt(o)}if(s.length!==ii||!e0(cu(s),n.keyId))throw bt(s),De("wrong_secret","Wrong password.");return s}function pu(n,e){if(n.length!==ii||!e0(cu(n),e.keyId))throw De("wrong_secret","This recovery key belongs to a different account key.")}var Be,De,yc,Xy,w8,XA,QA,ii,A2,_8,t0,E2,k8,gc,au,S8,P8,q2,x8,C8,I8,ya,Qy,eg=I(()=>{"use strict";W_();ky();v2();_2();hi();Ye();Be=class extends Error{code;reason;retryAfterMs;constructor(e,t,r={}){super(t),this.name="AccountKeyError",this.code=e,r.reason!==void 0&&(this.reason=r.reason),r.retryAfterMs!==void 0&&(this.retryAfterMs=r.retryAfterMs)}},De=(n,e,t)=>new Be(n,e,t===void 0?{}:{reason:t}),yc=new TextEncoder;Xy=n=>crypto.getRandomValues(new Uint8Array(n)),w8=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;XA="0123456789ABCDEFGHJKMNPQRSTVWXYZ",QA="MDB1",ii=32,A2=2,_8=55;t0=1,E2=1,k8=512,gc=12,au=1024,S8={mKib:19456,t:3,p:1},P8=19456,q2=24576,x8=2,C8=10,I8=4;ya=n=>typeof n=="number"&&Number.isSafeInteger(n)&&n>=0;Qy=async(n,e,t,r)=>{let o=()=>De("cancelled","Key derivation cancelled.");if(r?.aborted)throw o();try{return await w2(n,e,{t:t.t,m:t.mKib,p:t.p,dkLen:32,version:19,maxmem:q2*1024+(1<<20),asyncTick:20,onProgress:()=>{if(r?.aborted)throw o()}})}catch(s){throw s instanceof Be?s:De("params","Key derivation failed.")}}});function D2(n){if(n.length<3)return!1;let e=[...n].reverse().join("");return[$2,...q8].some(t=>t.includes(n)||t.includes(e))}function T8(n){for(let e=1;e<=n.length/2;e++)if(n.length%e===0&&n.slice(0,e).repeat(n.length/e)===n)return n.slice(0,e);return null}function M8(n){let e=[];for(let t of n){let r=/\p{L}/u.test(t)?"letter":/\p{Nd}/u.test(t)?"digit":t.charCodeAt(0)<128?"symbol":"other",o=e[e.length-1];o&&o.kind===r?o.text+=t:e.push({kind:r,text:t})}return e}function B2(n,e,t,r){let o=e.toLowerCase();if(t.has(o))return r.add("repeat"),1;t.add(o);let s=T8(o);if(s&&s.length<o.length)return r.add("repeat"),B2(n,s,new Set,r)+oi(o.length/s.length);if(n==="letter"){let i=[...o].map(c=>z2[c]??c).join("");if(du.has(o)||du.has(i))return r.add("common"),oi(du.size)+1;if(D2(o))return r.add("sequence"),oi($2.length)+oi(o.length)+1;let a=2.5*[...o].length;return o!==e&&e.toUpperCase()!==e?a+=1+oi([...e].length):e.toUpperCase()===e&&e.length>1&&(a+=1),a}return n==="digit"?E8.has(o)||D2(o)?(r.add("sequence"),4):/^(19|20)\d\d$/.test(o)||/^\d{6}$/.test(o)||/^\d{8}$/.test(o)?(r.add("date"),6):3.32*o.length:n==="symbol"?[...e].reduce((i,a)=>i+(a===" "?1:"!?.,*#-_".includes(a)?2:5),0):7*[...e].length}function L8(n){let e=[...n],t=e.map(i=>z2[i.toLowerCase()]??i.toLowerCase()),r=[],o="",s=0;for(;s<e.length;){let i=null;for(let a=Math.min(24,e.length-s);a>=4;a--){let c=t.slice(s,s+a).join("");if(du.has(c)){i=c;break}}i?(o&&r.push({word:null,text:o}),o="",r.push({word:i,text:e.slice(s,s+[...i].length).join("")}),s+=[...i].length):(o+=e[s],s++)}return o&&r.push({word:null,text:o}),r}function uu(n){typeof n!="string"&&(n="");let e=new TextEncoder().encode(n).length,t=n.normalize("NFKC"),r=[...t].length,o=new TextEncoder().encode(t).length,s=new Set,i=new Set,a=0,c=0,l=new Set;for(let h of L8(t)){if(h.word){s.add("common"),c++,l.add("word");let m=h.text.toLowerCase();a+=i.has(h.word)?1:oi(du.size)+1+(m!==h.text?1:0)+(m!==h.word?1:0),i.add(h.word);continue}for(let m of M8(h.text))c++,l.add(m.kind),a+=B2(m.kind,m.text,i,s)}a+=Math.max(0,l.size-1)+oi(Math.max(1,c));let p=a<oi(1e3)?0:a<oi(1e6)?1:a<oi(1e8)?2:a<oi(1e10)?3:4,d=[],u=e>au||o>au;r<gc&&d.push(`Use at least ${gc} characters.`),u&&d.push("The password is too long."),s.has("common")&&d.push("Avoid common words and passwords."),s.has("sequence")&&d.push("Avoid sequences like abcd, 1234 or qwerty."),s.has("repeat")&&d.push("Avoid repeated characters or words."),s.has("date")&&d.push("Avoid years and dates."),p<3&&d.length===0&&d.push("Add another word or two; uncommon words are best.");let f=p>=3&&r>=gc&&!u;return{score:p,acceptable:f,feedback:f?[]:d,bits:Math.round(a*10)/10}}var du,E8,z2,$2,q8,oi,V2=I(()=>{"use strict";eg();du=new Set(["password","passwort","passw0rd","letmein","welcome","admin","administrator","login","master","monkey","dragon","football","baseball","soccer","hockey","qwerty","qwertyuiop","asdfgh","asdfghjkl","zxcvbn","zxcvbnm","azerty","iloveyou","sunshine","princess","shadow","superman","batman","michael","jennifer","jessica","charlie","thomas","trustno1","abc","abcd","abcdef","abcdefg","abcdefgh","secret","freedom","whatever","starwars","pokemon","computer","internet","hello","mustang","ginger","cheese","summer","winter","spring","autumn","flower","killer","hunter","ranger","buster","soccer","tigger","pepper","jordan","harley","robert","matthew","daniel","andrew","joshua","ashley","nicole","chelsea","amanda","orange","purple","yellow","silver","golden","cookie","chocolate","mdbase","task","note","notes","obsidian","recovery","private","encryption","unlock","account","default","changeme","temp","test","testing","guest","root","user","system","server","database","oracle","google","apple","facebook","twitter","github","linkedin","amazon","netflix","spotify","windows","android","iphone","samsung","nokia","sony","january","february","march","april","june","july","august","september","october","november","december","monday","tuesday","wednesday","thursday","friday","saturday","sunday","spider","lovely","liverpool","arsenal","chelsea","manchester","barcelona","madrid","america","london","paris","berlin","sydney","melbourne","canada"]),E8=new Set(["123","1234","12345","123456","1234567","12345678","123456789","1234567890","111111","000000","123123","654321","696969","112233","121212","131313","007","666","777","888","999","420","69"]),z2={0:"o",1:"i",3:"e",4:"a",5:"s",7:"t",8:"b","@":"a",$:"s","!":"i","+":"t"},$2="abcdefghijklmnopqrstuvwxyz0123456789",q8=["qwertyuiop","asdfghjkl","zxcvbnm","1234567890"],oi=n=>Math.log2(Math.max(1,n))});function K2(){let n=null;return{get:async()=>n?n.slice():null,set:async e=>{n&&bt(n),n=e.slice()},clear:async()=>{n&&bt(n),n=null}}}function wa(n){if(!n||typeof n!="object"||Array.isArray(n))throw an("not_object");return n}function F2(n){if(typeof n.complete!="boolean"||!Array.isArray(n.pending)||n.pending.length>1024)throw an("strict_completion");let e=new Set,t=n.pending.map(r=>{let o=wa(r);if(typeof o.collection_id!="string"||typeof o.device_id!="string"||o.revoked_at!==null&&(!Number.isSafeInteger(o.revoked_at)||o.revoked_at<0))throw an("strict_pending");Jn(o.collection_id),Jn(o.device_id);let s=`${o.collection_id.toLowerCase()}/${o.device_id.toLowerCase()}`;if(e.has(s))throw an("strict_pending");return e.add(s),{collectionId:o.collection_id,deviceId:o.device_id,revokedAt:o.revoked_at}});if(n.complete&&t.length!==0)throw an("strict_completion");return{complete:n.complete,pending:t}}function uo(n){if(n instanceof Be)return n;let e=n&&typeof n=="object"?n:{},t=e.problem&&typeof e.problem=="object"?e.problem:{},r=typeof t.code=="string"?t.code:typeof e.code=="string"?e.code:"",o=typeof e.status=="number"?e.status:void 0,s=e.retryAfterMs??t.retryAfterMs??(typeof e.retry_after=="number"?e.retry_after*1e3:void 0),i=typeof s=="number"&&Number.isFinite(s)&&s>=0?s:void 0;return r==="rate_limited"||o===429?new Be("rate_limited","Too many account key requests; try again later.",i===void 0?{}:{retryAfterMs:i}):r==="version_conflict"||r==="rotate_requires_strict"?new Be("conflict","The account key changed; fetch the current state and retry.",{reason:r}):r==="strict_mode"?new Be("strict_mode","The account is in strict mode."):r==="account_key_proof_required"?new Be("wrong_secret","The account key held here is not the one registered for this bundle.",{reason:r}):r==="no_account_key"?new Be("no_account_key","The account has no account key."):r==="cancelled"||e.name==="AbortError"?new Be("cancelled","Account key request cancelled."):U8(r||(o===void 0?"port_failure":`http_${o}`),i)}var r0,j8,an,U8,tg,ng,W2=I(()=>{"use strict";eg();Ye();V2();r0=/^[0-9a-f]{64}$/,j8=/^([0-9a-f]{2}){1,512}$/,an=n=>new Be("internal","Invalid control-plane account-key response.",{reason:n}),U8=(n,e)=>new Be("unavailable","The account key service refused or was unreachable.",e===void 0?{reason:n}:{reason:n,retryAfterMs:e});tg=n=>{if(!Number.isSafeInteger(n)||n<0)throw an("version");return n};ng=class{lifetime=new AbortController;control;replica;secrets;argon2id;entropy;busy=Promise.resolve();last=null;constructor(e){if(this.control=e.control,this.replica=e.replica,!e.secrets)throw new Be("internal","PrivateAccount needs a secret store (the platform keychain).");this.secrets=e.secrets,this.argon2id=e.argon2id??Qy,this.entropy=e.entropy??Xy,Jn(this.control.accountId)}close(){this.lifetime.signal.aborted||(this.lifetime.abort(),this.control.close?.())}passwordStrength(e){return uu(e)}async status(e={}){return this.serial(e,t=>this.readStatus(t))}get lastStatus(){return this.last}async setup(e,t){return this.serial({signal:t},async r=>{let o=uu(e);if(ba(e),!o.acceptable)throw new Be("weak_password","The password is too weak.",{reason:"strength"});let s=await this.fetchState(r);if(s.mode==="password")throw new Be("already_set_up","This account already has an account key; unlock it instead.");let i=k2(this.entropy);try{let a=await Zy(i,e,this.control.accountId,{entropy:this.entropy,argon2id:this.argon2id,signal:r});this.check(r),await this.putBundle(i,s.version,a,r),await this.secrets.set(i);let c=P2(i),l=await this.keyAll(i,r);return l.length?{recoveryKey:c,incomplete:l}:{recoveryKey:c}}finally{bt(i)}})}async unlock(e,t){return this.serial({signal:t},async r=>{let o="recoveryKey"in e?lu(e.recoveryKey):null;try{let s=await this.requirePassword(r);o?pu(o,s.bundle):o=await N2(s.bundle,e.password,this.control.accountId,{argon2id:this.argon2id,signal:r}),this.check(r),await this.secrets.set(o);let i=await this.grantAll(o,r);return i.length?{incomplete:i}:{}}finally{o&&bt(o)}})}async changePassword(e,t){return this.serial({signal:t},async r=>{let o=uu(e);if(ba(e),!o.acceptable)throw new Be("weak_password","The password is too weak.",{reason:"strength"});let s=await this.secrets.get();if(!s)throw new Be("locked","Unlock the account key on this device first.");try{let i=await this.requirePassword(r);try{pu(s,i.bundle)}catch{throw new Be("conflict","The account key on the server is not the one unlocked here; unlock again.",{reason:"key_id_changed"})}let a=await Zy(s,e,this.control.accountId,{entropy:this.entropy,argon2id:this.argon2id,signal:r});this.check(r),await this.putBundle(s,i.version,a,r)}finally{bt(s)}})}async recover(e,t,r){return this.serial({signal:r},async o=>{let s=uu(t);if(ba(t),!s.acceptable)throw new Be("weak_password","The password is too weak.",{reason:"strength"});let i=lu(e);try{let a=await this.requirePassword(o);pu(i,a.bundle);let c=await Zy(i,t,this.control.accountId,{entropy:this.entropy,argon2id:this.argon2id,signal:o});this.check(o),await this.putBundle(i,a.version,c,o),await this.secrets.set(i);let l=await this.grantAll(i,o);return l.length?{incomplete:l}:{}}finally{bt(i)}})}async enableStrict(e){return this.serial({signal:e},async t=>{let r=await this.readStatus(t);if(r.mode==="strict"){r.strictComplete===!0&&await this.secrets.clear();let p=r.strictComplete===!0?!1:r.accountKeyKept;return this.last={...r,accountKeyKept:p},{version:r.version,complete:r.strictComplete,pending:r.pending,accountKeyKept:p,revocations:[],alreadyStrict:!0}}let o;try{o=await this.control.strict({expected_version:r.version},{signal:t})}catch(p){throw uo(p)}let s=wa(o);if(s.mode!=="strict"||tg(s.version)!==r.version+1||!Array.isArray(s.revocations))throw an("strict");let i=F2(s),a=s.revocations.map(p=>{let d=wa(p);if(typeof d.collection_id!="string"||typeof d.device_id!="string")throw an("strict");return Jn(d.collection_id),Jn(d.device_id),{collectionId:d.collection_id,deviceId:d.device_id}});i.complete===!0&&await this.secrets.clear();let c=await this.secrets.get(),l=c!==null;return c&&bt(c),this.last={mode:"strict",version:s.version,unlocked:!1,strictComplete:i.complete,pending:i.pending,accountKeyKept:l},{version:s.version,...i,accountKeyKept:l,revocations:a,alreadyStrict:!1}})}async keyCollections(e){return this.serial({signal:e},async t=>{let r=await this.secrets.get();if(!r)throw new Be("locked","Unlock the account key on this device first.");try{let o=await this.requirePassword(t);return pu(r,o.bundle),await this.keyAll(r,t)}finally{bt(r)}})}async lock(){await this.secrets.clear()}serial(e,t){let r=e.signal?AbortSignal.any([this.lifetime.signal,e.signal]):this.lifetime.signal,o=this.busy.then(()=>(this.check(r),t(r)),()=>(this.check(r),t(r)));return this.busy=o.catch(()=>{}),o}check(e){if(e.aborted)throw new Be("cancelled","Account key request cancelled.")}async readStatus(e){let t;try{t=await this.control.status({signal:e})}catch(l){throw uo(l)}this.check(e);let r=wa(t),o=tg(r.version),s,i=null;if(r.mode==="none"&&o===0)s="none";else if(r.mode==="strict")s="strict";else if(r.mode==="password"&&typeof r.key_id=="string"&&r0.test(r.key_id))s="password",i=r.key_id;else throw an("status");let a=s==="strict"?F2(r):void 0,c=await this.secrets.get();try{let l=i!==null&&c!==null&&c.length===32&&ut(cu(c))===i;return this.last={mode:s,unlocked:l,version:o,...a?{strictComplete:a.complete,pending:a.pending,accountKeyKept:c!==null}:{}}}finally{c&&bt(c)}}async fetchState(e){let t;try{t=await this.control.fetch({signal:e})}catch(i){throw uo(i)}this.check(e);let r=wa(t),o=tg(r.version);if(r.mode==="none"){if(o!==0)throw an("mode");return{mode:"none",version:0}}if(r.mode==="strict")return{mode:"strict",version:o};if(r.mode!=="password")throw an("mode");if(typeof r.key_id!="string"||!r0.test(r.key_id)||typeof r.bundle!="string"||!j8.test(r.bundle))throw an("bundle");let s=M2(Bi(r.bundle));if(ut(s.keyId)!==r.key_id)throw an("key_id");return{mode:"password",version:o,bundle:s}}async requirePassword(e){let t=await this.fetchState(e);if(t.mode==="none")throw new Be("no_account_key","The account has no account key yet; set one up on a device that holds the keys.");if(t.mode==="strict")throw new Be("strict_mode","The account is in strict mode; approve this device from an existing device.");return t}async putBundle(e,t,r,o){let s=ut(r.keyId),i=n0(r),a=O2(e,this.control.accountId),c;try{let p=ut(R2(a,this.control.accountId,i,t));c=await this.control.put({expected_version:t,key_id:s,bundle:ut(i),proof_pk:ut(a.pk),proof_sig:p},{signal:o})}catch(p){throw uo(p)}finally{bt(a.seed)}let l=wa(c);if(l.mode!=="password"||tg(l.version)!==t+1||l.key_id!==s)throw an("put")}async collections(e){let t;try{t=await this.replica.privateCollections({signal:e})}catch(r){throw uo(r)}if(this.check(e),!Array.isArray(t)||t.some(r=>typeof r!="string")||new Set(t).size!==t.length)throw an("collections");for(let r of t)Jn(r);return t}async keyAll(e,t){let r=[];for(let o of await this.collections(t)){this.check(t);try{await this.enrol(e,o,t),await this.replica.keyAccountKeyDevice(o,e,{signal:t})}catch(s){if(s instanceof Be&&s.code==="cancelled")throw s;r.push(o)}}return r}async grantAll(e,t){let r=[];for(let o of await this.collections(t)){this.check(t);try{await this.replica.selfGrantWithAccountKey(o,e,{signal:t})}catch(s){if(s instanceof Be&&s.code==="cancelled")throw s;r.push(o)}}return r}async enrol(e,t,r){let o;try{o=await this.control.challenge({signal:r})}catch(a){throw uo(a)}let s=typeof o=="string"?o.toLowerCase():typeof o?.challenge=="string"?o.challenge.toLowerCase():"";if(!r0.test(s))throw an("challenge");this.check(r);let i=x2(e,t);try{let a=ga("mdbase/v1/account-key-enrol",ue([Bi(s),Jn(t),Jn(i.device),Jn(this.control.accountId),i.signPk,i.kemPk,i.noisePk])),c=ut(C2(i,a)),l;try{l=await this.control.enrolRecoveryDevice(t,{challenge:s,recovery_device:i.device,sign_pk:ut(i.signPk),kem_pk:ut(i.kemPk),pop:c},{signal:r})}catch(d){throw uo(d)}let p=wa(l);if(p.collection_id!==t||p.device_id!==i.device||!Number.isSafeInteger(p.enrolled_at))throw an("enrol")}finally{I2(i)}}}});function i0(n){if(n instanceof pt)return n;if(n instanceof Mt)return new pt("unlock_strict");if(n instanceof ts)return new pt("unlock_unavailable");if(!(n instanceof Be))return null;switch(n.code){case"wrong_secret":return new pt("wrong_secret");case"invalid_recovery_key":return new pt("invalid_recovery_key",n.reason);case"no_account_key":return new pt("no_account_key");case"strict_mode":return new pt("unlock_strict");case"rate_limited":return new pt("rate_limited",void 0,n.retryAfterMs);case"cancelled":return null;default:return n.reason==="account_key_proof_unavailable"?new pt("unlock_unavailable"):new pt("unavailable",n.reason??n.code,n.retryAfterMs)}}async function B8(n,e){return(await G2(n,e)).mode}async function G2(n,e){let t;try{t=await n.status({signal:e})}catch(s){throw uo(s)}if(e.aborted)throw o0();let r=t&&typeof t=="object"&&!Array.isArray(t)?t:{},o=r.mode;if(o!=="password"&&o!=="strict"&&o!=="none")throw xt("response");return{mode:o,version:Number.isSafeInteger(r.version)&&r.version>=1?r.version:null,keyId:typeof r.key_id=="string"&&H2.test(r.key_id)?r.key_id:null}}async function ig(n,e){let t=new wc(n,()=>{throw xt("proof")},e);try{return await B8(t,e.signal)}catch(r){throw e.signal.aborted?r:i0(r)??r}finally{t.close()}}async function og(n,e,t,r){let o=r.signal,s=r.settleMs??z8,i=r.sealed,a="password"in t,c="recoveryKey"in t;if(a===c||typeof(a?t.password:t.recoveryKey)!="string"||!Number.isSafeInteger(s)||s<1)throw new pt("unavailable","binding");let l=()=>{if(o.aborted)throw o0();if(n.isCurrent()!==!0)throw xt("fenced")};if(l(),e.status().state==="keyed"){i?.clear();return}if(c)try{bt(lu(t.recoveryKey))}catch(g){throw i0(g)??g}else try{ba(t.password)}catch{throw new pt("wrong_secret")}let p,d=null,u={privateCollections:async()=>[n.collection],keyAccountKeyDevice:()=>Promise.reject(rg()),async selfGrantWithAccountKey(g,y,_){let v=_.signal??o;try{if(l(),g!==n.collection||!(y instanceof Uint8Array)||y.length!==32)throw xt("binding");let k=new Uint8Array(y),S;try{S=e.unlockConsuming(k)}finally{k.fill(0)}let x=Date.now()+s,P=100;for(;S.state==="pending";){if(Date.now()>=x)throw p="grant_pending",xt("grant_pending");if(await e.drive({signal:v}),l(),S=e.status(),S.state!=="pending")break;await fa(P,v),l(),P=Math.min(1e3,P*2)}if(S.state==="refused")throw p=S.reason,xt(S.reason)}catch(k){throw p===void 0&&(d={error:k}),k}}},f=new wc(n,g=>e.signFetch(g),r),h=null,m=i?{accountId:f.accountId,status:g=>f.status(g),challenge:g=>f.challenge(g),async fetch(g){let y=i.take(n,h?.version??null,h?.keyId??null);if(y)return y;let _=await f.fetch(g);return i.keep(n,_),_},put:()=>f.put(),strict:()=>f.strict(),enrolRecoveryDevice:()=>f.enrolRecoveryDevice(),close:()=>f.close()}:f,w=K2(),b=new ng({control:m,replica:u,secrets:w,...r.argon2id?{argon2id:r.argon2id}:{}});try{h=await G2(f,o),l();let g=h.mode;try{r.onMode?.(g)}catch{}if(g==="none")throw new pt("no_account_key");if(g==="strict")throw new pt("unlock_strict");if(!e.supportsFetchProof())throw new pt("unlock_unavailable");if(e.headKnown()<=0&&(await e.drive({signal:o}),l()),e.headKnown()<=0)throw new pt("unavailable","log_head_unknown");let y=await b.unlock(t,o),_=d;if(_)throw _.error;if(l(),y.incomplete?.length)throw new pt(p==="grant_pending"?"unavailable":"unlock_failed",p??"incomplete");if(e.status().state!=="keyed")throw new pt("unlock_failed","not_keyed");i?.clear()}catch(g){throw(!(g instanceof Be&&g.code==="wrong_secret")||o.aborted||n.isCurrent()!==!0)&&i?.clear(),o.aborted||n.isCurrent()!==!0?g:i0(g)??g}finally{try{await w.clear()}finally{b.close()}}}var pt,bc,N8,D8,z8,xt,o0,rg,$8,H2,wc,fu=I(()=>{"use strict";At();eg();ve();W2();nr();jy();Hm();pt=class extends Error{constructor(t,r,o){super(`app account key unlock: ${t}`);this.reason=t;this.detail=r;this.retryAfterMs=o;this.name="AppAccountKeyUnlockError"}reason;detail;retryAfterMs},bc=class{held=null;get holding(){return this.held!==null}take(e,t,r){let o=this.held;return o&&t!==null&&r!==null&&o.accountId===e.accountId&&o.connectorId===e.connectorId&&o.deviceId===e.deviceId&&o.version===t&&o.keyId===r?{mode:"password",version:o.version,key_id:o.keyId,bundle:o.bundle}:(this.held=null,null)}keep(e,t){this.held=null;let r=t&&typeof t=="object"&&!Array.isArray(t)?t:{};r.mode!=="password"||!Number.isSafeInteger(r.version)||r.version<1||typeof r.key_id!="string"||!H2.test(r.key_id)||typeof r.bundle!="string"||!/^([0-9a-f]{2}){1,512}$/.test(r.bundle)||(this.held=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,version:r.version,keyId:r.key_id,bundle:r.bundle}))}clear(){this.held=null}},N8=64*1024,D8=15e3,z8=45e3,xt=n=>new Be("unavailable","The account key service refused or was unreachable.",{reason:n}),o0=()=>new Be("cancelled","Account key request cancelled."),rg=()=>xt("not_supported"),$8=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),H2=/^[0-9a-f]{64}$/,wc=class{constructor(e,t,r={}){this.session=e;this.sign=t;for(let s of[e.accountId,e.connectorId,e.deviceId,e.collection])if(N(s).every(i=>i===0))throw xt("binding");let o=new URL(e.cpOrigin);if(o.origin!==e.cpOrigin||o.username||o.password||o.protocol!=="https:"&&!(r.allowLoopbackHttp===!0&&Ze(e.cpOrigin)))throw xt("binding");if(this.accountId=e.accountId,this.deviceId=e.deviceId,this.origin=o.origin,this.fetchImpl=r.fetch??globalThis.fetch,this.now=r.now??Date.now,e.isCurrent()!==!0)throw xt("fenced")}session;sign;accountId;lifetime=new AbortController;origin;deviceId;fetchImpl;now;check(e){if(e.aborted||this.lifetime.signal.aborted)throw o0();let t=!1;try{t=this.session.isCurrent()===!0&&this.session.accountId===this.accountId&&this.session.deviceId===this.deviceId&&this.session.cpOrigin===this.origin}catch{t=!1}if(!t)throw xt("fenced")}async request(e,t,r,o){let s=o.signal??this.lifetime.signal;this.check(s);let i=await this.session.connectorBearer({signal:s});if(this.check(s),typeof i!="string"||!i||i.length>16384||/[^\x21-\x7e]/.test(i))throw xt("binding");let a=new AbortController,c=()=>a.abort(),l=setTimeout(c,D8);l.unref?.(),s.addEventListener("abort",c,{once:!0}),this.lifetime.signal.addEventListener("abort",c,{once:!0});let p=new Uint8Array(N8),d=0,u=null,f=null;try{let h=this.fetchImpl;try{u=await h(`${this.origin}${t}`,{method:e,headers:{authorization:`Bearer ${i}`,...r},signal:a.signal,redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer"})}catch{throw this.check(s),xt("network")}if(this.check(s),a.signal.aborted)throw xt("timeout");if(u.body)for(f=u.body.getReader();;){let w;try{w=await f.read()}catch{throw this.check(s),xt("network")}try{if(this.check(s),a.signal.aborted)throw xt("timeout");if(w.done)break;if(d+w.value.length>p.length)throw a.abort(),xt("response");p.set(w.value,d),d+=w.value.length}finally{w.value?.fill(0)}}let m=Mo(p.subarray(0,d));if(!u.ok)throw vr(u.status,m,u.headers);if(!m||typeof m!="object"||Array.isArray(m))throw xt("response");return m}finally{p.fill(0),(f?.cancel()??u?.body?.cancel())?.catch(()=>{});try{f?.releaseLock()}catch{}clearTimeout(l),s.removeEventListener("abort",c),this.lifetime.signal.removeEventListener("abort",c)}}status(e){return this.request("GET","/v1/next/account-key/status",{},e)}challenge(e){return this.request("POST","/v1/next/devices/challenge",{},e)}async fetch(e){let t=null,r=null;try{let o=await this.request("POST","/v1/next/devices/challenge",{},e),s=o.challenge,i=o.expires_at;if(typeof s!="string"||!/^[0-9a-f]{64}$/.test(s)||typeof i!="number"||!Number.isSafeInteger(i)||i-this.now()<=5e3||i-this.now()>16*6e4)throw xt("response");t=Uint8Array.from(s.match(/../g).map(a=>parseInt(a,16)));try{r=this.sign(t)}catch(a){throw a instanceof ts?xt(a.reason):a instanceof Mt?new Be("strict_mode","The account is in strict mode."):xt("proof")}if(!(r instanceof Uint8Array)||r.length!==64)throw xt("proof");return await this.request("GET","/v1/next/account-key",{"x-mdbase-device-id":this.deviceId,"x-mdbase-challenge":s,"x-mdbase-signature":$8(r)},e)}finally{t?.fill(0),r?.fill(0)}}put(){return Promise.reject(rg())}strict(){return Promise.reject(rg())}enrolRecoveryDevice(){return Promise.reject(rg())}close(){this.lifetime.abort()}}});var Lr,vc=I(()=>{"use strict";Lr=class extends Error{reason="device_keys_unavailable";constructor(e){super(e),this.name="AppDeviceCustodyError"}}});function ag(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 jt();return n}function V8(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 jt();return ag(n.key)}var sg,Y2,jt,_c,s0=I(()=>{"use strict";tn();ve();vc();sg="device-key-kek",Y2="original-device-kek",jt=()=>new Lr("app device key provider unavailable; preserve storage and reopen");_c=class n{constructor(e,t,r){this.source=e;this.origin=t;this.lifetime=r;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:r,origin:o,mode:s,signal:i}=e;t=new n(r,o,i);let a=Object.values(t.scope).map(u=>{let f=N(u);if(f.every(h=>h===0))throw jt();return Array.from(f,h=>h.toString(16).padStart(2,"0")).join("")});if(!dt(o)||!["fresh","existing"].includes(s)||!globalThis.indexedDB||!globalThis.crypto?.subtle||typeof globalThis.CryptoKey!="function")throw jt();t.check(i);let c=crypto.subtle.generateKey.bind(crypto.subtle),l=`mdbase.app.device-key-kek.v1.${a.join(".")}`,p=await t.openDatabase(l,s);t.db=p,p.onversionchange=()=>t.close(),t.check(i);let d=await t.transaction("readonly",i,null);if(t.check(i),s==="existing"){if(d===null||typeof d=="boolean")throw jt();t.value=d}else{if(d!==null)throw jt();let u=ag(await c({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]));if(t.check(i),await t.transaction("readwrite",i,u)!==!0)throw jt();t.check(i),t.value=u}return t.check(i),t}catch{throw t?.close(),jt()}}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,r])=>this.source[t]!==r))throw jt()}catch{throw jt()}}openDatabase(e,t){return new Promise((r,o)=>{this.check(this.lifetime);let s=indexedDB.open(e,1),i=!1,a=!1,c=()=>{i=!0,o(jt())};this.lifetime.addEventListener("abort",c,{once:!0});let l=()=>this.lifetime.removeEventListener("abort",c);s.onblocked=c,s.onupgradeneeded=()=>{try{if(this.check(this.lifetime),i||t!=="fresh"||s.result.objectStoreNames.length!==0)throw jt();s.result.createObjectStore(sg),a=!0}catch{s.transaction?.abort()}},s.onerror=()=>{l(),o(jt())},s.onsuccess=()=>{l();try{if(this.check(this.lifetime),i||t==="fresh"&&!a||s.result.objectStoreNames.length!==1||!s.result.objectStoreNames.contains(sg))throw jt();r(s.result)}catch{s.result.close(),o(jt())}}})}transaction(e,t,r){return new Promise((o,s)=>{if(this.check(t),!this.db)throw jt();let i=this.db.transaction(sg,e,{durability:"strict"}),a=i.objectStore(sg),c=null,l=!1,p=()=>{l=!0;try{i.abort()}catch{}};t.addEventListener("abort",p,{once:!0}),this.lifetime.addEventListener("abort",p,{once:!0});let d=()=>{t.removeEventListener("abort",p),this.lifetime.removeEventListener("abort",p)};i.onerror=i.onabort=()=>{d(),c=null,s(jt())},i.oncomplete=()=>{d();try{if(this.check(t),l)throw jt();o(c)}catch{c=null,s(jt())}};let u=a.get(Y2);u.onsuccess=()=>{try{this.check(t);let f=V8(u.result);e==="readonly"?c=f:(c=f===null,c===!0&&r!==null&&a.add({version:1,key:ag(r)},Y2))}catch{p()}}})}deviceCustodyKek(e){if(this.check(e.signal),this.loaned||!this.value)throw jt();return this.loaned=!0,ag(this.value)}close(){this.closed||(this.closed=!0,this.value=null,this.db?.close(),this.db=null)}}});function X2(n){if(!(n instanceof Uint8Array)||!n.length||n.length>F8)throw Mn();return new Uint8Array(n)}var lg,J2,F8,Mn,Ac,a0=I(()=>{"use strict";tn();ve();vc();lg="original-device-keys",J2="custody",F8=256,Mn=()=>new Lr("app device key custody store unavailable");Ac=class n{constructor(e,t,r,o,s){this.db=e;this.source=t;this.scope=r;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 Mn()}}static async openChecked(e){let{source:t,signal:r,mode:o,origin:s}=e,i=Object.freeze({accountId:t.accountId,connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId}),a=t.isCurrent,c=t.installationOwned,l=()=>{try{return!r.aborted&&t.isCurrent===a&&t.installationOwned===c&&a.call(t)===!0&&c.call(t)===!0&&Object.keys(i).every(m=>t[m]===i[m])}catch{return!1}},p=[i.accountId,i.connectorId,i.deviceId,i.installationId].map(m=>{let w=N(m);if(w.every(b=>b===0))throw Mn();return Array.from(w,b=>b.toString(16).padStart(2,"0")).join("")});if(!dt(s)||Rt()!==s||!["fresh","existing"].includes(o)||!l()||!globalThis.indexedDB)throw Mn();let d=`mdbase.app-device-keys.v1:${p.join(":")}`,u=`mdbase.app.device-keys.v1.${p.join(".")}`,f=await new Promise((m,w)=>{let b=indexedDB.open(u,1),g=!1,y=()=>{g=!0,w(Mn())};r.addEventListener("abort",y,{once:!0});let _=()=>r.removeEventListener("abort",y);b.onblocked=y,b.onupgradeneeded=()=>{if(g||o!=="fresh"||!l()||b.result.objectStoreNames.length!==0){b.transaction?.abort();return}b.result.createObjectStore(lg)},b.onerror=()=>{_(),w(Mn())},b.onsuccess=()=>{if(_(),g||!l()||b.result.objectStoreNames.length!==1||!b.result.objectStoreNames.contains(lg)){b.result.close(),w(Mn());return}m(b.result)}}),h=new n(f,t,i,d,s);try{h.check(r);let m=await h.read(d,{signal:r});try{if(o==="fresh"!=(m===null))throw Mn();return h.check(r),h}finally{m?.fill(0)}}catch{throw h.close(),Mn()}}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(r=>this.source[r]!==this.scope[r]))throw Mn()}catch{throw Mn()}}async read(e,t){let r=await this.transaction("readonly",e,t.signal,null);try{return this.check(t.signal,e),r}catch{throw r instanceof Uint8Array&&r.fill(0),Mn()}}async create(e,t,r){this.check(r.signal,e);let o=X2(t);try{let s=await this.transaction("readwrite",e,r.signal,o);return this.check(r.signal,e),s===!0}finally{o.fill(0)}}transaction(e,t,r,o){return new Promise((s,i)=>{this.check(r,t);let a=this.db.transaction(lg,e,{durability:"strict"}),c=a.objectStore(lg),l=null,p=!1,d=()=>{p=!0;try{a.abort()}catch{}},u=()=>r.removeEventListener("abort",d);r.addEventListener("abort",d,{once:!0}),a.onabort=a.onerror=()=>{u(),l instanceof Uint8Array&&l.fill(0),i(Mn())},a.oncomplete=()=>{u();try{if(this.check(r,t),p)throw Mn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),i(Mn())}};let f=c.get(J2);f.onsuccess=()=>{let h=null;try{this.check(r,t),h=f.result===void 0?null:X2(f.result),e==="readonly"?(l=h,h=null):(l=h===null,l===!0&&o!==null&&c.add(new Uint8Array(o),J2))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db.close())}}});var bn,kc,l0=I(()=>{"use strict";Ye();ve();bn=()=>new Error("app device key custody unavailable; preserve storage and reopen"),kc=class{constructor(e,t,r){this.pin=e;this.key=t;this.store=r;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(N);if(o.some(s=>s.every(i=>i===0))||t.type!=="secret"||t.extractable||t.algorithm.name!=="AES-GCM"||t.algorithm.length!==256||!t.usages.includes("encrypt")||!t.usages.includes("decrypt"))throw bn();this.namespace=`mdbase.app-device-keys.v1:${o.map(s=>Array.from(s,i=>i.toString(16).padStart(2,"0")).join("")).join(":")}`,this.aad=ue(["mdbase/v1/app-device-keys-platform",...o]),this.check(new AbortController().signal)}catch{throw bn()}}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 bn()}catch{throw bn()}}async openNativeDevice(e,t){let r=null,o=null,s=!1;try{if(this.attempted)throw bn();this.attempted=!0;let i=t.signal,a=t.mode;if(this.check(i),!["fresh","existing"].includes(a)||t.noise.mode!==a||t.noise.mode==="existing"&&!(t.noise.envelope instanceof Uint8Array))throw bn();let c=t.noise.mode==="fresh"?{mode:"fresh"}:{mode:"existing",envelope:new Uint8Array(t.noise.envelope)};if(c.mode==="existing"&&(!c.envelope.length||c.envelope.length>1024))throw bn();let l=await this.store.read(this.namespace,{signal:i});if(this.check(i),a==="fresh"){if(l!==null)throw bn();r=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,r));if(this.check(i),o=ue(new Map([[0,1],[1,u],[2,f]])),await this.store.create(this.namespace,o,{signal:i})!==!0)throw bn();this.check(i)}else{if(!(l instanceof Uint8Array)||l.length===0||l.length>256)throw bn();o=new Uint8Array(l);let u=we(o);if(!(u instanceof Map))throw bn();let f=u;if(f.size!==3||f.get(0)!==1)throw bn();let h=f.get(1),m=f.get(2);if(!(h instanceof Uint8Array)||h.length!==12||!(m instanceof Uint8Array)||m.length!==80||(r=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(i),r.length!==64))throw bn()}this.check(i);let p=Object.freeze({connectorId:this.scope.connectorId,deviceId:this.scope.deviceId,installationId:this.scope.installationId,isCurrent:()=>{try{return this.check(i),!0}catch{return!1}}});s=!0;let d=e.openDeviceConsuming({pin:p,signSecretKey:r.subarray(0,32),kemSecretKey:r.subarray(32),opened:c});return this.check(i),d}catch{if(s)try{e.retireLog()}catch{}throw bn()}finally{r?.fill(0),o?.fill(0)}}}});function c0(n){if(!(n instanceof Uint8Array)||n.byteLength<1||n.byteLength>K8)throw Xn();return new Uint8Array(n)}function W8(n,e){return n===null||e===null?n===e:n.length===e.length&&n.every((t,r)=>t===e[r])}function p0(n){if(N(n).every(t=>t===0))throw Xn();return n.toLowerCase()}function d0(n,e){try{return n.isCurrent()===!0&&n.connectorId===e[0]&&n.deviceId===e[1]&&n.installationId===e[2]}catch{return!1}}var cg,Q2,K8,Xn,Sc,u0=I(()=>{"use strict";tn();ve();vc();cg="opaque-noise",Q2="custody",K8=4096,Xn=()=>new Lr("app noise custody store unavailable");Sc=class n{constructor(e,t,r,o){this.db=e;this.source=t;this.pins=r;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 Xn()}}static async openChecked(e){let{source:t,signal:r}=e,o=[t.connectorId,t.deviceId,t.installationId];if(!dt(e.origin)||Rt()!==e.origin||!["fresh","existing"].includes(e.mode)||r.aborted||!d0(t,o)||typeof globalThis.indexedDB>"u")throw Xn();let s=`mdbase.app.noise.v1.${p0(o[2])}.${p0(o[0])}.${p0(o[1])}`,i=await new Promise((c,l)=>{let p=indexedDB.open(s,1),d=!1,u=()=>{d=!0,l(Xn())};r.addEventListener("abort",u,{once:!0});let f=()=>r.removeEventListener("abort",u);p.onblocked=u,p.onupgradeneeded=()=>{if(d||r.aborted||e.mode!=="fresh"||!d0(t,o)||p.result.objectStoreNames.length!==0){p.transaction?.abort();return}p.result.createObjectStore(cg)},p.onerror=()=>{f(),l(Xn())},p.onsuccess=()=>{if(f(),d||r.aborted||p.result.objectStoreNames.length!==1||!p.result.objectStoreNames.contains(cg)){p.result.close(),l(Xn());return}c(p.result)}}),a=new n(i,t,o,e.origin);try{let c=await a.read(a.namespace,{signal:r});if(e.mode==="fresh"!=(c===null))throw Xn();return c?.fill(0),a.check(r),a}catch{throw a.close(),Xn()}}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||!d0(this.source,this.pins))throw Xn()}async read(e,t){this.check(t.signal,e);let r=await this.transaction("readonly",t.signal,null,null);try{return this.check(t.signal),r}catch{throw r instanceof Uint8Array&&r.fill(0),Xn()}}async compareAndSet(e,t,r,o){this.check(o.signal,e);let s=null,i=null;try{s=t===null?null:c0(t),i=c0(r);let a=await this.transaction("readwrite",o.signal,s,i);return this.check(o.signal),a===!0}finally{s?.fill(0),i?.fill(0)}}transaction(e,t,r,o){return new Promise((s,i)=>{this.check(t);let a=this.db.transaction(cg,e,{durability:"strict"}),c=a.objectStore(cg),l=null,p=!1,d=()=>{p=!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),i(Xn())},a.oncomplete=()=>{u();try{if(this.check(t),p)throw Xn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),i(Xn())}};let f=c.get(Q2);f.onsuccess=()=>{let h=null;try{this.check(t),h=f.result===void 0?null:c0(f.result),e==="readonly"?(l=h,h=null):(l=W8(h,r),l===!0&&o!==null&&c.put(new Uint8Array(o),Q2))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db.close())}}});function dg(n,e,t=H8){let r;return Promise.race([n.catch(()=>e),new Promise(o=>{r=setTimeout(()=>o(e),t)})]).finally(()=>clearTimeout(r))}function pg(n){return dg(new Promise(e=>{let t=indexedDB.deleteDatabase(n);t.onsuccess=()=>e(!0),t.onerror=()=>e(!1)}),!1)}function Z2(n){let{accountId:e,connectorId:t,deviceId:r,installationId:o}=n,s=[e,t,r,o].map(G8).join(".");return[`mdbase.app.device-key-kek.v1.${s}`,`mdbase.app.device-keys.v1.${s}`,`mdbase.app.noise.v1.${si(o)}.${si(t)}.${si(r)}`]}async function eE(n){try{return globalThis.indexedDB?(await Promise.all(Z2(n).map(pg))).every(Boolean):!1}catch{return!1}}function Y8(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 J8(n,e,t){let r=new Set(n.isolated?[]:n.databases);!n.isolated&&n.storageNamespace===void 0&&r.add(t);let{accountId:o,connectorId:s,deviceId:i,installationId:a}=n;if(o&&s&&i&&a){for(let d of Z2({accountId:o,connectorId:s,deviceId:i,installationId:a}))r.add(d);let c=[o,s,i,a].map(si).join("."),l=[`mdbase.app.cloud-copy-outcome.v1.${c}.`,`mdbase.app.private-bootstrap.v1.${c}.`];for(let d of n.collectionIds){let u=si(d);for(let f of["create","join"])r.add(`${l[0]}${u}.${f}`);for(let f of["create","enrol"])r.add(`${l[1]}${u}.${f}`)}let p=indexedDB.databases;if(typeof p=="function"){let d=await dg(p.call(indexedDB),[]);for(let{name:u}of d)u&&l.some(f=>u.startsWith(f))&&r.add(u)}}return r.delete(e),[...r]}async function X8(n,e){let t=globalThis.navigator?.storage;return typeof t?.getDirectory!="function"?!0:dg((async()=>{let r=await t.getDirectory(),o=`.mdbase-app-${si(n)}-${si(e)}-`,s=[];for await(let a of r.keys())a.startsWith(o)&&s.push(a);let i=!0;for(let a of s)try{await r.removeEntry(a,{recursive:!0})}catch{i=!1}return i})(),!1)}async function tE(n,e){try{if(!globalThis.indexedDB||!n.accountId||!n.connectorId||!n.deviceId||!n.installationId)return!1;let t=si(e),r=[n.accountId,n.connectorId,n.deviceId,n.installationId].map(si).join("."),o=["create","join"].map(a=>`mdbase.app.cloud-copy-outcome.v1.${r}.${t}.${a}`);o.push(...["create","enrol"].map(a=>`mdbase.app.private-bootstrap.v1.${r}.${t}.${a}`));let s=await Promise.all(o.map(pg)),i=globalThis.navigator?.storage;if(typeof i?.getDirectory=="function"){let a=await i.getDirectory();try{await a.removeEntry(`.mdbase-app-${si(n.accountId)}-${si(n.installationId)}-${t}`,{recursive:!0})}catch(c){if(!(c instanceof DOMException&&c.name==="NotFoundError"))return!1}}return s.every(Boolean)}catch{return!1}}async function nE(n){if(!globalThis.indexedDB)return Object.freeze({ledger:!1,complete:!1});let[e,t]=Y8(n),r=await pg(e),o=null;try{o=await J8(n,e,t)}catch{}let s=o?await Promise.all([...o,...n.isolated||n.storageNamespace!==void 0?[]:[IA]].map(pg)):[!1],i=n.storageNamespace===void 0?!0:await dg(QR(n),!1),a=n.accountId&&n.installationId?await X8(n.accountId,n.installationId).catch(()=>!1):!0;return Object.freeze({ledger:r,complete:r&&i&&a&&s.every(Boolean)})}var H8,G8,si,f0=I(()=>{"use strict";OA();ve();H8=5e3,G8=n=>Array.from(N(n),e=>e.toString(16).padStart(2,"0")).join(""),si=n=>(N(n),n.toLowerCase())});var ze,hu,Pc,h0=I(()=>{"use strict";Ye();ve();ze=()=>new Error("app Noise custody unavailable; preserve storage and reopen"),hu=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]),Pc=class{constructor(e,t,r){this.pin=e;this.key=t;this.store=r;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(N);if(o.some(s=>s.every(i=>i===0))||t.type!=="secret"||t.extractable||t.algorithm.name!=="AES-GCM"||t.algorithm.length!==256||!t.usages.includes("encrypt")||!t.usages.includes("decrypt"))throw ze();this.namespace=`mdbase.app-noise.v1:${this.scope.connectorId}:${this.scope.deviceId}:${this.scope.installationId}`,this.aad=ue(["mdbase/v1/app-noise-platform",...o]),this.check(new AbortController().signal)}catch{throw ze()}}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 ze()}catch{throw ze()}}receiptValue(e){if(e.connectorId!==this.scope.connectorId||e.deviceId!==this.scope.deviceId||e.installationId!==this.scope.installationId)throw ze();let t=[e.signPublicKey,e.kemPublicKey,e.noisePublicKey];if(t.some(r=>!(r instanceof Uint8Array)||r.length!==32||r.every(o=>o===0)))throw ze();return t.map(r=>new Uint8Array(r))}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(r=>r===0)))throw ze();return Object.freeze({...this.scope,signPublicKey:new Uint8Array(e[0]),kemPublicKey:new Uint8Array(e[1]),noisePublicKey:new Uint8Array(e[2])})}markerValue(e){let t=N(e.collection);if(t.every(r=>r===0)||typeof e.acknowledged!="boolean"||!(e.sasCommitment instanceof Uint8Array)||e.sasCommitment.length!==32||e.sasCommitment.every(r=>r===0))throw ze();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(i=>i===0)||typeof e[5]!="boolean")throw ze();let r=this.receipt(e.slice(1,4));for(let i of["signPublicKey","kemPublicKey","noisePublicKey"])if(!hu(r[i],t[i]))throw ze();let o=e[4];if(!(o instanceof Uint8Array)||o.length!==32||o.every(i=>i===0))throw ze();let s=Array.from(e[0],i=>i.toString(16).padStart(2,"0")).join("");return Object.freeze({...r,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,r=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 ze();t=new Uint8Array(o);let s=we(t);if(!(s instanceof Map))throw ze();let i=s,a=i.get(1),c=i.get(2);if(i.size!==3||i.get(0)!==1||!(a instanceof Uint8Array)||a.length!==12||!(c instanceof Uint8Array)||c.length<16||c.length>2064||(r=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(c))),this.check(e.signal),r.length>2048))throw ze();let l=we(r);if(!(l instanceof Map))throw ze();let p=l,d=p.get(1);if(!(p.get(0)===1&&p.size===3||p.get(0)===2&&p.size===4&&p.has(3))||!(d instanceof Uint8Array)||d.length===0||d.length>1024||!p.has(2))throw ze();let u=this.receipt(p.get(2)),f=p.get(0)===2?this.marker(p.get(3),u):null;return{value:Object.freeze({envelope:new Uint8Array(d),receipt:u,privateEnrolMarker:f}),encrypted:new Uint8Array(t)}}catch{throw ze()}finally{t?.fill(0),r?.fill(0)}}async write(e,t,r,o,s=null){let i=null,a=null;try{if(this.check(o.signal),!(e instanceof Uint8Array)||!e.length||e.length>1024)throw ze();let c=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),c.set(3,u)}if(i=ue(c),i.length>2048)throw ze();let l=globalThis.crypto.getRandomValues(new Uint8Array(12)),p=new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:l,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(i)));this.check(o.signal),a=ue(new Map([[0,1],[1,l],[2,p]]));let d=await this.store.compareAndSet(this.namespace,r,a,o);if(this.check(o.signal),d!==!0)throw ze()}catch{throw ze()}finally{i?.fill(0),a?.fill(0)}}async pending(e,t){let r=await this.read(t);if(this.check(t.signal),r){if(!hu(r.value.envelope,e))throw ze();return}await this.write(e,null,null,t),this.check(t.signal)}async privateEnrolPending(e,t){try{if(e.acknowledged!==!1)throw ze();await this.writePrivateMarker(e,!1,t)}catch{throw ze()}}async privateEnrolAcknowledged(e,t){try{await this.writePrivateMarker(e,!0,t)}catch{throw ze()}}async writePrivateMarker(e,t,r){this.check(r.signal);let o=this.marker(this.markerValue(e),e),s=await this.read(r);if(this.check(r.signal),!s?.value.receipt)throw ze();for(let a of["signPublicKey","kemPublicKey","noisePublicKey"])if(!hu(o[a],s.value.receipt[a]))throw ze();let i=s.value.privateEnrolMarker;if(i){if(i.collection!==o.collection||!hu(i.sasCommitment,o.sasCommitment))throw ze();if(i.acknowledged){if(!t)throw ze();return}if(!t)return}else if(t)throw ze();await this.write(s.value.envelope,s.value.receipt,s.encrypted,r,Object.freeze({...o,acknowledged:t})),this.check(r.signal)}async registered(e,t){let r=await this.read(t);if(this.check(t.signal),!r)throw ze();if(r.value.receipt){for(let o of["signPublicKey","kemPublicKey","noisePublicKey"])if(!hu(r.value.receipt[o],e[o]))throw ze();this.receiptValue(e);return}await this.write(r.value.envelope,e,r.encrypted,t),this.check(t.signal)}}});var va,Ut,ug,xc,m0=I(()=>{"use strict";At();ve();va=class extends Error{constructor(t){super(`app device registration: ${t}`);this.reason=t;this.name="AppDeviceRegistrationError"}reason},Ut=n=>new va(n),ug=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),xc=class{constructor(e,t,r,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(N(a).every(c=>c===0))throw Ut("binding");if(t.kind!=="mobile"&&t.kind!=="app-runtime")throw Ut("binding");this.rawOrigin=t.cpOrigin;let i=new URL(this.rawOrigin);if(i.username||i.password||i.pathname!=="/"||i.search||i.hash||i.protocol!=="https:"&&!(s.allowLoopbackHttp===!0&&Ze(this.rawOrigin))||(this.origin=i.origin,this.now=s.now??Date.now,this.fetchImpl=s.fetch??globalThis.fetch,!(r.envelope instanceof Uint8Array)||!r.envelope.length||r.envelope.length>1024)||!e.deviceCustodyCurrent(t,r)||(this.custody=Object.freeze({signPublicKey:new Uint8Array(r.signPublicKey),kemPublicKey:new Uint8Array(r.kemPublicKey),noisePublicKey:new Uint8Array(r.noisePublicKey),envelope:new Uint8Array(r.envelope)}),!this.current()))throw Ut("binding")}catch{throw e.retireLog(),Ut("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(),Ut("fenced")}async json(e,t,r,o){this.check(o);let s=new AbortController,i=()=>s.abort(),a=setTimeout(i,15e3);a.unref?.(),o.addEventListener("abort",i,{once:!0}),this.lifetime.signal.addEventListener("abort",i,{once:!0});let c=new Uint8Array(32*1024),l=0,p=null,d=null;try{let u=this.fetchImpl;if(p=await u(`${this.origin}${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,...r===void 0?{}:{"content-type":"application/json"}},body:r,signal:s.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(o),s.signal.aborted||!p.ok)throw Ut("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(),Ut("response");if(!p.body)throw Ut("response");for(d=p.body.getReader();;){let{done:m,value:w}=await d.read();try{if(this.check(o),s.signal.aborted)throw Ut("unavailable");if(m)break;if(l+w.length>c.length)throw s.abort(),Ut("response");c.set(w,l),l+=w.length}finally{w?.fill(0)}}let h=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c.subarray(0,l)));if(!h||typeof h!="object"||Array.isArray(h))throw Ut("response");return h}catch(u){throw this.check(o),u instanceof va?u:Ut("unavailable")}finally{c.fill(0),(d?.cancel()??p?.body?.cancel())?.catch(()=>{}),d?.releaseLock(),clearTimeout(a),o.removeEventListener("abort",i),this.lifetime.signal.removeEventListener("abort",i)}}async register(e){let t=null,r=null;try{if(this.check(e.signal),this.attempted)throw Ut("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 Ut("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 Ut("response");t=Uint8Array.from(s.challenge.match(/../g).map(l=>parseInt(l,16)));let i=this.runtime.signCpEnrol(t);this.check(e.signal),r=i.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_v2"],challenge:s.challenge,sign_pk:ug(i.signPublicKey),kem_pk:ug(i.kemPublicKey),noise_pk:ug(i.noisePublicKey),sig:ug(r)}),e.signal);if(this.check(e.signal),a.device_id!==this.scope.deviceId)throw Ut("response");let c=Object.freeze({connectorId:this.scope.connectorId,deviceId:this.scope.deviceId,installationId:this.scope.installationId,signPublicKey:new Uint8Array(i.signPublicKey),kemPublicKey:new Uint8Array(i.kemPublicKey),noisePublicKey:new Uint8Array(i.noisePublicKey)});return await this.persistence.registered(c,e),this.check(e.signal),this.runtime.acknowledgeDeviceRegistration(c),c}catch(o){throw this.close(),o instanceof va?o:Ut("unavailable")}finally{t?.fill(0),r?.fill(0)}}close(){this.lifetime.signal.aborted||(this.lifetime.abort(),this.custody.envelope.fill(0),this.runtime.retireLog())}}});var fr,Q8,Z8,be,rE,Cc,mu=I(()=>{"use strict";OA();jy();tn();ve();Vs();Es();ie();$m();Cd();e2();RA();TA();nr();xd();c2();Fm();Id();jA();p2();VA();KA();u2();fu();s0();a0();l0();u0();vc();f0();h0();m0();Hm();fr=class extends Error{constructor(t,r,o){super(`app cloud copy host: ${t}`,o);this.reason=t;this.stage=r;this.name="AppCloudCopyHostError"}reason;stage},Q8=32,Z8=8,be=(n,e)=>new fr(n,e),rE=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]),Cc=class n{constructor(e,t,r,o,s){this.source=e;this.installation=t;this.originalRelease=r;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 i of[e.accountId,e.connectorId,e.deviceId,e.installationId])if(N(i).every(a=>a===0))throw be("binding");if(e.kind!=="app-runtime"&&e.kind!=="mobile"||r.schema!=="mdbn-app-trust/release/1"||r.cpOrigin!==e.cpOrigin||r.logOrigin!==e.logOrigin||!/^[0-9a-f]{64}$/.test(r.assetSha256)||!r.trustedRoots.length||r.trustedRoots.length>64||!r.policyPins.length||r.policyPins.length>65536)throw be("binding");if(this.trust=Object.freeze({...r,source:Object.freeze({...r.source}),trustedRoots:Object.freeze(r.trustedRoots.map(i=>{if(!(i instanceof Uint8Array)||i.length!==32||i.every(a=>a===0))throw be("binding");return new Uint8Array(i)})),policyPins:new Uint8Array(r.policyPins)}),this.pin=Object.freeze({...this.selected,isCurrent:()=>this.current(),installationOwned:()=>this.current(),connectorBearer:async({signal:i})=>{this.check(i);let a=await this.bearerCallback.call(this.source,Object.freeze({signal:i}));return this.check(i),a}}),e.approvalMode==="strict")throw new Mt;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;restoredPrivateMarker=null;privateStore=null;privateBootstrap=null;privateMetadata=null;accountKeyPin=null;accountKeyWork=!1;accountKeySealed=new bc;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;readWake=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(([r,o])=>this.source[r]===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((r,o)=>rE(r,t.trustedRoots[o]))&&rE(e.policyPins,t.policyPins)}catch{return!1}}check(e){if(e.aborted||!this.current())throw be("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:r,release:o,origin:s,mode:i,signal:a,loadRuntime:c,fetch:l,allowLoopbackHttp:p}=e,d=null;try{if(!["fresh","existing"].includes(i))throw be("binding");d=new n(t,r,o,s,a);let{custody:u,restored:f}=await d.openOwnedDevice({mode:i,signal:a,loadRuntime:c,requireReceipt:!0});if(i==="existing")d.native.acknowledgeDeviceRegistration(f.receipt),d.check(a),d.publicReceipt=d.native.registeredDeviceReceipt();else{let h=await new xc(d.native,d.pin,u,d.noise,{fetch:l,allowLoopbackHttp:p}).register(Object.freeze({signal:a}));d.check(a),d.publicReceipt=h}return d}catch(u){throw await d?.close(),u instanceof fr||u instanceof Mt?u:new fr("unavailable","device_open",{cause:u})}}static async openInstallationDevice(e){let{signIn:t,installation:r,release:o,origin:s,signal:i,loadRuntime:a,allowLoopbackHttp:c}=e,l=null;try{let p=t.confirmedHostSession(o.logOrigin,o.environment);l=new n(p,r,o,s,i),l.signIn=t;let d=await t.prepareOriginalDevice(r);if(l.check(i),d.mode==="fresh"&&!await eE(d.pin))throw new Lr("an unfinished device creation could not be cleared");l.check(i);let{custody:u,restored:f}=await l.openOwnedDevice({mode:d.mode,signal:i,loadRuntime:a,requireReceipt:!1});if(l.originalCustody=u,f?.receipt&&t.view().state!=="paired")throw be("recovery_required");return await l.noise.pending(new Uint8Array(u.envelope),{signal:i}),l.check(i),t.view().state==="paired"&&await l.completeInstallationSignIn(),l}catch(p){throw await l?.close(),p}}async attestInstallation(){if(this.check(this.lifetime),!this.signIn||!this.native||!this.originalCustody||!this.noise)throw be("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 be("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:r,loadRuntime:o,requireReceipt:s}=e;this.check(r),this.provider=await _c.open({source:this.pin,origin:this.origin,mode:t,signal:r}),this.check(r),this.key=this.provider.deviceCustodyKek({signal:r}),this.check(r),this.keys=await Ac.open({source:this.pin,origin:this.origin,mode:t,signal:r}),this.check(r),this.noiseStore=await Sc.open({source:this.pin,origin:this.origin,mode:t,signal:r}),this.check(r),this.noise=new Pc(this.pin,this.key,this.noiseStore);let i=await this.noise.restore({signal:r});if(this.check(r),t==="existing"?!i||s&&!i.receipt:i!==null)throw be("recovery_required");this.restoredPrivateMarker=i?.privateEnrolMarker??null;let a=await o(Object.freeze({signal:r}));if(this.check(r),!(a instanceof Uint8Array)||!a.length)throw be("binding");this.native=await Ql.createDevice(new Uint8Array(a)),this.check(r);let c=await new kc(this.pin,this.key,this.keys).openNativeDevice(this.native,{signal:r,mode:t,noise:t==="fresh"?{mode:"fresh"}:{mode:"existing",envelope:i.envelope}});return this.check(r),{custody:c,restored:i}}async bootstrapCloudCopy(e){let{scope:t,collectionCurrent:r,purpose:o,outcomeMode:s,signal:i,reconcile:a,fetch:c,allowLoopbackHttp:l}=e,p=this.operationSignal(i),d=e.displayName,u=d===void 0?void 0:sr(d);if(u!==void 0&&o!=="create"||(this.check(p),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)||N(t.collection).every(w=>w===0)))throw be("binding");let f=Object.freeze({account:t.account,installation:t.installation,collection:t.collection}),h=()=>{try{return this.current()&&!p.aborted&&e.scope===t&&e.collectionCurrent===r&&Object.entries(f).every(([w,b])=>t[w]===b)&&r.call(e)===!0&&this.outcomeStore?.fenced!==!0}catch{return!1}};if(!h())throw be("fenced");this.collectionAttempted=!0,this.collectionSignal=p,this.collectionCurrent=h,this.collectionScope=f;let m=Object.freeze({...this.pin,collection:f.collection,purpose:o,assetSha256:this.trust.assetSha256,...u===void 0?{}:{displayName:u},isCurrent:h});this.collectionSession=m;try{this.outcomeStore=await Vy.open({source:m,origin:this.origin,mode:s,signal:p}),this.checkCollection(p),this.outcome=new $y(m,this.publicReceipt,this.key,this.outcomeStore,{mode:s,signal:p}),this.native.prepareCloudCopyCollection(m),this.checkCollection(p),this.bootstrap=new Vl(this.native,m,this.trust,this.outcome,{fetch:c,allowLoopbackHttp:l,...u===void 0?{}:{displayName:u}});let w=await this.bootstrap.bootstrap(Object.freeze({signal:p,...a?{reconcile:a}:{}}));return this.checkCollection(p),this.bootstrapConfirmed=!0,w}catch(w){throw await this.close(),w}}async bootstrapPrivateDevice(e){let{scope:t,collectionCurrent:r,signal:o,fetch:s,allowLoopbackHttp:i}=e,a=this.operationSignal(o);if(this.check(a),this.collectionAttempted||!this.native||!this.key||!this.noise||!this.publicReceipt||t.account!==this.selected.accountId||t.installation!==this.selected.installationId||N(t.collection).every(u=>u===0))throw be("binding");let c=this.restoredPrivateMarker;if(c&&c.collection!==t.collection)throw be("private_device_limit");let l=Object.freeze({account:t.account,installation:t.installation,collection:t.collection}),p=()=>{try{return this.current()&&!a.aborted&&e.scope===t&&e.collectionCurrent===r&&Object.entries(l).every(([u,f])=>t[u]===f)&&r.call(e)===!0}catch{return!1}};if(!p())throw be("fenced");this.collectionAttempted=!0,this.collectionSignal=a,this.collectionCurrent=p,this.collectionScope=l;let d=Object.freeze({...this.pin,collection:l.collection,purpose:"enrol",rootPublicKey:new Uint8Array(this.trust.trustedRoots[0]),isCurrent:p});this.collectionSession=d;try{this.privateStore=await Gy.open({source:d,origin:this.origin,mode:c?"existing":"fresh",signal:a}),this.checkCollection(a);let u=new Wy(d,this.publicReceipt,this.key,this.privateStore,this.noise,{allowLoopbackHttp:i});this.native.preparePrivateCollection(d,c?{mode:"existing",marker:c}:{mode:"fresh"}),this.checkCollection(a),this.privateBootstrap=new Fy(this.native,d,u,{fetch:s,allowLoopbackHttp:i}),this.privateMetadata=await this.privateBootstrap.bootstrap(Object.freeze({signal:a})),this.checkCollection(a),this.bootstrapConfirmed=!0}catch(u){throw await this.close(),u}}adoptPrivateDevice(e,t){let r=this.operationSignal(e.signal);this.checkCollection(r);let o=this.privateMetadata,s=this.publicReceipt;if(!this.native||!this.privateBootstrap||!o||!s||!this.bootstrapConfirmed||this.adoptedEndpoint!==null)throw be("fenced");let i=o.collection;this.native.adoptDevice({replicaId:e.replicaId,endpoint:e.endpoint,opened:e.opened,sqliteVersion:e.sqliteVersion,collection:i,deviceId:o.deviceId,state:"e2e",cloudCopyOptIn:!1,trustedRoots:this.trust.trustedRoots.map(a=>new Uint8Array(a)),policyPins:new Uint8Array(this.trust.policyPins),trustedSigners:[],expectedGenesis:o.expectedGenesis},t),this.checkCollection(r),this.adoptedEndpoint=e.endpoint,this.accountKeyPin=Object.freeze({connectorId:s.connectorId,deviceId:s.deviceId,installationId:s.installationId,collection:i,approvalMode:"password-ak1",isCurrent:()=>this.collectionCurrent?.()===!0})}checkCollection(e){if(this.check(e),this.collectionCurrent?.()!==!0)throw be("fenced")}adoptCloudCopy(e,t){let r=this.operationSignal(e.signal);if(this.checkCollection(r),!this.bootstrap||!this.bootstrapConfirmed||this.adoptedEndpoint!==null)throw be("fenced");let o=e.endpoint;this.bootstrap.adoptCollection({...e,signal:this.collectionSignal},t),this.checkCollection(r),this.adoptedEndpoint=o}async openCollectionSql(e){let{replicaId:t,endpoint:r,openSql:o}=e,s=this.operationSignal(e.signal);if(this.checkCollection(s),!this.bootstrapConfirmed||!this.collectionScope||this.sqlAttempted||this.adoptedEndpoint!==null||N(t).every(i=>i===0)||typeof r!="bigint"&&!Number.isSafeInteger(r)||BigInt(r)<0n||BigInt(r)>(1n<<64n)-1n)throw be("binding");this.sqlAttempted=!0;try{let i=await o.call(e,Object.freeze({scope:this.collectionScope,signal:s})),a=i.close;if(this.sqlClose=async()=>{await a.call(i)},this.collectionSql=i.sql,this.checkCollection(s),e.openSql!==o)throw be("fenced");this.privateBootstrap?this.adoptPrivateDevice({signal:s,replicaId:t,endpoint:r,opened:i.opened,sqliteVersion:i.sqliteVersion},i.sql):this.adoptCloudCopy({signal:s,replicaId:t,endpoint:r,opened:i.opened,sqliteVersion:i.sqliteVersion,cloudCopyOptIn:!0},i.sql)}catch(i){throw await this.close(),i}}async startCollectionLog(e){let{fetch:t,allowLoopbackHttp:r}=e,o=this.operationSignal(e.signal);if(this.checkCollection(o),!this.native||!this.collectionSession||this.adoptedEndpoint===null)throw be("binding");let s=t??globalThis.fetch,i=r===!0;if(this.authority&&(s!==this.logRequest||i!==this.logLoopback))throw be("fenced");if(this.pump)return;if(this.logWork){await this.logWork,this.checkCollection(o);return}this.authority||(this.logRequest=s,this.logLoopback=i,this.authority=new Bl(this.native,Object.freeze({...this.collectionSession,endpoint:this.adoptedEndpoint,directOrigins:Object.freeze([])}),{fetch:s,allowLoopbackHttp:r,tokenCache:XR()}));let a=this.authority,c=(async()=>{await a.accessToken(Object.freeze({signal:o})),this.checkCollection(o),this.pump=this.native.bindLogTransport(a.logTransport())})();this.logWork=c;try{await c}finally{this.logWork===c&&(this.logWork=null)}}peopleAuthority(){if(this.checkCollection(this.lifetime),!this.collectionSession||this.adoptedEndpoint===null||!this.logRequest||this.accountKeyPin)throw be("binding");if(!this.peopleMetadata){let e=this.adoptedEndpoint,t=this.collectionSession,r=new fc(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 i=await t.connectorBearer({signal:this.lifetime});return this.checkCollection(this.lifetime),s.throwIfAborted(),i}}),{fetch:this.logRequest,allowLoopbackHttp:this.logLoopback}),o=Object.freeze({collection:r.collection,isCurrent:()=>r.isCurrent(),request:(s,i)=>r.request(s,i)});this.peopleMetadata={authority:r,view:o}}return this.peopleMetadata.view}timerConsentKey(e){let t=this.timerGrant(e);return t?JSON.stringify(t.consent):null}timerGrant(e){let t=this.source.timerConsent,r=t?.call(this.source);if(!r?.approved)return null;let o=r.grants.find(s=>s.collectionId===e);return o?{callback:t,consent:r,grant:o}:null}openTimersPort(e){if(this.checkCollection(this.lifetime),!this.readVerified||!this.logRequest||!this.collectionScope||e.signal.aborted)throw be("binding");let{scope:t,generation:r,signal:o}=e,s=this.collectionScope;if(t.account!==s.account||t.installation!==s.installation||t.collection!==s.collection||N(r).every(m=>m===0))throw be("binding");let i=this.timerGrant(t.collection);if(!i)return null;let{callback:a,consent:c,grant:l}=i,p=globalThis.WorkerGlobalScope;if(typeof p!="function"||!(globalThis instanceof p)||N(l.grantId).every(m=>m===0)||!/^[0-9a-f]{64}$/.test(l.declarationDigest))throw be("binding");let d=JSON.stringify(c),u=new MessageChannel,f=()=>{try{return!o.aborted&&e.signal===o&&e.scope===t&&e.generation===r&&this.collectionCurrent?.()===!0&&this.current()&&t.account===s.account&&t.installation===s.installation&&t.collection===s.collection&&this.source.timerConsent===a&&JSON.stringify(a?.call(this.source))===d}catch{return!1}},h=o2(u.port1,{scope:s,generation:r,grantId:l.grantId,cpOrigin:new URL(this.selected.cpOrigin).origin,signal:o,isCurrent:f,fetch:this.logRequest,...this.signIn?{journal:{read:()=>this.signIn.originalTimerChannel(l.grantId),write:m=>this.signIn.retainTimerChannel(l.grantId,m)}}:{},bearer:async()=>{if(!f())throw be("fenced");let m=await this.bearerCallback.call(this.source,{signal:this.lifetime});if(!f())throw be("fenced");return m}});return this.timerPorts.add(h),Object.freeze({port:u.port2,close:async()=>{await h.close(),u.port2.close(),this.timerPorts.delete(h)}})}serverProblem(){return this.pump?.serverProblem??null}transportHealth(){return this.pump?.transportHealth??null}initialSync(){try{return this.native?hc(this.native.observations().status):"unavailable"}catch{return"unavailable"}}holdsLog(){try{if(!this.native)return!1;let e=this.native.observations().status;return e.mode==="local_only"||e.headKnown>0}catch{return!1}}keyWaitDetail(){try{return this.native?Dy(this.native.observations().status):null}catch{return null}}keyringSettled(){if(!this.native)throw be("binding");let e=this.native.observations();return e.requiresReopen||e.keyringRebuildFailed?"failed":e.keyringRebuilding?"pending":"settled"}pendingWrites(){try{return this.native?.observations().status.pending??0}catch{return 0}}pushLog(e){try{let t=this.native?.pushLog(e)===!0;return t&&this.readWake?.(),t}catch{return!1}}openLogPush(e){this.checkCollection(this.lifetime);let t=this.native,r=this.authority,o=this.collectionSession,s=this.logRequest;if(!t||!this.pump||!r||!o||!s)throw be("binding");if(!t.supportsLogPush||typeof WebSocket!="function")return null;let i=this.logLoopback,a=r.origin,c=()=>{try{return this.collectionCurrent?.()===!0&&this.current()&&this.authority===r&&r.isCurrent()}catch{return!1}};return new Uy({origin:a,collection:r.collection,deviceId:o.deviceId,isCurrent:c,accessToken:l=>r.accessToken(l),invalidateToken:l=>r.invalidateToken(l),nonce:async({signal:l})=>{let p=await s(`${a}/v1/nonce`,{signal:l,cache:"no-store",credentials:"omit",redirect:"error",referrerPolicy:"no-referrer"}),d=(await p.text()).trim();if(!p.ok||!/^[0-9a-f]{64}$/.test(d))throw be("unavailable","push_nonce");return Uint8Array.from(d.match(/../g).map(u=>parseInt(u,16)))},signHello:(l,p)=>c()?t.signLogHello(l,p):null},e,{allowLoopbackHttp:i})}async driveCollection(e){let t=this.operationSignal(e.signal);if(this.checkCollection(t),!this.native||!this.pump||this.adoptedEndpoint===null)throw be("binding");for(let r=0;r<Z8;r++){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 be("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:r=!1,local:o=!1}=e,s=this.operationSignal(e.signal);if(this.checkCollection(s),!this.native||!this.collectionScope||this.adoptedEndpoint===null||!Number.isSafeInteger(t)||t<1||t>15e3||typeof r!="boolean"||typeof o!="boolean"||r&&(o||!this.pump))throw be("binding");if(o&&!this.holdsLog())return Promise.reject(be("unavailable","local_read_without_log"));if(this.readWork)return this.readWork.then(()=>{this.checkCollection(s)});let i=this.verifyRead(s,t,r,o,e.onProgress);return this.readWork=i,i.finally(()=>{this.readWork===i&&(this.readWork=null)}).catch(()=>{}),i}async verifyRead(e,t,r,o,s){let i=new AbortController,a=()=>i.abort(),c=()=>o?null:this.pump;this.readAbort=i;let l=!1,p=null;c()&&(this.readWake=()=>{l=!0,p?.()});let d=v=>l?(l=!1,Promise.resolve()):c()?new Promise((k,S)=>{if(i.signal.aborted){S(i.signal.reason);return}let x=()=>{clearTimeout(R),i.signal.removeEventListener("abort",C),p===P&&(p=null)},P=()=>{x(),l=!1,k()},C=()=>{x(),S(i.signal.reason)},R=setTimeout(()=>{x(),k()},v);p=P,i.signal.addEventListener("abort",C,{once:!0})}):fa(v,i.signal);e.addEventListener("abort",a,{once:!0});let u=null,f="read_connect",h=null,m=()=>h??=be(r?"sync_stalled":"unavailable",f),w,b=new Promise((v,k)=>{w=()=>k(m()),i.signal.addEventListener("abort",w,{once:!0})});b.catch(()=>{});let g=null,y=v=>{if(v!==g){g=v;try{s?.(v)}catch{}}},_=()=>{this.checkCollection(e);let v=r?c().terminalProblem:null;if(pn(v))throw new On(It(v)??"unavailable",v);let k=this.native.observations();if(k.requiresReopen||k.keyringRebuildFailed)throw be("recovery_required");let S=hc(k.status);return y(S==="installing"?"loading_snapshot":S==="waiting_for_key"?"waiting_for_key":S==="behind"?"replaying":S===null?"verifying_read":"syncing"),k};this.readVerified=!1;try{if(c()){let k=!1,S=()=>{let E=_();return k=r&&l2(E.status),[E.status.confirmedThrough,E.status.installing?.done??0,E.status.installing?.total??0,c().readProgress]},x=S(),P=Date.now(),C=new Map,R=null,O=()=>{try{let E=Date.now(),j=S();j.some((V,U)=>V>x[U])&&(P=E,R=null),x=j.map((V,U)=>Math.max(V,x[U]));let B=c().responseProgress(),D=new Set(B.map(V=>V.id));for(let V of C.keys())D.has(V)||C.delete(V);for(let V of B){let U=C.get(V.id);V.bytes>(U?.bytes??0)&&C.set(V.id,{bytes:V.bytes,at:E})}let J=(k?Math.max(t,a2):t)-(E-P);J<=0&&(R??=new Set(C.keys()),J=Math.max(0,...[...R].map(V=>{let U=C.get(V);return U?t-(E-U.at):0}))),J<=0?a():u=setTimeout(O,Math.min(250,J))}catch(E){h=E,a()}};u=setTimeout(O,Math.min(250,t))}else u=setTimeout(a,t);this.readClient=await Promise.race([yi.connect({app:{name:"app-local-read-gate",version:"1"},connector:Jl(this.native,{collection:this.collectionScope.collection}),reconnect:!1,signal:i.signal}).then(k=>{if(i.signal.aborted)throw k.close(),m();return k}),b]),this.checkCollection(e);let v=250;for(;!i.signal.aborted;){f="read_catch_up",l=!1,this.native.tick();let k=c();k&&await Promise.race([k.pump(),b]),this.checkCollection(e);let S=_();if(r&&hc(S.status)!==null){await d(v),v=Math.min(1e3,v*2);continue}f="read_query";try{if(await Promise.race([this.readClient.query({limit:1},{signal:i.signal}),b]),this.checkCollection(e),i.signal.aborted)throw m();this.readVerified=!0;return}catch(x){if(this.checkCollection(e),!(x instanceof oe)||x.code!=="unavailable"||!c()||i.signal.aborted)throw x}await d(v),v=Math.min(1e3,v*2)}throw m()}catch(v){throw this.checkCollection(e),i.signal.aborted?m():v}finally{u!==null&&clearTimeout(u),e.removeEventListener("abort",a),i.signal.removeEventListener("abort",w),this.readWake=null,p=null,this.readClient?.close(),this.readClient=null,this.readAbort=null}}get privateDevice(){return this.accountKeyPin!==null}accountKeyState(){if(!this.native||!this.accountKeyPin||this.adoptedEndpoint===null)throw be("binding");return this.native.accountKeyStatus(this.accountKeyPin)}async settlePrivateKey(e){let{timeoutMs:t=15e3}=e,r=this.operationSignal(e.signal);if(this.checkCollection(r),!this.native||!this.pump||!this.accountKeyPin||this.adoptedEndpoint===null||!Number.isSafeInteger(t)||t<1||t>15e3)throw be("binding");let o=null,s=Date.now(),i=100,a=!1,c=async()=>a?!0:(a=!0,await this.wakeCollectionLog({signal:r}),!1);for(;;){let l=this.accountKeyState();if(l.state==="keyed")return"keyed";if(l.state==="refused"&&l.reason==="outcome_unknown")throw be("recovery_required");await this.driveCollection({signal:r});let p=this.pump?.terminalProblem;if(pn(p))throw new On(It(p)??"unavailable",p);if(this.accountKeyState().state==="keyed")return"keyed";let d=this.native.observations();if(d.requiresReopen||d.keyringRebuildFailed)throw be("recovery_required");let u=hc(d.status);if(u==="offline"||this.pump?.transportHealth?.kind==="offline")throw be("unavailable","key_wait_offline");let f=u==="waiting_for_key"?Dy(d.status)?.key:void 0;if(u===null||f!==void 0&&f!=="reading"){if(await c())return"locked";continue}let h=Date.now(),m=[d.status.confirmedThrough,d.status.headKnown,this.pump.readProgress];if((o===null||m.some((w,b)=>w>o[b]))&&(s=h),o=o===null?m:m.map((w,b)=>Math.max(w,o[b])),h-s>=t)throw be("sync_stalled");await fa(i,r),this.checkCollection(r),i=Math.min(1e3,i*2)}}accountKeySession(e){let t=this.collectionSession;if(!t)throw be("binding");return Object.freeze({accountId:this.selected.accountId,connectorId:e.connectorId,deviceId:e.deviceId,collection:e.collection,cpOrigin:this.selected.cpOrigin,isCurrent:()=>this.collectionCurrent?.()===!0&&this.accountKeyPin===e,connectorBearer:async({signal:r})=>{r.throwIfAborted(),this.checkCollection(this.lifetime);let o=await t.connectorBearer({signal:this.lifetime});return this.checkCollection(this.lifetime),r.throwIfAborted(),o}})}async accountKeyMode(e){let t=this.operationSignal(e.signal);this.checkCollection(t);let r=this.accountKeyPin;if(!r||!this.logRequest)throw be("binding");return ig(this.accountKeySession(r),{signal:t,fetch:this.logRequest,allowLoopbackHttp:this.logLoopback})}async unlockAccountKey(e,t){let r=this.operationSignal(t.signal);this.checkCollection(r);let o=this.native,s=this.accountKeyPin,i=this.logRequest;if(!o||!s||!i||!this.pump||this.adoptedEndpoint===null||this.accountKeyWork)throw be("binding");let a=Object.freeze({supportsFetchProof:()=>o.supportsAccountKeyFetchProof,signFetch:c=>o.signAccountKeyFetch(s,this.selected.accountId,c),unlockConsuming:c=>o.unlockAccountKeyConsuming(s,c),status:()=>o.accountKeyStatus(s),drive:c=>this.driveCollection({signal:c.signal}),headKnown:()=>o.observations().status.headKnown});this.accountKeyWork=!0;try{await og(this.accountKeySession(s),a,e,{signal:r,fetch:i,allowLoopbackHttp:this.logLoopback,sealed:this.accountKeySealed,...t.onMode?{onMode:t.onMode}:{}}),this.checkCollection(r)}finally{this.accountKeyWork=!1}}onLogWork(e){this.logWorkListener=e}attachDataFacade(e){if(this.checkCollection(this.lifetime),!this.native||!this.collectionScope||!this.readVerified||this.facades.size>=Q8||this.facades.has(e))throw be("fenced");let t=Object.freeze({...this.collectionScope,isCurrent:()=>{try{return this.checkCollection(this.lifetime),!0}catch{return!1}}}),r=Bm(this.native,e,t,()=>this.logWorkListener?.());return this.facades.set(e,r),r.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 be("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 r of this.facades.values())r.close();this.facades.clear()},()=>this.peopleMetadata?.authority.close(),()=>this.bootstrap?.close(),()=>this.outcome?.close(),()=>this.accountKeySealed.clear()])try{t()}catch{e=!0}return this.closeResult??=(async()=>{try{await Promise.all([...this.timerPorts].map(async r=>{try{await r.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 be("unavailable","close_fence")}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.privateStore?.close(),this.noiseStore?.close(),this.keys?.close(),this.provider?.close()}})()}}});var Ic,eD,tD,fs,Ln,Oc,fg=I(()=>{"use strict";Ic="original-join",eD=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,tD="00000000-0000-0000-0000-000000000000",fs=class extends Error{constructor(t){super(`app collection join: ${t}`);this.reason=t;this.name="AppCollectionJoinError"}reason},Ln=(n="recovery_required")=>new fs(n),Oc=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(r=>typeof r!="string"||!eD.test(r)||r===tD)||typeof e.databaseName!="string"||!e.databaseName.length||e.databaseName.length>256||/[\u0000-\u001f\u007f]/.test(e.databaseName)||typeof e.isCurrent!="function")throw Ln("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 Ln("fenced")}marker(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).sort().join()!=="account,collection,installation,phase,version")throw Ln();let t=e;if(t.version!==1||t.phase!=="attempted"&&t.phase!=="completed"||Object.entries(this.options.scope).some(([r,o])=>t[r]!==o))throw Ln();return t}open(e){if(this.check(e),!globalThis.indexedDB)throw Ln();return new Promise((t,r)=>{let o=indexedDB.open(this.options.databaseName,1),s=!1,i=()=>e.removeEventListener("abort",a),a=()=>{s=!0,i();try{o.transaction?.abort()}catch{}r(Ln())};e.addEventListener("abort",a,{once:!0}),o.onblocked=o.onerror=a,o.onupgradeneeded=()=>{try{if(this.check(e),s||o.result.objectStoreNames.length)throw Ln();o.result.createObjectStore(Ic)}catch{try{o.transaction?.abort()}catch{}}},o.onsuccess=()=>{i();try{if(this.check(e),s||o.result.objectStoreNames.length!==1||!o.result.objectStoreNames.contains(Ic))throw Ln();t(o.result)}catch{o.result.close(),r(Ln())}}})}async change(e,t){if(this.check(t),this.busy)throw Ln("busy");this.busy=!0;let r=null;try{return r=await this.open(t),this.check(t),await new Promise((o,s)=>{this.check(t);let i=r.transaction(Ic,"readwrite",{durability:"strict"}),a=null,c,l=()=>{try{i.abort()}catch{}},p=()=>t.removeEventListener("abort",l);t.addEventListener("abort",l,{once:!0}),i.onabort=i.onerror=()=>{p(),s(c??Ln())},i.oncomplete=()=>{p();try{if(this.check(t),!a)throw Ln();o(Object.freeze(a))}catch{s(Ln())}};let d=i.objectStore(Ic),u=d.get(this.key);u.onsuccess=()=>{try{this.check(t);let f=u.result;if(f===void 0){if(e!=="prepare")throw Ln();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){c=f,l()}}})}catch(o){throw o instanceof fs?o:Ln()}finally{r?.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 r=null;try{r=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 i=r.transaction(Ic,e==="mark"?"readwrite":"readonly"),a=!1;i.onabort=i.onerror=()=>s(!1),i.oncomplete=()=>s(e==="mark"||a);let c=i.objectStore(Ic);if(e==="mark")c.put({version:1,synced:!0},o);else{let l=c.get(o);l.onsuccess=()=>{let p=l.result;a=!!p&&p.version===1&&p.synced===!0}}})}catch{return!1}finally{r?.close()}}async complete(e){await this.change("complete",e.signal)}}});function oE(n){let e=Object.freeze({...n,setupJournal:Object.freeze({...n.setupJournal})}),t=RI(e.sql);if(typeof e.handoff!="function")throw ai("binding");let r=new Set;return async o=>{let s=JSON.stringify([o.scope.account,o.scope.installation,o.scope.collection]);if(r.has(s))throw ai("fenced");r.add(s);let{host:i,installation:a,signal:c,collection:l,setupPolicy:p}=o,d=a.isCurrent,u=l.displayName,f=l.mode==="private",h=de=>{if(re())try{o.onProgress?.(de)}catch{}},m=Object.freeze({account:o.scope.account,installation:o.scope.installation,collection:o.scope.collection}),w=JSON.stringify([m.account,m.installation,m.collection]),b=new AbortController,g=!1,y=!0,_=null,v=null,k=null,S=null,x=null,P=null,C=null,R=null,O="setup_required",E=null,j=!1,B=!1,D=null,J=null,V="settled",U=null,ce=!1,ee=null,te=!1,Ce=null,et=null,$=new Map,Y=new Map,K=()=>{try{return i.timerConsentKey(m.collection)}catch{return}},Z=null,_e=new Set,re=()=>{try{return!g&&!b.signal.aborted&&!c.aborted&&o.signal===c&&o.host===i&&o.installation===a&&a.isCurrent===d&&d.call(a)===!0&&o.collection===l&&o.setupPolicy===p&&a.scope.account===m.account&&a.scope.installation===m.installation&&JSON.stringify([o.scope.account,o.scope.installation,o.scope.collection])===w&&l.collectionId===m.collection}catch{return!1}},ne=()=>{if(!re())throw ai("fenced")},Ke=()=>{for(let de of[..._e])try{de()}catch{}},Ve=()=>{if(k)return k;g=!0,O="setup_required",_!==null&&clearTimeout(_),_=null,ee!==null&&clearTimeout(ee),ee=null,et=null;try{U?.close()}catch{}U=null;try{i.onLogWork?.(null)}catch{}c.removeEventListener("abort",Ft);let de=[...$.values()];return $.clear(),k=Promise.resolve().then(async()=>{let Ie=!1;try{await x?.close()}catch{Ie=!0}try{await S?.close()}catch{Ie=!0}for(let st of de){try{await st.timers?.close()}catch{Ie=!0}try{await st.control.close()}catch{Ie=!0}try{st.data.port1.postMessage([1,JSON.stringify([m.account,m.installation,m.collection]),"close"])}catch{Ie=!0}for(let hr of[st.data.port1,st.data.port2,st.command.port1,st.command.port2])try{hr.close()}catch{Ie=!0}}try{C?.port1.postMessage([1,JSON.stringify([m.account,m.installation,m.collection]),"close"])}catch{Ie=!0}for(let st of[C?.port1,C?.port2,R?.port1,R?.port2])try{st?.close()}catch{Ie=!0}await v?.catch(()=>{});try{P?.close()}catch{Ie=!0}if(Ie)throw ai("unavailable");_e.clear(),r.delete(s)}),b.abort(),Ke(),k},Ft=()=>{Ve().catch(()=>{})},Re=null,nt=0,ci=()=>{let de=It(Z);if(de!==null)return de==="collection_migrating"?Math.min(6e5,Math.max(5e3,Z?.retryAfterMs??3e4)):3e5;let Ie=Math.min(6e4,1e3*2**Math.min(Math.max(nt,Di),6));return Re?.kind==="offline"?Un?Ie:null:Re?.kind==="server_busy"||Re?.kind==="rate_limited"?Re.retryAfterMs??Ie:Di||Re?Ie:250},yo=()=>{let de=null;try{de=i.serverProblem()}catch{de=null}let Ie=null;try{Ie=i.transportHealth()}catch{Ie=null}nt=Ie?nt+1:0;let st=JSON.stringify(Ie)===JSON.stringify(Re);(de!==Z||!st)&&(Z=de,Re=Ie,Ke())},go=Number.POSITIVE_INFINITY,Di=0,bo=0,hs=!1,Un=null,cn=de=>{let Ie=de&&typeof de=="object"&&typeof de.code=="string"?de.code:null;try{console.debug("mdbase: sync turn failed",{reason:Re?.kind??It(Z)??Ie??"unknown",failures:Di})}catch{}},wo=()=>{if(y||Date.now()-bo>=nD)return!1;try{return i.pendingWrites()>0}catch{return!1}},zc=()=>i.startCollectionLog({signal:b.signal,fetch:e.fetch,allowLoopbackHttp:e.allowLoopbackHttp}),Aa=de=>{Ce=de,Cg(),$c(!1),Un?.(),Ke()},ms=()=>{if(!(U||!re())){try{U=typeof i.openLogPush=="function"?i.openLogPush({push:de=>{re()&&(i.pushLog(de),Cg())},live:$c,ended:de=>{if(!j){et??=de,$c(!1);return}Aa(de)}}):null}catch{U=null}if(U){try{U.start()}catch{try{U.close()}catch{}U=null,ka(!0);return}$c(!1)}else ka(!0)}},jr=async()=>{let de=D;D=null,await(de??zc()),ne(),B=!0,ms()},V0=()=>{if(!(V!=="pending"||!B)){try{V=i.keyringSettled?.()??"settled"}catch{return}V==="failed"&&F0(new fr("recovery_required"))}},F0=de=>{J=de,j=!1,_!==null&&clearTimeout(_),_=null,Ke()},HE=de=>{let Ie=null;try{Ie=de.server}catch{Ie=null}let st=pn(Ie)&&It(Ie)!==null?Ie:null,hr=!pn(Ie)&&de instanceof lr&&de.reason==="response",wn=st?null:hr?{kind:"unreachable"}:Ld(de);if(!st&&(wn===null||wn.kind==="auth")){F0(de);return}nt=wn?nt+1:0,(st!==Z||JSON.stringify(wn)!==JSON.stringify(Re))&&(Z=st,Re=wn,Ke())},ys=()=>{if(!j||!re())return;if(!y&&!wo()&&!te){v||U?.suspend();return}if(_!==null||v)return;let de=te?0:ci();te=!1,de!==null&&(_=setTimeout(()=>{if(_=null,!re())return;let Ie=y&&Date.now()>=go;Ie&&(go=Number.POSITIVE_INFINITY);let st=v=B?Ie?i.wakeCollectionLog({signal:b.signal}):i.driveCollection({signal:b.signal}):jr().then(()=>i.driveCollection({signal:b.signal}));st.then(()=>{v===st&&(v=null),Di=0,hs=!0,re()&&(yo(),V0()),Un?.(),ys()},hr=>{v===st&&(v=null),Di++,re()&&(B?(yo(),V0()):HE(hr)),cn(hr),Un?.(),ys()})},de))},Cg=()=>{re()&&(te=!0,_!==null&&clearTimeout(_),_=null,ys())},ka=de=>{ce!==de&&(ce=de,Ke())},$c=de=>{if(ee!==null&&clearTimeout(ee),ee=null,de){ka(!1);return}if(!U?.available){ka(Ce===null);return}U.suspended||(ee=setTimeout(()=>{ee=null,re()&&!U?.live&&ka(!0)},iE))},K0=de=>{if(ne(),de){(!U?.live||Re?.kind==="offline")&&(go=0),Di=0,nt=0,Re?.kind==="offline"&&(te=!0);try{U?.resume(),U&&!U.live&&$c(!1)}catch{}}else y&&(bo=Date.now());y=de,_!==null&&clearTimeout(_),_=null,ys()},GE=()=>new Promise((de,Ie)=>{let st,hr=null,wn=Qn=>{Un=null,hr!==null&&clearTimeout(hr),b.signal.removeEventListener("abort",Sa),Qn?Ie(Qn):de()},Sa=()=>wn(ai("fenced"));b.signal.addEventListener("abort",Sa,{once:!0}),Un=()=>{if(!re()){wn(ai("fenced"));return}if(Ce!==null){wn();return}let Qn="first_turn";if(hs)try{Qn=typeof i.initialSync=="function"?i.initialSync():null}catch{Qn="unavailable"}if(Qn===null||Qn==="offline"||Re?.kind==="offline"){wn();return}let mr=null;if(Qn==="waiting_for_key"&&typeof i.keyWaitDetail=="function")try{mr=i.keyWaitDetail()}catch{mr=null}let Pa=Qn+(mr?JSON.stringify(mr):"");if(Pa!==st){st=Pa;try{console.debug("mdbase: waiting for the first sync",{...mr,reason:Qn})}catch{}}},hr=setTimeout(()=>wn(),rD),Un()});c.addEventListener("abort",Ft,{once:!0});try{ne(),P=new Wl({...e.setupJournal,scope:m,isCurrent:re});let de=new Oc({databaseName:e.joinDatabaseName,scope:m,isCurrent:re});if(f)h("joining"),await i.bootstrapPrivateDevice({scope:m,collectionCurrent:re,signal:b.signal,fetch:e.fetch,allowLoopbackHttp:e.allowLoopbackHttp}),ne();else{let Ct=await de.prepare({signal:b.signal});ne(),h("joining"),await i.bootstrapCloudCopy({scope:m,collectionCurrent:re,purpose:"join",outcomeMode:Ct.outcomeMode,signal:b.signal,...Ct.outcomeMode==="existing"?{reconcile:"explicit-unknown-outcome"}:{},fetch:e.fetch,allowLoopbackHttp:e.allowLoopbackHttp}),ne(),await de.complete({signal:b.signal}),ne()}let Ie=i.registeredReceipt();if(Ie.installationId!==m.installation)throw ai("binding");let st=null,hr=async Ct=>{let qt=await t(Ct);return st=qt.ledger??null,qt};h("opening_store"),await i.openCollectionSql({signal:b.signal,replicaId:Ie.deviceId,endpoint:0,openSql:hr}),ne();let wn=!0;try{wn=i.holdsLog?.()??!0}catch{wn=!1}let Sa=!f&&wn&&await de.syncedBefore({signal:b.signal});ne();let Qn=async()=>{h("connecting_log");let Ct=Date.now()+oD;for(let qt=0;;qt++)try{await zc(),ne();break}catch(yr){ne();let zi=yr instanceof lr&&yr.reason==="unavailable"?yr.server:null;if(!pn(zi)||zi.status!==503||zi.code!=="busy"||It(zi)!==null||qt+1>=sD)throw yr;let Bc=zi.retryAfterMs??1e3*2**qt;if(Date.now()+Bc>=Ct||(await fa(Bc,b.signal),ne(),Date.now()>=Ct))throw yr}B=!0};Sa?(D=zc(),D.catch(()=>{})):await Qn();let mr=crypto.randomUUID(),Pa=null,W0=null,Ig=null;if(f){h("syncing");let Ct=await i.settlePrivateKey({signal:b.signal});if(ne(),Ct==="locked"){let qt=await i.accountKeyMode({signal:b.signal});ne(),E={mode:qt,unlocking:!1,problem:null}}}let H0=async()=>{let Ct=f?await de.syncedBefore({signal:b.signal}):Sa;ne();let qt=!1;if(Sa&&!B)try{await i.waitForVerifiedRead({signal:b.signal,local:!0,timeoutMs:iD,onProgress:h}),ne(),qt=!0}catch{ne();let Kt=D;D=null;let wt=Kt?await Kt.then(()=>!0,()=>!1):!1;ne(),wt?B=!0:await Qn()}if(qt||(ms(),h("syncing"),await i.waitForVerifiedRead({signal:b.signal,cold:!Ct,onProgress:h}),ne()),j=!0,i.onLogWork?.(Cg),et!==null){let Kt=et;et=null,Aa(Kt)}qt?(V="pending",te=!0,ys(),ee=setTimeout(()=>{ee=null,re()&&!U?.live&&ka(!0)},iE)):(ys(),Ct&&(h("syncing"),await GE()),ne()),h("checking_setup"),de.markSynced({signal:b.signal}).catch(()=>{});let yr=await P.load(b.signal);ne();let zi=yr&&yr.version!==1&&(yr.phase==="attempted"||yr.phase==="confirmed")?"reconcile-original":yr===null&&p==="approved-new-collection"?"approved-new":"inspect",Bc=e.people===!0&&!f,G0=Bc?{people:!0}:f?{privateDevice:!0}:{},XE={owner:null},Y0=(Kt,wt,Wt,$i)=>zI(wt,{scope:m,generation:mr},{journal:P,resourceSetup:i.attachDataFacade(Kt),signal:b.signal,isCurrent:re,ledger:()=>re()?st:null,setupTurn:XE,assess(Vc){ne(),O=Vc,Ke()},foreground:Wt,onProtocolFailure:$i,...Bc?{peopleAuthority:i.peopleAuthority()}:{}});x=i.openTimersPort({scope:m,generation:mr,signal:b.signal}),ne();let QE=K()??null;C=new MessageChannel,R=new MessageChannel,S=Y0(C.port1,R.port1,K0,Ft),ne();let Og=Kt=>{if(Y.delete(Kt.dataPort),C&&R&&Kt.dataPort===C.port2){let Wt={data:C,command:R,control:S,timers:x};C=null,R=null,S=null,x=null;try{i.detachDataFacade(Wt.data.port1)}catch{}Wt.timers?.close().catch(()=>{}),Wt.control?.close().catch(()=>{});for(let $i of[Wt.data.port1,Wt.command.port1])try{$i.close()}catch{}return}let wt=$.get(Kt.dataPort);if(wt){$.delete(Kt.dataPort);try{i.detachDataFacade(wt.data.port1)}catch{}wt.timers?.close().catch(()=>{}),wt.control.close().catch(()=>{});for(let Wt of[wt.data.port1,wt.command.port1])try{Wt.close()}catch{}}},J0=(Kt=zi==="reconcile-original"?zi:"inspect")=>{if(!re()||Ce!==null)return null;let wt=new MessageChannel,Wt=new MessageChannel,$i=null,Vc=null;try{$i=i.openTimersPort({scope:m,generation:mr,signal:b.signal});let xa=null,eq=K()??null;return Vc=Y0(wt.port1,Wt.port1,()=>{},()=>{xa&&Og(xa)}),xa=Object.freeze({schema:"mdbn-app-collection/1",scope:m,generation:mr,displayName:u,setupMode:Kt,dataPort:wt.port2,controlPort:Wt.port2,...G0,...$i?{timerPort:$i.port}:{}}),$.set(wt.port2,{data:wt,command:Wt,control:Vc,timers:$i}),Y.set(wt.port2,eq),xa}catch{try{i.detachDataFacade(wt.port1)}catch{}$i?.close().catch(()=>{}),Vc?.close().catch(()=>{});for(let xa of[wt.port1,wt.port2,Wt.port1,Wt.port2])xa.close();return null}},ZE=Kt=>{if(!re()||!Y.has(Kt.dataPort))return null;let wt=K();if(wt===void 0||wt===Y.get(Kt.dataPort))return null;let Wt=J0(Kt.setupMode);return Wt&&Og(Kt),Wt};Pa=J0,W0=Og,Ig=ZE,Y.set(C.port2,QE),e.handoff(Object.freeze({schema:"mdbn-app-collection/1",scope:m,generation:mr,displayName:u,setupMode:zi,dataPort:C.port2,controlPort:R.port2,...G0,...x?{timerPort:x.port}:{}})),ne(),ys()},YE=Object.freeze({scope:m,generation:mr,isCurrent:re,setForeground:K0,attach:()=>Pa?Pa():null,detach:Ct=>{W0?.(Ct)},renewTimers:Ct=>Ig?Ig(Ct):null}),JE={get state(){return re()?E?"needs_unlock":O:"setup_required"},get locked(){return re()&&E?Object.freeze({...E}):null},get problem(){return re()?Z:null},get health(){return re()?Re:null},get live(){return re()?!ce:null},get ended(){return re()?Ce:null},get failure(){return re()?J:null},connection:YE,close:Ve,subscribe(Ct){return ne(),_e.add(Ct),()=>{_e.delete(Ct)}},...f?{unlock:async Ct=>{if(ne(),!E||E.unlocking)throw ai("binding");E={mode:E.mode,unlocking:!0,problem:null},Ke();try{await i.unlockAccountKey(Ct,{signal:b.signal,onMode:qt=>{E&&re()&&(E={...E,mode:qt})}}),ne()}catch(qt){if(qt instanceof pt&&re()&&E){E={mode:E.mode,unlocking:!1,problem:qt.reason},Ke();return}throw await Ve(),qt}try{await H0(),ne()}catch(qt){throw await Ve(),qt}E=null,Ke()}}:{}};return E||await H0(),ne(),Object.freeze(JE)}catch(de){throw await Ve(),de}}}async function hg(n,e){if(n.schema!=="mdbn-app-collection/1"||Rc.has(n.dataPort)||Rc.has(n.controlPort)||n.dataPort===n.controlPort||!["inspect","approved-new","reconcile-original"].includes(n.setupMode)||n.people!==void 0&&n.people!==!0||n.privateDevice!==void 0&&(n.privateDevice!==!0||n.people!==void 0)||e.signal.aborted||n.timerPort&&(Rc.has(n.timerPort)||n.timerPort===n.dataPort||n.timerPort===n.controlPort))throw ai("binding");Rc.add(n.dataPort),Rc.add(n.controlPort),n.timerPort&&Rc.add(n.timerPort);let t=Object.freeze({...n.scope}),r=n.generation,o=n.setupMode,s=n.people===!0,i=n.dataPort,a=n.controlPort,c=e.signal,l=!1,p=null,d=null,u=null,f,h=()=>{if(!l){l=!0,c.removeEventListener("abort",h);for(let m of[()=>f?.close(),()=>d?.close(),()=>p?.close(),()=>u?.close(),()=>i.close(),()=>a.close()])try{m()}catch{}}};c.addEventListener("abort",h,{once:!0});try{if(u=Vm(i,{...t,isCurrent:()=>!l&&!c.aborted}),d=zm(a,{scope:t,generation:r},{signal:c,isCurrent:()=>!l,onClose:h,...s?{people:!0}:{}}),n.timerPort&&(f=new Fa(s2(n.timerPort,{scope:t,generation:r},{signal:c,onClose:()=>{}}),{criteria:e.timerCriteria??[]})),p=await yi.connect({app:e.app,connector:u,reconnect:!1,signal:c,ledger:d.ledger}),l||c.aborted)throw p.close(),ai("fenced");let m=s?Nm(p,d):void 0;return Object.freeze({client:p,resourceSetup:d.resourceSetup,...m?{people:m}:{},journal:d.journal,scope:t,setupMode:o,close:h,...f?{timers:f}:{},assess:(w,b)=>d.assess(w,b),setForeground:(w,b)=>d.setForeground(w,b)})}catch(m){throw h(),m}}var iE,nD,rD,iD,oD,sD,yu,ai,Rc,y0=I(()=>{"use strict";nr();Cd();mu();jy();Wm();Es();fw();TA();EI();fg();Js();es();Fm();fu();qd();iE=1e4,nD=12e4,rD=2e3,iD=5e3,oD=15e3,sD=3,yu=class extends Error{constructor(t){super(`app web collection: ${t}`);this.reason=t;this.name="AppWebCollectionError"}reason},ai=n=>new yu(n);Rc=new WeakSet});function aD(n,e){return Object.freeze({collection:n,isCurrent:e,request:()=>Promise.reject(A("upgrade_required","People is not available for a Private collection opened by this app","people_unsupported"))})}var ln,mg,lD,Ec,g0=I(()=>{"use strict";y0();ie();Sp();ln=class extends Error{constructor(t){super("SDK application connection unavailable");this.code=t;this.name="ApplicationUiConnectionError"}code},mg=new WeakSet;lD=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,Ec=class{app;signal;current=null;pending=null;opening=null;retiring=null;closing=null;epoch=0;timerCriteria;constructor(e,t,r=[]){this.app=Object.freeze({...e}),this.signal=t,this.timerCriteria=Object.freeze([...r]),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 r=t.caller,o=t.isCurrent,s=[e.dataPort,e.controlPort,...e.timerPort?[e.timerPort]:[]];if(s.some(y=>!(y instanceof MessagePort))||new Set(s).size!==s.length||s.some(y=>mg.has(y))){for(let y of new Set(s))y instanceof MessagePort&&!mg.has(y)&&(mg.add(y),y.close());return Promise.reject(new ln("application_connection_binding"))}for(let y of s)mg.add(y);let i=y=>{for(let _ of s)_.close();return Promise.reject(new ln(y))};if(this.pending||this.current||this.retiring)return i("application_connection_busy");if(this.closing||this.signal.aborted||r.aborted||!o())return i("application_connection_fenced");let a=Object.freeze({...e.scope}),c=e.generation,l=e.displayName;if(e.schema!=="mdbn-app-collection/1"||Object.keys(a).sort().join()!=="account,collection,installation"||Object.values(a).some(y=>!lD.test(y)||y==="00000000-0000-0000-0000-000000000000")||typeof c!="string"||!c||c.length>256||typeof l!="string"||!l.trim()||new TextEncoder().encode(l).length>4096||!["inspect","approved-new","reconcile-original"].includes(e.setupMode))return i("application_connection_binding");let p=e.privateDevice===!0;if(e.privateDevice!==void 0&&(!p||e.people!==void 0))return i("application_connection_binding");if(e.people!==!0&&!p)return i("application_connection_people_unavailable");let d=Object.freeze({...e,scope:a,generation:c,displayName:l}),u=new AbortController,f=this.epoch;this.opening=u;let h=()=>u.abort();r.addEventListener("abort",h,{once:!0});let m=AbortSignal.any([this.signal,u.signal]),w=()=>!m.aborted&&!this.closing&&!this.retiring&&this.epoch===f&&o(),b=null,g=Promise.resolve().then(async()=>{if(!w()||r.aborted)throw new ln("application_connection_fenced");if(b=await hg(d,{app:this.app,signal:m,timerCriteria:this.timerCriteria}),!w()||r.aborted)throw new ln("application_connection_fenced");if(b.client.collection!==a.collection||b.client.link!=="open")throw new ln("application_connection_binding");if(p?b.people!==void 0:!b.people)throw new ln(p?"application_connection_binding":"application_connection_people_unavailable");let y=b,_=b.people??new gi(y.client,aD(a.collection,()=>w()&&this.current?.ui===y&&y.client.link==="open")),v=Object.freeze({id:a.collection,scope:a,generation:c,displayName:l,records:y.client,files:y.client.files,people:_,...y.timers?{timers:y.timers}:{},isCurrent:()=>w()&&this.current?.ui===y&&y.client.link==="open"});return this.current={public:v,ui:y,lifetime:u},v}).catch(y=>{u.abort(),b?.close();for(let _ of s)_.close();throw y}).finally(()=>{r.removeEventListener("abort",h),this.pending===g&&(this.pending=null,this.opening=null)});return this.pending=g,g}retire(){if(this.retiring)return this.retiring;++this.epoch;let e=this.current,t=this.pending;this.opening?.abort(),e?.lifetime.abort();let r=Promise.resolve().then(async()=>{await t?.catch(()=>{}),e?.ui.close(),this.current===e&&(this.current=null)});return this.retiring=r,r.then(()=>{this.retiring===r&&(this.retiring=null)},()=>{}),r}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 hD(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 Vt("unsupported");let e=n.contracts.map(r=>{if(!r||!Tc(r.id,256)||!Tc(r.version,128)||!fD.test(r.digest))throw Vt("unsupported");return Object.freeze({id:r.id,version:r.version,digest:r.digest})}),t=n.requiredNativeCapabilities.map(r=>{if(!Tc(r,128))throw Vt("unsupported");return r});if(new Set(e.map(r=>JSON.stringify([r.id,r.version]))).size!==e.length||new Set(t).size!==t.length||n.typeIssues!==void 0&&n.typeIssues!=="block"&&n.typeIssues!=="degrade")throw Vt("unsupported");return Object.freeze({capabilityContractVersion:2,typeIssues:n.typeIssues??"block",contracts:Object.freeze(e),requiredNativeCapabilities:Object.freeze(t)})}function mD(n){let e=fe(n,"path");return typeof e=="string"&&e?e:null}function qc(n,e){return Object.freeze({reason:n,...n==="fenced"&&e?{detail:e}:{}})}function b0(n){if(!X(n))return;let e=fe(n.details,"condition"),t=cD.find(r=>r===e);if(t)return t;if(n.code==="unauthenticated")return"read_unauthenticated";if(n.code==="cancelled")return"read_cancelled"}function w0(n){try{if(X(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 _0(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 A0(n){return n.mode==="local_only"}function Mc(n){return JSON.stringify(n,(e,t)=>typeof t=="bigint"?`${t}n`:t instanceof Uint8Array?[...t]:t)}function aE(n,e,t){return new v0(n,e,t)}var cD,pD,dD,uD,sE,fD,Tc,Vt,v0,k0=I(()=>{"use strict";ie();vn();cD=["binding_invalid","binding_aborted","binding_not_current","readiness_closed","read_aborted","session_closed","session_replaced","session_collection_mismatch","read_unauthenticated","read_cancelled"],pD=4096,dD=2*1024*1024,uD=64,sE=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,fD=/^sha256:[0-9a-f]{64}$/,Tc=(n,e=4096)=>typeof n=="string"&&!!n.trim()&&new TextEncoder().encode(n).length<=e,Vt=(n,e)=>A(n==="fenced"?"unauthenticated":n==="budget"?"too_large":"unavailable","collection readiness unavailable",{reason:`readiness_${n}`,...e?{details:{condition:e}}:{}});v0=class{constructor(e,t,r){this.client=e;if(this.declared=hD(t),!sE.test(r.collection)||r.collection==="00000000-0000-0000-0000-000000000000"||!sE.test(r.generation))throw Vt("fenced","binding_invalid");this.binding=Object.freeze({collection:r.collection,generation:r.generation,signal:r.signal,isCurrent:r.isCurrent.bind(r)}),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=w0(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:qc(t,b0(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,r){e?.throwIfAborted();let o=this.fenceDetail(e);if(o)throw Vt("fenced",o);if(t?.closed)throw Vt("fenced","session_closed");if(t&&t!==this.client.currentSession())throw Vt("fenced","session_replaced");if(t&&t.hello.collection!==this.binding.collection)throw Vt("fenced","session_collection_mismatch");if(r!==void 0&&(r!==this.epoch||this.watch?.state!=="active"))throw Vt("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,r=this.client.describe({signal:this.readSignal}).then(o=>{this.closed||this.snapshotValue.assessment!==e||Mc(o)!==t&&this.recheck()},()=>{this.closed||this.recheck()});this.probing=r.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:qc("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(this.invalidate),this.stops.push(this.watch.subscribe(this.invalidate),this.client.onLink(this.invalidate),this.client.onStatus(e=>{let t=_0(this.client);(t!==this.lastStatus||A0(e))&&(this.lastStatus=t,this.invalidate())})))}start(e){return this.refresh(e)}refresh(e,t=!1){try{if(this.check(e),this.pending)throw Vt("busy")}catch(a){return Promise.reject(a)}t||(this.retrySince=null);let r=AbortSignal.any([this.binding.signal,this.lifetime.signal,...e?[e]:[]]),o,s,i=Promise.resolve().then(async()=>{this.check(r),this.attach();let a=await this.client.readyForRead(r);this.check(r,a),await this.watch.ready,this.check(r,a);let c=this.epoch;this.dirty=!1,this.check(r,a,c);let l=await this.inventory(r,a,c),p=await this.client.describe({signal:this.readSignal});this.check(r,a,c);let d=this.evaluate(p,a),u=Mc(p);for(let w of d.paths){let b=l.find(y=>y.path===w);if(!b)throw Vt("changed");let g=await this.client.resources.get(w,{signal:this.readSignal});if(this.check(r,a,c),g.path!==b.path||g.revision!==b.revision||g.size!==b.size||g.state!=="confirmed")throw Vt("changed")}let f=await this.inventory(r,a,c);if(JSON.stringify(l)!==JSON.stringify(f))throw Vt("changed");this.check(r,a,c);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?qc(d.reason):null,witness:h,...d.unavailable.length?{unavailableTypes:Object.freeze(d.unavailable)}:{}});return o=a,s=c,this.retries=0,this.failures=0,this.retrySince=null,this.assessedSession=a,this.assessedEpoch=c,this.assessedCatalog=u,this.publish({checking:!1,assessment:m,problem:m.problem}),this.check(r,a,c),m}).catch(a=>{let c=r.aborted||this.closed?"fenced":w0(a);throw this.retryLater(c,t)||this.publish({checking:!1,assessment:null,problem:qc(c,this.fenceDetail(r)??b0(a))}),a});return this.pending=i,this.publish({checking:!0,assessment:null,problem:null}),i.finally(()=>{this.pending===i&&(this.pending=null),this.schedule()}).catch(()=>{}),i.then(a=>{try{if(this.check(r,o,s),this.snapshotValue.assessment!==a)throw Vt("changed");return a}catch(c){let l=r.aborted?"fenced":w0(c);throw this.snapshotValue.assessment===a&&!this.retryLater(l)&&this.publish({checking:!1,assessment:null,problem:qc(l,this.fenceDetail(r)??b0(c))}),c}})}async inventory(e,t,r){let o=[],s=new Set,i,a="",c=0;for(let l=0;l<uD;l++){this.check(e,t,r);let p=await this.client.resources.list({text:!1,limit:128,...i?{cursor:i}:{},signal:this.readSignal});this.check(e,t,r);for(let d of p.resources){if(!Tc(d.path)||d.path<=a||!Tc(d.revision,128)||!Number.isSafeInteger(d.size)||d.size<0||d.state!=="confirmed")throw Vt("catalog_response");a=d.path;let u=Object.freeze({path:d.path,revision:d.revision,size:d.size,state:d.state});if(c+=new TextEncoder().encode(JSON.stringify(u)).length,o.length>=pD||c>dD)throw Vt("budget");o.push(u)}if(p.complete===!0&&p.cursor===void 0)return o;if(p.complete!==!1||!Tc(p.cursor)||s.has(p.cursor))throw Vt("catalog_response");s.add(p.cursor),i=p.cursor}throw Vt("budget")}evaluate(e,t){let r=e.issues.filter(d=>d.severity==="error"),o=new Set;for(let d of r){let u=mD(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 i=new Set,a=new Set,c=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(c.has(d.name))return{status:"incompatible",reason:"catalog_response",paths:[],unavailable:[]};c.add(d.name)}let l,p=[];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(i.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(i.add(h.path),o.has(h.path)){if(this.declared.typeIssues!=="degrade")return s;p.some(m=>m.name===h.name)||p.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:[...i].sort(),unavailable:p}}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:qc("fenced",this.fenceDetail())})}await this.pending?.catch(()=>{})}}});function gD(n){let e=o=>o?Object.freeze({code:`readiness_${o.reason}`,...o.detail?{detail:o.detail}:{}}):null,t=e(n.problem),r=n.assessment?.unavailableTypes;return Object.freeze({checking:n.checking,assessment:n.assessment?Object.freeze({status:n.assessment.status,problem:e(n.assessment.problem),...r?.length?{unavailableTypes:r}:{}}):null,problem:t})}var lE,yD,gu,Ni,yg,cE=I(()=>{"use strict";Ep();ie();k0();lE=["configuration","files"],yD=["people","notifications"],gu=class extends Error{constructor(t,r){super("SDK application readiness unavailable");this.code=t;this.detail=r;this.name="ApplicationReadinessError"}code;detail},Ni=(n,e=!1,t)=>Object.freeze({checking:e,assessment:null,problem:n?Object.freeze({code:n,...t?{detail:t}:{}}):null});yg=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?aE(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(X(e)){let t=Ts(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=Ni(e?"readiness_unsupported":"readiness_fenced"),r=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;r=h?Ni("readiness_fenced",!1,h):gD(u)}let o=u=>{if(!e)return t;let f=this.sources[u];if(!f)return Ni(`${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 Ni(`${u}_unavailable`)}},s=Object.freeze({capabilities:r,contracts:r,configuration:o("configuration"),files:o("files"),people:o("people"),notifications:o("notifications")}),i=[s.capabilities,s.contracts,s.configuration,s.files],a=e&&(this.checking||i.some(u=>u.checking)),c=null,l=null;if(!e)l=Object.freeze({code:"readiness_fenced"});else if(!a){let u=["capabilities","contracts",...lE].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`})),i.every(f=>f.assessment!==null)){let f=s.configuration.assessment?.status==="setup_required",h=y=>y.assessment?.status==="incompatible"&&!(f&&y===r&&y.assessment.problem?.code==="readiness_contract_mismatch"),m=i.find(h),w=i.find(y=>y.assessment?.status==="setup_required"),b=m??w,g=r.assessment?.unavailableTypes;c=Object.freeze({status:m?"incompatible":w?"setup_required":"ready",problem:b?.assessment?.problem??null,...g?.length?{unavailableTypes:g}:{}})}}let p=this.fenceDetail();if(p)return this.lastReady=null,Object.freeze({checking:!1,assessment:null,problem:Object.freeze({code:this.connectionProblem(),detail:p}),facets:Object.freeze({capabilities:Ni("readiness_fenced",!1,p),contracts:Ni("readiness_fenced",!1,p),configuration:Ni("readiness_fenced",!1,p),files:Ni("readiness_fenced",!1,p),people:Ni("readiness_fenced",!1,p),notifications:Ni("readiness_fenced",!1,p)})});let d=!l||/_(changed|busy)$/.test(l.code);if(l===null&&c!==null&&!a)this.lastReady=Object.freeze({checking:a,assessment:c,problem:l,facets:s});else{if(this.lastReady&&d&&(a||c===null)&&(this.lastReady.assessment?.status==="ready"||!this.checking))return Object.freeze({...this.lastReady,facets:s});this.lastReady=null}return Object.freeze({checking:a,assessment:c,problem:l,facets:s})}refresh(e={}){let t=e.signal,r=this.fenceDetail()??(t?.aborted?"caller_aborted":null);if(r)return Promise.reject(new gu("application_readiness_fenced",r));if(this.pending)return Promise.reject(new gu("application_readiness_busy"));this.checking=!0;let o=Promise.resolve().then(async()=>{if(!this.current())return this.getSnapshot();await this.advisory;let s=[],i=async(c,l)=>{try{await l()}catch(p){let d=!1;try{d=c.getSnapshot().checking===!0}catch{}if(!d||!this.current())throw p;s.push(p)}},a=this.native;a&&await i(a,()=>a.start());for(let c of lE){let l=this.sources[c];if(!this.current())break;l&&await i(l,()=>l.refresh())}if(await this.reassessAfterSetup(),s.length)throw s[0];return this.getSnapshot()}).finally(()=>{if(this.pending!==o)return;this.pending=null,this.checking=!1;let s=(async()=>{for(let i of yD){let a=this.sources[i];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 i=this.fenceDetail()??(t?.aborted?"caller_aborted":null);if(i)throw new gu("application_readiness_fenced",i);return s})}async reassessAfterSetup(){if(!this.native||!this.current())return;let e=this.native.getSnapshot(),t=null;try{t=this.sources.configuration?.getSnapshot()??null}catch{}e.checking||e.assessment?.status!=="setup_required"||t?.checking||t?.assessment?.status!=="ready"||await this.native.start().catch(r=>{if(!(X(r)&&r.reason==="readiness_busy"))throw r})}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 bD(n){let e=new Set,t=[],r=[];for(let o of n.review?.packs??[]){if(o.status!=="conflict"&&o.status!=="downgrade")continue;let s=o.installedVersion?Ms(o.installedVersion,o.version):"unknown";s==="installed_newer"&&!o.resources.some(i=>i.action==="conflict")?(e.add(o.id),r.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(r),compatible:e,major:Object.freeze(t)})}function wD(n,e){let t=n,r=t.provisions?.type_packs;return!e.size||!Array.isArray(r)?n:{...t,provisions:{...t.provisions,type_packs:r.filter(o=>!(typeof o?.manifest?.id=="string"&&e.has(o.manifest.id)))}}}function dE(n){return new Proxy({},{get(e,t){let r=Reflect.get(n,t,n);return typeof r!="function"?r:async(...o)=>{let s=o.find(a=>a instanceof AbortSignal),i=Date.now()+vD;for(let a=25;;a=Math.min(a*2,500))try{return await r.apply(n,o)}catch(c){if(!(c instanceof Rr&&c.reason==="busy")||!s)throw c;if(Date.now()+a>i)throw Je("busy_timeout");await _D(a,s)}}}})}function fE(n,e){let t=Object.freeze({...n,scope:Object.freeze({...n.scope}),journal:dE(n.journal)});if(e&&(e=dE(e)),Object.values(t.scope).some($=>!pE.test($)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/.test($))||!pE.test(t.generation)||!["inspect","approved-new","reconcile-original"].includes(t.setupMode))throw Je("binding");let r=JSON.stringify([t.scope.account,t.scope.installation,t.scope.collection]),o=new AbortController,s=AbortSignal.any([t.signal,o.signal]),i=new Set,a=fo(),c=null,l=null,p=!1,d,u=null,f=!1,h=!1,m=0,w=!1,b=!1,g=null,y=null,_=()=>{try{return JSON.stringify([t.client.link,_0(t.client)])}catch{return null}},v=[],k=new WeakMap;function S($,Y){if($?.throwIfAborted(),p||s.aborted||t.isCurrent()!==!0||JSON.stringify([t.journal.scope.account,t.journal.scope.installation,t.journal.scope.collection])!==r||Y&&(Y.closed||t.client.currentSession()!==Y||Y.hello.collection!==t.scope.collection))throw Je("fenced")}function x($){a=Object.freeze($);for(let Y of i)try{Y()}catch{}}function P(){if(p)return;let $=_();if($!==null&&$===y)return;if(y=$,c||!a.assessment||u===null||t.client.link!=="open"){C();return}if(f){h=!0;return}f=!0;let Y=a,K=u;t.client.describe({signal:s}).then(Z=>{!p&&a===Y&&Mc(Z)!==K&&C()},()=>{p||C()}).finally(()=>{f=!1,h&&!p&&(h=!1,y=null,P())})}function C(){p||(w=!0,c||x(fo(null,!0)),R())}function R(){p||c||b||!w||(b=!0,setTimeout(()=>{if(b=!1,p||c||!w)return;let $=te(!1,{},void 0,!0);g=c,$.catch(()=>{})},m?Math.min(5e3,250*2**m):50))}function O(){if(a.assessment)try{S(void 0,d)}catch{p||s.aborted||t.isCurrent()!==!0?x(fo("configuration_fenced")):(w=!0,y=null,x(fo(null,!0)),R())}return a}async function E($,Y,K){let Z=await t.client.awaitReceipt($.mutationId,{timeoutMs:12e4,signal:s});if(S(Y,K),Z.mutation!==$.mutationId||Z.state!=="confirmed"||Z.status!=="applied"||(Z.conflicts?.length??0)!==0||Z.published==="publishing"||Z.published==="not_published")throw Je("recovery_required");return Z}async function j($,Y,K){let Z,_e=0,re=0,ne=new Set,Ke=new Set,Ve=new TextEncoder;for(let Ft=0;Ft<64;Ft++){S(Y,K);let Re=await t.client.resources.list({text:!1,limit:128,...Z===void 0?{}:{cursor:Z},signal:s});if(S(Y,K),Re.resources.length>128)throw Je("recovery_required");for(let nt of Re.resources){let ci=Ve.encode(nt.path).length;if(_e++,re+=ci+128,!nt.path||ci>4096||Ke.has(nt.path)||nt.state!=="confirmed"||!S0.test(nt.revision)||!Number.isSafeInteger(nt.size)||nt.size<0||_e>4096||re>2*1024*1024||$.has(nt.path))throw Je("recovery_required");Ke.add(nt.path)}if(Re.complete===!0&&Re.cursor===void 0)return;if(Re.complete!==!1||!Re.resources.length||typeof Re.cursor!="string"||!Re.cursor||Ve.encode(Re.cursor).length>4096||ne.has(Re.cursor))throw Je("recovery_required");ne.add(Re.cursor),Z=Re.cursor}throw Je("recovery_required")}async function B($,Y,K){let Z=$.version===2?$.plan.readback:$.plan.resourceReadback,_e=new Set(Z.filter(re=>re.doc===null).map(re=>re.path));_e.size&&await j(_e,Y,K);for(let re of Z){if(re.doc===null)continue;let ne=await t.client.resources.get(re.path,{signal:s});if(S(Y,K),ne.path!==re.path||ne.text!==re.doc||ne.state!=="confirmed")throw Je("recovery_required")}if($.version!==2)for(let re of $.plan.sources){let ne=await t.client.get(re.id,{signal:s});if(S(Y,K),ne.id!==re.id||ne.path!==re.path||ne.state.state!=="confirmed"||ne.state.hold||ne.state.unresolved)throw Je("recovery_required")}}async function D($,Y,K){return await E($,Y,K),$.phase==="attempted"&&($=$.version===2?await t.journal.recordConfirmed($.mutationId,s):await t.journal.recordResourceConfirmed($.mutationId,s),S(Y,K)),$.phase==="verified"||(await B($,Y,K),$.phase==="confirmed"&&($=$.version===2?await t.journal.recordVerified($.mutationId,s):await t.journal.recordResourceVerified($.mutationId,s),S(Y,K))),$}async function J($,Y){let K=await t.journal.load(s);if(S($,Y),!K)return{journaled:!1,previous:null};if(K=Jt(K,t.scope),K.version===1||K.phase==="prepared")throw Je("recovery_required");if(K.phase==="attempted"&&(K.version===3||K.version===4)&&t.journal.recordResourceRejected){let Z=await t.client.awaitReceipt(K.mutationId,{timeoutMs:12e4,signal:s});S($,Y),Z.mutation===K.mutationId&&Z.state==="rejected"&&(K=Jt(await t.journal.recordResourceRejected(K.mutationId,s),t.scope),S($,Y))}if(K.version===1)throw Je("recovery_required");return K.phase==="rejected"?{journaled:!0,previous:K.version===4?K.previous:null}:{journaled:!0,previous:await D(K,$,Y)}}async function V($,Y){let K=t.compiledManifest.manifest,Z=await P0(e.assess(K,s,$),$),_e=Z;Z.status==="conflict"&&!Z.review&&(_e=await e.assess(K,s,Or({})));let re=bD(_e);if(!re.compatible.size)return{assessed:Z,manifest:K,newer:re};let ne=wD(K,re.compatible),Ke=Y?$??Or({}):$;return Z=await P0(e.assess(ne,s,Ke),Ke),{assessed:Z,manifest:ne,newer:re}}async function U($,Y,K={}){S(Y);let Z=await t.client.readyForRead(s);S(Y,Z),v.length||(y=_(),v.push(t.client.onStatus(bo=>{A0(bo)&&(y=null),P()}),t.client.onLink(P))),w=!1;let{journaled:_e,previous:re}=await J(Y,Z);if(!e)throw Je("unsupported");let ne=null;try{ne=Mc(await t.client.describe({signal:s}))}catch{}S(Y,Z);let Ke=await V(K.decisions,!1),Ve=Ke.assessed,Ft=Ke.manifest;if(S(Y,Z),!S0.test(Ve.assessmentDigest)||!["current","provision","conflict"].includes(Ve.status))throw Je("response");if(K.expected!==void 0&&Ve.assessmentDigest!==K.expected)throw x0();let Re=!_e&&t.setupMode==="approved-new";if(Ve.status==="provision"&&($||Re)){if(t.setupMode==="reconcile-original")throw Je("recovery_required");if(!(t.compiledManifest.operations.includes("apply_collection_setup")||t.compiledManifest.operations.includes("apply_type_pack"))||!Z.hello.grant.capabilities.includes("definitions.manage"))throw Je("not_authorized");let bo=K.records??[];if(bo.length&&!Z.hello.grant.capabilities.includes("records.create"))throw Je("not_authorized");let hs=$t(await P0(e.apply(Ft,Ve.assessmentDigest,s,K.decisions),K.decisions));if(S(Y,Z),hs.assessmentDigest!==Ve.assessmentDigest)throw Je("response");if(hs.sources.length)throw Je("unsupported_source_provision");let Un=bo.length?$t({...hs,sources:bo.map(jr=>({id:crypto.randomUUID(),path:jr.path,document:jr.document}))}):hs,cn;if(re){if(!t.journal.prepareResourceRound)throw Je("recovery_required");cn=await t.journal.prepareResourceRound(Un,re.mutationId,s)}else cn=await t.journal.prepareResources(Un,s);if(S(Y,Z),cn=Jt(cn,t.scope),cn.version!==3&&cn.version!==4||cn.phase!=="prepared"||JSON.stringify(cn.plan)!==JSON.stringify(Un))throw Je("recovery_required");let wo=Jt(await t.journal.recordResourceAttempt(cn.mutationId,s),t.scope);if(S(Y,Z),wo.version!==3&&wo.version!==4||wo.mutationId!==cn.mutationId||wo.phase!=="attempted"||JSON.stringify(wo.plan)!==JSON.stringify(Un))throw Je("recovery_required");let zc=[...Un.resourceOps,...Un.sources.map(jr=>({kind:"create",id:jr.id,path:jr.path,document:jr.document}))],Aa=await t.client.submit(zc,{mutationId:cn.mutationId,wait:"confirmed",signal:s});if(S(Y,Z),Aa.mutationId!==cn.mutationId)throw Je("recovery_required");let ms;try{ms=await Aa.confirmed}catch(jr){throw S(Y,Z),Aa.receipt.state!=="rejected"||!t.journal.recordResourceRejected?jr:(await t.journal.recordResourceRejected(cn.mutationId,s),S(Y,Z),x0(cn.mutationId,jr))}if(S(Y,Z),ms.state!=="confirmed"||ms.status!=="applied"||(ms.conflicts?.length??0)!==0)throw Je("recovery_required");await D(wo,Y,Z),w=!1,y=_();try{ne=Mc(await t.client.describe({signal:s}))}catch{ne=null}if(Ve=await e.assess(Ft,s),S(Y,Z),Ve.status!=="current"||!S0.test(Ve.assessmentDigest))throw Je("recovery_required")}let nt=Ve.status==="conflict"&&Ke.newer.major.length>0,ci=Ve.status==="conflict"?nt?"installed_newer":"setup_conflict":null,yo=ci?Object.freeze({code:ci}):null,go=Object.freeze({status:Ve.status==="current"?"ready":nt?"incompatible":"setup_required",problem:yo});d=Z,u=ne;let Di=Object.freeze({checking:!1,assessment:go,problem:yo});return m=0,x(w?fo(null,!0):Di),S(Y,Z),Di}function ce($={}){try{S($.signal)}catch(Z){return Promise.reject(Z)}let Y=c,K=(Y?Y.then(()=>{},()=>{}):Promise.resolve()).then(()=>ee($));return c=K,K.finally(()=>{c===K&&(c=null)}).catch(()=>{}),K}async function ee($){let Y=iy($.records),K=Or($.adopt===void 0?{}:{adopt:$.adopt}),Z=AbortSignal.any([s,...$.signal?[$.signal]:[]]),_e=await t.client.readyForRead(s);if(S(Z,_e),await J(Z,_e),!e)throw Je("unsupported");let{assessed:re,newer:ne}=await V(K,!0);if(S(Z,_e),!re.review)throw Je("response");let Ke=[];if(re.status!=="current")for(let Re of Y){let nt=await t.client.find({path:Re.path},{signal:s});S(Z,_e),Ke.push({path:Re.path,free:nt===null})}let Ve=_e.hello.grant.capabilities,Ft=Nd(re,{records:Ke,canManage:Ve.includes("definitions.manage")&&(t.compiledManifest.operations.includes("apply_collection_setup")||t.compiledManifest.operations.includes("apply_type_pack")),canCreateRecords:Ve.includes("records.create"),newer:ne});return k.set(Ft,Object.freeze({decisions:K,records:Y.filter(Re=>Ke.some(nt=>nt.path===Re.path&&nt.free))})),Ft}function te($,Y={},K,Z=!1){try{S(Y.signal)}catch(ne){return Promise.reject(ne)}if(c&&c===g){let ne=c;return ne.then(()=>{},()=>{}).then(()=>c&&c!==ne?Promise.reject(Je("busy")):te($,Y,K))}if(c)return Promise.reject(Je("busy"));let _e=AbortSignal.any([s,...Y.signal?[Y.signal]:[]]),re=Promise.resolve().then(()=>U($,_e,K)).catch(ne=>{let Ke=s.aborted||_e.aborted,Ve=X(ne)&&ne.reason==="configuration_busy_timeout";Ve&&(w=!1);let Ft=!Ke&&!Ve&&(w||uE(ne));throw Ft&&uE(ne)&&(w=!0,m=Math.min(m+1,4)),!Ke&&!Ve&&!w&&Z&&m<5&&!p&&t.isCurrent()===!0&&(m++,w=!0,Ft=!0),x(Ft?fo(null,!0):fo(Ke?"configuration_fenced":Ve?"configuration_busy_timeout":"configuration_unavailable")),ne});return c=re,x(fo(null,!0)),re.finally(()=>{c===re&&(c=null),g===re&&(g=null),R()}).catch(()=>{}),re.then(ne=>(S(_e,d),ne))}let Ce=()=>{if(!l){p=!0,t.signal.removeEventListener("abort",et),o.abort();for(let Y of v.splice(0))Y();x(fo("configuration_fenced"));let $=c;l=Promise.resolve().then(async()=>{await $})}return l},et=()=>{Ce().catch(()=>{})};return t.signal.addEventListener("abort",et,{once:!0}),Object.freeze({getSnapshot:O,subscribe($){return i.add($),()=>{i.delete($)}},assess:$=>te(!1,$),configure:$=>te(!0,$),plan:ce,async apply($,Y={}){let K=k.get($);if(!K)throw new TypeError("setup.apply needs a plan returned by setup.plan");if($.refusal)throw A($.refusal.code==="setup_conflict"?"conflict":$.refusal.code==="installed_newer"?"upgrade_required":"forbidden",$.refusal.message,$.refusal.code);if($.status==="current"){await te(!1,Y,{decisions:K.decisions,expected:$.digest});return}await te(!0,Y,{decisions:K.decisions,expected:$.digest,records:K.records})},close:Ce})}var pE,S0,Je,x0,P0,vD,_D,uE,fo,hE=I(()=>{"use strict";ie();Js();k0();es();Gf();oy();pE=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,S0=/^sha256:[0-9a-f]{64}$/,Je=n=>A("unavailable","application configuration unavailable",`configuration_${n}`),x0=(n,e)=>new oe(A("conflict","This collection changed since the setup was reviewed. Review it again.","setup_changed").toProblem(),{...n?{mutationId:n}:{},...e===void 0?{}:{cause:e}}),P0=async(n,e)=>{try{return await n}catch(t){throw e?.adopt&&Object.keys(e.adopt).length&&X(t,"unavailable")&&t.reason==="resource_setup_unavailable"?x0(void 0,t):t}};vD=15e3,_D=(n,e)=>new Promise((t,r)=>{if(e.aborted){r(e.reason);return}let o=()=>{clearTimeout(s),r(e.reason)},s=setTimeout(()=>{e.removeEventListener("abort",o),t()},n);e.addEventListener("abort",o,{once:!0})});uE=n=>X(n)&&n.reason==="configuration_busy",fo=(n=null,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n?Object.freeze({code:n}):null})});function mE(n){return{issuer:n.issuer,subject:n.subject,name:n.name,...n.accountId===void 0?{}:{account_id:n.accountId}}}function yE(n){let e=n.scope,t=e.account,r=e.installation,o=e.collection,s=n.generation,i=n.signal,a=n.people,c=n.isCurrent.bind(n),l=typeof a?.current=="function"?a.current.bind(a):void 0,p=typeof a?.members=="function"?a.members.bind(a):void 0,d=new Set,u=_a(null),f=!1,h=!1,m=null;function w(){try{return f||i.aborted||c()!==!0?!1:!f&&!i.aborted&&n.scope===e&&n.generation===s&&n.signal===i&&n.people===a&&!!s&&s.length<=256&&[t,r,o].every(k=>typeof k=="string"&&!!k&&k.length<=128)&&e.account===t&&e.installation===r&&e.collection===o}catch{return!1}}function b(k){u=w()?k:ho;for(let S of[...d])try{S()}catch{}w()||(u=ho)}function g(){return w()||(u=ho),u}function y(){if(!f){f=!0,i.removeEventListener("abort",y),u=ho;for(let k of[...d])try{k()}catch{}d.clear()}}i.addEventListener("abort",y,{once:!0}),i.aborted&&y();function _(k,S){return!w()||S?.aborted?Promise.reject(bu()):new Promise((x,P)=>{let C=!1,R=(j,B)=>{C||(C=!0,S?.removeEventListener("abort",O),i.removeEventListener("abort",O),d.delete(E),B!==void 0?P(B):x(j))},O=()=>R(void 0,bu()),E=()=>{w()||O()};d.add(E),S?.addEventListener("abort",O,{once:!0}),i.addEventListener("abort",O,{once:!0}),k.then(()=>{!w()||S?.aborted?O():R(g())},()=>R(void 0,bu())),(!w()||S?.aborted)&&O()})}function v(k={}){let S=k.signal;if(!w()||S?.aborted)return Promise.reject(bu());if(m)return Promise.reject(A("unavailable","People readiness READ is occupied","people_readiness_busy"));let x=Promise.resolve().then(async()=>{if(!w())return ho;if(!l||!p)return _a("people_unsupported");try{let C=await l({signal:i});if(!w()||(Hl("identity",{...mE(C),...C.personSettingsUrl===void 0?{}:{person_settings_url:C.personSettingsUrl}}),!w()))return ho;let R=await p({signal:i});return w()?!Array.isArray(R)||R.length>1e3?_a("people_response"):(Hl("members",{members:Array.from(R,O=>({...mE(O),role:O.role}))}),w()?AD:ho):ho}catch{return _a(w()?"people_unavailable":"people_fenced")}});m=x,b(_a(null,!0));let P=x.then(C=>(b(C),g()),()=>(b(_a("people_unavailable")),g())).finally(()=>{m===x&&(m=null)});return _(P,S)}return Object.freeze({getSnapshot:g,subscribe(k){return f?()=>{}:(d.add(k),()=>{d.delete(k)})},start(k={}){return h?_(m??Promise.resolve(g()),k.signal):!w()||k.signal?.aborted?Promise.reject(bu()):(h=!0,v(k))},refresh:v,close:y})}var _a,ho,AD,bu,gE=I(()=>{"use strict";qd();ie();_a=(n,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n===null?null:Object.freeze({code:n})}),ho=_a("people_fenced"),AD=Object.freeze({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null}),bu=()=>A("cancelled","People readiness ended","people_readiness_fenced")});function gg(n){if(!n||!Array.isArray(n.criteria))return Object.freeze([]);let e=n.criteria.filter(t=>t?.event?.id===tm.id&&t.event.version===tm.version&&t.event.digest===tm.digest).map(t=>t.id);return Object.freeze([...new Set(e)])}var C0=I(()=>{"use strict";dd()});function bE(n){let e=n.scope,t=e.account,r=e.installation,o=e.collection,s=n.generation,i=n.signal,a=n.isCurrent.bind(n),c=n.notifications,l=c?.declaration,p=c?.timerNamespace,d=n.timers,u=typeof d?.list=="function"?d.list.bind(d):void 0,f=new Set,h=li(null),m=!1,w=!1,b=null;function g(){try{return m||i.aborted||a()!==!0?!1:!m&&!i.aborted&&n.signal===i&&n.scope===e&&n.generation===s&&!!s&&s.length<=256&&[t,r,o].every(x=>typeof x=="string"&&!!x&&x.length<=128)&&e.account===t&&e.installation===r&&e.collection===o&&n.notifications===c&&c?.declaration===l&&c?.timerNamespace===p&&n.timers===d}catch{return!1}}function y(x){h=g()?x:bg;for(let P of[...f])try{P()}catch{}g()||(h=bg)}function _(){return g()||(h=bg),h}function v(){if(!m){m=!0,i.removeEventListener("abort",v),h=bg;for(let x of[...f])try{x()}catch{}f.clear()}}i.addEventListener("abort",v,{once:!0}),i.aborted&&v();function k(x,P){return!g()||P?.aborted?Promise.reject(wu()):new Promise((C,R)=>{let O=!1,E=(D,J)=>{O||(O=!0,P?.removeEventListener("abort",j),i.removeEventListener("abort",j),f.delete(B),J!==void 0?R(J):C(D))},j=()=>E(void 0,wu()),B=()=>{g()||j()};f.add(B),P?.addEventListener("abort",j,{once:!0}),i.addEventListener("abort",j,{once:!0}),x.then(()=>{!g()||P?.aborted?j():E(_())},()=>E(void 0,wu())),(!g()||P?.aborted)&&j()})}function S(x={}){let P=x.signal;if(!g()||P?.aborted)return Promise.reject(wu());if(b)return Promise.reject(A("unavailable","Notification readiness READ is occupied","notification_readiness_busy"));let C=Promise.resolve().then(async()=>{if(!g())return li("notifications_fenced");if(l===null&&c&&Object.hasOwn(c,"declaration"))return Object.freeze({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null});if(!u&&gg(l).length)return li("notifications_consent_required");if(!l||typeof l!="object"||!u||typeof p!="string"||!/^[A-Za-z0-9._-]{1,64}$/.test(p))return li("notifications_unsupported");try{let O=await u(p,{signal:i});return g()?!O||O.namespace!==p||!Array.isArray(O.timers)||O.timers.length>1e4?li("notifications_response"):li("notifications_unsupported"):li("notifications_fenced")}catch{return li(g()?"notifications_unavailable":"notifications_fenced")}});b=C,y(li(null,!0));let R=C.then(O=>(y(O),_()),()=>(y(li("notifications_unavailable")),_())).finally(()=>{b===C&&(b=null)});return k(R,P)}return Object.freeze({getSnapshot:_,subscribe(x){return m?()=>{}:(f.add(x),()=>{f.delete(x)})},start(x={}){return w?k(b??Promise.resolve(_()),x.signal):!g()||x.signal?.aborted?Promise.reject(wu()):(w=!0,S(x))},refresh:S,close:v})}var kD,li,bg,wu,wE=I(()=>{"use strict";ie();C0();kD=n=>Object.freeze({code:n}),li=(n,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n===null?null:kD(n)}),bg=li("notifications_fenced"),wu=()=>A("cancelled","Notification readiness ended","notification_readiness_fenced")});function AE(n){let e=new Set,t=!1,r=()=>{if(t||!n.isCurrent())return vE;let s=n.declaration;if(!s)return I0;let i;try{i=n.grant()}catch{return SD}return i?s.required.some(a=>!i.actions.includes(a))?_E("files_access_missing"):n.scope==="collection"&&i.scope.kind!=="collection"?_E("files_scope_missing"):I0:I0},o=r();return Object.freeze({getSnapshot:()=>t||!n.isCurrent()?vE:o,subscribe(s){return t?()=>{}:(e.add(s),()=>{e.delete(s)})},async refresh(){let s=r();if(s!==o){o=s;for(let i of[...e])try{i()}catch{}}return o},close(){t=!0,e.clear()}})}var wg,I0,vE,SD,_E,kE=I(()=>{"use strict";wg=n=>Object.freeze(n),I0=wg({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null}),vE=wg({checking:!1,assessment:null,problem:Object.freeze({code:"files_fenced"})}),SD=wg({checking:!1,assessment:null,problem:Object.freeze({code:"files_unavailable"})}),_E=n=>wg({checking:!1,assessment:Object.freeze({status:"incompatible",problem:Object.freeze({code:n})}),problem:null})});var vg,SE=I(()=>{"use strict";g0();cE();hE();gE();wE();C0();yp();Zm();kE();vg=class{constructor(e,t,r,o="block",s=()=>[]){this.typeIssues=o;this.consented=s;this.compiled=e,this.signal=r,this.ui=new Ec(t,r,gg(this.compiled.manifest.notifications)),r.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,r){let o=this.epoch,s=()=>!this.signal.aborted&&!this.closing&&!this.retiring&&this.epoch===o&&r(),i=!!this.opening||!!this.selected||!!this.retiring||!!this.closing,a=this.ui.adopt(e,{caller:t,isCurrent:s});if(i)return a;let c=null,l=[],p=a.then(d=>{if(!s()||t.aborted)throw new ln("application_connection_fenced");let u=this.ui.owned();if(!u)throw new ln("application_connection_binding");let f=Xm(this.compiled);f&&LS(d.files,nO(f,()=>this.consented(d.id)));let h=new AbortController,m=AbortSignal.any([this.signal,h.signal]);c=h;let w=()=>s()&&d.isCurrent(),b={scope:d.scope,generation:d.generation,signal:m,isCurrent:w},g=fE({client:d.records,compiledManifest:this.compiled,journal:u.journal,...b,setupMode:u.setupMode},u.resourceSetup);l.push(()=>g.close());let y={getSnapshot:g.getSnapshot,subscribe:g.subscribe,refresh:g.assess,close:g.close},_=yE({people:d.people,...b});l.push(()=>_.close());let v=this.compiled.manifest.notifications,k=bE({notifications:{declaration:v?.criteria?.length?v:null},timers:d.timers,...b});l.push(()=>k.close());let S=this.compiled.manifest.requirements.files?.scope?.kind,x=AE({declaration:f,scope:typeof S=="string"?S:null,grant:()=>d.files.grant,isCurrent:w});l.push(()=>x.close());let P=this.compiled.nativeCapabilities?{...this.compiled.nativeCapabilities,contracts:this.compiled.manifest.requirements.contracts,typeIssues:this.typeIssues}:null,C=new yg({connection:d,nativeRequirements:P,signal:m,isCurrent:w,configuration:y,files:x,people:_,notifications:k}),R=C.subscribe(this.changed);return this.selected={connection:d,lifetime:h,readiness:C,configuration:g,unsubscribe:R},c=null,l.length=0,this.changed(),d}).catch(async d=>{c?.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===p&&(this.opening=null)});return this.opening=p,p}assess(e={}){return!this.selected||!this.selected.connection.isCurrent()||this.retiring||this.closing?Promise.reject(new ln("application_connection_fenced")):this.selected.readiness.refresh(e)}async configure(e={}){let t=this.selected,r=this.epoch;if(!t||!t.connection.isCurrent()||this.retiring||this.closing)throw new ln("application_connection_fenced");if(await t.configuration.configure(e),e.signal?.aborted||this.epoch!==r||this.selected!==t||!t.connection.isCurrent())throw new ln("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 ln("application_connection_fenced")):t.configuration.plan(e)}async applySetup(e,t={}){let r=this.selected,o=this.epoch;if(!r||!r.connection.isCurrent()||this.retiring||this.closing)throw new ln("application_connection_fenced");if(await r.configuration.apply(e,t),t.signal?.aborted||this.epoch!==o||this.selected!==r||!r.connection.isCurrent())throw new ln("application_connection_fenced");return r.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 r=this.ui.retire(),o=Promise.resolve().then(async()=>{let i=(await Promise.allSettled([r,t?.catch(()=>{}),e?.readiness.close()])).find(a=>a.status==="rejected");if(i?.status==="rejected")throw i.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 O0(n,e){return!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!==e.split(",").sort().join()?Lc():n}function R0(n){(typeof n!="string"||!PD.test(n)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/.test(n))&&Lc()}function PE(n){let e=O0(n,"rpc,action,value");if((!Number.isSafeInteger(e.rpc)||e.rpc<1||e.rpc>4294967295)&&Lc(),e.action==="cancel")e.value!==null&&Lc();else if(e.action==="prepare"){let t=O0(e.value,`requestId,accountId,appId,challenge${Object.hasOwn(e.value,"authorizationId")?",authorizationId":""}`);for(let r of["requestId","accountId","appId"])R0(t[r]);t.authorizationId!==void 0&&R0(t.authorizationId),(typeof t.challenge!="string"||!/^[0-9a-f]{64}$/.test(t.challenge))&&Lc()}else if(e.action==="finish"){let t=O0(e.value,"requestId,authorizationRequestId,collectionId");for(let r of Object.keys(t))R0(t[r])}else Lc();return Object.freeze({...e,value:e.value===null?null:Object.freeze({...e.value})})}var PD,Lc,xE=I(()=>{"use strict";Od();PD=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,Lc=()=>{throw new xe("application_worker_binding")}});function E0(n){if(!n||typeof n!="object"||Array.isArray(n))throw new xe("application_worker_binding");let e=n,t=e.unlock;if(e.status==="needs_unlock"!=(t!=null)||t!=null&&(typeof t!="object"||!["password","strict","none"].includes(t.mode)||typeof t.unlocking!="boolean"||!(t.problem===null||typeof t.problem=="string"&&/^[a-z][a-z0-9_]{0,63}$/.test(t.problem))))throw new xe("application_worker_binding");if(!["not_started","starting","signed_out","authorizing","unselected","opening","setup_required","ready","blocked","closed","needs_unlock"].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))||!(e.unsynced==null||typeof e.unsynced=="object"&&e.unsynced.collectionId===e.selectedCollectionId&&typeof e.unsynced.sessionStatus=="string")||!(e.unsyncedWork==null||typeof e.unsyncedWork=="object"&&Number.isSafeInteger(e.unsyncedWork.since)&&e.unsyncedWork.since>=0))throw new xe("application_worker_binding");return Object.freeze({...e,openingProgress:hm(e.openingProgress)?e.openingProgress:null})}var jc,_g,CE=I(()=>{"use strict";Gv();xE();Od();jc=class extends Error{constructor(t){super("SDK application operation unavailable");this.code=t;this.name="ApplicationWorkerReplyError"}code};_g=class{port;binding;owner;nextId=0;active=null;portal=null;fault=null;stopping=null;stopReply=null;watch=null;closedPortal=null;abandoned=!1;constructor(e,t,r){if(!uI(t))throw new xe("application_worker_binding");this.port=e,this.binding=t,this.owner=Object.freeze({...r}),e.addEventListener("message",this.message),e.addEventListener("messageerror",this.messageError),e.start()}id(){if(this.nextId===Rm)throw new xe("application_worker_stop_failed");return++this.nextId}send(e,t,r){let o=u_([cr,this.binding,e,t,r],this.binding);try{this.port.postMessage(o)}catch{throw this.quarantine("application_worker_unavailable"),this.fault}}request(e,t,r,o){if(this.fault||this.stopping||r.aborted)return Promise.reject(this.fault??new xe("application_worker_fenced"));if(this.active)return Promise.reject(new xe("application_worker_busy"));let s;try{s=this.id(),u_([cr,this.binding,s,e,t],this.binding)}catch(c){return Promise.reject(c)}if(o){if(!["authorize","renewExpiredPairing","requestFileAccess"].includes(e))return Promise.reject(new xe("application_worker_binding"));this.portal?.life.abort(),this.portal&&(this.closedPortal=this.portal.id);try{this.portal?.value.close()}catch{return this.quarantine("application_worker_stop_failed"),Promise.reject(this.fault)}this.portal={id:s,value:o,caller:r,life:new AbortController,lastRpc:0,busy:!1},this.watchPortal()}let i,a=new Promise(c=>{i=c});return new Promise((c,l)=>{let p={id:s,caller:r,done:a,finish:i,resolve:c,reject:l,fenced:!1,reply:!1,handoff:null,cancel:()=>{p.fenced=!0,l(new xe("application_worker_fenced"))}};this.active=p,r.addEventListener("abort",p.cancel,{once:!0});try{this.send(s,e,t)}catch(d){l(d)}r.aborted&&p.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,this.closedPortal=e.id);try{this.send(0,"approvalClosed",!0)}catch{}}},500))}messageError=()=>this.quarantine("application_worker_unavailable");quarantine(e){if(!this.fault){this.fault=new xe(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]!==cr||t[1]!==this.binding||!Number.isInteger(t[3])||t[3]<0||t[3]>Rm)throw new xe("application_worker_binding");if(this.fault)return;let[,,r,o,s]=t;if(r==="nativeSnapshot"){if(o!==0)throw new xe("application_worker_binding");let l=E0(s);this.stopping||this.owner.snapshot(l);return}if(r==="fatal"){if(o!==0)throw new xe("application_worker_binding");this.quarantine("application_worker_stop_failed");return}if(r==="nativeAuthorization"){let l=PE(s),p=this.portal;if(o===this.closedPortal&&p?.id!==o){l.action!=="cancel"&&this.port.postMessage([cr,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!1}]);return}if(!p||p.id!==o||this.stopping||p.caller.aborted||l.rpc<=p.lastRpc)throw new xe("application_worker_fenced");if(p.lastRpc=l.rpc,l.action==="cancel")p.life.abort();else if(p.busy)throw new xe("application_worker_binding");l.action!=="cancel"&&(p.busy=!0);let d=AbortSignal.any([p.caller,p.life.signal]);Promise.resolve().then(()=>{if(!this.owner.nativeAuthorization)throw new xe("application_worker_unavailable");return this.owner.nativeAuthorization(l,p.value,d)}).then(u=>{if(d.aborted||this.portal!==p||this.stopping)throw new xe("application_worker_fenced");this.port.postMessage([cr,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!0,value:u}])},()=>{this.port.postMessage([cr,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!1}])}).catch(()=>{try{this.port.postMessage([cr,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!1}])}catch{}}).finally(()=>{p.busy=!1});return}if(r==="portal"){if(!s||!["navigate","focus","close"].includes(s.action))throw new xe("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(s.action==="focus")try{l.value.focus?.()}catch{}else{if(this.stopping||typeof s.uri!="string"||s.uri.length>8192)throw new xe("application_worker_binding");l.value.navigate(s.uri)}return}if(r==="handoff"&&o===0){if(!s||s.schema!=="mdbn-app-collection/1")throw new xe("application_worker_binding");let l=[s.dataPort,s.controlPort,...s.timerPort?[s.timerPort]:[]];if(l.some(p=>!(p instanceof MessagePort)))throw new xe("application_worker_binding");if(this.stopping||!this.owner.attached){for(let p of l)p.close();return}this.owner.attached(s);return}if(r==="handoff"){let l=this.active;if(!l||l.id!==o||l.reply||l.handoff)throw new xe("application_worker_binding");if(this.stopping){if(!s||s.schema!=="mdbn-app-collection/1")throw new xe("application_worker_binding");for(let p of[s.dataPort,s.controlPort,...s.timerPort?[s.timerPort]:[]]){if(!(p instanceof MessagePort))throw new xe("application_worker_binding");p.close()}l.handoff=Promise.resolve();return}l.handoff=Promise.resolve().then(()=>this.owner.handoff(s,l.caller)),l.handoff.catch(()=>{});return}if(r!=="reply"||!s||typeof s.ok!="boolean"||!s.ok&&(!s.problem||typeof s.problem.code!="string"||s.problem.code.length>128))throw new xe("application_worker_binding");let i=this.stopReply;if(i&&i.id===o){if(s.ok){let l=E0(s.snapshot);if(l.status!=="closed"||l.selectedCollectionId!==null)throw new xe("application_worker_stop_failed");i.resolve()}else i.reject(new xe("application_worker_stop_failed"));return}let a=this.active;if(!a||a.id!==o||a.reply)throw new xe("application_worker_binding");a.reply=!0;let c=s.ok?E0(s.snapshot):null;this.settle(a,c,s.ok?null:Object.freeze({code:s.problem.code}))}catch{this.quarantine("application_worker_binding")}};async settle(e,t,r){try{if(await e.handoff,e.fenced||e.caller.aborted||this.stopping||this.fault)throw this.fault??new xe("application_worker_fenced");if(r)throw new jc(r.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 xe("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 xe("application_worker_fenced"))),this.stopping=Promise.resolve().then(async()=>{if(this.fault)throw new xe("application_worker_stop_failed");this.portal?.life.abort(),this.portal?.value.close(),this.portal=null;let t=this.id();if(await new Promise((r,o)=>{this.stopReply={id:t,resolve:r,reject:o};try{this.send(t,"close",null)}catch(s){o(s)}}),await e?.done,this.fault)throw new xe("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 OE={};Ca(OE,{ApplicationRuntime:()=>T0,ApplicationRuntimeError:()=>jn});function xD(n,e){let t=()=>A("invalid_request","Pass the collection and either { password } or { recoveryKey }.","unlock_secret_invalid");if(typeof n!="string"||!e||typeof e!="object")throw t();let r=Object.hasOwn(e,"password"),o=Object.hasOwn(e,"recoveryKey");if(r===o)throw t();let s=r?e.password:e.recoveryKey;if(typeof s!="string"||!s.length)throw t();let i=new TextEncoder().encode(s);if(i.length>d_)throw i.fill(0),t();return Object.freeze([n,r?"password":"recoveryKey",i])}function IE(n){try{if(!n||!vu.test(String(n.name)))return;let e=o=>typeof o=="string"&&vu.test(o)?o:"-",t=`${n.name}:${e(n.code)}`;typeof n.stage=="string"&&vu.test(n.stage)&&(t+=`@${n.stage}`),n.cause&&vu.test(String(n.cause.name))&&(t+=` cause=${n.cause.name}:${e(n.cause.code)}`);let r=n.server?.status;return Number.isInteger(r)&&r>=100&&r<=599&&(t+=` http=${r}${n.server.code&&vu.test(n.server.code)?`:${n.server.code}`:""}`),t}catch{return}}var jn,vu,q0,T0,RE=I(()=>{"use strict";ie();Od();YR();SE();g0();At();Zm();CE();f_();jn=class extends Error{constructor(t){super("SDK application runtime unavailable");this.code=t;this.name="ApplicationRuntimeError"}code},vu=/^[A-Za-z][A-Za-z0-9_]{0,63}$/;q0=()=>{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})})},T0=class{lifetime=new AbortController;scope;worker;cpOrigin;lab;appName;sourceAdopt=null;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:q0()});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.appName=e.declaration.name,this.lab=ql(e.declaration.environment),this.scope=new vg(e.compiledManifest,{name:e.declaration.name,version:"1"},this.lifetime.signal,e.typeIssues,t=>Qm(this.raw,t)),this.worker=new _g(e.port,e.binding,{snapshot:t=>{this.closed||(this.raw=t,this.followSession(),this.publish())},handoff:(t,r)=>{if(this.sourceAdopt)return this.sourceAdopt(t,r);let o=this.epoch;return this.scope.adopt(t,r,()=>!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,unlock:null}),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 r=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,r,()=>!this.closed&&this.epoch===o).catch(s=>{throw this.portsFailed=e.scope.collection,s}),this.portsFailed=null,this.complete(this.raw,r)},r)).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,r=this.scope.selectedId();if(r!==null&&(r!==t||!e&&this.raw.status!=="opening"&&this.raw.status!=="authorizing")){let o=this.lifetime.signal;this.queue(()=>this.action(async()=>(this.scope.selectedId()===r&&(++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,unlock:null,readiness:q0()});else{let e=this.scope.getReadiness()??q0(),t=this.raw.status,r=this.raw.problem,o,s=this.raw.problemDetail,i=this.raw.selectedCollectionId,a=this.retiring&&e.problem?.code==="readiness_fenced",c=i!==null&&(this.scope.getReadiness()===null||a)&&this.portsFailed!==i;if((t==="ready"||t==="setup_required")&&c)t="opening";else if(t==="ready"||t==="setup_required"){let u=this.assessing&&!e.assessment&&e.problem?.code!=="readiness_fenced";if(t=e.checking||u?"opening":e.assessment?.status==="ready"?"ready":e.assessment?.status==="setup_required"?"setup_required":"blocked",t==="blocked"){let f=e.problem??e.assessment?.problem;r=f?.code??"application_readiness_unavailable",o=f?.detail,s=void 0}}let l=`${r}:${o??IE(s)??""}`;if(t==="blocked"&&r&&l!==this.loggedProblem){this.loggedProblem=l;try{let u=o??IE(s);u?console.error("mdbase application blocked:",r,u):console.error("mdbase application blocked:",r)}catch{}}else t!=="blocked"&&(this.loggedProblem=null);let{problemDetail:p,...d}=this.raw;this.snapshot=Object.freeze({...d,...s?{problemDetail:s}:{},status:t,problem:r,openingProgress:t==="opening"?e.checking?"checking_setup":this.raw.openingProgress??null:null,collections:Object.freeze(this.raw.collections.map(u=>Object.freeze({...u}))),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 jn("application_fenced"));if(this.pending)return Promise.reject(new jn("application_busy"));this.assessing=!0;let r=Promise.resolve().then(async()=>{if(this.closed||t.aborted)throw new jn("application_fenced");let o=await e();if(this.closed||t.aborted)throw new jn("application_fenced");return o}).finally(async()=>{(this.assessing||this.retiring)&&(this.assessing=!1,this.retiring=!1,this.publish()),await this.worker.drain(),this.pending===r&&(this.pending=null)});return this.pending=r,r}async complete(e,t){if(this.closed||t.aborted)throw new jn("application_fenced");let r=!!(e.selectedCollectionId&&this.scope.connection(e.selectedCollectionId));if(this.raw=e,this.assessing=r,this.publish(),r){try{await this.scope.assess({signal:t}).catch(()=>{})}finally{this.assessing=!1}this.publish()}if(this.closed||t.aborted)throw new jn("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={},r=null){let o=this.signal(t);return this.action(async()=>this.complete(await this.worker.request("authorize",r,o,e),o),o).catch(s=>{throw e.close(),s})}authorize(e={}){let t=this.signal(e),r;try{r=Em(qm(this.cpOrigin,t,()=>!this.closed,this.lab))}catch(o){return Promise.reject(o)}return this.authorizeReserved(r,e)}select(e,t={}){let r=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,r):this.snapshot;++this.epoch;let o=this.retireOwn();if(this.publish(),await o,this.closed||r.aborted)throw new jn("application_fenced");return this.complete(await this.worker.request("select",e,r),r)},r)}unlock(e,t,r={}){let o=this.signal(r),s;try{s=xD(e,t)}catch(a){return Promise.reject(a)}let i=()=>{s[2].fill(0)};return this.action(async()=>{if(this.raw.selectedCollectionId!==e||this.raw.status!=="needs_unlock")throw A("invalid_request","This collection is not waiting to be unlocked.","unlock_not_locked");let a;try{a=this.worker.request("unlock",s,o)}finally{i()}return this.complete(await a,o)},o).finally(i)}openUnsynced(e={}){let t=this.signal(e);return this.action(async()=>{let r=this.raw.unsynced?.collectionId??null;if(r!==null&&this.raw.selectedCollectionId===r&&(this.raw.status==="ready"||this.raw.status==="setup_required")&&this.scope.connection(r)?.isCurrent())return this.snapshot.status==="blocked"?this.complete(this.raw,t):this.snapshot;++this.epoch;let o=this.retireOwn();if(this.publish(),await o,this.closed||t.aborted)throw new jn("application_fenced");return this.complete(await this.worker.request("openUnsynced",null,t),t)},t)}async retireUnsynced(e,t,r={}){let o=this.signal(r),s=!0;return await this.queue(()=>this.action(async()=>{try{return this.complete(await this.worker.request("retireUnsynced",[e,t],o),o)}catch(i){if(i instanceof jc&&i.code==="application_worker_busy")return s=!1,this.snapshot;throw i}},o)),s}discardUnsynced(e={}){let t=this.signal(e);return this.action(async()=>{let r=this.raw.unsynced?.collectionId??null,o=r!==null&&this.raw.selectedCollectionId===r;if(o){++this.epoch;let s=this.retireOwn();if(this.publish(),await s,this.closed||t.aborted)throw new jn("application_fenced")}try{return this.complete(await this.worker.request("discardUnsynced",null,t),t)}catch(s){throw o&&s instanceof jc&&s.code==="application_worker_busy"&&!this.closed&&!t.aborted&&this.complete(await this.worker.request("openUnsynced",null,t),t),s}},t)}async withUnsyncedSource(e,t={}){let r=this.signal(t),o=new Ec({name:this.appName,version:"1"},r),s=null;try{if(await this.queue(()=>this.action(async()=>{this.sourceAdopt=(i,a)=>(s=o.adopt(i,{caller:a,isCurrent:()=>!this.closed&&!r.aborted}),s.then(()=>{}));try{await this.worker.request("attachUnsynced",null,r)}finally{this.sourceAdopt=null}return this.snapshot},r)),!s)throw new jn("application_connection_unavailable");return await e(await s,r)}finally{if(await o.close().catch(()=>{}),!this.closed){let i=this.lifetime.signal;await this.queue(()=>this.action(async()=>(await this.worker.request("detachUnsynced",null,i),this.snapshot),i)).catch(()=>{})}}}assess(e={}){let t=this.signal(e);return this.action(async()=>(await this.scope.assess({signal:t}),this.settled()),t).then(r=>r.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 jn("application_fenced")):this.scope.planSetup({...e,signal:t})}applySetup(e,t={}){let r=this.signal(t);return this.action(async()=>(await this.scope.applySetup(e,{signal:r}),this.settled()),r)}cancelAuthorization(e={}){let t=this.signal(e);return this.action(async()=>this.complete(await this.worker.request("cancelAuthorization",null,t),t),t)}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 r=this.signal(t);return this.action(async()=>(this.raw.selectedCollectionId===e&&(++this.epoch,await this.retireOwn()),this.complete(await this.worker.request("forget",e,r),r)),r)}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),r=this.raw.selectedCollectionId,o=e.discard!==!0&&r?HR(this.scope.connection(r)):0;return o>0?Promise.reject(GR(o)):this.action(async()=>(++this.epoch,await this.retireOwn(),this.complete(await this.worker.request("signOut",null,t),t)),t)}deleteCollection(e,t,r={}){let o=this.signal(r);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,r,o,s={}){let i=this.signal(s);return this.action(async()=>(this.raw=await this.worker.request("requestFileAccess",[t,r,o],i,e),this.publish(),this.snapshot),i).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 jn("application_stop_failed")}),this.publish(),this.closing)}}});var GD={};Ca(GD,{ACCOUNT_KEY_STATES:()=>Fb,API_VERSIONS:()=>df,AppHost:()=>B0,COLLECTION_UNAVAILABLE_REASONS:()=>vw,CborError:()=>Me,Client:()=>Tf,DESCRIBE_TYPING_MAX_PATHS:()=>tp,DESCRIBE_TYPING_MAX_TYPES:()=>ep,DEVICE_KINDS:()=>Bb,ERROR_CODES:()=>_u,FilesApi:()=>Na,Float64:()=>vt,HOLD_COMPARE_SCHEME:()=>Rp,HOLD_TITLE:()=>Op,IkInitiator:()=>oc,IkResponder:()=>Iy,LiveQuery:()=>Va,MAX_CONVENIENCE_BYTES:()=>uf,MAX_DEPTH:()=>qg,MDBASE_NOTIFICATION_CLICK:()=>mw,MDBASE_NOTIFICATION_TYPE:()=>Ip,MdbaseClient:()=>yi,MdbaseError:()=>oe,MdbasePeopleClient:()=>gi,NoiseError:()=>gt,PERSON_CONTRACT:()=>cw,PROBLEM_CODES:()=>px,PresenceApi:()=>Ba,READ_MANY_MAX_CONCURRENCY:()=>Hb,READ_MANY_MAX_REFS:()=>Wb,RecordReader:()=>dp,RecordSet:()=>$a,SESSION_LIFETIME_MS:()=>cA,SLOW_OPENING_MS:()=>Jf,SchemaError:()=>ae,Session:()=>Cs,TEMPORAL_HINTS:()=>Wu,TimersApi:()=>Fa,WasmRuntime:()=>Xl,Write:()=>Rs,applicationPhase:()=>qp,approvalReadiness:()=>zS,bytesEqual:()=>Mg,clientPrologue:()=>Ti,collectionUnavailableError:()=>Vn,compareVersions:()=>Sw,connect:()=>lw,controlRouteResolver:()=>BE,createMdbase:()=>ME,createViewSource:()=>kf,decode:()=>we,describeDiagnostic:()=>Wf,describeError:()=>Ts,describeHold:()=>ex,diffEdits:()=>ef,duplexCarrier:()=>uA,effectiveCapabilities:()=>LE,encode:()=>ue,encodeSecret:()=>Nn,fileGrant:()=>$b,formatSas:()=>VS,framedPort:()=>af,fromHex:()=>Bi,generateKeyPair:()=>sc,handleMdbaseNotificationClick:()=>QP,handleMdbasePush:()=>XP,holdCompareLink:()=>ww,holdNotice:()=>tx,inProcessConnector:()=>Jl,indexedDbKeyStorage:()=>D0,isCollectionUnavailableReason:()=>Wa,isConfirmed:()=>DP,isErrorCode:()=>vo,isMdbaseError:()=>X,isProtected:()=>Yi,isReadyPhase:()=>gx,isValid:()=>fq,keyPairFromSecret:()=>_R,loadOrCreateClientKey:()=>$E,localLinkConnector:()=>UE,localLinkFirstPayload:()=>U0,mdbaseError:()=>A,memoryKeyStorage:()=>N0,memoryWriteLedgerStore:()=>Cf,nextRelayConnector:()=>CR,noiseChannel:()=>pA,noiseConnector:()=>Mi,orderTargets:()=>Zd,parseCollectionAvailability:()=>wr,parseHoldCompareLink:()=>ZP,parseMdbaseNativeNotification:()=>yw,parseMdbasePush:()=>Nf,parseVersion:()=>Ja,pipeCloseError:()=>ca,portPair:()=>kS,problemCodeOf:()=>Aw,queryPages:()=>mf,readMany:()=>hf,readMdbaseNotificationData:()=>gw,readViewSourceRecord:()=>Af,recoveryFor:()=>sq,relayConnector:()=>jE,relayPipeCarrier:()=>cc,resolveRecordLinks:()=>ZS,revisionOf:()=>Dr,routeFromControl:()=>z0,sameIdentity:()=>jf,showMdbaseNotification:()=>bw,staticKeyOf:()=>xy,streamCarrier:()=>kR,structMap:()=>Tg,summarizeSync:()=>Mf,syncStatusText:()=>nx,toHex:()=>ut,toPlain:()=>gr,toValue:()=>Xe,updateViewSource:()=>Sf,uuidv7:()=>zr,valueEquals:()=>Io,versionRelation:()=>Ms,webSocketCarrier:()=>ac,wire:()=>wb});ie();Zt();Zt();Es();gf();Gb();Xb();Zb();yp();yp();ew();Ye();mi();ff();var ST=["collection_not_yet_migrated","collection_migrating","update_required","account_suspended"];function Mf(n){let e=n.status,t=e.mode==="local_only",r=n.writes??null,o=Math.max(e.pending,r?.pending.length??0),s=!t&&n.transport?n.transport.kind:null,i=n.link===void 0||n.link==="open",a=i?t?"local":n.online===!1||s==="offline"?"offline":s?"reconnecting":e.connection==="offline"?"offline":e.connection==="connecting"?"reconnecting":"online":"reconnecting",c=[],l=t?void 0:ST.find(f=>f===n.problem);l&&c.push(l),r?.rejected.length&&c.push("rejected"),e.unresolved>0&&c.push("conflicts"),e.holds>0&&c.push("held"),e.incidents.length&&c.push("incident"),o>0&&n.storageWarning&&c.push("storage_may_be_evicted");let p=a==="offline"||s!==null||!i,d=c.length?"attention":o>0&&p?"saved_on_device":a==="offline"?"offline":a==="reconnecting"?"reconnecting":o>0?"saving":!t&&(e.installing!==void 0||e.resyncing!==void 0||e.confirmedThrough<e.headKnown)?"catching_up":"saved",u=n.pendingForMs;return{state:d,connection:a,health:s,live:t||typeof n.live!="boolean"?null:n.live,pending:o,pendingFor:o===0?null:u===void 0?"while":u<2e3?"moment":u<3e4?"while":"long",writes:r,attention:c,conflicts:e.unresolved,holds:e.holds,incidents:e.incidents}}function DP(n){return n.state==="confirmed"}iw();Sp();fw();ie();var Ip="mdbase.notification",mw="mdbase.notification.click",WP=/^[\x21-\x7e]{1,256}$/,qT=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Eo=n=>A("invalid_request",n,"invalid_push_payload"),TT=()=>A("upgrade_required","The push uses an envelope version this SDK does not support.","unsupported_push_version");function GP(n){if(typeof n=="string")try{n=JSON.parse(n)}catch{throw Eo("The push payload is not JSON.")}else if(n&&typeof n=="object"&&typeof n.json=="function")try{n=n.json()}catch{throw Eo("The push payload is not JSON.")}if(!n||typeof n!="object"||Array.isArray(n))throw Eo("The push payload is not an object.");return n}function Ka(n,e,t){return typeof n=="string"&&n.length>=e&&n.length<=t}function YP(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n;return!Ka(e.title,1,80)||e.body!==void 0&&!Ka(e.body,0,160)||e.tag!==void 0&&!Ka(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 JP(n,e,t){if(n.type!==Ip)throw Eo("The payload is not an mdbase notification.");if(e!==1)throw typeof e=="number"&&Number.isSafeInteger(e)&&e>1?TT():Eo("The payload has no valid envelope version.");if(!Ka(n.signal_id,1,256)||!WP.test(n.signal_id)||!Ka(n.cursor,1,256)||!WP.test(n.cursor)||!Ka(n.criterion_id,1,100)||!qT.test(n.criterion_id))throw Eo("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 Nf(n){let e=GP(n),t=JP(e,e.version,YP(e.presentation));if(!t.presentation)throw Eo("The push has no valid presentation.");return t}function yw(n){if(!n||typeof n!="object"||Array.isArray(n))throw Eo("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 JP(e,t,null)}function gw(n){try{return yw(n)}catch{return null}}function MT(n){return{type:Ip,version:n.version,signal_id:n.signalId,criterion_id:n.criterionId,cursor:n.cursor}}async function bw(n,e,t={}){let r=Nf(e),o=r.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:MT(r)}),r}function hw(n){return globalThis[n]}function LT(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 HP(n,e,t){let r=()=>A("invalid_request",`The notification click ${t} must be on the app's own origin.`,"click_target_cross_origin");if(typeof n!="string")throw r();if(e===null){if(!n.startsWith("/")||n.startsWith("//")||n.startsWith("/\\"))throw r();return n}let o;try{o=new URL(n,`${e}/`)}catch{throw r()}if(o.origin!==e)throw r();return o.href}function XP(n,e={}){let t;try{t=GP(n.data?.text()??null)}catch{return!1}if(t.type!==Ip)return!1;let r=e.registration??hw("registration");if(!r)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{Nf(t)}catch(s){let i=s instanceof oe&&s.reason==="unsupported_push_version"?YP(t.presentation):null;if(!i)throw s;return await r.showNotification(i.title,{...i.body?{body:i.body}:{},...i.tag?{tag:i.tag}:{},...o}),null}return bw(r,t,o)})()),!0}function QP(n,e={}){let t=gw(n.notification.data);if(!t)return!1;n.notification.close();let r=e.clients??hw("clients"),o=hw("registration")?.scope,s=LT(o),i=e.scope===void 0?o:HP(e.scope,s,"scope"),a=e.url===void 0?i??"/":HP(e.url,s,"url");return r&&n.waitUntil((async()=>{let l=(await r.matchAll({type:"window",includeUncontrolled:!0})).find(d=>!i||d.url.startsWith(i));if(!l)return r.openWindow(a);await l.focus();let p={type:mw,notification:t};return l.postMessage(p),l})()),!0}var Op="mdbase protected your edit",jT={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."}},UT={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}},NT={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"]},Rp="mdbase://hold/compare",Df=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ww(n,e){if(!Df.test(n)||!Df.test(e))throw new Error("holdCompareLink: collection and id are UUIDs");return`${Rp}?collection=${n.toLowerCase()}&id=${e.toLowerCase()}`}function ZP(n){if(typeof n!="string"||n.length>512||!n.startsWith(`${Rp}?`))return null;let e=new URLSearchParams(n.slice(Rp.length+1)),t=e.get("collection")??"",r=e.get("id")??"";return!Df.test(t)||!Df.test(r)?null:{collectionId:t.toLowerCase(),id:r.toLowerCase()}}function ex(n,e){let t=n.reason==="read_only",r=n.theirs!==void 0,o=(e.canCompare??!0)&&r,s=c=>!c||!e.capabilities||e.capabilities.includes(c),i=NT[n.reason].filter(c=>c==="compare"?o:(!t||e.host===!0)&&(c!=="take_theirs"||r||t)).map(c=>{let l={action:c,...UT[c]};return t&&c==="take_theirs"&&(l.label="Discard local changes",l.description="Discard unsynced changes on this device.",l.needs="collection.read"),l}).filter(c=>s(c.needs)),a=jT[n.reason];return{id:n.id,path:n.path,reason:n.reason,title:Op,cause:a.cause,detail:a.detail,since:n.since,saves:n.saves,hasTheirs:r,actions:i,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?ww(e.collectionId,n.id):null}}function tx(n){return n.length?n.length===1?`${Op}: ${n[0].path} is waiting for your choice.`:`${Op}: ${n.length} files are waiting for your choice.`:null}function nx(n){let e=(r,o)=>`${r} ${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}`}Ep();Gf();Ep();var Jf=15e3,Yf=(n,e)=>{try{return!!n&&n.id===e&&n.isCurrent()}catch{return!1}},Ls=(n,e)=>Ts(n,e),Zi=(n,e)=>Ls(n,e);function qp(n,e={}){let t=oM(n,e),r=sM(t,n,e);return r.kind==="opening"&&n.status==="opening"&&n.selectedCollectionId===r.collectionId&&n.openingProgress?{...r,progress:n.openingProgress}:r}function oM(n,e){let t={...e.cpOrigin?{cpOrigin:e.cpOrigin}:{},...e.messages?{messages:e.messages}:{}},r=n.selection,o=r?.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:Zi(n.problem,t)};if(r?.state==="invalid")return{kind:"problem",collectionId:null,problem:Zi(r.problem??"application_selection_invalid",t)};let s=n.signIn?.state==="paired";if(r?.state==="approving"||n.status==="authorizing"){let p=r?.approval??null;return s?p?.kind==="add"?{kind:"authorizing",purpose:"add",collectionId:null}:{kind:"authorizing",purpose:"approve",collectionId:p?.collectionId??o?.collectionId??null}:{kind:"authorizing",purpose:"sign_in",collectionId:p?.collectionId??o?.collectionId??null}}let i=n.unsynced??null;if(i&&n.selectedCollectionId===i.collectionId){let p=i.collectionId;return n.status==="ready"&&Yf(e.connection,p)?{kind:"unsynced",collectionId:p,connection:e.connection,rechecking:n.readiness.checking}:n.status==="blocked"||n.status==="setup_required"&&!n.readiness.checking&&n.readiness.assessment?{kind:"problem",collectionId:p,problem:(n.status==="blocked"?Ls(n,t):Ls(n.readiness,t))??Zi("open_failed",t)}:{kind:"opening",collectionId:p,displayName:null,slow:!!e.slow}}if(n.status==="not_started"||n.status==="starting"){let p=o?.collectionId??null;return p&&n.status==="starting"?{kind:"opening",collectionId:p,displayName:o?.displayName??null,slow:!!e.slow}:{kind:"starting"}}if(n.status==="signed_out")return e.openingUnsynced&&!n.problem?{kind:"starting"}:{kind:"signed_out",notice:n.problem?Ls(n,t):null};if(n.status==="blocked"){let p=n.selectedCollectionId??o?.collectionId??null;return n.problem==="recovery_account_mismatch"?{kind:"problem",collectionId:p,problem:Ts(n,{...t,recoveryAccountLabel:n.recoveryAccountLabel})}:{kind:"problem",collectionId:p,problem:p&&n.removedScopeIds?.includes(p)?Zi("installation_scope_removed",t):Ls(n,t)??Zi("open_failed",t)}}if(n.status==="needs_unlock"&&n.selectedCollectionId){let p=n.selectedCollectionId,d=n.unlock??null;return d?{kind:"needs_unlock",collectionId:p,displayName:n.collections.find(u=>u.collectionId===p)?.displayName??o?.displayName??null,mode:d.mode,unlocking:d.unlocking,problem:d.problem===null?null:Ls(d.problem,t)??Zi("unlock_failed",t)}:{kind:"problem",collectionId:p,problem:Zi("open_failed",t)}}if(r?.state==="approval_required"&&o?.collectionId&&n.removedScopeIds?.includes(o.collectionId))return{kind:"problem",collectionId:o.collectionId,problem:Zi("installation_scope_removed",t)};if(r?.state==="approval_required"&&o?.collectionId)return{kind:"needs_approval",collectionId:o.collectionId,displayName:o.displayName,declined:r.problem==="application_selection_not_approved"};if(r?.state==="pending"&&o?.collectionId)return{kind:"opening",collectionId:o.collectionId,displayName:o.displayName,slow:!!e.slow};let a=r?.usable??(n.status==="ready"||n.status==="setup_required"?n.collections.find(p=>p.collectionId===n.selectedCollectionId)??null:null);if(n.status==="setup_required"&&a)return n.readiness.assessment?.status==="incompatible"?{kind:"problem",collectionId:a.collectionId,problem:Ls(n.readiness,t)??Zi("incompatible",t)}:{kind:"needs_setup",collectionId:a.collectionId,collection:a};if(n.status==="ready"&&a&&Yf(e.connection,a.collectionId))return{kind:"ready",collectionId:a.collectionId,collection:a,connection:e.connection,rechecking:n.readiness.checking,problem:null,unavailableTypes:n.readiness.assessment?.unavailableTypes??[]};let c=n.status==="opening"||n.status==="ready"||r?.state==="opening"||r?.state==="usable",l=n.selectedCollectionId??o?.collectionId??null;if(c&&l){let p=n.collections.find(d=>d.collectionId===l)?.displayName??o?.displayName??null;return{kind:"opening",collectionId:l,displayName:p,slow:!!e.slow}}return e.startPending&&s&&n.status==="unselected"&&!n.problem&&r?.state==="none"?{kind:"starting"}:{kind:"choosing",lastApproval:r?.lastApproval??null}}function sM(n,e,t){let r=t.previous;return r?.kind==="needs_setup"&&n.kind==="opening"&&n.collectionId===r.collectionId&&e.selectedCollectionId===r.collectionId&&e.readiness.checking?r:r?.kind==="unsynced"&&n.kind==="opening"&&n.collectionId===r.collectionId&&e.selectedCollectionId===r.collectionId&&Yf(t.connection,r.collectionId)?{...r,connection:t.connection,rechecking:!0}:!r||r.kind!=="ready"||n.kind==="ready"||!Yf(t.connection,r.collectionId)||e.selectedCollectionId!==r.collectionId?n:n.kind==="opening"&&n.collectionId===r.collectionId?{...r,connection:t.connection,rechecking:!0,problem:null}:n.kind==="problem"&&n.problem.transient?{...r,connection:t.connection,rechecking:!0,problem:n.problem}:n}function gx(n,e){return n?.kind==="ready"&&(e===void 0||n.collectionId===e)}Tl();Ep();tn();am();At();var UL=["http","https","file","javascript","data","blob","about","capacitor","chrome-extension","moz-extension"];function Vv(n,e){if(typeof n!="string"||!n||n.length>2048||n.includes("*"))return!1;let t=e&&typeof e=="object"?e.redirect_uris:void 0;if(!Array.isArray(t)||!t.includes(n))return!1;let{id:r,homepage:o}=e,s;try{s=new URL(n)}catch{return!1}if(s.username||s.password||s.hash)return!1;if(s.protocol==="https:"||s.protocol==="http:"){let a;try{a=new URL(String(o))}catch{return!1}return s.origin===a.origin&&(s.protocol==="https:"||Ze(s.origin))}let i=s.protocol.slice(0,-1);return typeof r=="string"&&i.includes(".")&&/^[a-z][a-z0-9+.-]*$/.test(i)&&!UL.includes(i)&&(i===r||i.startsWith(`${r}.`))&&s.hostname.length>0}um();tn();ie();At();var Ir=n=>A("unavailable","application asset unavailable",n),BL=()=>A("cancelled","application asset read fenced","application_asset_fenced");function xi(n){if(n.aborted)throw BL()}function q1(n,e){let t=Object.freeze({...n}),r=Object.freeze({...e}),o,s;try{o=new URL(t.url),s=new URL(r.origin)}catch{throw Ir("application_asset_binding")}if(!dt(r.origin)||s.protocol!==o.protocol||!Go(r.environment)||Pi(r.environment)&&!Yo(r.origin)||kt(o)!==r.origin||o.username||o.password||o.search||o.hash||!/^[0-9a-f]{64}$/.test(t.sha256)||!Number.isSafeInteger(t.bytes)||t.bytes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<t.bytes||t.maxBytes>4*1024*1024)throw Ir("application_asset_binding");let i=r.fetch??globalThis.fetch;if(typeof i!="function")throw Ir("application_asset_unavailable");let a=new URL(o.href);return a.searchParams.set("mdbase-sdk-asset",t.sha256),async({signal:c})=>{xi(c);let l=null,p;try{globalThis.caches&&(l=await globalThis.caches.open("mdbase.sdk.application-assets.v1"),p=await l.match(a.href))}catch{}let d=p!==void 0;if(!p){xi(c);try{p=await i(o.href,{signal:c,credentials:"omit",cache:"force-cache",redirect:"error"})}catch{throw xi(c),Ir("application_asset_fetch")}}let u=p.body?.getReader();if(!u)throw xi(c),Ir("application_asset_response");let f=!1,h=null,m=()=>h??=Promise.resolve().then(async()=>{try{await u.cancel()}catch{throw Ir("application_asset_stop_failed")}}),w=()=>{m().catch(()=>{})};c.addEventListener("abort",w,{once:!0});try{if(xi(c),!p.ok||p.redirected||p.url&&p.url!==o.href)throw Ir("application_asset_response");let b=p.headers.get("content-length"),g=p.headers.get("content-encoding");if(b!==null&&(g===null||g.trim().toLowerCase()==="identity")&&(!/^(?:0|[1-9][0-9]*)$/.test(b)||Number(b)!==t.bytes))throw Ir("application_asset_binding");let y=new Uint8Array(t.bytes),_=0;for(;;){let k=await u.read();if(xi(c),k.done){f=!0;break}if(!(k.value instanceof Uint8Array)||k.value.byteLength>t.bytes-_)throw Ir("application_asset_binding");y.set(k.value,_),_+=k.value.byteLength}if(_!==t.bytes)throw Ir("application_asset_binding");let v=new Uint8Array(await crypto.subtle.digest("SHA-256",y));if(xi(c),Array.from(v,k=>k.toString(16).padStart(2,"0")).join("")!==t.sha256)throw Ir("application_asset_binding");if(xi(c),l&&!d)try{await l.put(a.href,new Response(y))}catch{}return xi(c),y}catch(b){throw xi(c),X(b)?b:Ir("application_asset_response")}finally{c.removeEventListener("abort",w);try{(!f||c.aborted)&&await m()}finally{u.releaseLock()}}}}Xo();tn();ie();lm();At();var Bs={runtime:{sha256:"87dbf3a587668ef2238aee243b1ab904c34845a40c0e39373371d3932d80fd9e",bytes:4070902,maxBytes:4070902,source:{repository:"mdbase-dev/mdbase-connect",commit:"10cb483f38b359d22c8d90892b99361381590050"}},sqlite:{sha256:"2ee8f3dab694532afc8840e07703127287662d08b74e6ff50491ce63f00d5752",bytes:868907,maxBytes:11e5,initializer:{sha256:"a6d3fe46aa3f924e7686329f97b0564549ef1f787e0c19924179aef7f72bcc01",bytes:642742},asyncProxy:{sha256:"9f1970e05ee07a79332498858740b705eeb1dcee03bc150f6f690bc0fb5f0a06",bytes:32505}}};var fm={},FL=Object.freeze({sha256:Bs.runtime.sha256,bytes:Bs.runtime.bytes,maxBytes:Bs.runtime.maxBytes}),KL=Object.freeze({sha256:Bs.sqlite.sha256,bytes:Bs.sqlite.bytes,maxBytes:Bs.sqlite.maxBytes}),gd=()=>A("unavailable","SDK packaged application assets unavailable","application_packaged_assets_unavailable");function T1(n,e,t){if(!Go(n))throw gd();let r=$s();Cr({environment:n,appOrigin:e,release:r});let o,s;try{let c=new URL(t??fm.url);if(kt(c)!==e||c.username||c.password||(o=t===void 0?new URL("../native/runtime.wasm",fm.url):new URL("../native/runtime.wasm",c),s=t===void 0?new URL("../native/sqlite3.wasm",fm.url):new URL("../native/sqlite3.wasm",c),kt(o)!==e||kt(s)!==e))throw gd()}catch{throw gd()}let i=(c,l)=>Object.freeze({url:c.href,...l}),a=async c=>{let l=globalThis.WorkerGlobalScope;if(typeof l!="function"||!(globalThis instanceof l))throw gd();let p=t===void 0?new URL("../native/sqlite3.js",fm.url):new URL("../native/sqlite3.js",t),{default:d}=await import(p.href);return globalThis.sqlite3ApiConfig={disable:{vfs:{opfs:!0,"opfs-wl":!0}}},d(c)};return Object.freeze({release:()=>$s(),runtime:i(o,FL),sqlite:i(s,KL),initializeSqlite:a})}Gv();vb();var HL="mdbase:startup:",GL=new Set(["signed_out","authorizing","choosing","needs_approval","needs_setup","problem","unavailable","closed"]);function YL(){let n=globalThis.performance;return typeof n?.now=="function"&&typeof n.measure=="function"?n:null}var mm=class{clock=YL();began=this.clock?.now()??0;stage=null;since=this.began;done=this.clock===null;measure(e,t,r){try{this.clock?.measure(`${HL}${e}`,{start:t,end:r})}catch{}}async time(e,t){if(this.done)return t();let r=this.clock.now();try{return await t()}finally{this.measure(e,r,this.clock.now())}}observe(e){if(this.done)return;let t=e.kind==="opening"&&e.progress?`opening:${e.progress}`:e.kind;if(t===this.stage)return;let r=this.clock.now();this.stage!==null&&this.measure(this.stage,this.since,r),this.stage=t,this.since=r;let o=e.kind==="ready"||e.kind==="unsynced";o&&this.measure("total",this.began,r),(o||GL.has(e.kind))&&(this.done=!0)}};function M1(n,e,t){if(n.requested.collectionId!==null){let r=n.requested.collectionId!==t?.selection.requested.collectionId;r&&vs("mdbase:open:requested"),n.requested.approved&&(r||!t?.selection.requested.approved)&&vs("mdbase:open:approved")}e.kind==="opening"&&hm(e.progress)&&(t?.phase.kind==="opening"&&t.phase.collectionId===e.collectionId?t.phase.progress:null)!==e.progress&&vs(`mdbase:open:stage:${e.progress}`),e.kind==="ready"&&(t?.phase.kind!=="ready"||t.phase.connection!==e.connection)&&vs("mdbase:open:ready")}lm();At();Xo();tn();var hn=class extends Error{constructor(t){super("SDK collection selection unavailable");this.code=t;this.name="ApplicationSelectionError"}code},bd=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",fn=(n,e,t=null)=>Object.freeze({requestedCollectionId:n,source:e,problem:t});function L1(n,e){return n.source!=="none"?n:e.storedId!==void 0&&e.storedId!==null?bd(e.storedId)?fn(e.storedId,"stored"):fn(null,"stored","application_selection_invalid"):e.collections.length>1024||e.collections.some(t=>!bd(t.collectionId))||new Set(e.collections.map(t=>t.collectionId)).size!==e.collections.length?fn(null,"none","application_selection_metadata"):e.preferredId!==void 0&&e.preferredId!==null?bd(e.preferredId)&&e.collections.some(t=>t.collectionId===e.preferredId)?fn(e.preferredId,"preferred"):fn(null,"preferred","application_selection_metadata"):e.collections.length===1?fn(e.collections[0].collectionId,"sole"):fn(null,"none")}var ym=class{port;origin;parameter;fallback;listeners=new Set;snapshot=fn(null,"none");stopListening=null;started=!1;closed=!1;constructor(e,t={},r=null){let o,s;try{o=new URL(e),s=new URL(t.fallbackPath??"/",o)}catch{throw new hn("application_selection_binding")}let i=t.parameter??"collection";if(!dt(e)||kt(o)!==e||kt(s)!==e||s.username||s.password||s.search||s.hash||typeof i!="string"||!/^[a-z][a-zA-Z0-9_.-]{0,63}$/.test(i)||["code","state","error","error_description"].includes(i))throw new hn("application_selection_binding");this.origin=e,this.parameter=i,this.fallback=s.href,this.port=r}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 hn("application_selection_fenced")}url(){let e;try{e=new URL(this.port.href())}catch{throw new hn("application_selection_binding")}if(kt(e)!==this.origin||e.username||e.password)throw new hn("application_selection_binding");return e}read(){if(!this.port)return fn(null,"none");let e;try{e=this.url().searchParams.getAll(this.parameter)}catch{return fn(null,"url","application_selection_binding")}return e.length===0?fn(null,"none"):e.length!==1?fn(null,"url","application_selection_duplicate"):e[0]===""?fn(null,"url","application_selection_empty"):bd(e[0])?fn(e[0],"url"):fn(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&&!bd(e))throw new hn("application_selection_invalid");let r=t.history??"replace";if(r!=="push"&&r!=="replace")throw new hn("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,r)}return this.publish(fn(e,e===null?"none":"user")),this.snapshot}returnUrl(e){this.check();try{let t=new URL(e,this.origin);if(kt(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 j1(){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 JL=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",Ml=n=>n.status==="ready"||n.status==="setup_required",Ll=n=>n.status==="needs_unlock",U1=n=>n.signIn?.state==="paired"&&(n.status==="unselected"||n.status==="blocked"||Ml(n)||Ll(n)),XL=n=>n.status==="not_started"||n.status==="starting"||n.status==="signed_out"||n.status==="authorizing",Ci=(n,e)=>e===null?null:n.collections.find(t=>t.collectionId===e)??null,gm=class{browser;session;memory;preferredId;schedule;listeners=new Set;stops=[];value;key="";startTarget=null;startApplied=!1;startHeld=!0;failed=null;before=null;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=this.keyOf(this.value)}startPending(){return this.startHeld}keyOf(e){return JSON.stringify(e)+(this.startHeld?"|start":"")}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 r=this.session.getSnapshot();return e!==null&&r.selectedCollectionId===e&&r.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&&(Ml(o)||Ll(o))||!Ci(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&&!JL(e))return Promise.reject(new hn("application_selection_invalid"));if(this.approval&&!this.approval.settled)return Promise.reject(new hn("application_selection_busy"));e!=null&&e!==this.requested().requestedCollectionId&&(this.startTarget=null,this.browser.select(e,t.history?{history:t.history}:{}));let r=this.session.getSnapshot().signIn,o=r?.nativeSelection?.requestId??r?.collectionSelection?.requestId??null,s,i=e===null?null:this.requested().requestedCollectionId;try{s=this.session.authorize({...t.signal?{signal:t.signal}:{},collectionHint:i})}catch(p){return Promise.reject(p)}let a=i===null?"add":"collection",c=new Set(this.session.getSnapshot().collections.map(p=>p.collectionId)),l={receipt:o,kind:a,collectionId:i,before:c,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),p=>{if(this.approval===l){this.approval=null;let d=p?.code;(d==="cancelled"||d==="aborted")&&(this.lastApproval=Object.freeze({kind:a,outcome:"closed",collectionId:i}))}throw this.changed(),p})}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 hn("application_selection_empty")):this.approve(t,e)}resync(){this.closed||(this.attempted=void 0,this.failed=null,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 hn("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;if(e!==this.lastRequested&&(this.lastRequested=e,this.attempted=void 0,this.failed=null,this.declined!==e&&(this.declined=null)),e!==null&&this.attempted===e){let o=this.session.getSnapshot();o!==this.before&&(o.status==="blocked"?o.selectedCollectionId===e:o.status==="unselected"&&o.problem!==null)&&(this.failed=e)}let t=this.derive(),r=this.keyOf(t);if(t.state==="usable"&&this.remember(t.usable.collectionId),r!==this.key){this.key=r,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(),r=t.requestedCollectionId,o=Ci(e,r),s=Ml(e)?Ci(e,e.selectedCollectionId):null,i,a=null;t.problem?(i="invalid",a=t.problem):this.approval?i="approving":r===null?i="none":s?.collectionId===r?i="usable":e.selectedCollectionId===r&&(e.status==="blocked"||e.status==="opening"||Ll(e))?i=e.status==="blocked"?"blocked":"opening":U1(e)?o?i="opening":this.session.listing?.()?i="pending":(i="approval_required",this.declined===r&&(a="application_selection_not_approved")):i="pending";let c=this.approval?Object.freeze({kind:this.approval.kind,collectionId:this.approval.collectionId,reopenable:this.approval.settled}):null;return Object.freeze({state:i,problem:a,approval:c,lastApproval:this.lastApproval,usable:s?Object.freeze({...s}):null,requested:Object.freeze({collectionId:r,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={},r=!1){this.attempted=e,this.failed=null,this.before=this.session.getSnapshot();let o=t.signal?{signal:t.signal}:{},s=Promise.resolve().then(()=>e===null?this.session.clear(o):this.session.open(e,o)),i=s.then(()=>{},()=>{}).finally(()=>{this.opening===i&&(this.opening=null,this.changed())});return this.opening=i,r?s.then(()=>{}):i}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||e.approval?.outcome==="closed")){let o=this.approval;this.approval=null,this.attempted=void 0,this.lastApproval=Object.freeze({kind:o.kind,outcome:e.problem==="approval_window_closed"||e.approval?.outcome==="closed"?"closed":"declined",collectionId:o.collectionId}),this.refresh()}else{if(!this.approval.settled||XL(e))return;let o=e.signIn?.nativeSelection;if(o&&o.requestId!==this.approval.receipt&&!Ci(e,o.collectionId)&&this.session.listing?.())return;this.finishApproval(e)}if(!U1(e))return;if(!this.startApplied){if(this.browser.getSnapshot().source==="none"){let o=null;try{o=this.memory?.read()??null}catch{}if(o!==null&&!Ci(e,o)&&this.session.listing?.()){this.startHeld=!1,this.refresh();return}this.startApplied=!0;let s=L1(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)}else this.startApplied=!0;this.startHeld=!1,this.refresh()}let t=this.requested(),r=t.requestedCollectionId;if(!t.problem){if(r===null){this.attempted!==null&&e.selectedCollectionId!==null&&(Ml(e)||Ll(e))&&this.run(null);return}if(e.selectedCollectionId===r&&(Ml(e)||Ll(e)||e.status==="opening")){this.attempted=r,this.failed=null;return}if(e.selectedCollectionId===r&&e.status==="blocked"){this.failed=r;return}Ci(e,r)&&(this.attempted===r&&(this.failed!==r||e.status!=="unselected"||e.problem!==null)||(this.failed=null,this.run(r)))}}finishApproval(e){let t=this.approval,r=t.receipt;this.approval=null,this.attempted=void 0;let o=u=>u!==null&&Ci(e,u)?t.before.has(u)?"unchanged":"added":e.approval?.outcome==="closed"?"closed":"declined",s=e.signIn?.collectionSelection,i=e.signIn?.nativeSelection,c=(i&&i.requestId!==r&&Ci(e,i.collectionId)?i.collectionId:null)??(s&&s.requestId!==r&&Ci(e,s.selectedCollectionId)?s.selectedCollectionId:null);if(c!==null){c!==this.requested().requestedCollectionId&&(this.startTarget=null,this.browser.select(c,{history:"replace"})),this.lastApproval=Object.freeze({kind:t.kind,outcome:o(c),collectionId:c}),this.refresh(),e.selectedCollectionId===c&&(Ml(e)||Ll(e)||e.status==="opening")?this.attempted=c:this.run(c);return}let l=this.requested().requestedCollectionId;l!==null&&!Ci(e,l)&&(this.declined=l);let p=t.kind==="add"?e.collections.find(u=>!t.before.has(u.collectionId))?.collectionId??null:null,d=t.kind==="add"?p:t.collectionId??l;this.lastApproval=Object.freeze({kind:t.kind,outcome:o(d),collectionId:d}),this.refresh()}};Od();f_();ie();var Zl="unsynced",Wj="current";var C_="moved.",Gm=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/;var I_=class extends Error{constructor(t){super(`app unsynced collection: ${t}`);this.reason=t;this.name="AppUnsyncedCollectionError"}reason},pr=(n="unavailable")=>new I_(n);function Hj(n){if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!=="account,collection,device,installation,replica,version")throw pr();let e=n,t=[e.account,e.installation,e.collection,e.replica,e.device];if(e.version!==1||t.some(r=>typeof r!="string"||!Gm.test(r))||new Set(t).size!==t.length)throw pr();return Object.freeze({...e})}function GI(n,e){if(e.throwIfAborted(),!globalThis.indexedDB)throw pr();return new Promise((t,r)=>{let o=indexedDB.open(n,1),s=!1,i=()=>e.removeEventListener("abort",a),a=()=>{s=!0,i();try{o.transaction?.abort()}catch{}r(pr("fenced"))};e.addEventListener("abort",a,{once:!0}),o.onblocked=o.onerror=a,o.onupgradeneeded=()=>{try{if(s||o.result.objectStoreNames.length)throw pr();o.result.createObjectStore(Zl)}catch{try{o.transaction?.abort()}catch{}}},o.onsuccess=()=>{if(i(),s||o.result.objectStoreNames.length!==1||!o.result.objectStoreNames.contains(Zl)){o.result.close(),r(pr());return}t(o.result)}})}async function Gj(n,e,t,r,o){let s=await GI(n,o);try{return await new Promise((i,a)=>{let c=s.transaction(Zl,r?"readwrite":"readonly",{durability:"strict"}),l=null,p=null;c.onabort=c.onerror=()=>a(p??pr()),c.oncomplete=()=>i(l);let d=c.objectStore(Zl),u=d.get(e);u.onsuccess=()=>{try{if(u.result!==void 0){l=t(u.result);return}if(!r)return;let f=t(r());d.add(f,e),l=f}catch(f){p=f,c.abort()}}})}finally{s.close()}}async function Yj(n,e,t){let r=await GI(n,e);try{return await new Promise((o,s)=>{let i=r.transaction(Zl,"readwrite",{durability:"strict"}),a,c=null;i.onabort=i.onerror=()=>s(c??pr()),i.oncomplete=()=>o(a),t(i.objectStore(Zl),l=>{a=l},l=>{c=l,i.abort()})})}finally{r.close()}}var YI=/^sha256:[0-9a-f]{64}$/;function JI(n){let e=n;if(!e||e.version!==1||!e.revisions||typeof e.revisions!="object"||Array.isArray(e.revisions))throw pr();let t=new Map;for(let[r,o]of Object.entries(e.revisions)){if(!Gm.test(r)||typeof o!="string"||!YI.test(o))throw pr();t.set(r,o)}return t}async function XI(n,e,t){if(!Gm.test(e))throw pr("binding");return await Gj(n,C_+e,JI,null,t)??new Map}function QI(n,e,t,r){for(let[o,s]of t)if(!Gm.test(o)||!YI.test(s))return Promise.reject(pr("binding"));return Yj(n,r,(o,s,i)=>{let a=o.get(Wj),c=o.get(C_+e);c.onsuccess=()=>{try{if(a.result===void 0||Hj(a.result).collection!==e){i(pr());return}let l=c.result===void 0?new Map:JI(c.result);for(let[p,d]of t)l.set(p,d);o.put({version:1,revisions:Object.fromEntries(l)},C_+e),s()}catch(l){i(l)}}})}var V7=720*60*60*1e3;ie();var O_=new WeakMap,Jj=100,Xj=(n,e)=>`unsynced/1\0${n}\0${e}`;async function Ym(n,e,t){try{return await n.get(e,{signal:t})}catch(r){if(X(r,"not_found"))return null;throw r}}function Qj(n,e){let t=n.lastIndexOf("/"),r=n.lastIndexOf("."),o=r>t+1?r:n.length;return`${n.slice(0,o)} ${e}${n.slice(o)}`}async function Zj(n,e){let t=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`unsynced/1\0copy\0${n}\0${e}`))).slice(0,16);t[6]=t[6]&15|128,t[8]=t[8]&63|128;let r=[...t].map(o=>o.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function eU(n){if(n.document===void 0)throw A("invalid_request","the source record has no document");return{path:n.path,document:n.document}}async function R_(n,e,t={}){let{signal:r}=t,o=t.map??eU;if(n.collection===e.collection)throw A("invalid_request","a collection cannot be transferred into itself");let s=t.ledger?await t.ledger.read(n.collection,r):new Map,i=new Map,a=await e.describe(r?{signal:r}:{}),c=new Set(a.types.map(b=>b.name.toLowerCase())),l=[],p=new Map,d=new Set,u=new Set,f=0;for await(let b of n.pages({},{include:{body:!0,document:!0},signal:r}))for(let g of b.records){r?.throwIfAborted();let y=null;if(await Ym(e,g.id,r)){let S=s.get(g.id);if(S===void 0&&i.set(g.id,g.revision),S===void 0||S===g.revision){l.push(Object.freeze({sourceId:g.id,sourcePath:g.path,outcome:"present"}));continue}if(y=await Zj(g.id,g.revision),await Ym(e,y,r)){i.set(g.id,g.revision),l.push(Object.freeze({sourceId:g.id,sourcePath:g.path,outcome:"present"}));continue}}let _=await o(g);if(_===null){l.push(Object.freeze({sourceId:g.id,sourcePath:g.path,outcome:"skipped"}));continue}if(!_||typeof _!="object"||_.id!==void 0&&_.id!==g.id)throw A("invalid_request","the transfer map must keep the record ID");i.set(g.id,g.revision);let v=_.path??g.path,k=v;for(let S=2;d.has(k.toLowerCase())||await Ym(e,{path:k},r);S++){if(S>Jj)throw A("conflict",`no free path beside ${v}`,"path_taken");k=Qj(v,S)}d.add(k.toLowerCase());for(let S of _.type?[_.type]:g.types)c.has(S.toLowerCase())||u.add(S);p.set(g.id,Object.freeze({..._,id:y??g.id,path:k})),k!==v&&!y&&f++,l.push(Object.freeze({sourceId:g.id,sourcePath:g.path,outcome:y?"changed":"create",path:k,...y?{copyId:y}:k!==v?{renamedFrom:v}:{}}))}let h=new Map;if(t.addTypes&&u.size){let b=new Map((await n.describe(r?{signal:r}:{})).types.map(g=>[g.name.toLowerCase(),g]));for(let g of[...u].sort()){let y=b.get(g.toLowerCase());if(!y?.revision)continue;let _;try{_=(await n.resources.get(y.path,{signal:r})).text}catch(v){if(X(v,"not_found"))continue;throw v}typeof _=="string"&&(h.set(y.name,_),u.delete(g))}}let m=b=>l.filter(g=>g.outcome===b).length,w=Object.freeze({source:n.collection,destination:e.collection,items:Object.freeze(l),missingTypes:Object.freeze([...u].sort()),addTypes:Object.freeze([...h.keys()].sort()),counts:Object.freeze({create:m("create"),present:m("present"),skipped:m("skipped"),renamed:f,changed:m("changed")})});return O_.set(w,Object.freeze({inputs:p,types:h,map:t.map,ledger:t.ledger,settle:i})),w}async function ZI(n,e,t,r){let o=O_.get(n);if(!o)throw A("invalid_request","plan the transfer first");if(e.collection!==n.source||t.collection!==n.destination)return!1;let s=await R_(e,t,{...o.map?{map:o.map}:{},...o.ledger?{ledger:o.ledger}:{},...r?{signal:r}:{}});return s.counts.create===0&&s.counts.changed===0}async function eO(n,e,t={}){let r=O_.get(n),{signal:o}=t;if(!r)throw A("invalid_request","plan the transfer first");let{inputs:s}=r;if(e.collection!==n.destination)throw A("invalid_request","the plan is for another collection");let i=n.items.filter(m=>m.outcome==="create"||m.outcome==="changed"),a=[],c=[],l=0,p=n.counts.present,d=0,u=()=>{try{t.onProgress?.(Object.freeze({done:d,total:i.length}))}catch{}};r.ledger&&r.settle.size&&await r.ledger.record(n.source,r.settle,o);let f=[],h=[];for(let[m,w]of r.types){o?.throwIfAborted();try{await e.createType(w,o?{signal:o}:{}),f.push(m)}catch(b){o?.throwIfAborted(),X(b,"conflict")?f.push(m):h.push(Object.freeze({name:m,code:X(b)?b.code:"unavailable"}))}}u();for(let m of i){o?.throwIfAborted();try{let w=await e.create(s.get(m.sourceId),{intent:Xj(n.source,m.copyId??m.sourceId),...o?{signal:o}:{}});c.push(w.mutationId),l++}catch(w){o?.throwIfAborted(),await Ym(e,m.copyId??m.sourceId,o).catch(()=>null)?p++:a.push(Object.freeze({sourceId:m.sourceId,code:X(w)?w.code:"unavailable"}))}d++,u()}return Object.freeze({source:n.source,destination:n.destination,created:l,present:p,skipped:n.counts.skipped,failed:Object.freeze(a),addedTypes:Object.freeze(f),failedTypes:Object.freeze(h),mutations:Object.freeze(c),retired:!1})}Zm();$f();Qo();Qf();var sO="mdbn-app-tabs/1",E_="\0mdbn-port";var Ud=n=>typeof n=="string"&&/^[0-9a-f-]{36}$/.test(n);function iU(n){if(!n||typeof n!="object")return null;let e=n;switch(e.k){case"join":case"leave":return Ud(e.tab)?e:null;case"leader":case"bye":case"fault":case"signedOut":case"signedIn":return Ud(e.leader)?e:null;case"joined":return Ud(e.tab)&&Ud(e.leader)&&typeof e.binding=="string"?e:null;case"m":return Ud(e.tab)&&typeof e.up=="boolean"&&Number.isSafeInteger(e.s)&&e.s>=0?e:null;default:return null}}function q_(n){if(!n||typeof n!="object")return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function T_(n,e,t=0){return n instanceof MessagePort?{[E_]:e(n)}:t>=6?n:Array.isArray(n)?n.map(r=>T_(r,e,t+1)):q_(n)?Object.fromEntries(Object.entries(n).map(([r,o])=>[r,T_(o,e,t+1)])):n}function M_(n,e,t,r=0){if(q_(n)&&Object.keys(n).length===1&&Number.isSafeInteger(n[E_])){let o=e(n[E_]);return t.push(o),o}return r>=6?n:Array.isArray(n)?n.map(o=>M_(o,e,t,r+1)):q_(n)?Object.fromEntries(Object.entries(n).map(([o,s])=>[o,M_(s,e,t,r+1)])):n}var ey=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=r=>{let o=r.ports.length?T_(r.data,s=>{let i=this.next;return this.next+=2,this.bridge(s,i),i}):r.data;try{this.send(t,o)}catch{}}}deliver(e,t){let r=this.streams.get(e);if(!r)return;let o=[],s=M_(t,i=>{let a=new MessageChannel;return this.bridge(a.port1,i),a.port2},o);try{r.postMessage(s,o)}catch{for(let i of o)i.close()}}close(){for(let e of this.streams.values()){e.onmessage=null;try{e.close()}catch{}}this.streams.clear()}},ty=class{constructor(e,t,r,o=()=>{},s={}){this.env=t;this.lost=r;this.signedInElsewhere=o;this.role=s;this.base=e.storageNamespace===void 0?`${sO}/${e.cpOrigin}/${e.appId}/${e.build}`:`${sO}/namespace/${JSON.stringify([e.cpOrigin,e.appId,e.build,e.storageNamespace])}`}env;lost;signedInElsewhere;role;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(iU(t.data)),this.channel=e,e}post(e){this.channel?.postMessage(e)}hold(e,t,r){return new Promise((o,s)=>{let i=c=>{if(!c){o(null);return}return new Promise(l=>o(l))};(t?this.env.locks.request(e,{ifAvailable:!0},i):this.env.locks.request(e,{signal:r},i)).catch(s)})}async elect(e){e.throwIfAborted(),this.open(),this.presence??=await this.hold(`${this.base}/tab/${this.tab}`,!0),e.throwIfAborted();let t=this.role.lead!==!1;if(t&&!this.leading&&(this.leading=await this.hold(`${this.base}/leader`,!0)),this.leading)return e.aborted&&(this.resign(),e.throwIfAborted()),{kind:"leader"};let r=new AbortController,o=()=>r.abort();e.addEventListener("abort",o,{once:!0});let s=t?this.hold(`${this.base}/leader`,!1,r.signal):null,i;try{i=await new Promise((d,u)=>{s?.then(f=>{f&&d({release:f})},()=>{}),this.joining={resolve:d,reject:u},e.addEventListener("abort",()=>u(e.reason),{once:!0}),this.join()})}catch(d){throw this.joining=null,r.abort(),d}finally{e.removeEventListener("abort",o)}if(this.joining=null,"release"in i)return this.leading=i.release,e.aborted&&(this.resign(),e.throwIfAborted()),{kind:"leader"};e.aborted&&(r.abort(),e.throwIfAborted());let a=new MessageChannel,c=this.tab,l=new ey((d,u)=>this.post({k:"m",tab:c,up:!0,s:d,d:u}),!0);l.bridge(a.port2,0);let p={leader:i.leader,tunnel:l,wait:r,port:a.port1,left:!1,signedOut:!1};return this.follower=p,(s??this.hold(`${this.base}/leader`,!1,r.signal)).then(d=>{if(!d)return;let u=this.follower===p&&!p.left;u&&t?this.leading=d:d(),u&&this.departed(p)},()=>{}),{kind:"follower",port:a.port1,binding:i.binding,leave:()=>this.leave(p)}}join(){this.post({k:"join",tab:this.tab,...this.role.lead===!1?{needsLeader:!0}:{}})}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 r=this.leading;if(this.leading=null,r?.(),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,r=this.follower;switch(e.k){case"join":{if(!t&&e.needsLeader===!0&&this.role.lead!==!1&&!this.leading&&!r&&!this.joining&&this.hold(`${this.base}/leader`,!0).then(l=>{l&&(l(),this.role.wanted?.())},()=>{}),!t||t.followers.has(e.tab)||e.tab===this.tab)return;let o=crypto.randomUUID(),s=new MessageChannel,i=e.tab,a=new ey((l,p)=>this.post({k:"m",tab:i,up:!1,s:l,d:p}),!1);a.bridge(s.port1,0);let c=new AbortController;t.followers.set(i,{binding:o,tunnel:a,watch:c});try{t.worker.attach(s.port2,o)}catch{t.followers.delete(i),a.close();return}this.post({k:"joined",tab:i,binding:o,leader:this.tab}),t.faulted&&this.post({k:"fault",leader:this.tab}),this.hold(`${this.base}/tab/${i}`,!1,c.signal).then(l=>{l?.(),this.drop(t,i)},()=>{});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.join();return;case"bye":r&&r.leader===e.leader&&this.departed(r,e.signedOut===!0);return;case"signedOut":r&&r.leader===e.leader&&(r.signedOut=!0);return;case"signedIn":!t&&!r&&!this.joining&&e.leader!==this.tab&&this.signedInElsewhere();return;case"fault":r&&!r.left&&r.leader===e.leader&&r.port.dispatchEvent(new MessageEvent("messageerror"));return;case"m":e.up&&t?t.followers.get(e.tab)?.tunnel.deliver(e.s,e.d):!e.up&&r&&e.tab===this.tab&&r.tunnel.deliver(e.s,e.d);return}}drop(e,t){let r=e.followers.get(t);if(r){e.followers.delete(t),r.watch.abort(),r.tunnel.close();try{e.worker.detach(r.binding)}catch{}}}};function Ri(n){try{return n()}catch{return}}function oU(){let n=Ri(()=>globalThis.crypto?.subtle),e=Ri(()=>globalThis.navigator?.storage),t=Ri(()=>typeof e?.getDirectory=="function"?()=>e.getDirectory.call(e):void 0);return{subtle:n,abortSignalAny:Ri(()=>typeof AbortSignal=="function"&&typeof AbortSignal.any=="function")===!0,randomUUID:Ri(()=>typeof globalThis.crypto?.randomUUID=="function")===!0,worker:Ri(()=>typeof Worker=="function")===!0,messageChannel:Ri(()=>typeof MessageChannel=="function")===!0,locks:Ri(()=>typeof globalThis.navigator?.locks?.request=="function")===!0,broadcastChannel:Ri(()=>typeof BroadcastChannel=="function")===!0,indexedDB:Ri(()=>typeof globalThis.indexedDB<"u")===!0,getDirectory:t}}async function aO(n=oU(),e=!0){let t=[];if(n.subtle||t.push("web_crypto"),n.abortSignalAny||t.push("abort_signal_any"),n.randomUUID||t.push("random_uuid"),e&&!n.worker&&t.push("worker"),n.messageChannel||t.push("message_channel"),n.locks||t.push("web_locks"),n.broadcastChannel||t.push("broadcast_channel"),n.indexedDB||t.push("indexed_db"),n.subtle)try{await n.subtle.generateKey({name:"X25519"},!1,["deriveBits"])}catch{t.push("x25519")}if(t.length)return{ok:!1,problem:"browser_unsupported",missing:Object.freeze(t)};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 ny(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 lO(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 cO="Some changes are only on this device. Stay online so they can sync.";async function ry(n,e,t=!1){let r=!1;try{r=await n?.persisted()===!0,!r&&t&&(r=await n?.persist?.()===!0)}catch{}return{persistent:r,installed:e}}oy();var fO=Object.freeze(new Set);function hO(n,e){let t=`mdbase.${n}.forgotten-collections.v1.${encodeURIComponent(e)}`,r=()=>{try{return globalThis.localStorage??null}catch{return null}},o=null,s=()=>{let a=null;try{a=r()?.getItem(t)??null}catch{}if(o&&o.raw===a)return o;let c=null,l=fO;try{let p=a?JSON.parse(a):null;p?.v===1&&typeof p.account=="string"&&p.account.length<=64&&Array.isArray(p.ids)&&p.ids.length<=1024&&p.ids.every(d=>typeof d=="string"&&d.length>0&&d.length<=64)&&(c=p.account,l=Object.freeze(new Set(p.ids)))}catch{}return o={raw:a,account:c,ids:l},o},i=(a,c)=>{try{c.size?r()?.setItem(t,JSON.stringify({v:1,account:a,ids:[...c].slice(-1024)})):r()?.removeItem(t)}catch{}o=null};return Object.freeze({read(a){let c=s();return a&&c.account===a?c.ids:fO},add(a,c){let l=s(),p=new Set(l.account===a?l.ids:[]);p.has(c)||(p.add(c),i(a,p))},remove(a,c){let l=s();if(l.account!==a||!l.ids.has(c))return!1;let p=new Set(l.ids);return p.delete(c),i(a,p),!0},clear(){try{r()?.removeItem(t)}catch{}o=null}})}var uU=new Set(["owner","editor","viewer"]),ns=(n,e=512)=>typeof n=="string"&&n.length>0&&n.length<=e,fU=new Set(["unselected","opening","setup_required","ready"]);function mO(n){let e=n;return!e||typeof e!="object"||!ns(e.collectionId,64)||typeof e.displayName!="string"||e.displayName.length>512||!uU.has(e.role)?null:Object.freeze({collectionId:e.collectionId,displayName:e.displayName,role:e.role})}function yO(n){let e=n;return!e||typeof e!="object"||e.state!=="paired"||!ns(e.requestId,64)||!ns(e.installationId,64)||!ns(e.deviceId,64)||!ns(e.appId,64)||e.kind!=="app-runtime"&&e.kind!=="mobile"||!ns(e.verificationUri,2048)||!ns(e.accountId,64)||!Array.isArray(e.collectionIds)||e.collectionIds.length>1024||!e.collectionIds.every(t=>ns(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 gO(n,e){let t=`mdbase.${n}.session-hint.v1.${encodeURIComponent(e)}`,r=null,o=null,s=()=>{try{return globalThis.localStorage??null}catch{return null}},i=()=>{let c=null;try{c=s()?.getItem(t)??null}catch{return null}if(r&&r.raw===c)return r.value;let l=null;try{let p=c?JSON.parse(c):null,d=p?.v===1?yO(p.signIn):null,u=Array.isArray(p?.collections)&&p.collections.length<=1024?p.collections.map(mO):null;d&&u&&u.every(f=>f!==null)&&(l=Object.freeze({signIn:d,collections:Object.freeze(u)}))}catch{l=null}return r={raw:c,value:l},l},a=()=>{o=null;try{s()?.removeItem(t)}catch{}};return Object.freeze({read:i,clear:a,observe(c){if(c.status==="signed_out"&&c.signIn===null){o!==""&&(a(),o="");return}if(!fU.has(c.status)||c.signIn?.state!=="paired")return;let l=yO(c.signIn),p=c.collections.map(mO);if(!l||!p.every(u=>u!==null))return;let d=JSON.stringify({v:1,signIn:l,collections:p});if(d!==o){o=d;try{s()?.setItem(t,d)}catch{}}}})}j_();ie();tn();vn();function jN(n,e){return new Promise((t,r)=>{let o=()=>{clearTimeout(s),r(A("cancelled","The original collection closed."))};if(n.aborted){r(A("cancelled","The original collection closed."));return}let s=setTimeout(()=>{n.removeEventListener("abort",o),t()},e);n.addEventListener("abort",o,{once:!0})})}var UN=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,dc=Object.freeze({checking:!1,assessment:null,problem:null}),NN=Object.freeze({capabilities:dc,contracts:dc,configuration:dc,files:dc,people:dc,notifications:dc}),Ui=(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({...NN,configuration:Object.freeze({checking:n,assessment:t,problem:null})})})},My=n=>n==="approval_required"?"device_approval_required":n,DN=n=>n.state==="opening"||n.state==="unavailable"&&n.reason!=="sync_required"&&n.reason!=="access_removed"&&n.reason!=="collection_deleted",PA=n=>{if(X(n)){let e=fe(n.details,"availability");return typeof e=="string"?My(e):n.reason??n.code}return"open_failed"},xA=n=>{if(!X(n))return;let e=bO(n.details);return Object.freeze({name:"MdbaseError",code:n.code,...e?{relay:e}:{}})};function zN(n){let e=n.manifest?.redirect_uris;return(Array.isArray(e)?e.filter(r=>typeof r=="string"):[]).find(r=>{try{return kt(new URL(r))===n.origin}catch{return!1}})??new URL("/",n.origin).href}function WR(n,e,t){if(n.signIn?.state!=="paired"||!e.length&&!t)return n;let r=new Set(n.collections.map(c=>c.collectionId)),o=e.filter(c=>!r.has(c.collectionId)),s=o.length?Object.freeze([...n.collections,...o]):n.collections;if(!t||n.status!=="unselected"||r.has(t.collectionId))return s===n.collections?n:Object.freeze({...n,collections:s});let{problemDetail:i,...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 Ly=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(()=>(KR(),FR));return new t({declaration:this.options.declaration,redirectUri:this.options.grantRedirectUri??zN(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 r=t.filter(i=>i.account_id===e);if(this.bindingsAccount===e&&JSON.stringify(r)===JSON.stringify(this.bindings))return;let o=this.bindings;this.bindingsAccount=e,this.bindings=Object.freeze([...r]),this.settled=null,this.listed=null;let s=this.open;if(s){let i=o?.find(c=>c.collection_id===s.id),a=r.find(c=>c.collection_id===s.id);!a||e!==s.scope.account?this.close(!1):(a.grant_id!==i?.grant_id||a.client_noise_public_key!==i?.client_noise_public_key)&&this.openCollection(s.id,s.scope).catch(()=>{})}this.setList([])}async nativeAuthorization(e,t,r){if(e.action==="cancel")return this.native?.life.abort(),this.native?.prepared?.cancel(),this.native=null,null;if(this.closed||r.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 c=AbortSignal.any([r,a.life.signal]),l=await this.grants();if(!l.prepareAuthorization)throw A("unavailable","Native authorization unavailable");let p=btoa(String.fromCharCode(...Uint8Array.from(e.value.challenge.match(/../g),u=>parseInt(u,16)))).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,""),d=await l.prepareAuthorization({authorizationNonce:p,expectedAccountId:e.value.accountId,signal:c});if(a.prepared=d,this.native!==a||c.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 i=await s.finish({popup:t,collection:e.value.collectionId,signal:AbortSignal.any([r,o.life.signal])});if(this.native!==o||r.aborted||!i.nativeCompletion)throw A("unauthenticated","Original Native completion unavailable");return i.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 r=await this.grants(),o=this.bindings,s=[];if(o)for(let a of o)a.account_id===e&&await r.verifiedStoredNativeGrant?.(a)&&s.push(a);let i=await r.collections(o===null?{}:{bindings:s});if(this.closed||o!==this.bindings)return;this.listed=e,this.setList(i)}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(r=>UN.test(r.collectionId)).map(r=>Object.freeze({collectionId:r.collectionId,displayName:r.displayName,role:r.role??"editor",availability:r.availability,kind:"private"})));JSON.stringify(t)!==JSON.stringify(this.list)&&(this.list=t,this.changed())}setAvailability(e,t){this.list.some(r=>r.collectionId===e&&JSON.stringify(r.availability)!==JSON.stringify(t))&&(this.list=Object.freeze(this.list.map(r=>r.collectionId===e?Object.freeze({...r,availability:t}):r)),this.changed())}set(e,t){if(this.open!==e||e.life.signal.aborted)return;let{problemDetail:r,...o}=e.state,{problemDetail:s,...i}=t,a=i.problem===null?void 0:s??(i.problem===void 0?r:void 0);e.state=Object.freeze({...o,...i,...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 r={id:e,scope:t,life:new AbortController,client:null,setup:null,connection:null,stopLink:null,state:Object.freeze({collectionId:e,status:"opening",problem:null,readiness:Ui(!0,null)})};this.open=r,this.changed();let o=r.life.signal;try{let s=await this.grants(),i=this.bindings?.find(d=>d.account_id===t.account&&d.collection_id===e),a=async()=>{if(this.bindings!==null&&(!i||this.bindingsAccount!==t.account||!this.bindings.includes(i)||!await s.verifiedStoredNativeGrant?.(i)))throw A("unauthenticated","Original account-bound Native grant unavailable");if(o.aborted)throw A("cancelled","Original Native open fenced")};await a();let c=await s.availability(e,{signal:o});if(this.setAvailability(e,c),DN(c)&&(c.state==="unavailable"&&this.set(r,{status:"blocked",problem:My(c.reason),readiness:Ui(!1,null)}),c=await s.waitForAvailable(e,{signal:o,timeoutMs:this.options.waitMs??10*6e4,onAvailability:d=>{this.setAvailability(e,d),d.state==="unavailable"?this.set(r,{status:"blocked",problem:My(d.reason)}):this.set(r,{status:"opening",problem:null,readiness:Ui(!0,null)})}})),c.state!=="available"){if(c.state==="opening")throw A("unavailable","The collection is still getting ready","collection_unavailable");this.set(r,{status:"blocked",problem:My(c.reason),readiness:Ui(!1,null)});return}this.set(r,{status:"opening",problem:null}),await a();let l=await(this.options.connect??$N(this.options.declaration))(s,e,o,d=>{this.open===r&&!o.aborted&&(d.reason==="not_served"||d.reason==="device_not_serving"||d.reason==="no_device_online")&&this.set(r,{status:"blocked",problem:PA(d),problemDetail:xA(d),readiness:Ui(!1,null)})});if(this.open!==r||o.aborted||l.collection!==e){if(l.close(),this.open===r&&!o.aborted)throw A("invalid_request","a different collection opened","collection_mismatch");return}r.client=l,r.state.status==="blocked"&&this.set(r,{status:"opening",problem:null,readiness:Ui(!0,null)}),r.setup=s.setup(l),r.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===r&&!o.aborted&&!this.closed}),await this.assessOpen(r);let p=0;r.stopLink=l.onLink((d,u)=>{u?this.set(r,{problem:PA(u),problemDetail:xA(u)}):d==="open"&&this.set(r,{problem:null});let f=++p;s.availability(e,{signal:o}).then(h=>{this.open===r&&!o.aborted&&f===p&&this.setAvailability(e,h)}).catch(()=>{})})}catch(s){throw this.open===r&&!o.aborted&&this.set(r,{status:"blocked",problem:PA(s),problemDetail:xA(s),readiness:Ui(!1,null)}),s}}async assessOpen(e){this.set(e,{readiness:Ui(!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 r;try{r=await e.setup.assess({signal:e.life.signal})}catch(o){if(!X(o)||o.code!=="rate_limited")throw o;let s=o.retryAfterMs;await jN(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:r==="ready"?"ready":"setup_required",problem:null,readiness:Ui(!1,r)}),r}}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 r=this.current(),o=await r.setup.apply(e,t);this.set(r,{status:o==="ready"?"ready":"setup_required",problem:null,readiness:Ui(!1,o)})}async configure(e={}){let r=await this.current().setup.plan(e.signal?{signal:e.signal}:{});await this.apply(r,e)}async add(e,t,r){let o;try{o=await this.grants()}catch(i){throw e.close(),i}let s=await o.authorize({popup:e,...t?{collection:t}:{},...r?{signal:r}:{}});return await this.refresh().catch(()=>{}),s.collectionId}async forget(e){this.open?.id===e&&this.close();let t=await this.grants(),r=this.bindings?.find(o=>o.collection_id===e&&o.account_id===this.bindingsAccount);(this.bindings===null||r&&await t.verifiedStoredNativeGrant?.(r))&&await(r?t.forget(e,{expectedNoisePublicKey:r.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 $N(n){return async(e,t,r,o)=>{let{connect:s}=await Promise.resolve().then(()=>(Es(),Tf));return s({connector:e.connector(t),app:{name:n.id,version:"1"},signal:r,waitForDevice:!0,onWaiting:o})}}var kg={};function ID(n){let e=globalThis.document;return!e||typeof e.addEventListener!="function"||e.visibilityState!=="hidden"?Promise.resolve():new Promise((t,r)=>{let o=()=>{e.visibilityState!=="hidden"&&(e.removeEventListener("visibilitychange",o),n.removeEventListener("abort",s),t())},s=()=>{e.removeEventListener("visibilitychange",o),r(n.reason)};e.addEventListener("visibilitychange",o),n.addEventListener("abort",s,{once:!0})})}var qE=new WeakMap;function OD(n){let e=n.unsynced;if(!e)return n;let t=qE.get(n);return t||(t=Object.freeze({...n,status:e.sessionStatus,selectedCollectionId:null,unsynced:null}),qE.set(n,t)),t}var M0=class extends Error{code="application_not_yet_available";constructor(){super("mdbase cannot run in this context"),this.name="MdbaseApplicationUnavailableError"}},j0=Object.freeze({code:"application_not_yet_available"}),Uc=Object.freeze({checking:!1,assessment:null,problem:j0}),RD=Object.freeze({checking:!1,assessment:null,problem:j0,facets:Object.freeze({capabilities:Uc,contracts:Uc,configuration:Uc,files:Uc,people:Uc,notifications:Uc})}),Nc=Object.freeze({checking:!1,assessment:null,problem:null}),Ag=Object.freeze({checking:!1,assessment:null,problem:null,facets:Object.freeze({capabilities:Nc,contracts:Nc,configuration:Nc,files:Nc,people:Nc,notifications:Nc})}),L0=()=>new M0,TE=Object.freeze({state:"none",problem:null,usable:null,requested:Object.freeze({collectionId:null,source:"none",displayName:null,approved:!1})});function ED(n){let e={status:"blocked",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:j0.code,timing:null,readiness:RD,selection:TE},t=Object.freeze({...e,phase:qp(e,n?{messages:n}:{}),sync:null,writes:null,links:null}),r=()=>Promise.reject(L0());return Object.freeze({getSnapshot:()=>t,subscribe:()=>()=>{},start:r,signIn:r,addCollection:r,cancelAuthorization:r,select:r,approve:r,reauthorize:r,refreshCollectionList:r,requestAccess:r,chooseAnother:r,assess:r,configure:r,setup:Object.freeze({plan:r,apply:r}),forget:r,deleteCollection:r,unlock:r,connection:()=>null,setForeground(){throw L0()},close:r,signOut:r,unsynced:Object.freeze({open:r,planTransfer:r,transfer:r,discard:r})})}var qD=n=>typeof n=="object"&&n!==null&&["postMessage","terminate","addEventListener","removeEventListener"].every(e=>typeof n[e]=="function"),TD=(n,e)=>(!e||typeof Worker=="function")&&typeof MessageChannel=="function"&&Rt()!==null&&dt(n);function MD(n){if(n===void 0)return{build:null,host:!0};if(!n||typeof n!="object"||typeof n.build!="string"||!n.build||n.build.length>128||/[\u0000-\u001f\u007f]/.test(n.build))throw new TypeError("session.build must be a short non-empty string");if(n.host!==void 0&&typeof n.host!="boolean")throw new TypeError("session.host must be a boolean");return{build:n.build,host:n.host!==!1}}function LD(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 r=n.returnUrl,o=n.grantReturnUrl;r!==void 0&&(Vv(r,e.manifest)||t()),o!==void 0&&(!Vv(o,e.manifest)||new URL(o).origin!==e.origin)&&t();let s=n.open.bind(n),i=n.close?.bind(n);return Object.freeze({open:s,...i?{close:i}:{},...r!==void 0?{returnUrl:r}:{},...o!==void 0?{grantReturnUrl:o}:{}})}async function jD(n){let e=!0;if(n.webPush){let t=globalThis.navigator?.serviceWorker,r;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=>{r=setTimeout(()=>o(!1),5e3)})]).finally(()=>clearTimeout(r)))}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 UD(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 Sg=class{mdbase;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:Ag});composed=null;hint=null;forgotten=null;handledApproval=null;refreshing=null;refreshedAt=0;approvalPortal=null;revision=0;links=null;cpOrigin=null;messages;opening=null;syncing=null;storagePolicy=null;pendingSave=null;signIn;typeIssues;createWorker;session;privates=null;unsyncedFirst;unsyncedTried=!1;unsyncedOpening=0;timing=new mm;overlaid=new WeakMap;constructor(e,t={}){this.declaration=so(e),this.compiled=Jo(this.declaration);let r=t.readiness?.typeIssues??"block";if(r!=="block"&&r!=="degrade")throw new TypeError('readiness.typeIssues must be "block" or "degrade"');if(this.typeIssues=r,this.unsyncedFirst=t.unsynced===!0,t.urlSelection!==void 0&&typeof t.urlSelection!="boolean")throw new TypeError("urlSelection must be a boolean");if(t.worker!==void 0&&typeof t.worker!="function")throw new TypeError("worker must be a function");if(this.createWorker=t.worker??null,this.messages=t.messages,this.session=MD(t.session),!this.session.host&&this.createWorker)throw new TypeError("worker has no effect with session.host: false");if(this.signIn=LD(t.signIn,this.declaration),!TD(this.declaration.origin,this.session.host)){this.mdbase=ED(t.messages);return}try{let s=this.environment().cpOrigin;this.cpOrigin=s,this.hint=gO(this.declaration.storage.applicationNamespace,s),this.forgotten=hO(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.followNetwork(),this.memory=UD(this.declaration.storage.applicationNamespace),t.privateCollections!==!1&&(this.privates=new Ly({declaration:this.declaration,...this.signIn?.grantReturnUrl?{grantRedirectUri:this.signIn.grantReturnUrl}:{},onChange:()=>{this.revision++,this.notify()}})),this.selection=new gm({browser:new ym(this.declaration.origin,{},t.urlSelection===!1?null:j1()),session:this.selectionSession(),memory:this.memory}),this.selection.subscribe(()=>{this.unforgetApproved(),this.notify(!1)});let o=()=>this.getSnapshot();this.mdbase=Object.freeze({getSnapshot:o,subscribe:s=>(this.listeners.add(s),()=>{this.listeners.delete(s)}),start:s=>this.track(()=>{let i=this.unsyncedFirst&&(!this.unsyncedTried||this.runtime===null);return i&&(this.unsyncedOpening++,this.revision++,this.notify(!1)),this.call(async a=>{let c=a.getNativeSnapshot();c.status==="blocked"&&c.signIn&&c.selectedCollectionId===null?await a.queue(()=>a.start(s)):await this.timing.time("session",()=>this.started(a,s));let l=this.choose(),p=l.getSnapshot();p.state==="blocked"&&p.requested.approved&&p.requested.collectionId!==null&&await l.select(p.requested.collectionId,s);let d=a.getNativeSnapshot();this.unsyncedFirst&&!this.unsyncedTried&&d.status==="signed_out"&&!d.unsynced&&!d.signOutResult&&l.getSnapshot().requested.collectionId===null&&(this.unsyncedTried=!0,await this.timing.time("unsynced",()=>a.queue(()=>a.openUnsynced(s))))}).catch(a=>{let c=this.runtime?.getNativeSnapshot();if(!(a?.code==="open_in_another_tab"&&c?.status==="blocked"&&c.problem==="open_in_another_tab"))throw a}).finally(()=>{i&&(this.unsyncedOpening--,this.revision++,this.notify(!1))})}),signIn:s=>this.track(()=>this.approve(void 0,s)),approve:(s,i)=>this.track(()=>this.approve(s,i)),reauthorize:s=>this.track(()=>{let i=this.choose(),a=i.getSnapshot(),c=this.privates?.state()?.collectionId??a.usable?.collectionId??a.requested.collectionId;return c?this.approve(c,s):i.reauthorize(s)}),addCollection:s=>this.track(()=>this.approve(null,s)),cancelAuthorization:s=>this.track(()=>this.call(async i=>{await i.queue(()=>i.cancelAuthorization(s));let a=i.getNativeSnapshot();this.unsyncedFirst&&a.status==="signed_out"&&!a.unsynced&&this.choose().getSnapshot().requested.collectionId===null&&await i.queue(()=>i.openUnsynced(s))})),refreshCollectionList:s=>this.track(()=>Promise.all([this.call(i=>i.queue(()=>i.refreshCollections(s))),this.privates?.refresh(this.account()).catch(()=>{})])),requestAccess:(s,i)=>this.requestAccess(s,i),select:(s,i)=>this.track(()=>this.choose().select(s,{...i,history:"push"})),chooseAnother:s=>this.track(()=>this.choose().chooseAnother(s)),forget:(s,i)=>this.track(async()=>{let a=this.choose(),c=this.account();if(this.privates?.has(s)){await this.privates.forget(s),a.getSnapshot().requested.collectionId===s&&await a.select(null,i);return}if(c&&this.forgotten){this.forgotten.add(c,s),this.revision++,(a.getSnapshot().requested.collectionId===s||(this.runtime?.getSnapshot()??this.snapshot).selectedCollectionId===s)&&await a.select(null,i),this.notify(!1);return}await this.call(l=>l.queue(()=>l.forget(s,i))),a.getSnapshot().requested.collectionId===s&&await a.select(null,i)}),deleteCollection:(s,i)=>this.track(async()=>{let a=this.choose(),{confirmName:c,...l}=i??{};await this.call(p=>p.queue(()=>p.deleteCollection(s,c,l))),a.getSnapshot().requested.collectionId===s&&await a.select(null,l)}),unlock:(s,i,a)=>this.track(()=>this.call(c=>c.queue(()=>c.unlock(s,i,a)))),assess:s=>this.privates?.isOpen()?this.privates.assess():this.call(i=>i.queue(()=>i.assess(s))),configure:s=>this.track(()=>this.privates?.isOpen()?this.privates.configure(s):this.call(i=>i.queue(()=>i.configure(s)))),setup:Object.freeze({plan:s=>(this.privates?.isOpen()?this.privates.plan(s):this.call(i=>i.queue(()=>i.planSetup(s)))).then(i=>uO(i,this.getSnapshot().readiness)),apply:(s,i)=>dO(this.track(()=>this.privates?.isOpen()?this.privates.apply(s,i):this.call(a=>a.queue(()=>a.applySetup(s,i)))),o)}),connection:s=>this.connection(s),setForeground:s=>this.setForeground(s),close:()=>this.close(),signOut:s=>this.signOut(s),unsynced:Object.freeze({planTransfer:(s={})=>this.call(i=>{let a=this.transferDestination(null);return i.withUnsyncedSource((c,l)=>R_(c.records,a.records,{...s.map?{map:s.map}:{},...s.addTypes?{addTypes:!0}:{},ledger:this.transferLedger(),signal:l}),s)}),transfer:(s,i={})=>this.call(async a=>{let c=this.transferDestination(s?.destination??null),l=await eO(s,c.records,{...i.signal?{signal:i.signal}:{},...i.onProgress?{onProgress:i.onProgress}:{}});if(l.failed.length||l.failedTypes.length)return l;let p=i.signal?{signal:i.signal}:{};return await a.withUnsyncedSource((d,u)=>ZI(s,d.records,c.records,u),p)?Object.freeze({...l,retired:await a.retireUnsynced(s.source,s.destination,p)}):l}),discard:s=>this.track(async()=>{await this.call(async i=>(await this.started(i,s),i.queue(()=>i.discardUnsynced(s))))}),open:s=>this.track(async()=>{let i=this.choose();this.privates?.close(),i.getSnapshot().requested.collectionId!==null&&await i.select(null,{...s,history:"replace"}),await this.call(async a=>(await this.started(a,s),a.queue(()=>a.openUnsynced(s))))})})})}withPrivate(e){let t=this.privates;if(!t)return e;let r=this.overlaid.get(e);if(r&&r.revision===t.revision)return r.value;let o=WR(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()??TE,r=this.composed,o=e.signIn===null&&(e.status==="starting"||e.status==="blocked"&&e.problem==="open_in_another_tab")?this.hint?.read()??null:null;if(r&&r.base===e&&r.selection===t&&r.revision===this.revision&&r.hint===o)return r.value;let s=o?Object.freeze({...e,signIn:o.signIn,collections:o.collections}):e,i=this.forgotten?.read(s.signIn?.accountId)??null,a=i?.size&&s.collections.some(v=>i.has(v.collectionId)&&v.collectionId!==s.selectedCollectionId)?Object.freeze({...s,collections:Object.freeze(s.collections.filter(v=>!i.has(v.collectionId)||v.collectionId===s.selectedCollectionId))}):s,c=a.selectedCollectionId,l=c&&!this.closed?this.privates?.connection(c)??this.runtime?.connection(c)??null:null,p=this.unsyncedOpening>0&&!a.unsynced&&!a.signOutResult&&t.requested.collectionId===null,d=qp({...a,selection:t},{connection:l,previous:r?.value.phase??null,openingUnsynced:p,startPending:this.selection?.startPending()??!1,...this.cpOrigin?{cpOrigin:this.cpOrigin}:{},...this.messages?{messages:this.messages}:{}});d=this.trackOpening(d),this.timing.observe(d),M1(t,d,r?.value);let u=a.transport??null,f=globalThis.navigator?.onLine,h=this.trackSync(d,u!==null||f===!1),m=this.syncing?.writes()??null,w=this.trackPending(Math.max(h?.pending??0,m?.pending.length??0)),b=h&&w!==null?ny(h.pending,this.storagePolicy??{persistent:!1,installed:!1},{pendingForMs:w,connection:h.connection}).warning:null,g=this.syncing?.link(),y=h?Object.freeze(Mf({status:h,writes:m,problem:a.problem,transport:u,live:a.live??null,storageWarning:b!==null,...g===void 0?{}:{link:g},...typeof f=="boolean"?{online:f}:{},...w===null?{}:{pendingForMs:w}})):null,_=Object.freeze({...a,selection:t,phase:d,sync:y,storage:this.storagePolicy,saveWarning:b,links:this.linksFor(c)});return this.composed={base:e,selection:t,revision:this.revision,hint:o,value:_},_}linksFor(e){return this.links&&e?Object.freeze({...this.links,manageAccess:`${this.cpOrigin}/access?collection=${encodeURIComponent(e)}`}):this.links}trackPending(e){let t=this.syncing;if(this.pendingSave&&(this.closed||this.hidden||!e||this.pendingSave.id!==t?.id)&&this.clearPendingSave(),this.closed||this.hidden||!t||!e)return null;if(!this.pendingSave){let r={id:t.id,since:performance.now(),timer:null},o=s=>()=>{this.pendingSave===r&&(r.timer=s===null?null:setTimeout(o(null),s),this.revision++,this.notify(!1))};r.timer=setTimeout(o(28e3),2e3),this.pendingSave=r}return performance.now()-this.pendingSave.since}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 r={id:t,slow:!1,timer:setTimeout(()=>{this.opening===r&&(r.slow=!0,this.revision++,this.notify(!1))},Jf)};this.opening=r}return e.kind==="opening"&&this.opening.slow?{...e,slow:!0}:e}trackSync(e,t){let r=e.kind==="ready"?e.collectionId:null;if(this.syncing&&this.syncing.id!==r){try{this.syncing.stop()}catch{}this.syncing=null}if(e.kind!=="ready"||this.closed)return null;if(!this.syncing){let o=e.connection.records,s=null;try{s=o.status}catch{}let i={id:e.collectionId,stop:()=>{},status:s,writes:()=>null,link:()=>{}},a=()=>{this.syncing===i&&(this.revision++,this.getSnapshot(),this.notify(!1))},c=()=>{},l=()=>{},p=()=>{};try{c=o.onStatus(d=>{i.status=d,a()})}catch{}try{let d=o.ledger;l=d.subscribe(a),i.writes=()=>{try{return d.getSnapshot()}catch{return null}}}catch{}try{p=o.onLink(a),i.link=()=>{try{return o.link}catch{return}}}catch{}i.stop=()=>{c(),l(),p()},this.syncing=i}try{e.connection.records.setTransportDeferred(t)}catch{}return this.syncing.status}nativeAuthorization(e,t,r){return!this.privates||this.closed||this.hidden?Promise.reject(A("unavailable","Native authorization unavailable")):this.privates.nativeAuthorization(e,t,AbortSignal.any([r,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 r=()=>{t?.visibilityState!=="hidden"&&this.refreshCollections()};e.addEventListener("focus",r,{signal:this.lifetime.signal}),t&&typeof t.addEventListener=="function"&&t.addEventListener("visibilitychange",r,{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 r=e.getNativeSnapshot();r.signIn?.state!=="paired"||r.status!=="unselected"&&r.status!=="ready"&&r.status!=="setup_required"||(this.refreshedAt=t,this.privates?.refresh(r.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}},r=(s=!1)=>{this.closed||ry(e,t(),s).then(i=>{this.closed||this.storagePolicy?.persistent===i.persistent&&this.storagePolicy?.installed===i.installed||(this.storagePolicy=i,this.revision++,this.notify(!1))}).catch(()=>{})},o=globalThis.document;o&&typeof o.addEventListener=="function"&&o.addEventListener("visibilitychange",()=>{o.visibilityState!=="hidden"&&r()},{signal:this.lifetime.signal}),r(!0)}notify(e=!0){let t=this.runtime?.getSnapshot(),r=t?.signIn?.state==="paired"?t.signIn.accountId:null;if(r&&!this.closed&&!this.hidden&&(this.privates?.bind(r,t?.signIn?.nativeGrants??[]),this.privates?.ensure(r)),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(OD(this.runtime?.getNativeSnapshot()??this.snapshot)),subscribe:e=>(this.nativeListeners.add(e),()=>{this.nativeListeners.delete(e)}),open:(e,t={})=>this.call(async r=>{let o=this.privates,s=r.getNativeSnapshot().collections.some(c=>c.collectionId===e);if(!o||s||!o.has(e))return o?.close(),r.queue(()=>r.select(e,t));r.getNativeSnapshot().selectedCollectionId!==null&&await r.queue(()=>r.clearSelection(t));let i=r.getNativeSnapshot().signIn?.accountId,a=r.getNativeSnapshot().signIn?.installationId;if(!i||!a)throw A("unauthenticated","Sign in before opening a collection");o.openCollection(e,{account:i,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 Cr({environment:this.declaration.environment,appOrigin:this.declaration.origin,release:$s()})}initialize(){if(this.initialization)return this.initialization;let e=this.incarnation,t=Promise.resolve().then(async()=>{if(this.check(),typeof kg.url!="string")throw L0();let r=new URL(kg.url);if(kt(r)!==this.declaration.origin||Rt()!==this.declaration.origin)throw A("unavailable","Application module binding unavailable","application_worker_module_binding");let o=this.environment(),s=T1(this.declaration.environment,this.declaration.origin),i=await this.timing.time("capabilities",()=>aO(void 0,this.session.host));if(this.check(),!i.ok)throw A("unavailable","This browser can't run mdbase",{reason:i.problem,details:{missing:i.missing.join(",")}});let a=()=>{if(!this.unsyncedFirst)return;let P={origin:this.declaration.origin,environment:this.declaration.environment};for(let C of[s.runtime,s.sqlite])try{q1(C,P)({signal:this.lifetime.signal}).catch(()=>{})}catch{}},c=Promise.resolve().then(()=>(RE(),OE));c.catch(()=>{});let{registered:l,ApplicationRuntime:p}=await this.timing.time("registration",async()=>({registered:await dm({declaration:this.declaration,signal:this.lifetime.signal,isCurrent:()=>!this.closed,onRequest:a}),ApplicationRuntime:(await c).ApplicationRuntime}));if(this.check(),e!==this.incarnation)throw A("cancelled","Application entry fenced","application_entry_fenced");let d=P1(this.declaration,l);l.supersededDeclaredId&&console.info(`mdbase: ${Wf("application_registration_id_superseded")}`);let u=Xf(this.declaration),f=Object.freeze({cpOrigin:o.cpOrigin,appId:d.id,...u===null?{}:{storageNamespace:u}}),h=P=>(this.runtime=P,this.unsyncedTried=!1,P.subscribe(()=>{this.hint?.observe(P.getNativeSnapshot()),this.observeSignOut(P),P.getNativeSnapshot().signIn?.state==="paired"&&this.tabs?.signedIn(),this.notify(),this.awaitOtherTab(P,f)}),P.setForeground(this.foreground),this.notify(),P),m=this.tabsFor(f),w=new AbortController;this.election?.abort(),this.election=w;let b=await this.timing.time("election",()=>m.elect(AbortSignal.any([this.lifetime.signal,w.signal])));if(this.closed||this.hidden||e!==this.incarnation||w.signal.aborted)throw b.kind==="follower"?b.leave():m.resign(),A("cancelled","Application entry fenced","application_entry_fenced");if(b.kind==="follower")return h(new p({declaration:d,compiledManifest:this.compiled,typeIssues:this.typeIssues,cpOrigin:o.cpOrigin,port:b.port,binding:b.binding,releaseWorker:()=>b.leave(),nativeAuthorization:(P,C,R)=>this.nativeAuthorization(P,C,R)}));let g=new MessageChannel,y=crypto.randomUUID(),_,v=this.createWorker,k=v?new URL("./worker.js",r).href:null;try{if(!v)_=new Worker(new URL("./worker.js",kg.url),{type:"module"});else if(_=v(k),!qD(_))throw new TypeError("not a Worker")}catch{throw m.resign(),g.port1.close(),g.port2.close(),A("unavailable","Application Worker construction unavailable","application_worker_unavailable")}let S=P=>{P.preventDefault(),g.port1.dispatchEvent(new MessageEvent("messageerror")),m.fault()};_.addEventListener("error",S);let x=new p({declaration:d,compiledManifest:this.compiled,typeIssues:this.typeIssues,cpOrigin:o.cpOrigin,port:g.port1,binding:y,releaseWorker:()=>{_.removeEventListener("error",S),_.terminate(),m.resign()},nativeAuthorization:(P,C,R)=>this.nativeAuthorization(P,C,R)});try{_.postMessage([cr,y,d,...k!==null?[u,k]:u===null?[]:[u]],[g.port2])}catch{throw _.removeEventListener("error",S),_.terminate(),m.resign(),g.port1.close(),g.port2.close(),A("unavailable","Application bootstrap unavailable","application_worker_binding")}return m.lead({attach:(P,C)=>_.postMessage([cr,y,"attach",C],[P]),detach:P=>_.postMessage([cr,y,"detach",P])}),h(x)}).catch(r=>{let o=this.initialization===t;if(o&&(this.initialization=null),!this.closed&&o){let{problemDetail:s,...i}=this.snapshot,a=r instanceof oe&&r.reason==="application_registration_refused"?qs(r.details):null;this.snapshot=Object.freeze({...i,status:"blocked",problem:typeof r?.reason=="string"?r.reason:typeof r?.code=="string"?r.code:"application_entry_unavailable",...a?{problemDetail:Object.freeze({name:"MdbaseError",code:r.code,registration:a})}:{}}),this.notify()}throw r});this.initialization=t;{let{problemDetail:r,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 r=e.getNativeSnapshot().status;return r==="not_started"||r==="starting"||r==="blocked"&&!e.getNativeSnapshot().signIn?e.queue(()=>e.start(t)):Promise.resolve()}reservePortal(e){this.check();let t=this.environment(),r=e.signal?AbortSignal.any([this.lifetime.signal,e.signal]):this.lifetime.signal,o=ql(this.declaration.environment),s=()=>!this.closed,i=this.signIn?gI(t.cpOrigin,r,s,this.signIn,o):qm(t.cpOrigin,r,s,o);return{portal:Em(i),signal:r}}requestAccess(e,t){try{this.check();let r=this.runtime,o=r?.getNativeSnapshot(),s=o?.selectedCollectionId??null,i=Xm(this.compiled),a=()=>s&&r?Qm(r.getNativeSnapshot(),s):[],c=rO(i,e,t,a()),l=s?r.connection(s):null;if(!r||!s||!l)throw A("invalid_request","requestAccess needs an open collection","access_no_collection");let p=()=>iO(l.files,i,a());if(!c.length)return Promise.resolve(p());let{portal:d,signal:u}=this.reservePortal(t);return oO({granted:p,native:()=>r.getNativeSnapshot(),start:()=>r.queue(()=>r.requestFileAccess(d,s,c,t.reason,{signal:u})),poll:f=>r.queue(()=>r.pollFileAccess(f))},d,u)}catch(r){return Promise.reject(r)}}approve(e,t={}){let r=this.choose(),o=r.getSnapshot(),s=this.approvalPortal;if(s&&o.approval){if((e===void 0?o.requested.collectionId:e)!==o.approval.collectionId)return Promise.reject(new hn("application_selection_busy"));if(t.signal?.aborted)throw A("cancelled","Application entry fenced","application_entry_fenced");return s.closed||s.focus(),Promise.resolve()}return r.approve(e,t)}authorize(e={},t=null){let r;try{r=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(r,e,t)))).catch(o=>{try{r.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 r=t.getNativeSnapshot().signOutResult??null;await this.signedOut(t,r);let o=this.snapshot.signOutResult??r;return o&&await jD(o),this.getSnapshot()}async signedOut(e,t,r=!1){r||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:Ag,...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(),r){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){return this.tabs??=new ty({...e,build:this.session.build===null?kg.url:`app-build/${this.session.build}`},{locks:globalThis.navigator.locks,BroadcastChannel:globalThis.BroadcastChannel},this.leaderLost,this.signedInElsewhere,{lead:this.session.host,wanted:this.hostWanted})}leaderLost=e=>{if(this.closed||this.hidden)return;let t=this.runtime,r=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&&r&&(++this.incarnation,this.initialization=null),!r||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:Ag}),this.notify(),this.selection?.resync(),this.mdbase.start().catch(()=>{})};hostWanted=()=>{this.closed||this.hidden||this.signingOut||this.runtime!==null||this.initialization!==null||(this.selection?.resync(),this.mdbase.start().catch(()=>{}))};signedInElsewhere=()=>{this.closed||this.hidden||this.signingOut||this.runtime!==null||this.initialization!==null||this.snapshot.status!=="signed_out"||(this.selection?.resync(),this.mdbase.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")},r=()=>{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",r,{signal:this.lifetime.signal}),o.addEventListener("online",r,{signal:this.lifetime.signal})),t()}followNetwork(){let e=typeof window>"u"?globalThis:window;if(typeof e.addEventListener!="function")return;let t=()=>{this.closed||(this.revision++,this.notify(!1))};e.addEventListener("online",t,{signal:this.lifetime.signal}),e.addEventListener("offline",t,{signal:this.lifetime.signal})}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,r=this.signIn?.returnUrl!==void 0&&!/^https?:/i.test(this.signIn.returnUrl);t&&typeof t.addEventListener=="function"&&!r&&(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:r,...o}=this.snapshot;this.snapshot=Object.freeze({...o,status:t?"starting":this.snapshot.status,problem:null,selectedCollectionId:null,readiness:Ag})};pageShown=e=>{let t=this.hidden;this.closed||!t||!e.persisted||(this.hidden=null,this.notify(),t.resume&&(this.selection?.resync(),this.mdbase.start().catch(()=>{})))};awaitingOtherTab=!1;awaitOtherTab(e,t){let r=e.getNativeSnapshot(),o=globalThis.navigator?.locks;if(this.awaitingOtherTab||this.closed||r.status!=="blocked"||r.problem!=="open_in_another_tab"||!o)return;this.awaitingOtherTab=!0;let s=this.incarnation,i=this.lifetime.signal,a=()=>!this.closed&&!this.hidden&&s===this.incarnation&&this.runtime===e;W1(o,t,i).then(()=>ID(i)).then(()=>{this.awaitingOtherTab=!1,a()&&(this.selection?.resync(),this.mdbase.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}transferLedger(){let e=this.declaration.storage.unsyncedDatabaseName,t=new AbortController().signal;return Object.freeze({read:(r,o)=>XI(e,r,o??t),record:(r,o,s)=>QI(e,r,o,s??t)})}transferDestination(e){let t=this.getSnapshot().phase;if(t.kind!=="ready")throw A("invalid_request","Open the collection to bring this work into first.","unsynced_transfer_needs_collection");if(e!==null&&t.collectionId!==e)throw A("invalid_request","This plan is for another collection. Plan the transfer again.","unsynced_transfer_plan_stale");return t.connection}connection(e){return this.closed?null:this.privates?.connection(e)??this.runtime?.connection(e)??null}};function ME(n,e={}){return new Sg(n,e).mdbase}Tl();am();ie();function LE(n,e){let t=Jo(so(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 r=new Set(e.records.hello.grant.capabilities),o=new Set(t.required),s=Object.freeze([...new Set([...t.required,...t.optional??[]])].map(i=>Object.freeze({id:i,requirement:o.has(i)?"required":"optional",state:r.has(i)?"available":"missing"})));return Object.freeze({values:s,requiredAvailable:s.every(i=>i.requirement==="optional"||i.state==="available"),missing:Object.freeze(s.filter(i=>i.state==="missing").map(i=>i.id))})}Ye();ve();Es();Ua();up();ve();ie();la();lc();Qd();function jE(n){let e=N(n.collection),t=n.grant?N(n.grant):null;return Mi({description:`relay:${n.collection}`,staticKey:n.staticKey,target:async()=>{let r=await n.resolveRoute();if(!r)throw A("unavailable","no device of this collection is online","no_device_online");let o=Ti(e,t,N(r.targetDevice));return{prologue:o,...r.prologueFirst&&!r.pipe?{preamble:o}:{},remoteStatic:r.noisePublicKey,device:r.targetDevice,openCarrier:s=>r.pipe?cc(r.url,{accessToken:r.pipe.accessToken,collection:r.pipe.collection,grant:n.grant??"",device:r.targetDevice,devicePublicKey:r.noisePublicKey},n.webSocket,s):ac(r.url,n.webSocket,s)}}})}mA();lc();la();Ye();ve();ie();Zt();la();lc();var ND=new Uint8Array(16);function U0(n,e){if(n.length!==32)throw A("invalid_request","the link token is 32 bytes");let t=Ki.dec(e);if(t.kind!=="request"||t.method!=="hello")throw A("internal","expected the hello request");return ue(new Map([[0,n],[1,t.params]]))}function UE(n){let e=N(n.collection),t=n.staticKey??sc(),r=null;return Mi({description:"localhost-link",staticKey:t,firstPayload:o=>U0(r.token,o),target:async()=>{r=typeof n.link=="function"?await n.link():n.link;let o=r;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?ND:N(o.device));return{prologue:s,preamble:s,remoteStatic:o.noisePublicKey,openCarrier:i=>ac(`ws://127.0.0.1:${o.port}/v1/plugin`,n.webSocket,i)}}})}ky();ie();function N0(){let n=new Map;return{get:async e=>n.get(e),put:async(e,t)=>{n.set(e,t)},putIfAbsent:async(e,t)=>{let r=n.get(e);return r||(n.set(e,t),t)},delete:async e=>{n.delete(e)}}}function D0(n="mdbase-keys",e="keys"){let t=globalThis.indexedDB;if(!t)throw A("invalid_request","IndexedDB is not available here; pass another KeyStorage");let r=()=>new Promise((i,a)=>{let c=t.open(n,1);c.onupgradeneeded=()=>c.result.createObjectStore(e),c.onsuccess=()=>i(c.result),c.onerror=()=>a(c.error)}),o=async(i,a)=>{let c=await r();try{return await new Promise((l,p)=>{let d=c.transaction(e,i),u,f=!1;d.oncomplete=()=>f?l(u):p(A("unavailable","key storage transaction completed without a result","key_storage")),d.onabort=()=>p(d.error??A("unavailable","key storage transaction aborted","key_storage")),d.onerror=()=>p(d.error??A("unavailable","key storage transaction failed","key_storage"));try{a(d.objectStore(e),h=>{u=h,f=!0})}catch(h){d.abort(),p(h)}})}finally{c.close()}},s=(i,a)=>o(i,(c,l)=>{let p=a(c);p.onsuccess=()=>l(p.result)});return{get:i=>s("readonly",a=>a.get(i)),put:(i,a)=>s("readwrite",c=>c.put(a,i)).then(()=>{}),putIfAbsent:(i,a)=>o("readwrite",(c,l)=>{let p=c.get(i);p.onsuccess=()=>{if(p.result!==void 0){l(p.result);return}try{let d=c.add(a,i);d.onsuccess=()=>l(a)}catch{c.transaction.abort()}}}),delete:i=>s("readwrite",a=>a.delete(i)).then(()=>{})}}function zE(){return globalThis.crypto?.subtle}async function DD(){let n=zE();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 zD(n){return n.kind==="raw"?{publicKey:n.publicKey,nonExtractable:!1,dh:e=>ni.getSharedSecret(n.secretKey,e)}:{publicKey:n.publicKey,nonExtractable:!n.privateKey.extractable,dh:async e=>{let t=zE(),r=await t.importKey("raw",e,{name:"X25519"},!1,[]),o=await t.deriveBits({name:"X25519",public:r},n.privateKey,256);return new Uint8Array(o)}}}var $D=N0(),NE=new WeakMap;function DE(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 $E(n,e={}){let t=e.storage??(globalThis.indexedDB?D0():$D),r=e.requireNonExtractable,o=NE.get(t);o||(o=new Map,NE.set(t,o));let s=o.get(n);s||(s=(async()=>{let i=await t.get(n);if(i)return i;let a=await DD();if(!a){if(r)throw A("invalid_request","this platform cannot keep a non-extractable X25519 key","key_storage");let c=ni.utils.randomSecretKey();a={kind:"raw",secretKey:c,publicKey:ni.getPublicKey(c)}}return DE(a,r),t.putIfAbsent?t.putIfAbsent(n,a):(await t.put(n,a),a)})(),o.set(n,s));try{let i=await s;return DE(i,r),zD(i)}finally{o.get(n)===s&&o.delete(n)}}Qd();om();Ye();qo();ie();function z0(n,e){for(let t of n.targets??[]){if(!/^[0-9a-f]{64}$/i.test(t.noise_pk)||!t.url||!t.device)continue;let r={url:t.url,targetDevice:t.device,noisePublicKey:Bi(t.noise_pk)};return t.relay_collection?r.pipe={collection:t.relay_collection,accessToken:e}:t.kind==="hosted"&&(r.prologueFirst=!0),r}return null}function BE(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`,r=n.fetch??globalThis.fetch.bind(globalThis);return async()=>{let o=await n.accessToken(),s;try{s=await r(t,{headers:{authorization:`Bearer ${o}`},redirect:"error",credentials:"omit"})}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 i=await s.json(),a=wr(i.availability);if(a?.state==="unavailable")throw Vn(a.reason);let c=z0(i,o);if(!c&&i.reason==="no_device_registered")throw A("unavailable","this collection has no device set up to serve it","no_device_registered");return c}}$m();x_();qo();Es();var B0={};Ca(B0,{APP_BASES_PROFILE:()=>jb,APP_COLLECTION_SETUP_LIMITS:()=>lo,AppAccountKeyProofUnavailableError:()=>ts,AppAccountKeySealedBundle:()=>bc,AppAccountKeyUnlockError:()=>pt,AppCloudCopyBootstrapError:()=>Rn,AppCloudCopyHostError:()=>fr,AppCollectionControlError:()=>Rr,AppCollectionJoinError:()=>fs,AppCollectionJoinLedger:()=>Oc,AppCollectionSetupError:()=>qn,AppCollectionSetupJournal:()=>Wl,AppCpAccountKeyControl:()=>wc,AppCpAuthorityError:()=>lr,AppCpCloudCopyBootstrap:()=>Vl,AppCpDeviceRegistration:()=>xc,AppCpLogAuthority:()=>Bl,AppCpPeopleAuthority:()=>fc,AppDeviceRegistrationError:()=>va,AppHttpLogError:()=>On,AppHttpLogTransport:()=>$l,AppIndexedDbDeviceKeyProtectedStore:()=>Ac,AppIndexedDbDeviceKeyProvider:()=>_c,AppIndexedDbNoiseProtectedStore:()=>Sc,AppInstallationSignInError:()=>tt,AppLogHostError:()=>Pt,AppLogPump:()=>ea,AppProtectedInstallationSignIn:()=>Dl,AppReplicaOwnerError:()=>it,AppStrictDeviceApprovalError:()=>Mt,AppWasmRuntime:()=>Ql,AppWebCloudCopyHost:()=>Cc,AppWebCollectionError:()=>yu,AppWebDeviceKeyCustody:()=>kc,AppWebNoiseCustody:()=>Pc,AppWebSignInSession:()=>xg,UNSYNCED_STORAGE_WARNING:()=>cO,acquireAppInstallationLease:()=>_d,acquireAppReplicaLease:()=>vd,appBrowserDirectAccess:()=>Pg,appCollectionControlClient:()=>zm,appInstallationLockName:()=>Xv,appLocalConnector:()=>Vm,appLogHealth:()=>Ld,appModelPackPlan:()=>Ys,appModelResourcePlan:()=>$t,appMutationSaveState:()=>lO,appReplicaLockName:()=>wm,appSaveState:()=>ny,appStoragePolicy:()=>ry,attachAppLocalFacade:()=>Bm,createAppCollectionPeople:()=>Nm,createAppWebCollectionAdapter:()=>oE,decodeAppBasesCell:()=>Ps,decodeAppBasesDiscoveryResult:()=>of,decodeAppBasesResult:()=>nf,decodeAppBasesSourceResult:()=>sf,decodeAppCollectionSetupIntent:()=>Jt,encodeAppBasesDiscoveryRequest:()=>pp,encodeAppBasesRequest:()=>tf,encodeAppBasesSourceRequest:()=>rf,openAppWebCollectionClient:()=>hg,openOwnedAppWorker:()=>H1,probeAppStorage:()=>KE,readAccountKeyMode:()=>ig,selectAppEnvironment:()=>Cr,unlockPrivateDevice:()=>og,verifyAppHandover:()=>FE});Fm();Ub();function VE(n,e){return n.seq===e.seq&&n.chain===e.chain&&n.policyGeneration===e.policyGeneration&&n.catalogGeneration===e.catalogGeneration}async function FE(n,e){let t=null;try{let{runtime:r,localPort:o,localClient:s,hostedClient:i,source:a}=n,c=i.hello,l=s.hello,p=a.collection,d=a.deviceId,u=i.authenticatedDevice;if(!(P=>typeof P=="string"&&P.replace(/-/g,"").toLowerCase()===d.replace(/-/g,"").toLowerCase())(u))return null;let h=c.status.confirmedHead,m=h?Object.freeze({...h}):void 0;if(!m||!c.headWitness||c.headWitness.length>64*1024||m.seq===0||c.collection!==p||l.collection!==p)return null;t=new Uint8Array(c.headWitness);let w=t,b=()=>{try{return!e.aborted&&n.isCurrent()===!0&&a.isCurrent()===!0&&l.collection===p&&a.collection===p&&a.deviceId===d&&s.hello===l}catch{return!1}},g=()=>{try{let P=r.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(!b()||!g())return!1;let P=r.verifyHandover(o,a,w);return P!==null&&VE(P,m)},_=()=>{try{return!e.aborted&&b()&&i.hello===c&&i.authenticatedDevice===u}catch{return!1}};if(!_()||!y())return null;let v=await s.appliedPrefix(m.seq,{signal:e});if(!_()||!y()||v.seq!==m.seq||v.appliedThrough<m.seq||v.chain!==m.chain)return null;let k=Object.freeze({...m}),S=!1,x={head:k,appliedThrough:v.appliedThrough,isCurrent:()=>{if(S)return!1;try{return y()&&VE(k,m)}catch{return!1}},dispose:()=>{S=!0,w.fill(0)}};return t=null,x}catch{return null}finally{t?.fill(0)}}m0();l0();s0();a0();h0();u0();Id();Cd();RA();xd();Hm();Wm();async function KE(n){if(!n.worker)return{supported:!1,reason:"worker_required"};if(!n.storage?.getDirectory)return{supported:!1,reason:"opfs_unavailable"};let e,t,r=!1,o,s={supported:!1,reason:"probe_failed"};try{let i=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(i))return s;t=i.toLowerCase(),e=await(await n.storage.getDirectory()).getDirectoryHandle(".mdbase-app-probes",{create:!0});let a=await e.getFileHandle(t,{create:!0});if(r=!0,!a.createSyncAccessHandle)s={supported:!1,reason:"sync_handle_unavailable"};else{o=await a.createSyncAccessHandle();let c=new Uint8Array([109,100,98,110]),l=new Uint8Array(c.length);if(o.write(c,{at:0})!==c.length)throw new Error("short probe write");if(o.flush(),o.read(l,{at:0})!==c.length||l.some((p,d)=>p!==c[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 i=!0;try{o?.close()}catch{i=!1,s={supported:!1,reason:"cleanup_failed"}}if(r&&i&&e&&t)try{await e.removeEntry(t)}catch{s={supported:!1,reason:"cleanup_failed"}}}return s}Qo();Xo();y0();es();qd();Js();v_();fg();Sd();var $0=Object.freeze({status:"unsupported"}),Pg=Object.freeze({snapshot(){return $0},async check(n={}){return n.signal?.throwIfAborted(),$0},async request(n={}){return n.signal?.throwIfAborted(),$0},disable(){}});nr();Sd();mu();dI();ie();Sd();mu();Id();Js();es();fg();Cd();xd();VA();fu();Qo();vc();nr();var BD=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","private_device_limit","private_device_not_allowed"]),VD=new Set(["AbortError","ConstraintError","DataCloneError","InvalidStateError","NotAllowedError","NotFoundError","NotReadableError","OperationError","QuotaExceededError","SecurityError","TimeoutError","TransactionInactiveError","UnknownError","VersionError"]),FD=new Set(["device_open","push_nonce","local_read_without_log","read_connect","read_catch_up","read_query","key_wait_offline","close_fence"]),mo=(n,e,t,r={})=>Object.freeze({problem:n,detail:Object.freeze({name:e,code:t,...Object.fromEntries(Object.entries(r).filter(([,o])=>o!==void 0))})});function KD(n){let e=FD.has(n.stage)?n.stage:void 0;if(e!=="device_open"||n.cause instanceof fr)return{stage:e};let{name:t,code:r}=Dc(n.cause).detail;return{stage:e,cause:Object.freeze({name:t,code:r})}}function Dc(n){try{for(let[e,t]of[[tt,"AppInstallationSignInError"],[fr,"AppCloudCopyHostError"],[Rn,"AppCloudCopyBootstrapError"],[qn,"AppCollectionSetupError"],[Rr,"AppCollectionControlError"],[fs,"AppCollectionJoinError"],[lr,"AppCpAuthorityError"],[On,"AppHttpLogError"],[ha,"AppPrivateBootstrapError"],[pt,"AppAccountKeyUnlockError"]])if(n instanceof e){let r=n.reason,s={server:("server"in n?To(n.server):null)??void 0,...n instanceof fr?KD(n):{}};return r==="sync_stalled"?mo("unavailable",t,r,s):BD.has(r)?mo(r,t,r,s):mo("open_failed",t,null,s)}if(n instanceof Lr)return mo(n.reason,"AppDeviceCustodyError",n.reason);if(n instanceof it&&n.reason==="busy")return mo("open_in_another_tab","AppReplicaOwnerError","busy");if(n instanceof oe){let e=vo(n.code)?n.code:null;return mo(e==="outcome_unknown"?e:"open_failed","MdbaseError",e)}if(typeof DOMException<"u"&&n instanceof DOMException){let e=VD.has(n.name)?n.name:null;return mo("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 mo("open_failed",t,null)}catch{}return mo("open_failed","UnknownError",null)}Id();Xo();Qo();f0();ie();var WD=Object.freeze({status:"unselected",problem:null,transport:null,live:null}),mt=n=>new tt(n),WE=(n,e,t)=>n.problem===void 0||n.problem===e?t:void 0,HD=new Set(["collection_not_yet_migrated","collection_migrating","account_suspended","update_required"]),xg=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;restoredPending=!1;acknowledged=!1;consentPending=!1;listCached=!1;fileAccess=null;freshApproval=!1;approvalWindow=null;leftForApproval=!1;nativePending=null;forgotten=new Set;removedScopes=new Set;onAbort=()=>{this.close().catch(()=>{})};constructor(e){this.options=Object.freeze({...e}),this.environment=Cr({environment:e.environment,appOrigin:e.origin,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 r=this.base,o=e===null?void 0:this.slots.get(e);if(!o)return r;if(r.status!=="unselected"&&!t)return Object.freeze({...r,selectedCollectionId:o.id,transport:o.view.transport,live:o.view.live});let{problemDetail:s,...i}=r,{problemDetail:a,...c}=o.view;return Object.freeze({...i,...t?{status:"unselected",problem:null,approval:null}:{},...c,selectedCollectionId:o.id,...a?{problemDetail:a}:{}})}connection(e=this.focus){let t=e===null?void 0:this.slots.get(e),r=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()||!r||!["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=Pg;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 mt("fenced")}publish(e){this.check(),this.setBase(e),this.changed()}setBase(e){let{problemDetail:t,...r}=this.base,o=e.problemDetail??WE(e,r.problem,t);this.base=Object.freeze({...r,...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 r=this.base.timing;if(this.authorizationStartedAt!==null&&(t.status==="ready"||t.status==="setup_required")){let u=Math.max(0,performance.now()-this.authorizationStartedAt);r=Object.freeze({firstScreenMs:r?.firstScreenMs??u,readyMs:t.status==="ready"?r?.readyMs??u:r?.readyMs??null})}this.setBase({timing:r});let{problemDetail:o,unlock:s,...i}=e.view,{unlock:a,...c}=t,l=t.problemDetail??WE(t,i.problem,o),p=(t.status??i.status)==="opening"?"openingProgress"in t?t.openingProgress??null:i.openingProgress??null:null,d=(t.status??i.status)==="needs_unlock"?a??s??null:null;e.view=Object.freeze({...i,...c,openingProgress:p,...d?{unlock:d}:{},...l?{problemDetail:l}:{}}),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(mt("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:i,detail:a}=Dc(s);if(i==="open_failed")try{console.error("mdbase web sign-in open failed",a.name,a.code)}catch{}let c=this.openingSlot;if(this.openingSlot=null,c&&this.slots.get(c.id)===c){let l=!1;try{l=s instanceof Rn&&s.reason==="unavailable"&&s.retryable===!0&&c.view.status==="opening"&&this.base.collections.some(p=>p.collectionId===c.id)&&this.flow?.view().state==="paired"&&this.installation?.isCurrent()===!0}catch{}if(l){try{await this.closeSlot(c),this.check()}catch(p){throw!this.closing&&!this.options.signal.aborted&&this.publishSlot(c,{status:"blocked",problem:"recovery_required",problemDetail:Dc(p).detail}),p}this.publishSlot(c,{status:"unselected",problem:i,problemDetail:a})}else this.publishSlot(c,{status:"blocked",problem:i,problemDetail:a})}else this.publish({status:"blocked",problem:i,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 Dl.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(await this.openDevice(!1,this.options.recoveryFor!==void 0),await this.abandonUnfinishedNativeChoice(),this.flow.collectionConsentView()?.state==="pending")this.consentPending=!0,this.publish({status:"authorizing"});else{let r=null;try{r=this.flow.cachedApprovedCollections(this.installation)}catch{r=null}await this.refreshCollections(r)}else this.restoredPending=t.state==="pending"&&this.flow.requestSent(),this.publish({status:t.state==="pending"&&!this.restoredPending?"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(mt("busy"));let r=this.options.openPortal();return t?t.catch(()=>{}).then(()=>{try{this.check()}catch(s){throw r.close(),s}if(this.pending)throw r.close(),mt("busy");let o=this.base.status;return o!=="authorizing"&&o!=="signed_out"?(r.close(),this.getSnapshot()):this.beginAuthorization(r,e)}):this.beginAuthorization(r,e)}beginAuthorization(e,t){let r={collectionHint:t.collectionHint??null},o=this.flow.view();return this.restoredPending=!1,this.authorizationStartedAt=performance.now(),this.publish({timing:Object.freeze({firstScreenMs:null,readyMs:null}),approval:null}),this.operation(async()=>{try{if(o.state==="paired"){await this.openDevice(),this.check(),await this.abandonUnfinishedNativeChoice();let s=await this.flow.startCollectionConsent(this.installation,this.options.requestedCreateCollections??this.options.freshRequestedCreateCollections??!1,r,this.options.freshRequestedPrivateDevice===!0);this.check(),this.consentPending=!0,e.navigate(s.verificationUri)}else{let s=await this.flow.start(r).catch(i=>this.renewFromGesture(i));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 tt&&s.server?.status===429&&(this.authorizationRateLimit=s,this.authorizationRetryAt=Date.now()+Math.min(Ya,Math.max(Ga,s.server.retryAfterMs??3e4))),e.close(),s}})}requestFileAccess(e,t,r){if(this.check(),!this.flow||this.pending)return Promise.reject(mt("busy"));let o=this.options.openPortal();return this.operation(async()=>{try{if(this.flow.view().state!=="paired"||!this.installation||!this.base.collections.some(i=>i.collectionId===e))throw mt("refused");let s=await this.flow.startFileAccess(this.installation,e,t,r);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 r={state:"pending"};try{r=await this.flow.exchangeFileAccess(this.installation,t)}catch{}if(this.check(),this.fileAccess!==t||r.state==="pending"&&Date.now()<t.expiresAt)return this.getSnapshot();this.fileAccess=null,this.closeApprovalWindow();let o=r.state==="granted"?r.actions:null,s=o?Object.freeze(this.base.collections.map(i=>i.collectionId!==t.collectionId?i:Object.freeze({...i,fileActions:Object.freeze([...new Set([...i.fileActions??[],...o])])}))):this.base.collections;return this.publish({collections:s,fileAccess:Object.freeze({requestId:e,collectionId:t.collectionId,actions:o??t.actions,state:r.state==="pending"?"expired":r.state})}),this.getSnapshot()},!0)}async renewFromGesture(e){if(!(e instanceof tt)||e.reason!=="expired"&&e.reason!=="refused")throw e;try{return await this.flow.renewExpiredPairing()}catch(t){throw t instanceof tt&&t.reason==="recovery_required"?e:t}}renewExpiredPairing(){return this.operation(async()=>{if(!this.flow)throw mt("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(),r=this.consentPending?e.collectionConsentView():null;return(this.consentPending?r?.state!=="pending":!["pending","awaiting_approval"].includes(t.state))?null:JSON.stringify([t.requestId,t.installationId,t.deviceId,t.accountId,t.state,this.consentPending,r?.requestId,r?.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,r=this.pending,o=t?this.receiptGeneration(t):null,s=t&&r&&o!==null?Object.freeze({flow:t,operation:r,generation:o,caller:this.options.signal,installation:this.installation,attested:this.attested,acknowledged:this.acknowledged}):null;this.receiptRead=s;let i=!1;try{let a=await e();return i=a!=null,a}catch(a){if(a instanceof tt&&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&&(!i||!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(r){if(!(r instanceof tt)||r.reason!=="refused"&&r.reason!=="expired")throw r;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 mt("account_confirmation_required");let r=this.flow.pendingNativeSelection?.();if(r?.requestId===t.requestId){if(!await this.settleNativeChoice(r)){this.consentPending=!1,this.closeApprovalWindow(),this.publish({status:"unselected",problem:null,approval:Object.freeze({outcome:"closed"})}),await this.refreshCollections();return}}else if(this.flow.view().collectionSelection?.requestId!==t.requestId&&!this.deviceAccessWithoutPick(t.requestedPrivateDevice===!0?t.addedCollectionIds:[]))throw mt("response");this.consentPending=!1,this.freshApproval=!0,this.closeApprovalWindow(),await this.refreshCollections()}else await this.prepareNativeChoice(),this.resumeApprovalWindow(),this.publish({status:"authorizing",problem:null});return}let e;try{e=await this.exchangeReceipt(()=>this.flow.exchange())}catch(t){if(!this.restoredPending||!(t instanceof tt)||t.reason!=="expired"&&t.reason!=="refused")throw t;this.check(),this.restoredPending=!1,this.publish({status:"signed_out",problem:null});return}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(),this.resumeApprovalWindow()),e.state==="paired"){let t=this.flow.pendingNativeSelection?.(),r=t?.requestId===e.requestId&&!await this.settleNativeChoice(t);if(t?.requestId!==e.requestId&&e.collectionSelection?.requestId!==e.requestId&&!this.deviceAccessWithoutPick(e.privateDeviceCollectionIds??[]))throw mt("response");this.freshApproval=!0,this.closeApprovalWindow(),await this.openDevice(),this.check(),r&&this.publish({approval:Object.freeze({outcome:"closed"})}),await this.refreshCollections()}else this.publish({status:"authorizing",problem:null})}deviceAccessWithoutPick(e){let t=this.flow.view(),r=t.privateDeviceCollectionIds??[];return(t.collectionSelection??null)===null&&e.some(o=>r.includes(o))}resumeApprovalWindow(){if(!(!this.leftForApproval||!this.foreground||!this.approvalWindow||!this.appPartDone())){this.leftForApproval=!1;try{this.approvalWindow.focus?.()}catch{}}}appPartDone(){if(!this.attested)return!1;if(!this.approvalWindow?.nativeAuthorization||!this.installation||!this.flow.nativeAuthorizationContext(this.installation))return!0;let e=this.nativePending;return e!==null&&(e.attempted||e.failed)}async prepareNativeChoice(){let e=this.approvalWindow?.nativeAuthorization;if(!e||!this.installation)return;let t=this.flow.nativeAuthorizationContext(this.installation);if(!t)return;let r=this.nativePending;if(!r){if(r={context:t,port:e,life:new AbortController,prepared:null,failed:!1,attempted:!1},this.nativePending=r,t.authorizationId){r.failed=!0;return}let o=r,s=AbortSignal.any([this.lifetime.signal,this.flowLifetime.signal,r.life.signal]);e.prepare(t,s).then(i=>{this.nativePending!==o||s.aborted||(o.prepared=Object.freeze({...i}))},()=>{o.failed=!0})}if(r.context.requestId!==t.requestId||r.context.accountId!==t.accountId||r.context.challenge!==t.challenge)throw mt("fenced");if(r.prepared&&!r.attempted){r.attempted=!0;try{await this.flow.attachNativeAuthorization(this.installation,r.context,r.prepared),this.check()}catch{r.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 mt("recovery_required");let r=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 mt("fenced");await this.flow.completeNativeAuthorization(this.installation,r),this.check()}async settleNativeChoice(e){await this.openDevice(),this.check();try{return await this.finishNativeChoice(e),!0}catch(t){this.check();let r=!1;try{r=this.installation!==null&&await this.flow.abandonNativeSelection?.(this.installation)===!0}catch{r=!1}if(this.check(),!r)throw t;try{console.warn("mdbase: a Private collection pick was not finished",Dc(t).detail.code)}catch{}return!1}}async abandonUnfinishedNativeChoice(){let e=this.flow;if(!e.pendingNativeSelection?.()||e.view().nativeSelection)return;if(!this.installation||!e.abandonNativeSelection)throw mt("recovery_required");let t=await e.abandonNativeSelection(this.installation);if(this.check(),!t)throw mt("recovery_required")}holdApprovalWindow(e){this.approvalWindow!==e&&this.closeApprovalWindow(),this.approvalWindow=e,this.leftForApproval=!1}closeApprovalWindow(){let e=this.approvalWindow;this.approvalWindow=null,this.leftForApproval=!1;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 r=this.flow.confirmedSelection(),o=Object.freeze({account:r.accountId,installation:r.installationId});this.installationLease=await _d(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(r=>r.host!==null)||(this.host?!this.acknowledged&&this.flow.view().state==="paired"&&(await this.host.completeInstallationSignIn(),this.check(),this.acknowledged=!0):(this.host=await Cc.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}),this.check(),this.acknowledged=this.flow.view().state==="paired"))}async refreshCollections(e=null){let t=e??await this.flow.listApprovedCollections(this.installation);if(this.check(),this.listCached=e!==null,!e)for(let s of this.flow.view().collectionIds)t.some(i=>i.collectionId===s)||this.removedScopes.add(s);let r=Object.freeze(t.filter(s=>!this.forgotten.has(s.collectionId)));for(let s of this.slots.values()){if(s.usable&&s.selected&&!r.some(p=>p.collectionId===s.id)){s.usable=!1,s.lifetime?.abort(),await this.closeSlot(s),this.check(),this.deleteSlot(s);continue}let i=s.usable&&s.selected!==null&&r.some(p=>p.collectionId===s.id),{problemDetail:a,unlock:c,...l}=s.view;s.view=Object.freeze({...l,...i?this.assessed(s.selected):{status:"unselected"},problem:null})}this.publish({status:"unselected",collections:r,problem:null});let o=this.flow.view().collectionSelection?.selectedCollectionId;(this.options.autoSelect??"only")==="only"&&(this.freshApproval&&o&&r.some(s=>s.collectionId===o)?await this.openSlot(o,!0):r.length===1&&await this.openSlot(r[0].collectionId,!0))}schedulePoll(){if(this.pending&&!this.closing&&!this.options.signal.aborted)return;let e=this.foregroundRead;this.foregroundRead=null;for(let r of this.closing||this.options.signal.aborted?[]:this.slots.values()){let o=this.retryAfterMs(r);o===null||r.timer!==null||r.view.status!=="blocked"||(r.timer=setTimeout(()=>{r.timer=null,!(this.slots.get(r.id)!==r||r.view.status!=="blocked"||r.view.problem!=="collection_migrating"||this.flow?.view().state!=="paired")&&this.operation(()=>this.openSlot(r.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 r=null;try{r=To(t.problemDetail?.server)?.retryAfterMs??null}catch{r=null}return Math.min(Ya,Math.max(Ga,r??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,this.approvalWindow&&!this.appPartDone()&&(this.leftForApproval=!0)),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 cancelAuthorization(){for(this.check();this.pending;)await this.pending.catch(()=>{}),this.check();return this.operation(async()=>{if(this.base.status!=="authorizing")return this.getSnapshot();this.closeApprovalWindow();let e=Object.freeze({outcome:"closed"});return this.consentPending?(this.consentPending=!1,this.publish({status:"unselected",problem:null,approval:e}),await this.refreshCollections()):(await this.flow.forgetSentRequest(),this.check(),this.restoredPending=!1,this.publish({status:"signed_out",problem:null,approval:e})),this.getSnapshot()})}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 r=this.base.collections.find(h=>h.collectionId===e);if(!r||this.flow?.view().state!=="paired"||!this.installation)throw mt("refused");let o=t?[...this.slots.values()].filter(h=>h.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 h of o)h.usable=!1,h.lifetime?.abort();this.focus=e,this.settleBase(),this.publishSlot(s,{...this.assessed(s.selected),problem:null});for(let h of o)await this.closeSlot(h),this.check(),this.deleteSlot(h),this.changed();return}for(let h of o)h.usable=!1,h.lifetime?.abort();let i=s??{id:e,host:null,lease:null,leaseScope:null,selected:null,scope:null,lifetime:null,usable:!1,stopAssessment:null,timer:null,view:WD};i.usable=!1,i.lifetime?.abort(),this.slots.set(e,i),this.focus=e,this.openingSlot=i,this.settleBase(),this.publishSlot(i,{status:"opening",problem:null,openingProgress:null});for(let h of o)await this.closeSlot(h),this.check(),this.deleteSlot(h),this.changed();(i.lease||i.selected||i.host)&&await this.closeSlot(i),this.check(),await this.openDevice(!0),this.check(),i.host=this.host,this.host=null;let a=Object.freeze({...this.installation.scope,collection:e});i.lease=await vd(this.options.locks,a,this.lifetime.signal),i.leaseScope=a,this.check(),i.lifetime=new AbortController;let c=this.freshApproval&&this.flow.view().collectionSelection?.createdCollectionIds.includes(e)===!0,l=i.lifetime,p=await this.options.openCollection({host:i.host,installation:this.installation,scope:a,collection:r,setupPolicy:c?"approved-new-collection":"explicit",signal:l.signal,onProgress:h=>{this.closing||this.slots.get(i.id)!==i||i.lifetime!==l||l.signal.aborted||i.view.status!=="opening"||i.view.openingProgress!==h&&this.publishSlot(i,{openingProgress:h})}});i.selected=p,i.scope=a,this.check();let d=this.assessed(p);i.usable=!0,this.openingSlot===i&&(this.openingSlot=null),i.stopAssessment=p.subscribe?.(()=>{if(this.closing||this.slots.get(i.id)!==i||!i.usable||i.selected!==p||i.lifetime?.signal.aborted||!this.sameScope(i.scope,i.leaseScope)||i.scope?.collection!==i.id)return;let h=null;try{h=p.ended??null}catch{h=null}if(h){this.accessEnded(i,p,h);return}let m=null;try{m=p.failure??null}catch{m=null}if(m!==null){this.openFailedLate(i,p,m);return}let w;try{w=this.assessed(p)}catch{return}this.publishSlot(i,w.status==="needs_unlock"?{...w,problem:null,transport:null,live:null}:{...w,...this.liveProblem(i,p)})})??null;let u=null;try{u=p.ended??null}catch{u=null}let f=null;try{f=p.failure??null}catch{f=null}if(u){this.accessEnded(i,p,u);return}if(f!==null){this.openFailedLate(i,p,f);return}this.publishSlot(i,{...d,transport:null,live:null,openingProgress:null})}assessed(e){let t=e.state;if(t==="ready"||t==="setup_required")return{status:t};if(t!=="needs_unlock"||typeof e.unlock!="function")throw mt("response");let r=e.locked;if(!r||typeof r!="object"||!["password","strict","none"].includes(r.mode)||typeof r.unlocking!="boolean"||r.problem!==null&&(typeof r.problem!="string"||!/^[a-z][a-z0-9_]{0,63}$/.test(r.problem)))throw mt("response");return{status:t,unlock:Object.freeze({mode:r.mode,unlocking:r.unlocking,problem:r.problem})}}unlockCollection(e,t){let r=()=>{let o=this.slots.get(e);return o&&o.usable&&o.selected&&typeof o.selected.unlock=="function"&&o.view.status==="needs_unlock"&&!o.lifetime?.signal.aborted&&this.base.status==="unselected"&&this.installation?.isCurrent()===!0&&this.sameScope(o.scope,o.leaseScope)&&o.scope?.collection===e?o:null};return!this.closing&&!this.options.signal.aborted&&!this.pending&&!r()?Promise.reject(mt("refused")):this.operation(async()=>{let o=r();if(!o)throw mt("refused");let s=o.selected;this.openingSlot=o;try{await s.unlock(t),this.check()}catch(a){throw o.usable=!1,o.lifetime?.abort(),a}if(this.slots.get(o.id)!==o||o.selected!==s||!o.usable)throw mt("fenced");this.openingSlot===o&&(this.openingSlot=null);let i=this.assessed(s);return this.publishSlot(o,i.status==="needs_unlock"?{...i,problem:null}:{...i,...this.liveProblem(o,s)}),this.viewFor(e)})}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,r){if(e.selected!==t||!e.usable)return;let o=r==="gone"?"collection_deleted":r==="revoked"?"unauthenticated":"access_removed";r!=="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 i=await this.flow.listApprovedCollections(this.installation);this.check(),this.publish({collections:Object.freeze(i.filter(a=>!this.forgotten.has(a.collectionId)))})}catch{}}).catch(()=>{})}};s()}openFailedLate(e,t,r){if(e.selected!==t||!e.usable)return;let{problem:o,detail:s}=Dc(r);if(o==="open_failed")try{console.error("mdbase web sign-in open failed",s.name,s.code)}catch{}e.usable=!1,this.publishSlot(e,{status:"blocked",problem:o,problemDetail:s,transport:null,live:null});let i=()=>{if(!(this.closing||this.options.signal.aborted||e.selected!==t||this.slots.get(e.id)!==e)){if(this.pending){this.pending.catch(()=>{}).then(i);return}this.operation(async()=>{await this.closeSlot(e),this.publishSlot(e,{status:"blocked",problem:o,problemDetail:s})},!0).catch(()=>{})}};i()}liveProblem(e,t){let r=null;try{r=t.problem??null}catch{r=null}let o=null;try{o=t.health??null}catch{o=null}let s=o?Object.freeze({...o}):null,i=null;try{let c=t.live;i=typeof c=="boolean"?c:null}catch{i=null}let a=pn(r)?It(r):null;return a&&r?{problem:a,problemDetail:Object.freeze({name:"AppHttpLogError",code:a,server:r}),transport:s,live:i}:{...HD.has(e.view.problem??"")?{problem:null}:{},transport:s,live:i}}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)}collectionListCached(){return this.listCached}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 mt("binding");let r=this.flow.collectionRecoveries(),o=this.slots.get(e);if(t===void 0&&!Object.hasOwn(r,e)&&!this.scopeWasRemoved(e))throw mt("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(),i=this.options;if(!await tE({cpOrigin:i.cpOrigin,appId:i.appId,accountId:s.accountId,connectorId:s.connectorId,installationId:s.installationId,deviceId:s.deviceId,collectionIds:[e],databases:[]},e))throw mt("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(r=>r.collectionId!==e))}),this.getSnapshot()})}deleteCollection(e,t){let r=null;return this.operation(async()=>{let o=this.base.collections.find(s=>s.collectionId===e);if(!this.flow||!this.installation||!o)r=new ei("collection_delete_not_found");else if(o.role!=="owner")r=new ei("collection_delete_not_owner");else{try{await this.flow.deleteApprovedCollection(this.installation,e,t)}catch(s){r=pI(s)}this.check()}return this.getSnapshot()}).then(o=>{if(r)throw r;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,r=null,o=null,s=!1;try{r=t?.view()??null}catch{r=null}try{o=t?.confirmedSelection().connectorId??null}catch{o=null}try{s=t?.hasWebPushChannel()===!0}catch{s=!1}let i=[...new Set([...r?.collectionIds??[],...this.base.collections.map(p=>p.collectionId)])];this.closeApprovalWindow(),this.fileAccess=null,this.consentPending=!1;try{await this.closeSlots()}catch(p){throw this.failSignOut(),p}this.check();let a="not_paired";if(t&&r?.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 c=this.options,l=await nE({cpOrigin:c.cpOrigin,appId:c.appId,...c.owner===void 0?{}:{owner:c.owner},...c.storageNamespace===void 0?{}:{storageNamespace:c.storageNamespace},accountId:r?.accountId??null,connectorId:o,installationId:r?.installationId??null,deviceId:r?.deviceId??null,collectionIds:i,databases:c.localDatabases??[],...c.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,...r}=this.base;this.focus=null,this.emit(Object.freeze({...r,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}};fu();mu();return oq(GD);})();
130
+ `);return{[pd.version]:String(jv),[pd.timestamp]:String(o),[pd.nonce]:s,[pd.signature]:Tn(await kA(n,new TextEncoder().encode(i)))}}async function _A(n,e){let t=await crypto.subtle.generateKey({name:e,namedCurve:"P-256"},!1,n);return{privateKey:t.privateKey,publicKey:Tn(new Uint8Array(await crypto.subtle.exportKey("raw",t.publicKey)))}}async function qN(){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 TN(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 MN(n,e){let t=new AbortController,r=()=>t.abort(),o=setTimeout(r,e);return o.unref?.(),n?.addEventListener("abort",r,{once:!0}),n?.aborted&&t.abort(),{signal:t.signal,done:()=>{clearTimeout(o),n?.removeEventListener("abort",r)}}}async function LN(n,e){let t=globalThis.navigator?.locks;if(t)return t.request(n,{mode:"exclusive"},e);let r=qy.get(n)??Promise.resolve(),o,s=new Promise(i=>{o=i});qy.set(n,s),await r;try{return await e()}finally{o(),qy.get(n)===s&&qy.delete(n)}}var SN,VR,as,PN,DR,CN,Tn,Ey,zR,$R,BR,Ty,ua,AA,ji,qy,SA,KR=I(()=>{"use strict";dd();Xo();Tl();Qf();am();vO();um();ve();qo();ie();vn();mA();la();lc();hp();Qd();Sp();OR();TR();jR();Db();NR();Yv();SN=new Set(["owner","editor","viewer"]),VR="mdbase.app-grant.v1",as=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,PN=15e3;DR=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),CN=new TextEncoder().encode("mdbase-next client noise key v1\0");Tn=n=>{let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")},Ey=n=>crypto.getRandomValues(new Uint8Array(n)),zR=n=>{let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,n),e},$R=(...n)=>{let e=new Uint8Array(n.reduce((r,o)=>r+o.length,0)),t=0;for(let r of n)e.set(r,t),t+=r.length;return e};BR=async n=>Tn(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n))));Ty=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]),ua=(n,e)=>!!e&&n.collection===e.collection&&n.owner===e.owner&&Ty(n.noisePublicKey,e.noisePublicKey),AA=(n,e)=>ua(n,e)&&Ty(n.refresh,e.refresh),ji=()=>A("cancelled","the stored grant changed during this operation"),qy=new Map;SA=class{constructor(e){this.options=e;this.declaration=so(e.declaration),this.cpOrigin=Cr({environment:this.declaration.environment,appOrigin:this.declaration.origin,release:wO()}).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??ON(),this.storeValue=e.store??null}options;declaration;cpOrigin;redirect;fetcher;callbacks;storeValue;registration=null;tokens=new Map;routeProbe;refreshing=new Map;forgotten=new Set;epoch=0;register(){let e=this.registration??=dm({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??=bx(Jo(this.declaration).manifest.id,Xf(this.declaration))}async store(){if(this.storeValue)return this.storeValue;let e=this.owner();return this.storeValue=UR(this.cpOrigin,(await this.register()).id,{owner:e})}async identity(){let e=await this.store(),t=await e.getIdentity();if(t)return t;let r=await _A(["sign"],"ECDSA");return e.putIdentityIfAbsent({version:1,privateKey:r.privateKey,publicKey:r.publicKey})}async request(e,t,r){let o=MN(r,PN);try{let s;try{s=await this.fetcher(`${this.cpOrigin}${e}`,{...t,redirect:"error",credentials:"omit",signal:o.signal})}catch{throw r?.aborted?A("cancelled","request cancelled"):A("unavailable","cannot reach the control plane","control_unreachable")}let i=null;try{let a=await s.json();a&&typeof a=="object"&&!Array.isArray(a)&&(i=a)}catch{i=null}return{status:s.status,body:i}}finally{o.done()}}async authorize(e){e=Object.freeze({...e});let t=await this.prepareAuthorization(e).catch(r=>{throw e.popup.close(),r});try{e.popup.navigate(t.authorizationUri);let{collectionId:r}=await t.finish(e);return{collectionId:r}}finally{t.cancel();try{e.popup.close()}catch{}}}async prepareAuthorization(e={}){if(e=Object.freeze({...e}),e.collection!==void 0&&!as.test(e.collection))throw A("invalid_request","collection must be a UUID");if(e.expectedAccountId!==void 0&&(!as.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)||!xN(e.authorizationNonce)))throw A("invalid_request","invalid original challenge","authorization_binding");let t=new AbortController,r=e.signal?AbortSignal.any([e.signal,t.signal]):t.signal,o=this.epoch,s=()=>{if(r.aborted)throw A("cancelled","authorization fenced","authorization_cancelled");if(o!==this.epoch)throw ji()};s();let i=await this.register(),a=Jo(this.declaration),c=await this.identity(),l=await _A(["deriveBits"],"ECDH"),p=await _A(["sign"],"ECDSA"),d=await qN(),u=Tn(Ey(32)),f=Tn(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(u)))),h=Tn(Ey(24)),m=crypto.randomUUID(),w=new Date,b={protocol_version:oo,authorization_id:m,application_id:i.id,application_declaration_id:String(a.manifest.id),application_manifest_digest:i.manifestDigest,application_installation_id:await p1(c.publicKey),installation_signing_public_key:c.publicKey,grant_agreement_public_key:l.publicKey,grant_signing_public_key:p.publicKey,flow:"authorization_code",authorization_nonce:e.authorizationNonce??Tn(Ey(32)),issued_at:w.toISOString(),expires_at:new Date(w.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:b,signature:Tn(await kA(c.privateKey,d1(b)))},y=$R(CN,zR(16),N(m),zR(32),d.publicKey),_={public_key:Tn(d.publicKey),signature:Tn(await kA(p.privateKey,y))};s();let v=await this.request("/oauth/authorization_request",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:i.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(_)})},r);s();let k=v.body?.authorization_uri;if(v.status!==200||v.body?.authorization_id!==m||typeof k!="string"||!k.startsWith(`${this.cpOrigin}/oauth/authorize?`))throw A("unavailable",`authorization could not be started (${v.status})`,"authorization_start");let S=null,x=this.awaitCallback(h,{navigate(){},close(){},get closed(){return S?.closed===!0}},{popup:{navigate(){},close(){}},signal:r,timeoutMs:e.timeoutMs});x.catch(()=>{});let P=!1;return Object.freeze({applicationId:i.id,manifestDigest:i.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 R=()=>t.abort();C.signal?.addEventListener("abort",R,{once:!0}),C.signal?.aborted&&t.abort();try{s();let O=C.collection??e.collection;if(O!==void 0&&!as.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 E=await x;s();let j=await this.request("/oauth/token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:E,client_id:i.id,redirect_uri:this.redirect.href,code_verifier:u})},r);s();let B=e.expectedAccountId?bm(j.body,{accountId:e.expectedAccountId,authorizationRequestId:m,applicationId:i.id,declarationId:b.application_declaration_id,manifestDigest:i.manifestDigest,applicationInstallationId:b.application_installation_id,applicationOrigin:this.redirect.origin,collectionId:O,grantSigningPublicKey:p.publicKey,clientNoisePublicKey:Tn(d.publicKey)}):void 0,D=await this.saveTokens(j,{noise:d,signing:p.privateKey,collection:O,check:s});return s(),{collectionId:D,...B?{nativeCompletion:B}:{}}}finally{C.signal?.removeEventListener("abort",R),t.abort()}}})}awaitCallback(e,t,r){let o=Math.min(Math.max(r.timeoutMs??6e5,1e3),18e5);return new Promise((s,i)=>{let a=null,c=f=>{p(),clearTimeout(d),clearInterval(u),r.signal?.removeEventListener("abort",l),f()},l=()=>c(()=>i(A("cancelled","authorization cancelled","authorization_cancelled"))),p=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 c(()=>i(A("forbidden","access was not approved","authorization_denied")));let w=h.searchParams.get("code");if(!w)return c(()=>i(A("unavailable","the authorization callback has no code","authorization_callback")));c(()=>s(w))}),d=setTimeout(()=>c(()=>i(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&&c(()=>i(A("cancelled","the authorization window was closed","authorization_cancelled")))},500);r.signal?.addEventListener("abort",l,{once:!0}),r.signal?.aborted&&l()})}async saveTokens(e,t){let r=e.body;if(e.status!==200||!r)throw e.status===400&&r&&typeof r.error=="string"&&r.error==="invalid_grant"?A("unauthenticated","the grant is no longer valid","grant_invalid"):e.status===400?Vn("sync_required"):A("unavailable",`token request failed (${e.status})`,"token_error");let o=r.access_token,s=r.refresh_token,i=r.collection_id,a=r.expires_in,c=r.refresh_expires_in;if(typeof o!="string"||typeof s!="string"||typeof i!="string"||!as.test(i)||typeof a!="number"||!(a>0)||typeof c!="number"||!(c>0))throw A("unavailable","invalid token response","token_response");let l=i.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 p=t.previous?.refreshKey??await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),d=Ey(12),u=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:d,additionalData:this.aad(l)},p,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:p,refresh:$R(d,u),refreshExpiresAt:Date.now()+c*1e3,...h?{signingPrivateKey:h}:{},...t.previous?.owner?{owner:t.previous.owner}:{}},w=this.epoch;return await this.withLock(l,"commit",async()=>{let b=await this.store();if(w!==this.epoch||t.previous&&!AA(t.previous,await b.getGrant(l)))throw ji();t.check?.(),await b.putGrant(m);let g=await b.getGrant(l);if(!g||!Ty(m.noisePublicKey,g.noisePublicKey)||!Ty(m.refresh,g.refresh))throw ji();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 r=await this.heldGrant(e),o=this.tokens.get(e);if(!t&&o&&ua(r,o)&&o.expiresAt-Date.now()>6e4)return o.access;let s=this.refreshing.get(e);if(s&&AA(r,s.grant)){let c=await s.work;return await this.assertCurrent(r),c}let i=this.withLock(e,"refresh",async()=>{let c=await this.assertCurrent(r);return this.refresh(e,c)}),a={grant:r,work:i};this.refreshing.set(e,a);try{let c=await i;return await this.assertCurrent(r),c}finally{this.refreshing.get(e)===a&&this.refreshing.delete(e)}}withLock(e,t,r){return LN(`mdbase.app-grant.${t}:${JSON.stringify([this.cpOrigin,this.owner(),e])}`,r)}async heldGrant(e){let t=await(await this.store()).getGrant(e);if(!t)throw Vn("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(!ua(e,t))throw ji();return t}async refresh(e,t){if(t.refreshExpiresAt<=Date.now())throw Vn("sync_required");let r;try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:t.refresh.slice(0,12),additionalData:this.aad(e)},t.refreshKey,t.refresh.slice(12));r=new TextDecoder().decode(c)}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:r,client_id:o.id}),i=t.signingPrivateKey?await EN(t.signingPrivateKey,"/oauth/token",s.toString(),r):{},a=await this.request("/oauth/token",{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...i},body:s});try{await this.saveTokens(a,{previous:t})}catch(c){throw X(c,"unauthenticated")&&c.reason==="grant_invalid"&&await this.withLock(e,"commit",async()=>{let l=await this.store();if(!AA(t,await l.getGrant(e)))throw ji();await l.deleteGrant(e),this.forgotten.add(e);let p=this.tokens.get(e);p&&ua(t,p)&&this.tokens.delete(e)}),c}return a.body.access_token}async route(e,t){for(let r=0;;r++){let o=await this.accessToken(e,r>0),s=await this.request(`/v1/next/collections/${encodeURIComponent(e)}/route`,{headers:{authorization:`Bearer ${o}`}},t);if(s.status===401&&r===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 i=s.body;if(typeof i.collection!="string"||i.collection.toLowerCase()!==e||!Array.isArray(i.targets))throw A("unauthenticated","the route does not match this collection's grant","route_mismatch");let c=wr(i.availability)??(Zd(i,null).length?{state:"available"}:{state:"unavailable",reason:i.reason==="no_device_registered"?"no_device_registered":"device_offline"});return{token:o,route:i,availability:c}}}async verifiedStoredNativeGrant(e){let t=await this.register(),r=await(await this.store()).getGrant(e.collection_id);return!!r&&e.application_id===t.id&&e.application_origin===this.declaration.origin&&r.owner===this.owner()&&Tn(r.noisePublicKey)===e.client_noise_public_key}async collections(e={}){let t=await(await this.store()).listGrants(),r=[];for(let s of t)(e.bindings===void 0||e.bindings.some(i=>i.collection_id===s.collection&&i.application_origin===this.declaration.origin&&Tn(s.noisePublicKey)===i.client_noise_public_key))&&r.push(s);let o=new Set(r.map(s=>s.collection));for(let s of r){let i;try{i=await this.accessToken(s.collection)}catch(l){if(X(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 ${i}`}},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!==i||!ua(s,l))throw ji();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 c=[];for(let l of a.body.collections){let p=typeof l.collection=="string"?l.collection.toLowerCase():"";if(!as.test(p)||c.some(f=>f.collectionId===p))continue;let d=wr(l.availability);if(l.state!=="synced_e2e"&&!d)continue;let u=o.has(p)?d??{state:"opening"}:{state:"unavailable",reason:"sync_required"};c.push(Object.freeze({collectionId:p,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:SN.has(l.role)?l.role:null}))}return c}return[]}async availability(e,t={}){let r=e.toLowerCase(),o=this.routeProbe={};try{let{token:s,route:i,availability:a}=await this.route(r,t.signal),c=this.tokens.get(r);return a.state==="available"&&!t.signal?.aborted&&c?.access===s&&(o.ready={credentials:c,route:i,until:performance.now()+3e3,signal:t.signal}),a}catch(s){let i=X(s)?fe(s.details,"availability"):void 0;if(typeof i=="string")return wr({state:"unavailable",reason:i});throw s}}async waitForAvailable(e,t={}){let r=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 i=await this.availability(e,t.signal?{signal:t.signal}:{});if((!s||i.state!==s.state||i.state==="unavailable"&&s.state==="unavailable"&&i.reason!==s.reason)&&t.onAvailability?.(i),s=i,i.state==="available"||i.state==="unavailable"&&(i.reason==="sync_required"||i.reason==="access_removed"))return i;let a=r-Date.now();if(a<=0)return i;await new Promise(c=>{let l=setTimeout(p,Math.min(o,a));function p(){clearTimeout(l),t.signal?.removeEventListener("abort",p),c()}t.signal?.addEventListener("abort",p,{once:!0})})}}connector(e){let t=e.toLowerCase();if(!as.test(t))throw A("invalid_request","collection must be a UUID");let r=null,o=this.options.webSocket,s;return pf({description:`app-grant:${t}`,open:async(i,a)=>{let c=s===void 0?this.routeProbe?.ready:void 0;this.routeProbe=void 0;let l=await(s??=this.heldGrant(t));if(await this.assertCurrent(l),a?.aborted)throw A("cancelled","connect aborted");let{token:p,route:d,availability:u}=c&&!c.signal?.aborted&&performance.now()<c.until&&c.credentials===this.tokens.get(t)&&ua(l,c.credentials)&&c.credentials.expiresAt>Date.now()?{token:c.credentials.access,route:c.route,availability:{state:"available"}}:await this.route(t,a);if(await this.assertCurrent(l),a?.aborted)throw A("cancelled","connect aborted");if(u.state==="unavailable")throw Vn(u.reason);if(!as.test(d.grant))throw A("unauthenticated","the route names no grant","route_mismatch");let f=fA(d,r);if(!f.length)throw Vn("device_offline");let h;for(let m of f){await this.assertCurrent(l);let w=new Uint8Array(32);for(let y=0;y<32;y++)w[y]=parseInt(m.noise_pk.slice(2*y,2*y+2),16);let b=Mi({description:`app-grant:${t}`,staticKey:TN(l),target:async()=>({prologue:Ti(N(m.relay_collection),N(d.grant),N(m.device)),remoteStatic:w,device:m.device,openCarrier:async y=>{await this.assertCurrent(l);let _=await cc(m.url,{accessToken:p,collection:m.relay_collection,grant:d.grant,device:m.device,devicePublicKey:w},o,y);try{return await this.assertCurrent(l),_}catch(v){throw _.close(),v}}})}),g;try{g=await b.open(i,a)}catch(y){if(!hA(y,a))throw y;r===m.device&&(r=null),h??=y;continue}try{await this.assertCurrent(l)}catch(y){throw g.port.close(),y}return PS(g.port,l),r=g.device??null,g}throw h},get target(){return r}})}people(e,t){let r=e.toLowerCase();if(!as.test(r))throw A("invalid_request","collection must be a UUID");return new gi(t,IR(r,{cpOrigin:this.cpOrigin,fetch:this.fetcher,accessToken:(o,s)=>this.accessToken(o,s),holds:o=>!this.forgotten.has(o)}))}setup(e){let t=Jo(this.declaration),r,o=async()=>{let i=e.currentSession(),a=i&&CS(i);if(!a||a.collection!==e.collection||(r??=a,!ua(r,a)))throw ji();return r};return qR({assertCurrent:async()=>this.assertCurrent(await o()),journal:LR({store:()=>this.store(),grant:o,assertCurrent:i=>this.assertCurrent(i),aad:this.aad(e.collection)}),client:e,manifest:t.manifest,operations:t.operations})}async forget(e,t={}){let r=e.toLowerCase(),o=t.expectedNoisePublicKey;await this.withLock(r,"commit",async()=>{let s=await this.store(),i=await s.getGrant(r);if(o!==void 0&&i&&Tn(i.noisePublicKey)!==o)throw ji();await s.deleteGrant(r),this.forgotten.add(r),this.tokens.delete(r),this.routeProbe=void 0})}async forgetAllGrants(){this.routeProbe=void 0,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 r=async(o,s)=>o.length?this.withLock(o[0],"commit",()=>r(o.slice(1),s)):s();await r(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 HR(n){let e=0,t=0;try{let r=n?.records.status.pending;e=typeof r=="number"&&r>0?r:0}catch{e=0}try{t=n?.records.ledger?.getSnapshot().pending.length??0}catch{t=0}return Math.max(e,t)}function GR(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 YR=I(()=>{"use strict";ie()});function JR(){return new Promise(n=>{let e;try{e=indexedDB.open(IA,1)}catch{n(null);return}e.onupgradeneeded=()=>{try{e.result.createObjectStore(uc)}catch{}},e.onsuccess=()=>{let t=e.result;t.onversionchange=()=>t.close(),n(t.objectStoreNames.contains(uc)?t:(t.close(),null))},e.onerror=e.onblocked=()=>n(null)})}function CA(n,e){return JR().then(t=>new Promise(r=>{if(!t){r(null);return}let o=null;try{let s=t.transaction(uc,n),i=e(s.objectStore(uc));i&&(i.onsuccess=()=>{o=i.result??null}),s.oncomplete=()=>{t.close(),r(o)},s.onerror=s.onabort=()=>{t.close(),r(null)}}catch{t.close(),r(null)}}))}function XR(){return typeof indexedDB>"u"?null:Object.freeze({async read(n,e){let t=await CA("readonly",r=>r.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 CA("readwrite",t=>t.put({value:e.value,expires:e.expires},n)).catch(()=>null)},async drop(n){await CA("readwrite",e=>e.delete(n)).catch(()=>null)}})}async function QR(n){let{cpOrigin:e,connectorId:t,deviceId:r}=n;if(!t||!r)return!0;let o=await JR();return o?new Promise(s=>{try{let i=o.transaction(uc,"readwrite"),a=i.objectStore(uc).openCursor();a.onsuccess=()=>{let c=a.result;if(c){if(typeof c.key=="string"){let l=c.key.split(" ");l.length===5&&l[0]===e&&l[2]===t&&l[3]===r&&c.delete()}c.continue()}},i.oncomplete=()=>{o.close(),s(!0)},i.onerror=i.onabort=()=>{o.close(),s(!1)}}catch{o.close(),s(!1)}}):!1}var IA,uc,OA=I(()=>{"use strict";IA="mdbase.app.log-token.v1",uc="tokens"});function fa(n,e){return new Promise((t,r)=>{if(e.aborted){r(e.reason);return}let o=()=>{clearTimeout(s),r(e.reason)},s=setTimeout(()=>{e.removeEventListener("abort",o),t()},n);e.addEventListener("abort",o,{once:!0})})}var jy=I(()=>{"use strict"});function ZN(n,e){let t=new URL(n);if(t.protocol==="https:")return`wss://${t.host}`;if(e&&Ze(n))return`ws://${t.host}`;throw new Error("app log push: origin")}function t8(n){let e=n.get(3);if(!(e instanceof Map))return null;let t=e.get(0),r=e.get(1);return{code:typeof t=="string"?t:"unavailable",reason:typeof r=="string"?r:""}}var BN,VN,FN,KN,WN,HN,GN,YN,JN,XN,QN,e8,ZR,Uy,e2=I(()=>{"use strict";At();Ye();ve();BN=4401,VN=4403,FN=4410,KN=3e4,WN=1e4,HN=6e4,GN=6e4,YN=15e3,JN=4,XN=64*1024,QN=1024*1024;e8=n=>[...n].map(e=>e.toString(16).padStart(2,"0")).join(""),ZR=(n,e,t)=>ue(new Map([[0,0],[1,n],[2,e],[3,t]]));Uy=class{constructor(e,t,r={}){this.source=e;this.events=t;this.base=ZN(e.origin,r.allowLoopbackHttp===!0),this.collectionBytes=N(e.collection);let o=r.WebSocket??globalThis.WebSocket;if(typeof o!="function")throw new Error("app log push: no WebSocket");this.Ws=o,this.random=r.random??Math.random,this.now=r.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 r=this.socket;if(this.socket=null,r){r.onopen=r.onmessage=r.onclose=r.onerror=null;try{r.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(GN,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,r;try{let i=this.life.signal;if(e=await this.source.accessToken({signal:i}),t=await this.source.nonce({signal:i}),this.paused||!this.available||!this.source.isCurrent())return;if(r=this.source.signHello(t,e),!r){++this.unsigned>=JN?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=${e8(t)}`)}catch{this.schedule();return}o.binaryType="arraybuffer",this.socket=o;let s=ZR(1,"hello",new Map([[0,[1,0]],[1,e],[2,N(this.source.deviceId)],[3,r]]));r.fill(0),t.fill(0),o.onopen=()=>{try{o.send(s)}catch{this.lost(o,1006)}},o.onmessage=i=>this.message(o,i.data),o.onclose=i=>this.lost(o,i.code),o.onerror=()=>{},this.opening=setTimeout(()=>{this.opening=null,this.lost(o,1006)},YN)}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>QN){this.lost(e,1009);return}let r=new Uint8Array(t),o;try{let a=we(r);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(r),o.get(1)==="closed"){let a=o.get(2),c=a instanceof Map?a.get(1):null;this.end(c==="gone"?"gone":c==="revoked"?"revoked":"forbidden")}return}if(o.get(0)!==1)return;let s=o.get(1),i=t8(o);if(s===1){if(i){this.refused(e,i);return}try{e.send(ZR(2,"subscribe",new Map([[0,this.collectionBytes],[1,0],[2,XN]])))}catch{this.lost(e,1006)}return}if(s===2){if(i){this.refused(e,i);return}let a=o.get(2);if(!(a instanceof Map)){this.lost(e,1007);return}let c=a.get(0),l=a.get(1);this.startPing(e),this.setLive(!0),(typeof c=="number"||typeof c=="bigint")&&l instanceof Uint8Array&&l.length===32&&this.deliver(ue(new Map([[0,2],[1,"head"],[2,new Map([[0,this.collectionBytes],[1,c],[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)},WN)}},KN)}lost(e,t){if(e!==this.socket)return;let r=this.isLive&&this.now()-this.liveSince>=HN;if(this.drop(1e3,"lost"),t===VN){this.end("forbidden");return}if(t===FN){this.end("gone");return}if(r&&(this.attempts=0),t===BN){this.token&&this.source.invalidateToken?.(this.token),this.token=null,this.attempts=0,this.schedule(!0);return}this.schedule()}}});function t2(n){if(!n||typeof n!="object"||Array.isArray(n))throw ri();return n}function n2(n){if(typeof n=="number"&&!Number.isSafeInteger(n))throw ri();let e=BigInt(n);if(e<0n||e>(1n<<64n)-1n)throw ri();return e}var ri,fc,RA=I(()=>{"use strict";At();ve();ie();ri=()=>A("unavailable","people metadata is unavailable","people_response");fc=class{constructor(e,t={}){this.session=e;this.rawOrigin=e.cpOrigin;let r=new URL(this.rawOrigin);if(r.username||r.password||r.pathname!=="/"||r.search||r.hash||r.protocol!=="https:"&&!(t.allowLoopbackHttp===!0&&Ze(e.cpOrigin)))throw A("invalid_request","invalid people CP origin","people_binding");this.cpOrigin=r.origin,this.collection=e.collection,this.connector=e.connectorId,this.device=e.deviceId,this.ep=n2(e.endpoint);for(let o of[this.collection,this.connector,this.device])if(N(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&&n2(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 r=new AbortController,o=()=>r.abort();t.signal?.addEventListener("abort",o,{once:!0}),this.lifetime.signal.addEventListener("abort",o,{once:!0});let s=setTimeout(o,15e3);s.unref?.();let i=new Uint8Array(1024*1024),a=0,c,l;try{let p=await this.session.connectorBearer({signal:r.signal});if(this.check(t.signal),r.signal.aborted)throw ri();if(typeof p!="string"||!/^(idev_|ct_)/.test(p)||p.length>16*1024||/[^\x21-\x7e]/.test(p))throw A("unauthenticated","invalid people credential","people_binding");let d=this.fetchImpl;if(c=await d(`${this.cpOrigin}/v1/authorities/${this.collection}/${e}?device_id=${this.device}`,{method:"GET",headers:{authorization:`Bearer ${p}`},signal:r.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(t.signal),r.signal.aborted)throw ri();let u=c.headers.get("content-length");if(u!==null&&/^(0|[1-9][0-9]*)$/.test(u)&&Number(u)>i.length||!c.body)throw ri();for(l=c.body.getReader();;){let{done:h,value:m}=await l.read();try{if(this.check(t.signal),r.signal.aborted)throw ri();if(h)break;if(a+m.length>i.length)throw ri();i.set(m,a),a+=m.length}finally{m?.fill(0)}}let f=t2(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(i.subarray(0,a))));if(this.check(t.signal),c.status===401)throw A("unauthenticated","people credential is no longer current","people_fenced");if(c.status===403){let h=t2(f.error);throw A("forbidden","people access was refused",e==="members"&&h.code==="people_permission_declined"?"people_permission_declined":"people_access")}if(c.status===404)throw A("upgrade_required","people metadata is unsupported","people_unsupported");if(!c.ok)throw ri();return f}catch(p){throw this.check(t.signal),p instanceof oe?p:ri()}finally{r.abort(),i.fill(0),(l?.cancel()??c?.body?.cancel())?.catch(()=>{}),l?.releaseLock(),clearTimeout(s),t.signal?.removeEventListener("abort",o),this.lifetime.signal.removeEventListener("abort",o)}}close(){this.lifetime.abort()}}});function Ny(n,e){if(typeof n!="string"||!e.test(n))throw ge("invalid_request","timer_input");return encodeURIComponent(n)}function ls(n,e){if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!==e.split(",").sort().join())throw ge("invalid_request","timer_input");return n}function r2(n){let e=ls(n,"id,fire_at");if(Ny(e.id,EA),typeof e.fire_at!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(e.fire_at)||!Number.isFinite(Date.parse(e.fire_at)))throw ge("invalid_request","timer_input");return{id:e.id,fire_at:e.fire_at}}function qA(n){if(typeof n!="string"||!n.length||n.length>100)throw ge("invalid_request","timer_input")}function r8(n,e,t){let r=`${n}/${Ny(t[0],n8)}`;if(e==="list"&&t.length===1)return{path:r,method:"GET",write:!1};if(e==="put"&&t.length===3){let o=ls(t[2],"criterion_id,fire_at");return qA(o.criterion_id),r2({id:t[1],fire_at:o.fire_at}),{path:`${r}/${Ny(t[1],EA)}`,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 ge("invalid_request","timer_input");return{path:`${r}/${Ny(t[1],EA)}${o===void 0?"":`?generation=${o}`}`,method:"DELETE",write:!0}}if((e==="reconcile"||e==="reconcileWithReceipt")&&t.length===2){let o=ls(t[1],`criterion_id,timers${e==="reconcileWithReceipt"?",recovery":""}`);if(qA(o.criterion_id),!Array.isArray(o.timers)||o.timers.length>1e4)throw ge("invalid_request","timer_input");let s=o.timers.map(r2);if(new Set(s.map(i=>i.id)).size!==s.length)throw ge("invalid_request","timer_input");if(e==="reconcileWithReceipt"){let i=ls(o.recovery,"protocol_version,operation_id,expected_revision");if(i.protocol_version!==1||typeof i.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(i.operation_id)||!Number.isSafeInteger(i.expected_revision)||i.expected_revision<0||i.expected_revision>=Number.MAX_SAFE_INTEGER)throw ge("invalid_request","timer_input")}return{path:`${r}/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:`${r}/operations/${t[1]}`,method:"GET",write:!1};throw ge("invalid_request","timer_input")}function o2(n,e){let t=i2(e.scope),r=e.generation,o=`/v1/next/collections/${e.scope.collection}/background-grants/${e.grantId}/timers`,s=!1,i=0,a=null,c=null,l=()=>{if(s||e.signal.aborted||!e.isCurrent())throw ge("unauthenticated","timer_fenced")},p=()=>{if(c)return c;s=!0,e.signal.removeEventListener("abort",d),a?.ctrl.abort();try{n.postMessage([1,t,r,"close"])}finally{n.removeEventListener("message",u),n.close()}return c=Promise.resolve().then(async()=>{await a?.work})},d=()=>{p()},u=f=>{let h=f.data;if(!Array.isArray(h)||h[0]!==1||h[1]!==t||h[2]!==r){p();return}if(h.length===4&&h[3]==="close"){p();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]<=i||a||typeof h[4]!="string"||!Array.isArray(h[5])){p();return}let m=h[3],w=h[4],b=h[5],g=new AbortController;i=m;let y=!1,_=w!=="list"&&w!=="lookupOperation",v=Promise.resolve().then(async()=>{let k=setTimeout(()=>g.abort(),1e4),S,x,P=new Uint8Array(ru),C=0,R=()=>{x?.cancel().catch(()=>{})};g.signal.addEventListener("abort",R,{once:!0});try{l(),g.signal.throwIfAborted();let O=o.slice(0,-7)+"/notifications/channels",E,j,B=null;if(w==="vapid"&&b.length===0){if(!e.journal)throw ge("upgrade_required","native_timer_channel_journal_unavailable");e.journal.read(),E={path:"/v1/notifications/vapid-public-key",method:"GET",write:!1}}else if(w==="registerChannel"&&b.length===1){if(!e.journal)throw ge("upgrade_required","native_timer_channel_journal_unavailable");let ee=b[0],te=ls(ee,`kind,criteria,${ee?.kind==="web_push"?"subscription":"token"}`);if(!["web_push","fcm"].includes(te.kind)||!Array.isArray(te.criteria)||!te.criteria.length||te.criteria.length>100||(te.criteria.forEach(qA),new Set(te.criteria).size!==te.criteria.length))throw ge("invalid_request","timer_input");let Ce;if(te.kind==="fcm"){if(typeof te.token!="string"||te.token.length<16||te.token.length>4096||/[\s\u0000-\u001f\u007f]/.test(te.token))throw ge("invalid_request","timer_input");Ce={transport:"fcm",token:te.token}}else{let K=ls(te.subscription,"endpoint,expirationTime,keys"),Z=ls(K.keys,"p256dh,auth");if(typeof K.endpoint!="string"||K.endpoint.length>2048||typeof Z.p256dh!="string"||typeof Z.auth!="string"||!/^[A-Za-z0-9_-]{87}$/.test(Z.p256dh)||!/^[A-Za-z0-9_-]{22}$/.test(Z.auth))throw ge("invalid_request","timer_input");let _e;try{_e=new URL(K.endpoint)}catch{throw ge("invalid_request","timer_input")}if(_e.protocol!=="https:"||_e.username||_e.password||_e.hash||_e.href!==K.endpoint||K.expirationTime!==null&&(!Number.isFinite(K.expirationTime)||K.expirationTime<0))throw ge("invalid_request","timer_input");Ce={subscription:K}}E={path:O,method:"POST",write:!0,body:{installation_id:e.scope.installation,criteria:[...te.criteria].sort(),...Ce}};let et=new TextEncoder().encode(JSON.stringify(E.body)),$;try{$=[...new Uint8Array(await crypto.subtle.digest("SHA-256",et))].map(K=>K.toString(16).padStart(2,"0")).join("")}finally{et.fill(0)}l(),g.signal.throwIfAborted();let Y=e.journal.read();if(B=Y,Y?.pending)throw ge("outcome_unknown","timer_channel_reapproval_required");j={grantId:e.grantId,kind:te.kind,targetDigest:$,channelId:Y?.channelId??null,pending:"register"}}else if(w==="unregisterChannel"&&b.length===1&&["web_push","fcm"].includes(b[0])){if(!e.journal)throw ge("upgrade_required","native_timer_channel_journal_unavailable");let ee=e.journal.read();if(B=ee,!ee){n.postMessage([1,t,r,m,!0,void 0]);return}if(ee.pending==="register")throw ge("outcome_unknown","timer_channel_reapproval_required");if(ee.kind!==b[0]||!ee.channelId)throw ge("invalid_request","timer_channel_kind");j={...ee,pending:"delete"},E={path:`${O}/${ee.channelId}`,method:"DELETE",write:!0}}else E=r8(o,w,b);_=E.write;let D=E.body===void 0?void 0:JSON.stringify(E.body);if(D&&new TextEncoder().encode(D).length>ru)throw ge("invalid_request","timer_input");let J=await e.bearer();if(l(),g.signal.throwIfAborted(),typeof J!="string"||!/^(idev_|ct_)[A-Za-z0-9_-]{43}$/.test(J))throw ge("unauthenticated","timer_credential");j&&(await e.journal.write(j),l(),g.signal.throwIfAborted()),y=_;let V=e.fetch;if(S=await V(`${e.cpOrigin}${E.path}`,{method:E.method,body:D,headers:{authorization:`Bearer ${J}`,...D===void 0?{}:{"content-type":"application/json"}},credentials:"omit",redirect:"error",cache:E.method==="GET"?"no-store":"default",referrerPolicy:"no-referrer",signal:g.signal}),l(),g.signal.throwIfAborted(),S.redirected)throw ge("unavailable","timer_response");if(w==="unregisterChannel"&&S.status===204){await e.journal.write(null),l(),g.signal.throwIfAborted(),n.postMessage([1,t,r,m,!0,void 0]);return}if(S.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase()!=="application/json"||!S.body)throw ge("unavailable","timer_response");let U=S.headers.get("content-length");if(U&&/^\d+$/.test(U)&&Number(U)>ru)throw ge("unavailable","timer_response");for(x=S.body.getReader();;){let ee=await x.read();try{if(l(),g.signal.throwIfAborted(),ee.done)break;if(C+ee.value.length>ru)throw ge("unavailable","timer_response");P.set(ee.value,C),C+=ee.value.length}finally{ee.value?.fill(0)}}let ce=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(P.subarray(0,C)));if(w==="unregisterChannel"&&S.status===404&&ce?.error?.code==="channel_not_found"){await e.journal.write(null),l(),g.signal.throwIfAborted(),n.postMessage([1,t,r,m,!0,void 0]);return}if(!S.ok){let ee=!!j&&S.status===503&&typeof ce?.error?.code=="string";throw S.status>=500&&!ee?ge("unavailable","timer_http"):ce?.error?.operation_outcome==="unknown"?ge("outcome_unknown","timer_write_unknown"):(j&&(await e.journal.write(B),l(),g.signal.throwIfAborted()),y=!1,ee?ge("unavailable","timer_http"):A(S.status===401||S.status===403?"unauthenticated":S.status===409?"conflict":S.status===404?"upgrade_required":S.status===429?"rate_limited":"invalid_request","Timer request was refused.","timer_refused"))}if(l(),g.signal.throwIfAborted(),w==="registerChannel"){if(typeof ce?.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(ce.channel_id))throw ge("unavailable","timer_channel_response");await e.journal.write({...j,channelId:ce.channel_id,pending:null}),l(),g.signal.throwIfAborted(),n.postMessage([1,t,r,m,!0,{channelId:ce.channel_id,installationId:e.scope.installation,criteria:E.body.criteria}])}else n.postMessage([1,t,r,m,!0,ce])}catch(O){let E=y?ge("outcome_unknown","timer_write_unknown"):O instanceof oe?O:ge(g.signal.aborted?"cancelled":"unavailable","timer_request");s||n.postMessage([1,t,r,m,!1,E.code,E.reason])}finally{clearTimeout(k),g.signal.removeEventListener("abort",R),P.fill(0),(x?.cancel()??S?.body?.cancel())?.catch(()=>{}),x?.releaseLock(),a?.id===m&&(a=null)}});a={id:m,ctrl:g,work:v}};n.addEventListener("message",u),n.start(),e.signal.addEventListener("abort",d,{once:!0});try{l()}catch(f){throw p(),f}return Object.freeze({close:p})}function s2(n,e,t){let r=i2(e.scope),o=e.generation,s=!1,i=0,a=null,c=()=>{if(s)return;s=!0,t.signal.removeEventListener("abort",c);let y=a;a=null,y?.signal?.removeEventListener("abort",y.abort),y?.reject(ge(y.write?"outcome_unknown":"cancelled","timer_port_closed"));try{n.postMessage([1,r,o,"close"])}finally{n.removeEventListener("message",l),n.close(),t.onClose()}},l=y=>{let _=y.data;if(!Array.isArray(_)||_[0]!==1||_[1]!==r||_[2]!==o){c();return}if(_.length===4&&_[3]==="close"){c();return}let v=a;if(!v||_[3]!==v.id||!(_.length===6&&_[4]===!0||_.length===7&&_[4]===!1&&typeof _[5]=="string"&&vo(_[5]))){c();return}a=null,v.signal?.removeEventListener("abort",v.abort),_[4]?v.resolve(_[5]):v.reject(A(_[5],"Timer request could not complete.",typeof _[6]=="string"?_[6]:void 0))},p=(y,_,v,k=!1)=>{if(s||t.signal.aborted||v.signal?.aborted)return Promise.reject(ge("cancelled","timer_port_closed"));if(a||d&&!k)return Promise.reject(ge("unavailable","timer_port_busy"));if(i>=Number.MAX_SAFE_INTEGER)return c(),Promise.reject(ge("unavailable","timer_port_closed"));let S=++i,x=y!=="list"&&y!=="lookupOperation"&&y!=="vapid";return new Promise((P,C)=>{let R=()=>{try{n.postMessage([1,r,o,S,"cancel"])}catch{c()}C(ge(x?"outcome_unknown":"cancelled","timer_request_cancelled"))};a={id:S,write:x,resolve:P,reject:C,abort:R,signal:v.signal},v.signal?.addEventListener("abort",R,{once:!0});try{if(new TextEncoder().encode(JSON.stringify(_)).length>ru)throw ge("invalid_request","timer_input");n.postMessage([1,r,o,S,y,_])}catch(O){a=null,v.signal?.removeEventListener("abort",R),C(O)}})},d=!1,u=()=>{if(s||t.signal.aborted)throw ge("cancelled","timer_port_closed")},f=y=>{if(!y?.length||y.length>100||y.some(_=>typeof _!="string"||!_.length||_.length>100)||new Set(y).size!==y.length)throw ge("invalid_request","timer_channel_criteria_required");return[...y].sort()},h=(y,_)=>{let v=ls(y,"channelId,installationId,criteria");if(typeof v.channelId!="string"||v.installationId!==e.scope.installation||JSON.stringify(v.criteria)!==JSON.stringify(_))throw ge("outcome_unknown","timer_channel_response");return{channelId:v.channelId,installationId:e.scope.installation,criteria:[..._]}},m=async(y,_)=>{if(u(),y.signal?.throwIfAborted(),d||a)throw ge("unavailable","timer_port_busy");d=!0;try{return await _()}finally{d=!1}},w=y=>m(y,async()=>{let _=f(y.criteria);if(y.installationId!==void 0&&y.installationId!==e.scope.installation)throw ge("invalid_request","timer_channel_installation");let v=y.serviceWorker;if(!v?.pushManager||typeof v.pushManager.getSubscription!="function"||typeof v.pushManager.subscribe!="function")throw ge("invalid_request","timer_push_platform");let k=await p("vapid",[],y,!0);if(u(),y.signal?.throwIfAborted(),typeof k.public_key!="string"||!/^[A-Za-z0-9_-]{87}$/.test(k.public_key))throw ge("unavailable","timer_vapid_response");let S=atob(k.public_key.replace(/-/g,"+").replace(/_/g,"/")),x=Uint8Array.from(S,R=>R.charCodeAt(0));if(x.length!==65||x[0]!==4||btoa(S).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")!==k.public_key)throw ge("unavailable","timer_vapid_response");let P=await v.pushManager.getSubscription();if(u(),y.signal?.throwIfAborted(),P){let R=P.options.applicationServerKey;if(!R||R.byteLength!==x.length||new Uint8Array(R).some((O,E)=>O!==x[E]))throw ge("invalid_request","timer_push_key_changed")}if(!P&&(P=await v.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:x}),s||t.signal.aborted||y.signal?.aborted))throw await P.unsubscribe(),ge("cancelled","timer_port_closed");let C=P.toJSON();return h(await p("registerChannel",[{kind:"web_push",criteria:_,subscription:{endpoint:C.endpoint,expirationTime:C.expirationTime??null,keys:C.keys}}],y,!0),_)}),b=y=>m(y,async()=>{let _=f(y.criteria);if(y.installationId!==void 0&&y.installationId!==e.scope.installation)throw ge("invalid_request","timer_channel_installation");return{...h(await p("registerChannel",[{kind:"fcm",criteria:_,token:y.token}],y,!0),_),transport:"fcm"}}),g=(y,_)=>m(_,async()=>{if(await p("unregisterChannel",["web_push"],_,!0),u(),_.signal?.throwIfAborted(),y){let v=await y.pushManager.getSubscription();u(),_.signal?.throwIfAborted(),v&&await v.unsubscribe(),u(),_.signal?.throwIfAborted()}});return n.addEventListener("message",l),n.start(),t.signal.addEventListener("abort",c,{once:!0}),t.signal.aborted&&c(),Object.freeze({list:(y,_)=>p("list",[y],_),put:(y,_,v,k)=>p("put",[y,_,v],k),cancel:(y,_,v,k)=>p("cancel",[y,_,v],k),reconcile:(y,_,v)=>p("reconcile",[y,_],v),reconcileWithReceipt:(y,_,v)=>p("reconcileWithReceipt",[y,_],v),lookupOperation:(y,_,v)=>p("lookupOperation",[y,_],v),registerWebPush:w,unregisterWebPush:g,registerFcm:b,unregisterFcm:y=>m(y,async()=>{await p("unregisterChannel",["fcm"],y,!0)}),close:c})}var n8,EA,ru,ge,i2,TA=I(()=>{"use strict";ie();n8=/^[A-Za-z0-9._-]{1,64}$/,EA=/^[A-Za-z0-9._:-]{1,128}$/,ru=2*1024*1024,ge=(n,e)=>A(n,"Timer request could not complete.",e),i2=n=>JSON.stringify([n.account,n.installation,n.collection])});function hc(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 Dy(n){let e=n.incidents.find(s=>s.kind==="waiting_for_key");if(!e)return null;let t={through:n.confirmedThrough,head:n.headKnown},r=s=>fe(e.details,s),o=r("reason");typeof o=="string"&&/^[a-z_]{1,32}$/.test(o)&&(t.key=o);for(let s of["position","at"]){let i=r(s);typeof i=="number"&&(t[s]=i)}return t}function l2(n){if(hc(n)!=="waiting_for_key")return!1;let e=Dy(n)?.key;return e==="reading"||e==="no_grant"}var a2,c2=I(()=>{"use strict";vn();a2=15e4});var zy,MA,Ge,LA,i8,$y,jA=I(()=>{"use strict";Ye();ve();Vs();zy=264*1024+256,MA=264*1024,Ge=()=>new Error("app cloud copy outcome unavailable; preserve storage and reopen"),LA=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]),i8=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),$y=class{constructor(e,t,r,o,s){this.source=e;this.store=o;this.key=r;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 i=e.displayName;if(this.displayName=i===void 0?void 0:sr(i),this.displayName!==void 0&&e.purpose!=="create"||i!==this.displayName)throw Ge();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(N);if(a.some(c=>c.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(c=>{if(!(c instanceof Uint8Array)||c.length!==32||c.every(l=>l===0))throw Ge();return new Uint8Array(c)})),t.connectorId!==e.connectorId||t.deviceId!==e.deviceId||t.installationId!==e.installationId)||typeof globalThis.CryptoKey!="function"||!(r instanceof CryptoKey)||r.type!=="secret"||r.extractable||r.algorithm.name!=="AES-GCM"||r.algorithm.length!==256||r.usages.length!==2||!r.usages.includes("encrypt")||!r.usages.includes("decrypt"))throw Ge();this.aad=ue(["mdbase/v1/app-cloud-copy-outcome-platform",...a,e.purpose,e.cpOrigin,e.logOrigin,e.assetSha256,...this.keys]),this.check(this.lifetime)}catch{throw Ge()}}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,r])=>this.source[t]!==r))throw Ge()}catch{throw Ge()}}operation(e){if(e){if(e.displayName!==this.displayName)throw Ge();for(let t of Object.keys(this.fields))if(e[t]!==this.fields[t])throw Ge();for(let[t,r]of["signPublicKey","kemPublicKey","noisePublicKey"].entries())if(!(e[r]instanceof Uint8Array)||!LA(e[r],this.keys[t]))throw Ge()}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 Ge();return Object.freeze({operation:t,genesisItem:new Uint8Array(e.genesisItem),expectedGenesis:e.expectedGenesis})}async hashChecked(e,t){let r=new TextEncoder().encode("mdbase/v1/chain"),o=new Uint8Array(1+r.length+e.genesisItem.length);o[0]=r.length,o.set(r,1),o.set(e.genesisItem,1+r.length);let s=new Uint8Array(await crypto.subtle.digest("SHA-256",o));if(this.check(t),e.expectedGenesis!==`sha256:${i8(s)}`)throw Ge()}async read(e){let t=null;try{this.check(e);let r=await this.io.read.call(this.store,Object.freeze({signal:e}));if(this.check(e),r===null){if(this.mode!=="fresh")throw Ge();return null}if(!(r instanceof Uint8Array)||!r.length||r.length>zy)throw Ge();let o=new Uint8Array(r),s=we(o);if(!(s instanceof Map))throw Ge();let i=s;if(i.size!==3||i.get(0)!==1)throw Ge();let a=i.get(1),c=i.get(2);if(!(a instanceof Uint8Array)||a.length!==12||!(c instanceof Uint8Array)||c.length<16||c.length>MA+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(c))),this.check(e),t.length>MA))throw Ge();let l=we(t);if(!(l instanceof Map))throw Ge();let p=l,d=p.get(0)===1&&p.size===3;if(!d&&!(p.get(0)===2&&p.size===4)||(d?null:p.get(3))!==(this.displayName??null))throw Ge();let u=p.get(1);if(!Array.isArray(u)||u.length!==3||u.some((m,w)=>!(m instanceof Uint8Array)||!LA(m,this.keys[w])))throw Ge();let f=p.get(2),h=null;if(f!==null){if(!Array.isArray(f)||f.length!==2||!(f[0]instanceof Uint8Array)||typeof f[1]!="string")throw Ge();h=this.metadata({operation:this.operation(),genesisItem:f[0],expectedGenesis:f[1]}),await this.hashChecked(h,e)}return{encrypted:o,metadata:h}}catch{throw Ge()}finally{t?.fill(0)}}async write(e,t,r){let o=null,s=null;try{if(this.check(r),o=ue(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>MA)throw Ge();let i=crypto.getRandomValues(new Uint8Array(12)),a=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:i,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(o)));if(this.check(r),s=ue(new Map([[0,1],[1,i],[2,a]])),s.length>zy)throw Ge();let c=await this.io.cas.call(this.store,t,s,Object.freeze({signal:r}));if(this.check(r),c!==!0)throw Ge()}catch{throw Ge()}finally{o?.fill(0),s?.fill(0)}}async restore(e){let{signal:t}=e,r=await this.read(t);return this.check(t),r===null?Object.freeze({state:"none"}):r.metadata===null?Object.freeze({state:"pending",operation:this.operation()}):Object.freeze({state:"completed",metadata:this.metadata(r.metadata)})}async pending(e,t){let{signal:r}=t;this.check(r),this.operation(e);let o=await this.read(r);this.check(r),!o&&await this.write(null,null,r)}async completed(e,t){let{signal:r}=t;this.check(r);let o=this.metadata(e);await this.hashChecked(o,r);let s=await this.read(r);if(this.check(r),!s)throw Ge();if(s.metadata){if(!LA(s.metadata.genesisItem,o.genesisItem)||s.metadata.expectedGenesis!==o.expectedGenesis)throw Ge();return}await this.write(o,s.encrypted,r)}close(){this.closed=!0,this.key=null}}});function NA(n){if(!(n instanceof Uint8Array)||!n.length||n.length>zy)throw yn();return new Uint8Array(n)}var By,UA,yn,o8,Vy,p2=I(()=>{"use strict";tn();ve();jA();By="public-outcome",UA="operation",yn=()=>new Error("app cloud copy outcome store unavailable; preserve storage and reopen"),o8=(n,e)=>n===null||e===null?n===e:n.length===e.length&&n.every((t,r)=>t===e[r]);Vy=class n{constructor(e,t,r){this.source=e;this.origin=t;this.lifetime=r;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,r])=>this.source[t]!==r))throw yn()}catch{throw yn()}}static async open(e){let{source:t,origin:r,mode:o,signal:s}=e,i=null;try{i=new n(t,r,s);let a=[i.fields.accountId,i.fields.connectorId,i.fields.deviceId,i.fields.installationId,i.fields.collection].map(l=>{if(N(l).every(p=>p===0))throw yn();return l.toLowerCase()});if(!dt(r)||!["fresh","existing"].includes(o)||!["create","join"].includes(i.fields.purpose)||!/^[0-9a-f]{64}$/.test(i.fields.assetSha256)||!globalThis.indexedDB)throw yn();i.check(s),i.db=await i.openDatabase(`mdbase.app.cloud-copy-outcome.v1.${a.join(".")}.${i.fields.purpose}`,o),i.db.onversionchange=()=>i.close(),i.check(s);let c=await i.read(Object.freeze({signal:s}));try{if(o==="fresh"!=(c===null))throw yn();i.check(s)}finally{c?.fill(0)}return i}catch{throw i?.close(),yn()}}openDatabase(e,t){return new Promise((r,o)=>{this.check(this.lifetime);let s=indexedDB.open(e,1),i=!1,a=!1,c=()=>{i=!0,o(yn())},l=()=>this.lifetime.removeEventListener("abort",c);this.lifetime.addEventListener("abort",c,{once:!0}),s.onblocked=c,s.onupgradeneeded=()=>{try{if(this.check(this.lifetime),i||t!=="fresh"||s.result.objectStoreNames.length!==0)throw yn();s.result.createObjectStore(By),a=!0}catch{s.transaction?.abort()}},s.onerror=()=>{l(),o(yn())},s.onsuccess=()=>{l();try{if(this.check(this.lifetime),i||t==="fresh"&&!a||s.result.objectStoreNames.length!==1||!s.result.objectStoreNames.contains(By))throw yn();r(s.result)}catch{s.result.close(),o(yn())}}})}async read(e){let{signal:t}=e;this.check(t);let r=await this.transaction("readonly",t,null,null);return this.check(t),r}async compareAndSet(e,t,r){let{signal:o}=r;this.check(o);let s=e===null?null:NA(e),i=NA(t);try{let a=await this.transaction("readwrite",o,s,i);return this.check(o),a===!0}finally{s?.fill(0),i.fill(0)}}transaction(e,t,r,o){return new Promise((s,i)=>{if(this.check(t),!this.db)throw yn();let a=this.db.transaction(By,e,{durability:"strict"}),c=a.objectStore(By),l=null,p=!1,d=()=>{p=!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),i(yn())},a.oncomplete=()=>{u();try{if(this.check(t),p)throw yn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),i(yn())}};let f=c.get(UA);f.onsuccess=()=>{let h=null;try{this.check(t),h=f.result===void 0?null:NA(f.result),e==="readonly"?(l=h,h=null):(l=o8(h,r),l===!0&&o!==null&&(r===null?c.add(new Uint8Array(o),UA):c.put(new Uint8Array(o),UA)))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db?.close(),this.db=null)}}});function $A(n,e){if(typeof n!="string"||!n.length||n.length>e*2||n.length%2||!/^[0-9a-f]+$/.test(n))throw ot("response");return Uint8Array.from(n.match(/../g).map(t=>parseInt(t,16)))}function BA(n){if(!n||typeof n!="object"||Array.isArray(n))throw ot("response");return n}var ha,ot,DA,zA,Fy,VA=I(()=>{"use strict";At();ve();Vs();ha=class extends Error{constructor(t){super(`app private bootstrap: ${t}`);this.reason=t;this.name="AppPrivateBootstrapError"}reason},ot=n=>new ha(n),DA=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),zA=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]);Fy=class{constructor(e,t,r,o={}){this.runtime=e;this.session=t;this.persistence=r;this.options=o;try{let s=o.displayName;if(this.displayName=s===void 0?void 0:sr(s),this.displayName!==void 0&&t.purpose!=="create")throw ot("binding");this.scope=Object.freeze({connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId,collection:t.collection,purpose:t.purpose,accountId:t.accountId,cpOrigin:t.cpOrigin,logOrigin:t.logOrigin});for(let i of[this.scope.connectorId,this.scope.deviceId,this.scope.installationId,this.scope.collection,this.scope.accountId])if(N(i).every(a=>a===0))throw ot("binding");if(this.origin(this.scope.cpOrigin),this.origin(this.scope.logOrigin),!(t.rootPublicKey instanceof Uint8Array)||t.rootPublicKey.length!==32||t.rootPublicKey.every(i=>i===0)||(this.root=new Uint8Array(t.rootPublicKey),this.fetchImpl=o.fetch??globalThis.fetch,this.now=o.now??Date.now,this.marker=this.scope.purpose==="enrol"?e.privateEnrolMarker():null,!this.current()))throw ot("binding")}catch{throw e.retireLog(),ot("binding")}}runtime;session;persistence;options;attempted=!1;lifetime=new AbortController;scope;root;marker;fetchImpl;now;displayName;origin(e){let t=new URL(e);if(t.username||t.password||t.pathname!=="/"||t.search||t.hash||t.protocol!=="https:"&&!(this.options.allowLoopbackHttp===!0&&Ze(e)))throw ot("binding");return t.origin}current(){try{return!this.lifetime.signal.aborted&&this.runtime.privateCollectionCurrent(this.session)&&this.session.isCurrent()===!0&&this.session.approvalMode==="password-ak1"&&zA(this.session.rootPublicKey,this.root)&&Object.entries(this.scope).every(([e,t])=>this.session[e]===t)}catch{return!1}}markerCopy(){let e=this.marker;if(!e)throw ot("binding");return Object.freeze({...e,sasCommitment:new Uint8Array(e.sasCommitment),signPublicKey:new Uint8Array(e.signPublicKey),kemPublicKey:new Uint8Array(e.kemPublicKey),noisePublicKey:new Uint8Array(e.noisePublicKey)})}check(e){if(!this.current()||e.aborted)throw this.close(),ot("fenced")}async json(e,t,r,o){this.check(o);let s=new AbortController,i=()=>s.abort(),a=setTimeout(i,15e3);a.unref?.(),o.addEventListener("abort",i,{once:!0}),this.lifetime.signal.addEventListener("abort",i,{once:!0});let c=new Uint8Array(1024*1024),l=0,p=null,d=null;try{let u=this.fetchImpl;if(d=await u(`${this.origin(this.scope.cpOrigin)}${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,...r===void 0?{}:{"content-type":"application/json"}},body:r,signal:s.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(o),s.signal.aborted||!d.ok)throw ot("unavailable");let f=d.headers.get("content-length");if(f!==null&&/^(0|[1-9][0-9]*)$/.test(f)&&Number(f)>c.length)throw s.abort(),ot("response");if(!d.body)throw ot("response");for(p=d.body.getReader();;){let{done:h,value:m}=await p.read();try{if(this.check(o),s.signal.aborted)throw ot("unavailable");if(h)break;if(l+m.length>c.length)throw s.abort(),ot("response");c.set(m,l),l+=m.length}finally{m?.fill(0)}}return BA(JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c.subarray(0,l))))}catch(u){throw this.check(o),u instanceof ha?u:ot("unavailable")}finally{c.fill(0),(p?.cancel()??d?.body?.cancel())?.catch(()=>{}),p?.releaseLock(),clearTimeout(a),o.removeEventListener("abort",i),this.lifetime.signal.removeEventListener("abort",i)}}copy(e){if(e.displayName!==this.displayName||e.collection!==this.scope.collection||e.deviceId!==this.scope.deviceId||e.logOrigin!==this.scope.logOrigin||!zA(e.rootPublicKey,this.root)||!(e.genesisItem instanceof Uint8Array)||!e.genesisItem.length||e.genesisItem.length>256*1024||e.expectedGenesis.length!==71||!/^sha256:[0-9a-f]{64}$/.test(e.expectedGenesis)||e.approval!==(this.scope.purpose==="create"?"creator":"pending"))throw ot("response");return Object.freeze({collection:e.collection,deviceId:e.deviceId,logOrigin:e.logOrigin,expectedGenesis:e.expectedGenesis,approval:e.approval,...this.displayName===void 0?{}:{displayName:this.displayName},rootPublicKey:new Uint8Array(e.rootPublicKey),genesisItem:new Uint8Array(e.genesisItem)})}async bootstrap(e){let t=null,r=null;try{if(this.check(e.signal),this.attempted)throw ot("fenced");this.attempted=!0;let o=await this.persistence.restoredCompletion(e);if(this.check(e.signal),o){let w=this.copy(o);return this.marker&&!this.marker.acknowledged&&(await this.persistence.privateEnrolAcknowledged(this.markerCopy(),e),this.check(e.signal)),w}if(this.marker?.acknowledged)throw ot("response");this.marker?await this.persistence.privateEnrolPending(this.markerCopy(),e):await this.persistence.pendingCreate({...this.runtime.registeredDeviceReceipt(),collection:this.scope.collection,...this.displayName===void 0?{}:{displayName:this.displayName}},e),this.check(e.signal);let s=await this.session.connectorBearer(e);if(this.check(e.signal),typeof s!="string"||!s||s.length>16384||/[^\x21-\x7e]/.test(s))throw ot("binding");let i=await this.json("/v1/next/devices/challenge",s,void 0,e.signal);if(this.check(e.signal),t=$A(i.challenge,32),t.length!==32||typeof i.expires_at!="number"||!Number.isSafeInteger(i.expires_at)||i.expires_at-this.now()<=5e3||i.expires_at-this.now()>16*6e4)throw ot("response");let a=this.scope.purpose==="enrol";r=a?this.runtime.signPrivateDeviceEnrol(t).signature:this.runtime.signPrivateCreate(t),this.check(e.signal);let c=await this.json(a?`/v1/next/collections/${this.scope.collection}/private/devices`:"/v1/next/collections/private",s,JSON.stringify({device_id:this.scope.deviceId,capabilities:["collection_mode_switch_v2"],challenge:i.challenge,sig:DA(r),...a?{sas_commit:DA(this.marker.sasCommitment)}:{collection_id:this.scope.collection,...this.displayName===void 0?{}:{display_name:this.displayName}}}),e.signal);if(this.check(e.signal),c.collection_id!==this.scope.collection||this.origin(c.log_url)!==this.origin(this.scope.logOrigin))throw ot("response");if(a){if(c.approval!=="pending"||typeof c.enrolled_at!="number"||!Number.isSafeInteger(c.enrolled_at)||c.enrolled_at<1)throw ot("response")}else if(c.state!=="private"||c.owner_account!==this.scope.accountId||!zA($A(c.root_public_key,32),this.root))throw ot("response");let l=BA(c.device);if(l.device_id!==this.scope.deviceId||typeof l.token!="string"||!l.token.length||l.token.length>16384||/[^\x21-\x7e]/.test(l.token)||typeof l.expires_at!="number"||!Number.isSafeInteger(l.expires_at)||l.expires_at-this.now()<=5e3||l.expires_at-this.now()>16*6e4)throw ot("response");let p=BA(c.genesis);if(p.seq!==1)throw ot("response");let d=$A(p.item,256*1024),u=new TextEncoder().encode("mdbase/v1/chain"),f=new Uint8Array(1+u.length+d.length);f[0]=u.length,f.set(u,1),f.set(d,1+u.length);let h=new Uint8Array(await crypto.subtle.digest("SHA-256",f));this.check(e.signal);let m=this.copy({collection:this.scope.collection,deviceId:this.scope.deviceId,logOrigin:this.scope.logOrigin,rootPublicKey:this.root,genesisItem:d,expectedGenesis:`sha256:${DA(h)}`,approval:a?"pending":"creator",...this.displayName===void 0?{}:{displayName:this.displayName}});return await this.persistence.completed(this.copy(m),e),this.check(e.signal),this.marker&&(await this.persistence.privateEnrolAcknowledged(this.markerCopy(),e),this.check(e.signal)),m}catch(o){throw this.close(),o instanceof ha?o:ot("unavailable")}finally{t?.fill(0),r?.fill(0)}}close(){this.lifetime.abort(),this.runtime.retireLog()}}});var Ky,FA,Oe,ma,s8,Wy,KA=I(()=>{"use strict";At();Ye();ve();Vs();Ky=264*1024,FA=Ky+256,Oe=()=>new Error("app private bootstrap custody unavailable; preserve storage and reopen"),ma=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]),s8=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),Wy=class{constructor(e,t,r,o,s,i={}){this.source=e;this.key=r;this.store=o;this.noise=s;try{let a=i.displayName;if(this.displayName=a===void 0?void 0:sr(a),this.displayName!==void 0&&e.purpose!=="create")throw Oe();this.pins=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});let c=[this.pins.accountId,this.pins.connectorId,this.pins.deviceId,this.pins.installationId,this.pins.collection].map(N);if(c.some(l=>l.every(p=>p===0))||!["create","enrol"].includes(this.pins.purpose))throw Oe();for(let l of[e.cpOrigin,e.logOrigin]){let p=new URL(l);if(!(i.allowLoopbackHttp===!0&&Ze(l))&&p.protocol!=="https:"||p.origin!==l||p.username||p.password)throw Oe()}if(!(e.rootPublicKey instanceof Uint8Array)||e.rootPublicKey.length!==32||e.rootPublicKey.every(l=>l===0)||(this.root=new Uint8Array(e.rootPublicKey),this.keys=[t.signPublicKey,t.kemPublicKey,t.noisePublicKey].map(l=>{if(!(l instanceof Uint8Array)||l.length!==32||l.every(p=>p===0))throw Oe();return new Uint8Array(l)}),this.checkReceipt(t),r.type!=="secret"||r.extractable||r.algorithm.name!=="AES-GCM"||r.algorithm.length!==256||!r.usages.includes("encrypt")||!r.usages.includes("decrypt")))throw Oe();this.aad=ue(["mdbase/v1/app-private-bootstrap-platform",...c,this.pins.purpose,e.cpOrigin,e.logOrigin,this.root]),this.check(new AbortController().signal)}catch{throw Oe()}}source;key;store;noise;pins;root;keys;aad;displayName;check(e){try{if(e.aborted||this.source.isCurrent()!==!0||this.source.approvalMode!=="password-ak1"||!ma(this.source.rootPublicKey,this.root)||Object.entries(this.pins).some(([t,r])=>this.source[t]!==r))throw Oe()}catch{throw Oe()}}checkReceipt(e){if(e.connectorId!==this.pins.connectorId||e.deviceId!==this.pins.deviceId||e.installationId!==this.pins.installationId||[e.signPublicKey,e.kemPublicKey,e.noisePublicKey].some((r,o)=>!(r instanceof Uint8Array)||r.length!==32||r.every(s=>s===0)||!ma(r,this.keys[o])))throw Oe()}commit(e){if(this.checkReceipt(e),this.pins.purpose!=="enrol"||e.collection!==this.pins.collection||typeof e.acknowledged!="boolean"||!(e.sasCommitment instanceof Uint8Array)||e.sasCommitment.length!==32||e.sasCommitment.every(t=>t===0))throw Oe();return new Uint8Array(e.sasCommitment)}markerCopy(e,t){return Object.freeze({connectorId:this.pins.connectorId,deviceId:this.pins.deviceId,installationId:this.pins.installationId,collection:this.pins.collection,signPublicKey:new Uint8Array(this.keys[0]),kemPublicKey:new Uint8Array(this.keys[1]),noisePublicKey:new Uint8Array(this.keys[2]),sasCommitment:new Uint8Array(t),acknowledged:e.acknowledged})}copy(e){if(e.displayName!==this.displayName||e.collection!==this.pins.collection||e.deviceId!==this.pins.deviceId||e.logOrigin!==this.pins.logOrigin||!(e.rootPublicKey instanceof Uint8Array)||!ma(e.rootPublicKey,this.root)||!(e.genesisItem instanceof Uint8Array)||!e.genesisItem.length||e.genesisItem.length>256*1024||!/^sha256:[0-9a-f]{64}$/.test(e.expectedGenesis)||e.approval!==(this.pins.purpose==="create"?"creator":"pending"))throw Oe();return Object.freeze({collection:this.pins.collection,deviceId:this.pins.deviceId,logOrigin:this.pins.logOrigin,rootPublicKey:new Uint8Array(this.root),genesisItem:new Uint8Array(e.genesisItem),expectedGenesis:e.expectedGenesis,approval:e.approval,...this.displayName===void 0?{}:{displayName:this.displayName}})}async hashChecked(e,t){let r=new TextEncoder().encode("mdbase/v1/chain"),o=new Uint8Array(1+r.length+e.genesisItem.length);o[0]=r.length,o.set(r,1),o.set(e.genesisItem,1+r.length);let s=new Uint8Array(await crypto.subtle.digest("SHA-256",o));if(this.check(t),e.expectedGenesis!==`sha256:${s8(s)}`)throw Oe()}async read(e){let t=null;try{this.check(e.signal);let r=await this.store.read(e);if(this.check(e.signal),r===null)return null;if(!(r instanceof Uint8Array)||!r.length||r.length>FA)throw Oe();let o=new Uint8Array(r),s=we(o);if(!(s instanceof Map))throw Oe();let i=s;if(i.size!==3||i.get(0)!==1)throw Oe();let a=i.get(1),c=i.get(2);if(!(a instanceof Uint8Array)||a.length!==12||!(c instanceof Uint8Array)||c.length<16||c.length>Ky+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(c))),this.check(e.signal),t.length>Ky))throw Oe();let l=we(t);if(!(l instanceof Map))throw Oe();let p=l,d=p.get(0)===1&&p.size===4;if(!d&&!(p.get(0)===2&&p.size===5)||(d?null:p.get(4))!==(this.displayName??null))throw Oe();let u=p.get(1);if(!Array.isArray(u)||u.length!==3||u.some((w,b)=>!(w instanceof Uint8Array)||!ma(w,this.keys[b])))throw Oe();let f=p.get(2);if(this.pins.purpose==="create"?f!==null:!(f instanceof Uint8Array)||f.length!==32||f.every(w=>w===0))throw Oe();let h=p.get(3),m=null;if(h!==null){if(!Array.isArray(h)||h.length!==2||!(h[0]instanceof Uint8Array)||typeof h[1]!="string")throw Oe();m=this.copy({...this.pins,rootPublicKey:this.root,genesisItem:h[0],expectedGenesis:h[1],approval:this.pins.purpose==="create"?"creator":"pending",...this.displayName===void 0?{}:{displayName:this.displayName}}),await this.hashChecked(m,e.signal)}return{encrypted:o,value:{commit:f===null?null:new Uint8Array(f),metadata:m}}}catch{throw Oe()}finally{t?.fill(0)}}async write(e,t,r){let o=null,s=null;try{if(this.check(r.signal),o=ue(new Map([[0,2],[1,this.keys.map(l=>new Uint8Array(l))],[2,e.commit],[3,e.metadata===null?null:[e.metadata.genesisItem,e.metadata.expectedGenesis]],[4,this.displayName??null]])),o.length>Ky)throw Oe();let i=crypto.getRandomValues(new Uint8Array(12)),a=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:i,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(o)));this.check(r.signal),s=ue(new Map([[0,1],[1,i],[2,a]]));let c=await this.store.compareAndSet(t,s,r);if(this.check(r.signal),c!==!0)throw Oe()}catch{throw Oe()}finally{o?.fill(0),s?.fill(0)}}async pendingCreate(e,t){if(this.check(t.signal),this.checkReceipt(e),this.pins.purpose!=="create"||e.collection!==this.pins.collection||e.displayName!==this.displayName)throw Oe();let r=await this.read(t);this.check(t.signal),!r&&await this.write({commit:null,metadata:null},null,t)}async privateEnrolPending(e,t){this.check(t.signal);let r=this.commit(e),o=this.markerCopy(e,r);if(o.acknowledged)throw Oe();let s=await this.read(t);if(this.check(t.signal),s&&!ma(s.value.commit,r))throw Oe();try{await this.noise.privateEnrolPending(o,t),this.check(t.signal)}catch{throw Oe()}s||await this.write({commit:r,metadata:null},null,t)}async completed(e,t){this.check(t.signal);let r=this.copy(e);await this.hashChecked(r,t.signal);let o=await this.read(t);if(this.check(t.signal),!o)throw Oe();if(o.value.metadata){if(!ma(o.value.metadata.genesisItem,r.genesisItem)||o.value.metadata.expectedGenesis!==r.expectedGenesis)throw Oe();return}await this.write({...o.value,metadata:r},o.encrypted,t)}async privateEnrolAcknowledged(e,t){this.check(t.signal);let r=this.commit(e),o=this.markerCopy(e,r),s=await this.read(t);if(this.check(t.signal),!s?.value.metadata||!ma(s.value.commit,r))throw Oe();try{await this.noise.privateEnrolAcknowledged(o,t),this.check(t.signal)}catch{throw Oe()}}async restoredCompletion(e){let t=await this.read(e);return this.check(e.signal),t?.value.metadata?this.copy(t.value.metadata):null}}});function HA(n){if(!(n instanceof Uint8Array)||!n.length||n.length>FA)throw gn();return new Uint8Array(n)}var Hy,d2,gn,WA,Gy,u2=I(()=>{"use strict";tn();ve();KA();Hy="public-outcome",d2="operation",gn=()=>new Error("app private bootstrap store unavailable"),WA=(n,e)=>n===null||e===null?n===e:n.length===e.length&&n.every((t,r)=>t===e[r]);Gy=class n{constructor(e,t,r,o,s){this.db=e;this.source=t;this.pins=r;this.root=o;this.origin=s;e.onversionchange=()=>this.close()}db;source;pins;root;origin;closed=!1;static async open(e){try{return await this.openChecked(e)}catch{throw gn()}}static async openChecked(e){let{source:t,signal:r}=e,o=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}),s=[o.accountId,o.connectorId,o.deviceId,o.installationId,o.collection];for(let d of s)if(N(d).every(u=>u===0))throw gn();if(!(t.rootPublicKey instanceof Uint8Array)||t.rootPublicKey.length!==32||t.rootPublicKey.every(d=>d===0))throw gn();let i=new Uint8Array(t.rootPublicKey);if(!dt(e.origin)||Rt()!==e.origin||!["fresh","existing"].includes(e.mode)||!["create","enrol"].includes(o.purpose)||!globalThis.indexedDB)throw gn();let a=()=>{try{return!r.aborted&&t.isCurrent()===!0&&t.approvalMode==="password-ak1"&&t.rootPublicKey instanceof Uint8Array&&WA(t.rootPublicKey,i)&&Object.entries(o).every(([d,u])=>t[d]===u)}catch{return!1}};if(!a())throw gn();let c=`mdbase.app.private-bootstrap.v1.${s.map(d=>d.toLowerCase()).join(".")}.${o.purpose}`,l=await new Promise((d,u)=>{let f=indexedDB.open(c,1),h=!1,m=()=>{h=!0,u(gn())},w=()=>r.removeEventListener("abort",m);r.addEventListener("abort",m,{once:!0}),f.onblocked=m,f.onupgradeneeded=()=>{if(h||!a()||e.mode!=="fresh"||f.result.objectStoreNames.length!==0){f.transaction?.abort();return}f.result.createObjectStore(Hy)},f.onerror=()=>{w(),u(gn())},f.onsuccess=()=>{if(w(),h||!a()||f.result.objectStoreNames.length!==1||!f.result.objectStoreNames.contains(Hy)){f.result.close(),u(gn());return}d(f.result)}}),p=new n(l,t,o,i,e.origin);try{let d=await p.read({signal:r});if(e.mode==="fresh"!=(d===null))throw gn();return d?.fill(0),p.check(r),p}catch{throw p.close(),gn()}}check(e){try{if(this.closed||e.aborted||Rt()!==this.origin||this.source.isCurrent()!==!0||this.source.approvalMode!=="password-ak1"||!(this.source.rootPublicKey instanceof Uint8Array)||!WA(this.source.rootPublicKey,this.root)||Object.entries(this.pins).some(([t,r])=>this.source[t]!==r))throw gn()}catch{throw gn()}}async read(e){this.check(e.signal);let t=await this.transaction("readonly",e.signal,null,null);return this.check(e.signal),t}async compareAndSet(e,t,r){this.check(r.signal);let o=null,s=null;try{o=e===null?null:HA(e),s=HA(t);let i=await this.transaction("readwrite",r.signal,o,s);return this.check(r.signal),i===!0}finally{o?.fill(0),s?.fill(0)}}transaction(e,t,r,o){return new Promise((s,i)=>{this.check(t);let a=this.db.transaction(Hy,e,{durability:"strict"}),c=a.objectStore(Hy),l=null,p=!1,d=()=>{p=!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),i(gn())},a.oncomplete=()=>{u();try{if(this.check(t),p)throw gn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),i(gn())}};let f=c.get(d2);f.onsuccess=()=>{let h=null;try{this.check(t),h=f.result===void 0?null:HA(f.result),e==="readonly"?(l=h,h=null):(l=WA(h,r),l===!0&&o!==null&&c.put(new Uint8Array(o),d2))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db.close())}}});var f2,h2=I(()=>{f2=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9])});function cs(n,e,t,r,o,s){let i=o[s],a=o[s+1],c=H[2*n],l=H[2*n+1],p=H[2*e],d=H[2*e+1],u=H[2*t],f=H[2*t+1],h=H[2*r],m=H[2*r+1],w=np(c,p,i);l=rp(w,l,d,a),c=w|0;let b=m^l,g=h^c;m=Nk(b,g),h=Dk(b,g),{h:f,l:u}=er(f,u,m,h),b=d^f,g=p^u,d=di(b,g,24),p=ui(b,g,24),H[2*n]=c,H[2*n+1]=l,H[2*e]=p,H[2*e+1]=d,H[2*t]=u,H[2*t+1]=f,H[2*r]=h,H[2*r+1]=m}function ps(n,e,t,r,o,s){let i=o[s],a=o[s+1],c=H[2*n],l=H[2*n+1],p=H[2*e],d=H[2*e+1],u=H[2*t],f=H[2*t+1],h=H[2*r],m=H[2*r+1],w=np(c,p,i);l=rp(w,l,d,a),c=w|0;let b=m^l,g=h^c;m=di(b,g,16),h=ui(b,g,16),{h:f,l:u}=er(f,u,m,h),b=d^f,g=p^u,d=_s(b,g,63),p=As(b,g,63),H[2*n]=c,H[2*n+1]=l,H[2*e]=p,H[2*e+1]=d,H[2*t]=u,H[2*t+1]=f,H[2*r]=h,H[2*r+1]=m}function a8(n,e={},t,r,o){if(Sn(t),n<=0||n>t)throw new Error('"dkLen" must be 1..'+t+", got "+n);let{key:s,salt:i,personalization:a}=e;if(s!==void 0&&(s.length<1||s.length>t))throw new Error('"key" expected to be undefined or of length=1..'+t);i!==void 0&&ft(i,r,"salt"),a!==void 0&&ft(a,o,"personalization")}var Bt,H,GA,YA,mc,m2=I(()=>{h2();Gu();fi();Bt=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),H=new Uint32Array(32);GA=class{buffer;buffer32;finished=!1;destroyed=!1;length=0;pos=0;blockLen;outputLen;canXOF=!1;constructor(e,t){Sn(e),Sn(t),this.blockLen=e,this.outputLen=t,this.buffer=new Uint8Array(e),this.buffer32=So(this.buffer)}update(e){Hi(this),ft(e);let{blockLen:t,buffer:r,buffer32:o}=this,s=e.length,i=e.byteOffset,a=e.buffer;for(let c=0;c<s;){this.pos===t&&(Nr(o),this.compress(o,0,!1),Nr(o),this.pos=0);let l=Math.min(t-this.pos,s-c),p=i+c;if(l===t&&!(p%4)&&c+l<s){let d=new Uint32Array(a,p,Math.floor((s-c)/4));Nr(d);for(let u=0;c+t<s;u+=o.length,c+=t)this.length+=t,this.compress(d,u,!1);Nr(d);continue}r.set(c===0&&l===s?e:e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){if(Hi(this),qa(e,this),e.byteOffset&3)throw new RangeError('"output" expected 4-byte aligned byteOffset, got '+e.byteOffset);let{pos:t,buffer32:r}=this;this.finished=!0,this.buffer.fill(0,t),Nr(r),this.compress(r,0,!0),Nr(r);let o=this.get(),s=e===this.buffer?r:So(e),i=Math.floor(this.outputLen/4);for(let p=0;p<i;p++)s[p]=en(o[p]);let a=this.outputLen%4;if(!a)return;let c=i*4,l=o[i];for(let p=0;p<a;p++)e[c+p]=l>>>8*p}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){let{buffer:t,length:r,finished:o,destroyed:s,outputLen:i,pos:a}=this;return e||=new this.constructor({dkLen:i}),e.set(...this.get()),e.buffer.set(t),e.destroyed=s,e.finished=o,e.length=r,e.pos=a,e.outputLen=i,e}clone(){return this._cloneInto()}},YA=class extends GA{v0l=Bt[0]|0;v0h=Bt[1]|0;v1l=Bt[2]|0;v1h=Bt[3]|0;v2l=Bt[4]|0;v2h=Bt[5]|0;v3l=Bt[6]|0;v3h=Bt[7]|0;v4l=Bt[8]|0;v4h=Bt[9]|0;v5l=Bt[10]|0;v5h=Bt[11]|0;v6l=Bt[12]|0;v6h=Bt[13]|0;v7l=Bt[14]|0;v7h=Bt[15]|0;constructor(e={}){e=sp({},e);let t=e.dkLen===void 0?64:e.dkLen;super(128,t),a8(t,e,64,16,16);let{key:r,personalization:o,salt:s}=e,i=0;if(r!==void 0&&(ft(r,void 0,"key"),i=r.length),this.v0l^=this.outputLen|i<<8|65536|1<<24,s!==void 0){ft(s,void 0,"salt");let a=So(xb(s));this.v4l^=en(a[0]),this.v4h^=en(a[1]),this.v5l^=en(a[2]),this.v5h^=en(a[3])}if(o!==void 0){ft(o,void 0,"personalization");let a=So(xb(o));this.v6l^=en(a[0]),this.v6h^=en(a[1]),this.v7l^=en(a[2]),this.v7h^=en(a[3])}if(r!==void 0){let a=new Uint8Array(this.blockLen);a.set(r),this.update(a),at(a)}}get(){let{v0l:e,v0h:t,v1l:r,v1h:o,v2l:s,v2h:i,v3l:a,v3h:c,v4l:l,v4h:p,v5l:d,v5h:u,v6l:f,v6h:h,v7l:m,v7h:w}=this;return[e,t,r,o,s,i,a,c,l,p,d,u,f,h,m,w]}set(e,t,r,o,s,i,a,c,l,p,d,u,f,h,m,w){this.v0l=e|0,this.v0h=t|0,this.v1l=r|0,this.v1h=o|0,this.v2l=s|0,this.v2h=i|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=p|0,this.v5l=d|0,this.v5h=u|0,this.v6l=f|0,this.v6h=h|0,this.v7l=m|0,this.v7h=w|0}compress(e,t,r){let{v0l:o,v0h:s,v1l:i,v1h:a,v2l:c,v2h:l,v3l:p,v3h:d,v4l:u,v4h:f,v5l:h,v5h:m,v6l:w,v6h:b,v7l:g,v7h:y}=this;H[0]=o,H[1]=s,H[2]=i,H[3]=a,H[4]=c,H[5]=l,H[6]=p,H[7]=d,H[8]=u,H[9]=f,H[10]=h,H[11]=m,H[12]=w,H[13]=b,H[14]=g,H[15]=y,H.set(Bt,16);let _=Ab(this.length),v=_b(this.length);H[24]=Bt[8]^_,H[25]=Bt[9]^v,r&&(H[28]=~H[28],H[29]=~H[29]);let k=0,S=f2;for(let x=0;x<12;x++)cs(0,4,8,12,e,t+2*S[k++]),ps(0,4,8,12,e,t+2*S[k++]),cs(1,5,9,13,e,t+2*S[k++]),ps(1,5,9,13,e,t+2*S[k++]),cs(2,6,10,14,e,t+2*S[k++]),ps(2,6,10,14,e,t+2*S[k++]),cs(3,7,11,15,e,t+2*S[k++]),ps(3,7,11,15,e,t+2*S[k++]),cs(0,5,10,15,e,t+2*S[k++]),ps(0,5,10,15,e,t+2*S[k++]),cs(1,6,11,12,e,t+2*S[k++]),ps(1,6,11,12,e,t+2*S[k++]),cs(2,7,8,13,e,t+2*S[k++]),ps(2,7,8,13,e,t+2*S[k++]),cs(3,4,9,14,e,t+2*S[k++]),ps(3,4,9,14,e,t+2*S[k++]);this.v0l^=H[0]^H[16],this.v0h^=H[1]^H[17],this.v1l^=H[2]^H[18],this.v1h^=H[3]^H[19],this.v2l^=H[4]^H[20],this.v2h^=H[5]^H[21],this.v3l^=H[6]^H[22],this.v3h^=H[7]^H[23],this.v4l^=H[8]^H[24],this.v4h^=H[9]^H[25],this.v5l^=H[10]^H[26],this.v5h^=H[11]^H[27],this.v6l^=H[12]^H[28],this.v6h^=H[13]^H[29],this.v7l^=H[14]^H[30],this.v7h^=H[15]^H[31],at(H)}destroy(){this.destroyed=!0,at(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},mc=ap(n=>new YA(n))});function ds(n,e,t,r){let o=Lt[2*n],s=Lt[2*n+1],i=Lt[2*e],a=Lt[2*e+1],c=Lt[2*t],l=Lt[2*t+1],p=Lt[2*r],d=Lt[2*r+1],u=0,f=0,h=0,m=0,w=0;u=Math.imul(o,i),f=((o>>>0)*(i>>>0)-(u>>>0))/4294967296+.5|0,h=(o>>>0)+(i>>>0)+(u<<1>>>0),s=s+a+(f<<1|u>>>31)+(h/4294967296|0)|0,o=h|0,m=d^s,w=p^o,d=w,p=m,u=Math.imul(c,p),f=((c>>>0)*(p>>>0)-(u>>>0))/4294967296+.5|0,h=(c>>>0)+(p>>>0)+(u<<1>>>0),l=l+d+(f<<1|u>>>31)+(h/4294967296|0)|0,c=h|0,m=a^l,w=i^c,a=m>>>24|w<<8,i=m<<8|w>>>24,u=Math.imul(o,i),f=((o>>>0)*(i>>>0)-(u>>>0))/4294967296+.5|0,h=(o>>>0)+(i>>>0)+(u<<1>>>0),s=s+a+(f<<1|u>>>31)+(h/4294967296|0)|0,o=h|0,m=d^s,w=p^o,d=m>>>16|w<<16,p=m<<16|w>>>16,u=Math.imul(c,p),f=((c>>>0)*(p>>>0)-(u>>>0))/4294967296+.5|0,h=(c>>>0)+(p>>>0)+(u<<1>>>0),l=l+d+(f<<1|u>>>31)+(h/4294967296|0)|0,c=h|0,m=a^l,w=i^c,a=m<<1|w>>>31,i=m>>>31|w<<1,Lt[2*n]=o,Lt[2*n+1]=s,Lt[2*e]=i,Lt[2*e+1]=a,Lt[2*t]=c,Lt[2*t+1]=l,Lt[2*r]=p,Lt[2*r+1]=d}function g2(n,e,t,r,o,s,i,a,c,l,p,d,u,f,h,m){ds(n,o,c,u),ds(e,s,l,f),ds(t,i,p,h),ds(r,a,d,m),ds(n,s,p,m),ds(e,i,d,u),ds(t,a,c,f),ds(r,o,l,h)}function iu(n,e,t,r,o){if(o)for(let s=0;s<256;s++){let i=n[e+s]^n[t+s];Lt[s]=i,n[r+s]^=i}else for(let s=0;s<256;s++){let i=n[e+s]^n[t+s];Lt[s]=i,n[r+s]=i}for(let s=0;s<128;s+=16)g2(s,s+1,s+2,s+3,s+4,s+5,s+6,s+7,s+8,s+9,s+10,s+11,s+12,s+13,s+14,s+15);for(let s=0;s<16;s+=2)g2(s,s+1,s+16,s+17,s+32,s+33,s+48,s+49,s+64,s+65,s+80,s+81,s+96,s+97,s+112,s+113);for(let s=0;s<256;s++)n[r+s]^=Lt[s];at(Lt)}function JA(n,e){let t=op(n),r=new Uint32Array(1),o=op(r);if(r[0]=en(e),e<=64)return mc.create({dkLen:e}).update(o).update(t).digest();let s=new Uint8Array(e),i=mc.create({}).update(o).update(t).digest(),a=0;for(s.set(i.subarray(0,32)),a+=32;e-a>64;a+=32){let c=mc.create({}).update(i);c.digestInto(i),c.destroy(),s.set(i.subarray(0,32),a)}return s.set(mc(i,{dkLen:e-a}),a),at(i,r),s}function l8(n,e,t,r,o,s,i=!1){let a;n===0?e===0?a=o-1:i?a=e*r+o-1:a=e*r+(o==0?-1:0):i?a=t-r+o-1:a=t-r+(o==0?-1:0);let c=n!==0&&e!==ou-1?(e+1)*r:0,l=Math.imul(s,s),p=((s>>>0)*(s>>>0)-(l>>>0))/4294967296+.5|0,d=Math.imul(a,p),u=((a>>>0)*(p>>>0)-(d>>>0))/4294967296+.5|0,f=a-1-u;return(c+f)%t}function us(n){return Number.isSafeInteger(n)&&n>=0&&n<c8}function d8(n={}){n=sp({},n);let e={t:3,m:b2,p:1,version:19,dkLen:32,maxmem:p8,asyncTick:10};for(let[l,p]of Object.entries(n))p!==void 0&&(e[l]=p);let{dkLen:t,p:r,m:o,t:s,version:i,onProgress:a,asyncTick:c}=e;if(!us(t)||t<4)throw new Error('"dkLen" must be 4..');if(!us(r)||r<1||r>=Math.pow(2,24))throw new Error('"p" must be 1..2^24');if(!us(o))throw new Error('"m" must be 0..2^32');if(!us(s)||s<1)throw new Error('"t" (iterations) must be 1..2^32');if(a!==void 0&&typeof a!="function")throw new Error('"onProgress" must be a function');if(Sn(c,"asyncTick"),!us(o)||o<8*r)throw new Error('"m" (memory) must be at least 8*p bytes');if(i!==16&&i!==19)throw new Error('"version" must be 0x10 or 0x13, got '+i);return e}function u8(n,e,t,r){let o=[],s=new Uint32Array(1),i=op(s),a,c,l=!1,p=(d,u)=>(typeof d=="string"&&o.push(u),u);try{let d=p(n,Qu(n,"password")),u=p(e,Qu(e,"salt"));if(!us(d.length))throw new Error('"password" must be less of length 1..4Gb');if(!us(u.length)||u.length<8)throw new Error('"salt" must be of length 8..4Gb');if(!Object.values(Yy).includes(t))throw new Error('"type" was invalid');let{p:f,dkLen:h,m,t:w,version:b,key:g,personalization:y,maxmem:_,onProgress:v,asyncTick:k}=d8(r),S=g;g=p(S,y2(S,"key"));let x=y;y=p(x,y2(x,"personalization")),a=mc.create();for(let P of[f,h,m,w,b,t])s[0]=en(P),a.update(i);for(let P of[d,u,g,y])s[0]=en(P.length),a.update(i).update(P);return c=new Uint32Array(18),a.digestInto(op(c)),l=!0,{H0:c,p:f,dkLen:h,m,t:w,version:b,maxmem:_,onProgress:v,asyncTick:k}}finally{a&&a.destroy(),at(s,...o),!l&&c&&at(c)}}function f8(n,e,t,r){let{H0:o,p:s,dkLen:i,m:a,t:c,version:l,maxmem:p,onProgress:d,asyncTick:u}=u8(n,e,t,r);try{let f=s,h=4*s*Math.floor(a/(ou*s)),m=Math.floor(h/s),w=Math.floor(m/ou),b=h*1024;if(!us(p))throw new Error('"maxmem" expected <2**32, got '+p);if(b>p)throw new Error('"maxmem" limit was hit: memUsed(mP*1024)='+b+", maxmem="+p);let g=new Uint32Array(b/4);for(let _=0;_<s;_++){let v=256*m*_;o[17]=en(_),o[16]=en(0),g.set(Nr(So(JA(o,1024))),v),o[16]=en(1),g.set(Nr(So(JA(o,1024))),v+256)}let y=()=>{};if(d){let _=c*ou*s*w-2*s,v=Math.max(Math.floor(_/1e4),1),k=0;y=()=>{k++,d&&(!(k%v)||k===_)&&d(k/_)}}return{type:t,mP:h,p:s,t:c,version:l,B:g,laneLen:m,lanes:f,segmentLen:w,dkLen:i,perBlock:y,asyncTick:u}}finally{at(o)}}function h8(n,e,t,r){let o=new Uint32Array(256);for(let i=0;i<e;i++)for(let a=0;a<256;a++)o[a]^=n[256*(t*i+t-1)+a];let s=JA(Nr(o),r);return at(n,o),s}function*m8(n,e){let{type:t,mP:r,p:o,t:s,version:i,B:a,laneLen:c,lanes:l,segmentLen:p,perBlock:d}=n;e[262]=r,e[264]=s,e[266]=t;for(let u=0;u<s;u++){let f=u!==0&&i===19;e[256]=u;for(let h=0;h<ou;h++){e[260]=h;let m=t==Yy.Argon2i||t==Yy.Argon2id&&u===0&&h<2;for(let w=0;w<o;w++){e[258]=w,e[268]=0;let b=0;u===0&&h===0&&(b=2,m&&(e[268]++,iu(e,256,2*256,0,!1),iu(e,0,2*256,0,!1)));let g=w*c+h*p+b;for(let y=b;y<p;y++,g++){d();let _=g%c?g-1:g+c-1,v,k;if(m){let C=y%128;C===0&&(e[268]++,iu(e,256,2*256,0,!1),iu(e,0,2*256,0,!1)),v=e[2*C],k=e[2*C+1]}else{let C=256*_;v=a[C],k=a[C+1]}let S=u===0&&h===0?w:k%l,x=l8(u,h,c,p,y,v,S==w),P=c*S+x;iu(a,256*_,256*P,g*256,f),yield}}}}at(e)}async function y8(n,e,t,r){let o=f8(e,t,n,r),s=new Uint32Array(3*256),i=m8(o,s),a=()=>at(s,o.B),c=Date.now();for(;!i.next().done;){let l=Date.now()-c;l>=0&&l<o.asyncTick||(await Jk(a),c=Date.now())}return h8(o.B,o.p,o.laneLen,o.dkLen)}var Yy,ou,y2,Lt,c8,b2,p8,w2,v2=I(()=>{m2();fi();Yy={Argon2d:0,Argon2i:1,Argon2id:2},ou=4,y2=(n,e="")=>n===void 0?Uint8Array.of():Qu(n,e),Lt=new Uint32Array(256);c8=Math.pow(2,32),b2=1024**2,p8=b2*1024;w2=(n,e,t={})=>y8(Yy.Argon2id,n,e,t)});function b8(n,e,t,r=32,o){ip(n),Sn(r,"length"),ft(e,void 0,"prk");let s=n.outputLen;if(e.length<s)throw new Error('"prk" must be at least HashLen octets');if(r>255*s)throw new Error("Length must be <= 255*HashLen");let i=Math.ceil(r/s);if(t===void 0?t=g8:ft(t,void 0,"info"),!i)return o&&at(e),new Uint8Array;let a=o&&i===1?e:new Uint8Array(i*s),{iHash:c,oHash:l}=sa.create(n,e),p=o?e:new Uint8Array(s),d=i>1?o?.iHash||n.create():void 0;for(let f=0;f<i-1;f++){su[0]=f+1;let h=c._cloneInto(d);f&&h.update(p),h.update(t).update(su).digestInto(p),l._cloneInto(d).update(p).digestInto(p),a.set(p,s*f)}if(su[0]=i,i>1&&c.update(p),c.update(t).update(su).digestInto(p),l.update(p).digestInto(p),a.set(p,s*(i-1)),c.destroy(),l.destroy(),d?.destroy(),p!==a&&at(p),at(su),r===a.length)return a;let u=a.slice(0,r);return at(a),u}var su,g8,Jy,_2=I(()=>{aA();fi();su=Uint8Array.of(0),g8=Uint8Array.of();Jy=(n,e,t,r,o)=>{ip(n),t===void 0&&(t=new Uint8Array(n.outputLen));let s=sa.create(n,t).update(e);return b8(n,s.digest(),r,o,s)}});function ga(n,e){let t=yc.encode(n);if(t.length>255)throw De("internal","domain tag longer than 255 bytes");return Qe(ZA(Uint8Array.of(t.length),t,e))}function ZA(...n){let e=0;for(let o of n)e+=o.length;let t=new Uint8Array(e),r=0;for(let o of n)t.set(o,r),r+=o.length;return t}function e0(n,e){if(n.length!==e.length)return!1;let t=0;for(let r=0;r<n.length;r++)t|=n[r]^e[r];return t===0}function bt(...n){for(let e of n)e.fill(0)}function Jn(n){if(!w8.test(n))throw De("internal","not a UUID");let e=n.replace(/-/g,"").toLowerCase(),t=new Uint8Array(16);for(let r=0;r<16;r++)t[r]=parseInt(e.slice(r*2,r*2+2),16);return t}function v8(n){let e="";for(let t of n)e+=t.toString(16).padStart(2,"0");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}function k2(n=Xy){let e=n(ii);if(e.length!==ii)throw De("internal","entropy returned the wrong length");return e}function S2(n){return ga("mdbase/v1/recovery-key-check",n).subarray(0,A2)}function P2(n){if(n.length!==ii)throw De("internal","recovery secret is 32 bytes");let e=ZA(n,S2(n)),t="",r=0,o=0;for(let s of e){for(r=r<<8|s,o+=8;o>=5;)t+=XA[r>>>o-5&31],o-=5;r&=(1<<o)-1}return o>0&&(t+=XA[r<<5-o&31]),bt(e),[QA,...t.match(/.{1,5}/g)].join("-")}function lu(n){if(typeof n!="string"||n.length>4096)throw De("invalid_recovery_key","Not a recovery key.","wrong_length");let e=n.toUpperCase().replace(/[\s-]/g,"").replace(/O/g,"0").replace(/[IL]/g,"1");if(!e.startsWith(QA))throw De("invalid_recovery_key","A recovery key starts with MDB1.","wrong_prefix");if(e=e.slice(QA.length),e.length!==_8)throw De("invalid_recovery_key","A recovery key has 55 characters after MDB1.","wrong_length");let t=new Uint8Array(ii+A2),r=0,o=0,s=0;for(let c of e){let l=XA.indexOf(c);if(l<0)throw De("invalid_recovery_key","A recovery key uses only Crockford base32 characters.","bad_character");r=r<<5|l,o+=5,o>=8&&(s<t.length&&(t[s++]=r>>>o-8&255),o-=8),r&=(1<<o)-1}if(s!==t.length||r!==0)throw De("invalid_recovery_key","Not a recovery key.","bad_character");let i=t.slice(0,ii),a=e0(S2(i),t.subarray(ii));if(bt(t),!a)throw bt(i),De("invalid_recovery_key","The recovery key has a typo (check failed).","checksum");return i}function x2(n,e){if(n.length!==ii)throw De("internal","recovery secret is 32 bytes");let t=Jn(e),r=Jy(Qe,n,t,yc.encode("mdbase/v1/recovery-sign"),32),o=Jy(Qe,n,t,yc.encode("mdbase/v1/recovery-kem"),32),s=Jd.getPublicKey(r),i=ni.getPublicKey(o);return{device:v8(ga("mdbase/v1/recovery-id",ZA(t,s)).subarray(0,16)),signSeed:r,signPk:s,kemSk:o,kemPk:i,noisePk:new Uint8Array(32)}}function C2(n,e){return Jd.sign(e,n.signSeed)}function I2(n){bt(n.signSeed,n.kemSk)}function O2(n,e){if(n.length!==ii)throw De("internal","recovery secret is 32 bytes");let t=Jy(Qe,n,Jn(e),yc.encode("mdbase/v1/account-key-proof"),32);return{seed:t,pk:Jd.getPublicKey(t)}}function A8(n,e,t){if(!Number.isSafeInteger(t)||t<0)throw De("internal","expected_version");return ga("mdbase/v1/account-key-rewrap",ue([Jn(n),Qe(e),t]))}function R2(n,e,t,r){return Jd.sign(A8(e,t,r),n.seed)}function cu(n){return ga("mdbase/v1/account-key-id",n)}function O8(n){if(!(ya(n.mKib)&&ya(n.t)&&ya(n.p)&&n.mKib>=P8&&n.mKib<=q2&&n.t>=x8&&n.t<=C8&&n.p>=1&&n.p<=I8&&n.mKib>=8*n.p&&n.salt instanceof Uint8Array&&n.salt.length===16))throw De("params","Unsupported key derivation parameters.")}function T2(n){return[E2,n.mKib,n.t,n.p,n.salt]}function R8(n){if(!Array.isArray(n)||n.length!==5)throw De("encoding","Not an account key bundle.");let[e,t,r,o,s]=n;if(!ya(e)||!ya(t)||!ya(r)||!ya(o)||!(s instanceof Uint8Array)||s.length!==16)throw De("encoding","Not an account key bundle.");if(e!==E2||t>4294967295||r>4294967295||o>4294967295)throw De("params","Unsupported key derivation parameters.");return{mKib:t,t:r,p:o,salt:s}}function n0(n){return ue(Tg([[0,t0],[1,T2(n.kdf)],[2,n.nonce],[3,n.ct],[4,n.keyId]]))}function M2(n){if(!(n instanceof Uint8Array)||n.length>k8)throw De("encoding","Not an account key bundle.");let e;try{e=we(n)}catch{throw De("encoding","Not an account key bundle.")}if(!(e instanceof Map)||e.size!==5||[...e.keys()].join()!=="0,1,2,3,4")throw De("encoding","Not an account key bundle.");let t=e,r=t.get(2),o=t.get(3),s=t.get(4);if(t.get(0)!==t0||!(r instanceof Uint8Array)||r.length!==24||!(o instanceof Uint8Array)||o.length!==48||!(s instanceof Uint8Array)||s.length!==32)throw De("encoding","Not an account key bundle.");let i={kdf:R8(t.get(1)),nonce:r,ct:o,keyId:s};if(!Mg(n0(i),n))throw De("encoding","Not an account key bundle.");return i}function L2(n){if(typeof n!="string")throw De("weak_password","The password is required.","too_short");if(yc.encode(n).length>au)throw De("weak_password","The password is too long.","too_long");let e=n.normalize("NFKC"),t=yc.encode(e);if(t.length>au)throw De("weak_password","The password is too long.","too_long");if([...e].length<gc)throw bt(t),De("weak_password",`The password needs at least ${gc} characters.`,"too_short");return t}function ba(n){bt(L2(n))}async function j2(n,e,t,r){O8(e);let o=L2(n);try{let s=await t(o,e.salt,{mKib:e.mKib,t:e.t,p:e.p},r);if(!(s instanceof Uint8Array)||s.length!==32)throw De("internal","The KDF runner returned the wrong length.");return s}finally{bt(o)}}function U2(n,e,t){return ga("mdbase/v1/account-key-bundle",ue([t0,Jn(n),e,T2(t)]))}async function Zy(n,e,t,r={}){if(n.length!==ii)throw De("internal","recovery secret is 32 bytes");ba(e);let o=r.entropy??Xy,s=r.kdf??{...S8,salt:o(16)},i=r.nonce??o(24);if(i.length!==24)throw De("internal","nonce is 24 bytes");let a=cu(n),c=await j2(e,s,r.argon2id??Qy,r.signal);try{let l=K_(c,i,U2(t,a,s)).encrypt(n);return{kdf:s,nonce:i,ct:l,keyId:a}}finally{bt(c)}}async function N2(n,e,t,r={}){let o=await j2(e,n.kdf,r.argon2id??Qy,r.signal),s;try{s=K_(o,n.nonce,U2(t,n.keyId,n.kdf)).decrypt(n.ct)}catch{throw De("wrong_secret","Wrong password.")}finally{bt(o)}if(s.length!==ii||!e0(cu(s),n.keyId))throw bt(s),De("wrong_secret","Wrong password.");return s}function pu(n,e){if(n.length!==ii||!e0(cu(n),e.keyId))throw De("wrong_secret","This recovery key belongs to a different account key.")}var Be,De,yc,Xy,w8,XA,QA,ii,A2,_8,t0,E2,k8,gc,au,S8,P8,q2,x8,C8,I8,ya,Qy,eg=I(()=>{"use strict";W_();ky();v2();_2();hi();Ye();Be=class extends Error{code;reason;retryAfterMs;constructor(e,t,r={}){super(t),this.name="AccountKeyError",this.code=e,r.reason!==void 0&&(this.reason=r.reason),r.retryAfterMs!==void 0&&(this.retryAfterMs=r.retryAfterMs)}},De=(n,e,t)=>new Be(n,e,t===void 0?{}:{reason:t}),yc=new TextEncoder;Xy=n=>crypto.getRandomValues(new Uint8Array(n)),w8=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;XA="0123456789ABCDEFGHJKMNPQRSTVWXYZ",QA="MDB1",ii=32,A2=2,_8=55;t0=1,E2=1,k8=512,gc=12,au=1024,S8={mKib:19456,t:3,p:1},P8=19456,q2=24576,x8=2,C8=10,I8=4;ya=n=>typeof n=="number"&&Number.isSafeInteger(n)&&n>=0;Qy=async(n,e,t,r)=>{let o=()=>De("cancelled","Key derivation cancelled.");if(r?.aborted)throw o();try{return await w2(n,e,{t:t.t,m:t.mKib,p:t.p,dkLen:32,version:19,maxmem:q2*1024+(1<<20),asyncTick:20,onProgress:()=>{if(r?.aborted)throw o()}})}catch(s){throw s instanceof Be?s:De("params","Key derivation failed.")}}});function D2(n){if(n.length<3)return!1;let e=[...n].reverse().join("");return[$2,...q8].some(t=>t.includes(n)||t.includes(e))}function T8(n){for(let e=1;e<=n.length/2;e++)if(n.length%e===0&&n.slice(0,e).repeat(n.length/e)===n)return n.slice(0,e);return null}function M8(n){let e=[];for(let t of n){let r=/\p{L}/u.test(t)?"letter":/\p{Nd}/u.test(t)?"digit":t.charCodeAt(0)<128?"symbol":"other",o=e[e.length-1];o&&o.kind===r?o.text+=t:e.push({kind:r,text:t})}return e}function B2(n,e,t,r){let o=e.toLowerCase();if(t.has(o))return r.add("repeat"),1;t.add(o);let s=T8(o);if(s&&s.length<o.length)return r.add("repeat"),B2(n,s,new Set,r)+oi(o.length/s.length);if(n==="letter"){let i=[...o].map(c=>z2[c]??c).join("");if(du.has(o)||du.has(i))return r.add("common"),oi(du.size)+1;if(D2(o))return r.add("sequence"),oi($2.length)+oi(o.length)+1;let a=2.5*[...o].length;return o!==e&&e.toUpperCase()!==e?a+=1+oi([...e].length):e.toUpperCase()===e&&e.length>1&&(a+=1),a}return n==="digit"?E8.has(o)||D2(o)?(r.add("sequence"),4):/^(19|20)\d\d$/.test(o)||/^\d{6}$/.test(o)||/^\d{8}$/.test(o)?(r.add("date"),6):3.32*o.length:n==="symbol"?[...e].reduce((i,a)=>i+(a===" "?1:"!?.,*#-_".includes(a)?2:5),0):7*[...e].length}function L8(n){let e=[...n],t=e.map(i=>z2[i.toLowerCase()]??i.toLowerCase()),r=[],o="",s=0;for(;s<e.length;){let i=null;for(let a=Math.min(24,e.length-s);a>=4;a--){let c=t.slice(s,s+a).join("");if(du.has(c)){i=c;break}}i?(o&&r.push({word:null,text:o}),o="",r.push({word:i,text:e.slice(s,s+[...i].length).join("")}),s+=[...i].length):(o+=e[s],s++)}return o&&r.push({word:null,text:o}),r}function uu(n){typeof n!="string"&&(n="");let e=new TextEncoder().encode(n).length,t=n.normalize("NFKC"),r=[...t].length,o=new TextEncoder().encode(t).length,s=new Set,i=new Set,a=0,c=0,l=new Set;for(let h of L8(t)){if(h.word){s.add("common"),c++,l.add("word");let m=h.text.toLowerCase();a+=i.has(h.word)?1:oi(du.size)+1+(m!==h.text?1:0)+(m!==h.word?1:0),i.add(h.word);continue}for(let m of M8(h.text))c++,l.add(m.kind),a+=B2(m.kind,m.text,i,s)}a+=Math.max(0,l.size-1)+oi(Math.max(1,c));let p=a<oi(1e3)?0:a<oi(1e6)?1:a<oi(1e8)?2:a<oi(1e10)?3:4,d=[],u=e>au||o>au;r<gc&&d.push(`Use at least ${gc} characters.`),u&&d.push("The password is too long."),s.has("common")&&d.push("Avoid common words and passwords."),s.has("sequence")&&d.push("Avoid sequences like abcd, 1234 or qwerty."),s.has("repeat")&&d.push("Avoid repeated characters or words."),s.has("date")&&d.push("Avoid years and dates."),p<3&&d.length===0&&d.push("Add another word or two; uncommon words are best.");let f=p>=3&&r>=gc&&!u;return{score:p,acceptable:f,feedback:f?[]:d,bits:Math.round(a*10)/10}}var du,E8,z2,$2,q8,oi,V2=I(()=>{"use strict";eg();du=new Set(["password","passwort","passw0rd","letmein","welcome","admin","administrator","login","master","monkey","dragon","football","baseball","soccer","hockey","qwerty","qwertyuiop","asdfgh","asdfghjkl","zxcvbn","zxcvbnm","azerty","iloveyou","sunshine","princess","shadow","superman","batman","michael","jennifer","jessica","charlie","thomas","trustno1","abc","abcd","abcdef","abcdefg","abcdefgh","secret","freedom","whatever","starwars","pokemon","computer","internet","hello","mustang","ginger","cheese","summer","winter","spring","autumn","flower","killer","hunter","ranger","buster","soccer","tigger","pepper","jordan","harley","robert","matthew","daniel","andrew","joshua","ashley","nicole","chelsea","amanda","orange","purple","yellow","silver","golden","cookie","chocolate","mdbase","task","note","notes","obsidian","recovery","private","encryption","unlock","account","default","changeme","temp","test","testing","guest","root","user","system","server","database","oracle","google","apple","facebook","twitter","github","linkedin","amazon","netflix","spotify","windows","android","iphone","samsung","nokia","sony","january","february","march","april","june","july","august","september","october","november","december","monday","tuesday","wednesday","thursday","friday","saturday","sunday","spider","lovely","liverpool","arsenal","chelsea","manchester","barcelona","madrid","america","london","paris","berlin","sydney","melbourne","canada"]),E8=new Set(["123","1234","12345","123456","1234567","12345678","123456789","1234567890","111111","000000","123123","654321","696969","112233","121212","131313","007","666","777","888","999","420","69"]),z2={0:"o",1:"i",3:"e",4:"a",5:"s",7:"t",8:"b","@":"a",$:"s","!":"i","+":"t"},$2="abcdefghijklmnopqrstuvwxyz0123456789",q8=["qwertyuiop","asdfghjkl","zxcvbnm","1234567890"],oi=n=>Math.log2(Math.max(1,n))});function K2(){let n=null;return{get:async()=>n?n.slice():null,set:async e=>{n&&bt(n),n=e.slice()},clear:async()=>{n&&bt(n),n=null}}}function wa(n){if(!n||typeof n!="object"||Array.isArray(n))throw an("not_object");return n}function F2(n){if(typeof n.complete!="boolean"||!Array.isArray(n.pending)||n.pending.length>1024)throw an("strict_completion");let e=new Set,t=n.pending.map(r=>{let o=wa(r);if(typeof o.collection_id!="string"||typeof o.device_id!="string"||o.revoked_at!==null&&(!Number.isSafeInteger(o.revoked_at)||o.revoked_at<0))throw an("strict_pending");Jn(o.collection_id),Jn(o.device_id);let s=`${o.collection_id.toLowerCase()}/${o.device_id.toLowerCase()}`;if(e.has(s))throw an("strict_pending");return e.add(s),{collectionId:o.collection_id,deviceId:o.device_id,revokedAt:o.revoked_at}});if(n.complete&&t.length!==0)throw an("strict_completion");return{complete:n.complete,pending:t}}function uo(n){if(n instanceof Be)return n;let e=n&&typeof n=="object"?n:{},t=e.problem&&typeof e.problem=="object"?e.problem:{},r=typeof t.code=="string"?t.code:typeof e.code=="string"?e.code:"",o=typeof e.status=="number"?e.status:void 0,s=e.retryAfterMs??t.retryAfterMs??(typeof e.retry_after=="number"?e.retry_after*1e3:void 0),i=typeof s=="number"&&Number.isFinite(s)&&s>=0?s:void 0;return r==="rate_limited"||o===429?new Be("rate_limited","Too many account key requests; try again later.",i===void 0?{}:{retryAfterMs:i}):r==="version_conflict"||r==="rotate_requires_strict"?new Be("conflict","The account key changed; fetch the current state and retry.",{reason:r}):r==="strict_mode"?new Be("strict_mode","The account is in strict mode."):r==="account_key_proof_required"?new Be("wrong_secret","The account key held here is not the one registered for this bundle.",{reason:r}):r==="no_account_key"?new Be("no_account_key","The account has no account key."):r==="cancelled"||e.name==="AbortError"?new Be("cancelled","Account key request cancelled."):U8(r||(o===void 0?"port_failure":`http_${o}`),i)}var r0,j8,an,U8,tg,ng,W2=I(()=>{"use strict";eg();Ye();V2();r0=/^[0-9a-f]{64}$/,j8=/^([0-9a-f]{2}){1,512}$/,an=n=>new Be("internal","Invalid control-plane account-key response.",{reason:n}),U8=(n,e)=>new Be("unavailable","The account key service refused or was unreachable.",e===void 0?{reason:n}:{reason:n,retryAfterMs:e});tg=n=>{if(!Number.isSafeInteger(n)||n<0)throw an("version");return n};ng=class{lifetime=new AbortController;control;replica;secrets;argon2id;entropy;busy=Promise.resolve();last=null;constructor(e){if(this.control=e.control,this.replica=e.replica,!e.secrets)throw new Be("internal","PrivateAccount needs a secret store (the platform keychain).");this.secrets=e.secrets,this.argon2id=e.argon2id??Qy,this.entropy=e.entropy??Xy,Jn(this.control.accountId)}close(){this.lifetime.signal.aborted||(this.lifetime.abort(),this.control.close?.())}passwordStrength(e){return uu(e)}async status(e={}){return this.serial(e,t=>this.readStatus(t))}get lastStatus(){return this.last}async setup(e,t){return this.serial({signal:t},async r=>{let o=uu(e);if(ba(e),!o.acceptable)throw new Be("weak_password","The password is too weak.",{reason:"strength"});let s=await this.fetchState(r);if(s.mode==="password")throw new Be("already_set_up","This account already has an account key; unlock it instead.");let i=k2(this.entropy);try{let a=await Zy(i,e,this.control.accountId,{entropy:this.entropy,argon2id:this.argon2id,signal:r});this.check(r),await this.putBundle(i,s.version,a,r),await this.secrets.set(i);let c=P2(i),l=await this.keyAll(i,r);return l.length?{recoveryKey:c,incomplete:l}:{recoveryKey:c}}finally{bt(i)}})}async unlock(e,t){return this.serial({signal:t},async r=>{let o="recoveryKey"in e?lu(e.recoveryKey):null;try{let s=await this.requirePassword(r);o?pu(o,s.bundle):o=await N2(s.bundle,e.password,this.control.accountId,{argon2id:this.argon2id,signal:r}),this.check(r),await this.secrets.set(o);let i=await this.grantAll(o,r);return i.length?{incomplete:i}:{}}finally{o&&bt(o)}})}async changePassword(e,t){return this.serial({signal:t},async r=>{let o=uu(e);if(ba(e),!o.acceptable)throw new Be("weak_password","The password is too weak.",{reason:"strength"});let s=await this.secrets.get();if(!s)throw new Be("locked","Unlock the account key on this device first.");try{let i=await this.requirePassword(r);try{pu(s,i.bundle)}catch{throw new Be("conflict","The account key on the server is not the one unlocked here; unlock again.",{reason:"key_id_changed"})}let a=await Zy(s,e,this.control.accountId,{entropy:this.entropy,argon2id:this.argon2id,signal:r});this.check(r),await this.putBundle(s,i.version,a,r)}finally{bt(s)}})}async recover(e,t,r){return this.serial({signal:r},async o=>{let s=uu(t);if(ba(t),!s.acceptable)throw new Be("weak_password","The password is too weak.",{reason:"strength"});let i=lu(e);try{let a=await this.requirePassword(o);pu(i,a.bundle);let c=await Zy(i,t,this.control.accountId,{entropy:this.entropy,argon2id:this.argon2id,signal:o});this.check(o),await this.putBundle(i,a.version,c,o),await this.secrets.set(i);let l=await this.grantAll(i,o);return l.length?{incomplete:l}:{}}finally{bt(i)}})}async enableStrict(e){return this.serial({signal:e},async t=>{let r=await this.readStatus(t);if(r.mode==="strict"){r.strictComplete===!0&&await this.secrets.clear();let p=r.strictComplete===!0?!1:r.accountKeyKept;return this.last={...r,accountKeyKept:p},{version:r.version,complete:r.strictComplete,pending:r.pending,accountKeyKept:p,revocations:[],alreadyStrict:!0}}let o;try{o=await this.control.strict({expected_version:r.version},{signal:t})}catch(p){throw uo(p)}let s=wa(o);if(s.mode!=="strict"||tg(s.version)!==r.version+1||!Array.isArray(s.revocations))throw an("strict");let i=F2(s),a=s.revocations.map(p=>{let d=wa(p);if(typeof d.collection_id!="string"||typeof d.device_id!="string")throw an("strict");return Jn(d.collection_id),Jn(d.device_id),{collectionId:d.collection_id,deviceId:d.device_id}});i.complete===!0&&await this.secrets.clear();let c=await this.secrets.get(),l=c!==null;return c&&bt(c),this.last={mode:"strict",version:s.version,unlocked:!1,strictComplete:i.complete,pending:i.pending,accountKeyKept:l},{version:s.version,...i,accountKeyKept:l,revocations:a,alreadyStrict:!1}})}async keyCollections(e){return this.serial({signal:e},async t=>{let r=await this.secrets.get();if(!r)throw new Be("locked","Unlock the account key on this device first.");try{let o=await this.requirePassword(t);return pu(r,o.bundle),await this.keyAll(r,t)}finally{bt(r)}})}async lock(){await this.secrets.clear()}serial(e,t){let r=e.signal?AbortSignal.any([this.lifetime.signal,e.signal]):this.lifetime.signal,o=this.busy.then(()=>(this.check(r),t(r)),()=>(this.check(r),t(r)));return this.busy=o.catch(()=>{}),o}check(e){if(e.aborted)throw new Be("cancelled","Account key request cancelled.")}async readStatus(e){let t;try{t=await this.control.status({signal:e})}catch(l){throw uo(l)}this.check(e);let r=wa(t),o=tg(r.version),s,i=null;if(r.mode==="none"&&o===0)s="none";else if(r.mode==="strict")s="strict";else if(r.mode==="password"&&typeof r.key_id=="string"&&r0.test(r.key_id))s="password",i=r.key_id;else throw an("status");let a=s==="strict"?F2(r):void 0,c=await this.secrets.get();try{let l=i!==null&&c!==null&&c.length===32&&ut(cu(c))===i;return this.last={mode:s,unlocked:l,version:o,...a?{strictComplete:a.complete,pending:a.pending,accountKeyKept:c!==null}:{}}}finally{c&&bt(c)}}async fetchState(e){let t;try{t=await this.control.fetch({signal:e})}catch(i){throw uo(i)}this.check(e);let r=wa(t),o=tg(r.version);if(r.mode==="none"){if(o!==0)throw an("mode");return{mode:"none",version:0}}if(r.mode==="strict")return{mode:"strict",version:o};if(r.mode!=="password")throw an("mode");if(typeof r.key_id!="string"||!r0.test(r.key_id)||typeof r.bundle!="string"||!j8.test(r.bundle))throw an("bundle");let s=M2(Bi(r.bundle));if(ut(s.keyId)!==r.key_id)throw an("key_id");return{mode:"password",version:o,bundle:s}}async requirePassword(e){let t=await this.fetchState(e);if(t.mode==="none")throw new Be("no_account_key","The account has no account key yet; set one up on a device that holds the keys.");if(t.mode==="strict")throw new Be("strict_mode","The account is in strict mode; approve this device from an existing device.");return t}async putBundle(e,t,r,o){let s=ut(r.keyId),i=n0(r),a=O2(e,this.control.accountId),c;try{let p=ut(R2(a,this.control.accountId,i,t));c=await this.control.put({expected_version:t,key_id:s,bundle:ut(i),proof_pk:ut(a.pk),proof_sig:p},{signal:o})}catch(p){throw uo(p)}finally{bt(a.seed)}let l=wa(c);if(l.mode!=="password"||tg(l.version)!==t+1||l.key_id!==s)throw an("put")}async collections(e){let t;try{t=await this.replica.privateCollections({signal:e})}catch(r){throw uo(r)}if(this.check(e),!Array.isArray(t)||t.some(r=>typeof r!="string")||new Set(t).size!==t.length)throw an("collections");for(let r of t)Jn(r);return t}async keyAll(e,t){let r=[];for(let o of await this.collections(t)){this.check(t);try{await this.enrol(e,o,t),await this.replica.keyAccountKeyDevice(o,e,{signal:t})}catch(s){if(s instanceof Be&&s.code==="cancelled")throw s;r.push(o)}}return r}async grantAll(e,t){let r=[];for(let o of await this.collections(t)){this.check(t);try{await this.replica.selfGrantWithAccountKey(o,e,{signal:t})}catch(s){if(s instanceof Be&&s.code==="cancelled")throw s;r.push(o)}}return r}async enrol(e,t,r){let o;try{o=await this.control.challenge({signal:r})}catch(a){throw uo(a)}let s=typeof o=="string"?o.toLowerCase():typeof o?.challenge=="string"?o.challenge.toLowerCase():"";if(!r0.test(s))throw an("challenge");this.check(r);let i=x2(e,t);try{let a=ga("mdbase/v1/account-key-enrol",ue([Bi(s),Jn(t),Jn(i.device),Jn(this.control.accountId),i.signPk,i.kemPk,i.noisePk])),c=ut(C2(i,a)),l;try{l=await this.control.enrolRecoveryDevice(t,{challenge:s,recovery_device:i.device,sign_pk:ut(i.signPk),kem_pk:ut(i.kemPk),pop:c},{signal:r})}catch(d){throw uo(d)}let p=wa(l);if(p.collection_id!==t||p.device_id!==i.device||!Number.isSafeInteger(p.enrolled_at))throw an("enrol")}finally{I2(i)}}}});function i0(n){if(n instanceof pt)return n;if(n instanceof Mt)return new pt("unlock_strict");if(n instanceof ts)return new pt("unlock_unavailable");if(!(n instanceof Be))return null;switch(n.code){case"wrong_secret":return new pt("wrong_secret");case"invalid_recovery_key":return new pt("invalid_recovery_key",n.reason);case"no_account_key":return new pt("no_account_key");case"strict_mode":return new pt("unlock_strict");case"rate_limited":return new pt("rate_limited",void 0,n.retryAfterMs);case"cancelled":return null;default:return n.reason==="account_key_proof_unavailable"?new pt("unlock_unavailable"):new pt("unavailable",n.reason??n.code,n.retryAfterMs)}}async function B8(n,e){return(await G2(n,e)).mode}async function G2(n,e){let t;try{t=await n.status({signal:e})}catch(s){throw uo(s)}if(e.aborted)throw o0();let r=t&&typeof t=="object"&&!Array.isArray(t)?t:{},o=r.mode;if(o!=="password"&&o!=="strict"&&o!=="none")throw xt("response");return{mode:o,version:Number.isSafeInteger(r.version)&&r.version>=1?r.version:null,keyId:typeof r.key_id=="string"&&H2.test(r.key_id)?r.key_id:null}}async function ig(n,e){let t=new wc(n,()=>{throw xt("proof")},e);try{return await B8(t,e.signal)}catch(r){throw e.signal.aborted?r:i0(r)??r}finally{t.close()}}async function og(n,e,t,r){let o=r.signal,s=r.settleMs??z8,i=r.sealed,a="password"in t,c="recoveryKey"in t;if(a===c||typeof(a?t.password:t.recoveryKey)!="string"||!Number.isSafeInteger(s)||s<1)throw new pt("unavailable","binding");let l=()=>{if(o.aborted)throw o0();if(n.isCurrent()!==!0)throw xt("fenced")};if(l(),e.status().state==="keyed"){i?.clear();return}if(c)try{bt(lu(t.recoveryKey))}catch(g){throw i0(g)??g}else try{ba(t.password)}catch{throw new pt("wrong_secret")}let p,d=null,u={privateCollections:async()=>[n.collection],keyAccountKeyDevice:()=>Promise.reject(rg()),async selfGrantWithAccountKey(g,y,_){let v=_.signal??o;try{if(l(),g!==n.collection||!(y instanceof Uint8Array)||y.length!==32)throw xt("binding");let k=new Uint8Array(y),S;try{S=e.unlockConsuming(k)}finally{k.fill(0)}let x=Date.now()+s,P=100;for(;S.state==="pending";){if(Date.now()>=x)throw p="grant_pending",xt("grant_pending");if(await e.drive({signal:v}),l(),S=e.status(),S.state!=="pending")break;await fa(P,v),l(),P=Math.min(1e3,P*2)}if(S.state==="refused")throw p=S.reason,xt(S.reason)}catch(k){throw p===void 0&&(d={error:k}),k}}},f=new wc(n,g=>e.signFetch(g),r),h=null,m=i?{accountId:f.accountId,status:g=>f.status(g),challenge:g=>f.challenge(g),async fetch(g){let y=i.take(n,h?.version??null,h?.keyId??null);if(y)return y;let _=await f.fetch(g);return i.keep(n,_),_},put:()=>f.put(),strict:()=>f.strict(),enrolRecoveryDevice:()=>f.enrolRecoveryDevice(),close:()=>f.close()}:f,w=K2(),b=new ng({control:m,replica:u,secrets:w,...r.argon2id?{argon2id:r.argon2id}:{}});try{h=await G2(f,o),l();let g=h.mode;try{r.onMode?.(g)}catch{}if(g==="none")throw new pt("no_account_key");if(g==="strict")throw new pt("unlock_strict");if(!e.supportsFetchProof())throw new pt("unlock_unavailable");if(e.headKnown()<=0&&(await e.drive({signal:o}),l()),e.headKnown()<=0)throw new pt("unavailable","log_head_unknown");let y=await b.unlock(t,o),_=d;if(_)throw _.error;if(l(),y.incomplete?.length)throw new pt(p==="grant_pending"?"unavailable":"unlock_failed",p??"incomplete");if(e.status().state!=="keyed")throw new pt("unlock_failed","not_keyed");i?.clear()}catch(g){throw(!(g instanceof Be&&g.code==="wrong_secret")||o.aborted||n.isCurrent()!==!0)&&i?.clear(),o.aborted||n.isCurrent()!==!0?g:i0(g)??g}finally{try{await w.clear()}finally{b.close()}}}var pt,bc,N8,D8,z8,xt,o0,rg,$8,H2,wc,fu=I(()=>{"use strict";At();eg();ve();W2();nr();jy();Hm();pt=class extends Error{constructor(t,r,o){super(`app account key unlock: ${t}`);this.reason=t;this.detail=r;this.retryAfterMs=o;this.name="AppAccountKeyUnlockError"}reason;detail;retryAfterMs},bc=class{held=null;get holding(){return this.held!==null}take(e,t,r){let o=this.held;return o&&t!==null&&r!==null&&o.accountId===e.accountId&&o.connectorId===e.connectorId&&o.deviceId===e.deviceId&&o.version===t&&o.keyId===r?{mode:"password",version:o.version,key_id:o.keyId,bundle:o.bundle}:(this.held=null,null)}keep(e,t){this.held=null;let r=t&&typeof t=="object"&&!Array.isArray(t)?t:{};r.mode!=="password"||!Number.isSafeInteger(r.version)||r.version<1||typeof r.key_id!="string"||!H2.test(r.key_id)||typeof r.bundle!="string"||!/^([0-9a-f]{2}){1,512}$/.test(r.bundle)||(this.held=Object.freeze({accountId:e.accountId,connectorId:e.connectorId,deviceId:e.deviceId,version:r.version,keyId:r.key_id,bundle:r.bundle}))}clear(){this.held=null}},N8=64*1024,D8=15e3,z8=45e3,xt=n=>new Be("unavailable","The account key service refused or was unreachable.",{reason:n}),o0=()=>new Be("cancelled","Account key request cancelled."),rg=()=>xt("not_supported"),$8=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),H2=/^[0-9a-f]{64}$/,wc=class{constructor(e,t,r={}){this.session=e;this.sign=t;for(let s of[e.accountId,e.connectorId,e.deviceId,e.collection])if(N(s).every(i=>i===0))throw xt("binding");let o=new URL(e.cpOrigin);if(o.origin!==e.cpOrigin||o.username||o.password||o.protocol!=="https:"&&!(r.allowLoopbackHttp===!0&&Ze(e.cpOrigin)))throw xt("binding");if(this.accountId=e.accountId,this.deviceId=e.deviceId,this.origin=o.origin,this.fetchImpl=r.fetch??globalThis.fetch,this.now=r.now??Date.now,e.isCurrent()!==!0)throw xt("fenced")}session;sign;accountId;lifetime=new AbortController;origin;deviceId;fetchImpl;now;check(e){if(e.aborted||this.lifetime.signal.aborted)throw o0();let t=!1;try{t=this.session.isCurrent()===!0&&this.session.accountId===this.accountId&&this.session.deviceId===this.deviceId&&this.session.cpOrigin===this.origin}catch{t=!1}if(!t)throw xt("fenced")}async request(e,t,r,o){let s=o.signal??this.lifetime.signal;this.check(s);let i=await this.session.connectorBearer({signal:s});if(this.check(s),typeof i!="string"||!i||i.length>16384||/[^\x21-\x7e]/.test(i))throw xt("binding");let a=new AbortController,c=()=>a.abort(),l=setTimeout(c,D8);l.unref?.(),s.addEventListener("abort",c,{once:!0}),this.lifetime.signal.addEventListener("abort",c,{once:!0});let p=new Uint8Array(N8),d=0,u=null,f=null;try{let h=this.fetchImpl;try{u=await h(`${this.origin}${t}`,{method:e,headers:{authorization:`Bearer ${i}`,...r},signal:a.signal,redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer"})}catch{throw this.check(s),xt("network")}if(this.check(s),a.signal.aborted)throw xt("timeout");if(u.body)for(f=u.body.getReader();;){let w;try{w=await f.read()}catch{throw this.check(s),xt("network")}try{if(this.check(s),a.signal.aborted)throw xt("timeout");if(w.done)break;if(d+w.value.length>p.length)throw a.abort(),xt("response");p.set(w.value,d),d+=w.value.length}finally{w.value?.fill(0)}}let m=Mo(p.subarray(0,d));if(!u.ok)throw vr(u.status,m,u.headers);if(!m||typeof m!="object"||Array.isArray(m))throw xt("response");return m}finally{p.fill(0),(f?.cancel()??u?.body?.cancel())?.catch(()=>{});try{f?.releaseLock()}catch{}clearTimeout(l),s.removeEventListener("abort",c),this.lifetime.signal.removeEventListener("abort",c)}}status(e){return this.request("GET","/v1/next/account-key/status",{},e)}challenge(e){return this.request("POST","/v1/next/devices/challenge",{},e)}async fetch(e){let t=null,r=null;try{let o=await this.request("POST","/v1/next/devices/challenge",{},e),s=o.challenge,i=o.expires_at;if(typeof s!="string"||!/^[0-9a-f]{64}$/.test(s)||typeof i!="number"||!Number.isSafeInteger(i)||i-this.now()<=5e3||i-this.now()>16*6e4)throw xt("response");t=Uint8Array.from(s.match(/../g).map(a=>parseInt(a,16)));try{r=this.sign(t)}catch(a){throw a instanceof ts?xt(a.reason):a instanceof Mt?new Be("strict_mode","The account is in strict mode."):xt("proof")}if(!(r instanceof Uint8Array)||r.length!==64)throw xt("proof");return await this.request("GET","/v1/next/account-key",{"x-mdbase-device-id":this.deviceId,"x-mdbase-challenge":s,"x-mdbase-signature":$8(r)},e)}finally{t?.fill(0),r?.fill(0)}}put(){return Promise.reject(rg())}strict(){return Promise.reject(rg())}enrolRecoveryDevice(){return Promise.reject(rg())}close(){this.lifetime.abort()}}});var Lr,vc=I(()=>{"use strict";Lr=class extends Error{reason="device_keys_unavailable";constructor(e){super(e),this.name="AppDeviceCustodyError"}}});function ag(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 jt();return n}function V8(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 jt();return ag(n.key)}var sg,Y2,jt,_c,s0=I(()=>{"use strict";tn();ve();vc();sg="device-key-kek",Y2="original-device-kek",jt=()=>new Lr("app device key provider unavailable; preserve storage and reopen");_c=class n{constructor(e,t,r){this.source=e;this.origin=t;this.lifetime=r;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:r,origin:o,mode:s,signal:i}=e;t=new n(r,o,i);let a=Object.values(t.scope).map(u=>{let f=N(u);if(f.every(h=>h===0))throw jt();return Array.from(f,h=>h.toString(16).padStart(2,"0")).join("")});if(!dt(o)||!["fresh","existing"].includes(s)||!globalThis.indexedDB||!globalThis.crypto?.subtle||typeof globalThis.CryptoKey!="function")throw jt();t.check(i);let c=crypto.subtle.generateKey.bind(crypto.subtle),l=`mdbase.app.device-key-kek.v1.${a.join(".")}`,p=await t.openDatabase(l,s);t.db=p,p.onversionchange=()=>t.close(),t.check(i);let d=await t.transaction("readonly",i,null);if(t.check(i),s==="existing"){if(d===null||typeof d=="boolean")throw jt();t.value=d}else{if(d!==null)throw jt();let u=ag(await c({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]));if(t.check(i),await t.transaction("readwrite",i,u)!==!0)throw jt();t.check(i),t.value=u}return t.check(i),t}catch{throw t?.close(),jt()}}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,r])=>this.source[t]!==r))throw jt()}catch{throw jt()}}openDatabase(e,t){return new Promise((r,o)=>{this.check(this.lifetime);let s=indexedDB.open(e,1),i=!1,a=!1,c=()=>{i=!0,o(jt())};this.lifetime.addEventListener("abort",c,{once:!0});let l=()=>this.lifetime.removeEventListener("abort",c);s.onblocked=c,s.onupgradeneeded=()=>{try{if(this.check(this.lifetime),i||t!=="fresh"||s.result.objectStoreNames.length!==0)throw jt();s.result.createObjectStore(sg),a=!0}catch{s.transaction?.abort()}},s.onerror=()=>{l(),o(jt())},s.onsuccess=()=>{l();try{if(this.check(this.lifetime),i||t==="fresh"&&!a||s.result.objectStoreNames.length!==1||!s.result.objectStoreNames.contains(sg))throw jt();r(s.result)}catch{s.result.close(),o(jt())}}})}transaction(e,t,r){return new Promise((o,s)=>{if(this.check(t),!this.db)throw jt();let i=this.db.transaction(sg,e,{durability:"strict"}),a=i.objectStore(sg),c=null,l=!1,p=()=>{l=!0;try{i.abort()}catch{}};t.addEventListener("abort",p,{once:!0}),this.lifetime.addEventListener("abort",p,{once:!0});let d=()=>{t.removeEventListener("abort",p),this.lifetime.removeEventListener("abort",p)};i.onerror=i.onabort=()=>{d(),c=null,s(jt())},i.oncomplete=()=>{d();try{if(this.check(t),l)throw jt();o(c)}catch{c=null,s(jt())}};let u=a.get(Y2);u.onsuccess=()=>{try{this.check(t);let f=V8(u.result);e==="readonly"?c=f:(c=f===null,c===!0&&r!==null&&a.add({version:1,key:ag(r)},Y2))}catch{p()}}})}deviceCustodyKek(e){if(this.check(e.signal),this.loaned||!this.value)throw jt();return this.loaned=!0,ag(this.value)}close(){this.closed||(this.closed=!0,this.value=null,this.db?.close(),this.db=null)}}});function X2(n){if(!(n instanceof Uint8Array)||!n.length||n.length>F8)throw Mn();return new Uint8Array(n)}var lg,J2,F8,Mn,Ac,a0=I(()=>{"use strict";tn();ve();vc();lg="original-device-keys",J2="custody",F8=256,Mn=()=>new Lr("app device key custody store unavailable");Ac=class n{constructor(e,t,r,o,s){this.db=e;this.source=t;this.scope=r;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 Mn()}}static async openChecked(e){let{source:t,signal:r,mode:o,origin:s}=e,i=Object.freeze({accountId:t.accountId,connectorId:t.connectorId,deviceId:t.deviceId,installationId:t.installationId}),a=t.isCurrent,c=t.installationOwned,l=()=>{try{return!r.aborted&&t.isCurrent===a&&t.installationOwned===c&&a.call(t)===!0&&c.call(t)===!0&&Object.keys(i).every(m=>t[m]===i[m])}catch{return!1}},p=[i.accountId,i.connectorId,i.deviceId,i.installationId].map(m=>{let w=N(m);if(w.every(b=>b===0))throw Mn();return Array.from(w,b=>b.toString(16).padStart(2,"0")).join("")});if(!dt(s)||Rt()!==s||!["fresh","existing"].includes(o)||!l()||!globalThis.indexedDB)throw Mn();let d=`mdbase.app-device-keys.v1:${p.join(":")}`,u=`mdbase.app.device-keys.v1.${p.join(".")}`,f=await new Promise((m,w)=>{let b=indexedDB.open(u,1),g=!1,y=()=>{g=!0,w(Mn())};r.addEventListener("abort",y,{once:!0});let _=()=>r.removeEventListener("abort",y);b.onblocked=y,b.onupgradeneeded=()=>{if(g||o!=="fresh"||!l()||b.result.objectStoreNames.length!==0){b.transaction?.abort();return}b.result.createObjectStore(lg)},b.onerror=()=>{_(),w(Mn())},b.onsuccess=()=>{if(_(),g||!l()||b.result.objectStoreNames.length!==1||!b.result.objectStoreNames.contains(lg)){b.result.close(),w(Mn());return}m(b.result)}}),h=new n(f,t,i,d,s);try{h.check(r);let m=await h.read(d,{signal:r});try{if(o==="fresh"!=(m===null))throw Mn();return h.check(r),h}finally{m?.fill(0)}}catch{throw h.close(),Mn()}}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(r=>this.source[r]!==this.scope[r]))throw Mn()}catch{throw Mn()}}async read(e,t){let r=await this.transaction("readonly",e,t.signal,null);try{return this.check(t.signal,e),r}catch{throw r instanceof Uint8Array&&r.fill(0),Mn()}}async create(e,t,r){this.check(r.signal,e);let o=X2(t);try{let s=await this.transaction("readwrite",e,r.signal,o);return this.check(r.signal,e),s===!0}finally{o.fill(0)}}transaction(e,t,r,o){return new Promise((s,i)=>{this.check(r,t);let a=this.db.transaction(lg,e,{durability:"strict"}),c=a.objectStore(lg),l=null,p=!1,d=()=>{p=!0;try{a.abort()}catch{}},u=()=>r.removeEventListener("abort",d);r.addEventListener("abort",d,{once:!0}),a.onabort=a.onerror=()=>{u(),l instanceof Uint8Array&&l.fill(0),i(Mn())},a.oncomplete=()=>{u();try{if(this.check(r,t),p)throw Mn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),i(Mn())}};let f=c.get(J2);f.onsuccess=()=>{let h=null;try{this.check(r,t),h=f.result===void 0?null:X2(f.result),e==="readonly"?(l=h,h=null):(l=h===null,l===!0&&o!==null&&c.add(new Uint8Array(o),J2))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db.close())}}});var bn,kc,l0=I(()=>{"use strict";Ye();ve();bn=()=>new Error("app device key custody unavailable; preserve storage and reopen"),kc=class{constructor(e,t,r){this.pin=e;this.key=t;this.store=r;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(N);if(o.some(s=>s.every(i=>i===0))||t.type!=="secret"||t.extractable||t.algorithm.name!=="AES-GCM"||t.algorithm.length!==256||!t.usages.includes("encrypt")||!t.usages.includes("decrypt"))throw bn();this.namespace=`mdbase.app-device-keys.v1:${o.map(s=>Array.from(s,i=>i.toString(16).padStart(2,"0")).join("")).join(":")}`,this.aad=ue(["mdbase/v1/app-device-keys-platform",...o]),this.check(new AbortController().signal)}catch{throw bn()}}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 bn()}catch{throw bn()}}async openNativeDevice(e,t){let r=null,o=null,s=!1;try{if(this.attempted)throw bn();this.attempted=!0;let i=t.signal,a=t.mode;if(this.check(i),!["fresh","existing"].includes(a)||t.noise.mode!==a||t.noise.mode==="existing"&&!(t.noise.envelope instanceof Uint8Array))throw bn();let c=t.noise.mode==="fresh"?{mode:"fresh"}:{mode:"existing",envelope:new Uint8Array(t.noise.envelope)};if(c.mode==="existing"&&(!c.envelope.length||c.envelope.length>1024))throw bn();let l=await this.store.read(this.namespace,{signal:i});if(this.check(i),a==="fresh"){if(l!==null)throw bn();r=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,r));if(this.check(i),o=ue(new Map([[0,1],[1,u],[2,f]])),await this.store.create(this.namespace,o,{signal:i})!==!0)throw bn();this.check(i)}else{if(!(l instanceof Uint8Array)||l.length===0||l.length>256)throw bn();o=new Uint8Array(l);let u=we(o);if(!(u instanceof Map))throw bn();let f=u;if(f.size!==3||f.get(0)!==1)throw bn();let h=f.get(1),m=f.get(2);if(!(h instanceof Uint8Array)||h.length!==12||!(m instanceof Uint8Array)||m.length!==80||(r=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(i),r.length!==64))throw bn()}this.check(i);let p=Object.freeze({connectorId:this.scope.connectorId,deviceId:this.scope.deviceId,installationId:this.scope.installationId,isCurrent:()=>{try{return this.check(i),!0}catch{return!1}}});s=!0;let d=e.openDeviceConsuming({pin:p,signSecretKey:r.subarray(0,32),kemSecretKey:r.subarray(32),opened:c});return this.check(i),d}catch{if(s)try{e.retireLog()}catch{}throw bn()}finally{r?.fill(0),o?.fill(0)}}}});function c0(n){if(!(n instanceof Uint8Array)||n.byteLength<1||n.byteLength>K8)throw Xn();return new Uint8Array(n)}function W8(n,e){return n===null||e===null?n===e:n.length===e.length&&n.every((t,r)=>t===e[r])}function p0(n){if(N(n).every(t=>t===0))throw Xn();return n.toLowerCase()}function d0(n,e){try{return n.isCurrent()===!0&&n.connectorId===e[0]&&n.deviceId===e[1]&&n.installationId===e[2]}catch{return!1}}var cg,Q2,K8,Xn,Sc,u0=I(()=>{"use strict";tn();ve();vc();cg="opaque-noise",Q2="custody",K8=4096,Xn=()=>new Lr("app noise custody store unavailable");Sc=class n{constructor(e,t,r,o){this.db=e;this.source=t;this.pins=r;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 Xn()}}static async openChecked(e){let{source:t,signal:r}=e,o=[t.connectorId,t.deviceId,t.installationId];if(!dt(e.origin)||Rt()!==e.origin||!["fresh","existing"].includes(e.mode)||r.aborted||!d0(t,o)||typeof globalThis.indexedDB>"u")throw Xn();let s=`mdbase.app.noise.v1.${p0(o[2])}.${p0(o[0])}.${p0(o[1])}`,i=await new Promise((c,l)=>{let p=indexedDB.open(s,1),d=!1,u=()=>{d=!0,l(Xn())};r.addEventListener("abort",u,{once:!0});let f=()=>r.removeEventListener("abort",u);p.onblocked=u,p.onupgradeneeded=()=>{if(d||r.aborted||e.mode!=="fresh"||!d0(t,o)||p.result.objectStoreNames.length!==0){p.transaction?.abort();return}p.result.createObjectStore(cg)},p.onerror=()=>{f(),l(Xn())},p.onsuccess=()=>{if(f(),d||r.aborted||p.result.objectStoreNames.length!==1||!p.result.objectStoreNames.contains(cg)){p.result.close(),l(Xn());return}c(p.result)}}),a=new n(i,t,o,e.origin);try{let c=await a.read(a.namespace,{signal:r});if(e.mode==="fresh"!=(c===null))throw Xn();return c?.fill(0),a.check(r),a}catch{throw a.close(),Xn()}}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||!d0(this.source,this.pins))throw Xn()}async read(e,t){this.check(t.signal,e);let r=await this.transaction("readonly",t.signal,null,null);try{return this.check(t.signal),r}catch{throw r instanceof Uint8Array&&r.fill(0),Xn()}}async compareAndSet(e,t,r,o){this.check(o.signal,e);let s=null,i=null;try{s=t===null?null:c0(t),i=c0(r);let a=await this.transaction("readwrite",o.signal,s,i);return this.check(o.signal),a===!0}finally{s?.fill(0),i?.fill(0)}}transaction(e,t,r,o){return new Promise((s,i)=>{this.check(t);let a=this.db.transaction(cg,e,{durability:"strict"}),c=a.objectStore(cg),l=null,p=!1,d=()=>{p=!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),i(Xn())},a.oncomplete=()=>{u();try{if(this.check(t),p)throw Xn();s(l)}catch{l instanceof Uint8Array&&l.fill(0),i(Xn())}};let f=c.get(Q2);f.onsuccess=()=>{let h=null;try{this.check(t),h=f.result===void 0?null:c0(f.result),e==="readonly"?(l=h,h=null):(l=W8(h,r),l===!0&&o!==null&&c.put(new Uint8Array(o),Q2))}catch{d()}finally{h?.fill(0)}}})}close(){this.closed||(this.closed=!0,this.db.close())}}});function dg(n,e,t=H8){let r;return Promise.race([n.catch(()=>e),new Promise(o=>{r=setTimeout(()=>o(e),t)})]).finally(()=>clearTimeout(r))}function pg(n){return dg(new Promise(e=>{let t=indexedDB.deleteDatabase(n);t.onsuccess=()=>e(!0),t.onerror=()=>e(!1)}),!1)}function Z2(n){let{accountId:e,connectorId:t,deviceId:r,installationId:o}=n,s=[e,t,r,o].map(G8).join(".");return[`mdbase.app.device-key-kek.v1.${s}`,`mdbase.app.device-keys.v1.${s}`,`mdbase.app.noise.v1.${si(o)}.${si(t)}.${si(r)}`]}async function eE(n){try{return globalThis.indexedDB?(await Promise.all(Z2(n).map(pg))).every(Boolean):!1}catch{return!1}}function Y8(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 J8(n,e,t){let r=new Set(n.isolated?[]:n.databases);!n.isolated&&n.storageNamespace===void 0&&r.add(t);let{accountId:o,connectorId:s,deviceId:i,installationId:a}=n;if(o&&s&&i&&a){for(let d of Z2({accountId:o,connectorId:s,deviceId:i,installationId:a}))r.add(d);let c=[o,s,i,a].map(si).join("."),l=[`mdbase.app.cloud-copy-outcome.v1.${c}.`,`mdbase.app.private-bootstrap.v1.${c}.`];for(let d of n.collectionIds){let u=si(d);for(let f of["create","join"])r.add(`${l[0]}${u}.${f}`);for(let f of["create","enrol"])r.add(`${l[1]}${u}.${f}`)}let p=indexedDB.databases;if(typeof p=="function"){let d=await dg(p.call(indexedDB),[]);for(let{name:u}of d)u&&l.some(f=>u.startsWith(f))&&r.add(u)}}return r.delete(e),[...r]}async function X8(n,e){let t=globalThis.navigator?.storage;return typeof t?.getDirectory!="function"?!0:dg((async()=>{let r=await t.getDirectory(),o=`.mdbase-app-${si(n)}-${si(e)}-`,s=[];for await(let a of r.keys())a.startsWith(o)&&s.push(a);let i=!0;for(let a of s)try{await r.removeEntry(a,{recursive:!0})}catch{i=!1}return i})(),!1)}async function tE(n,e){try{if(!globalThis.indexedDB||!n.accountId||!n.connectorId||!n.deviceId||!n.installationId)return!1;let t=si(e),r=[n.accountId,n.connectorId,n.deviceId,n.installationId].map(si).join("."),o=["create","join"].map(a=>`mdbase.app.cloud-copy-outcome.v1.${r}.${t}.${a}`);o.push(...["create","enrol"].map(a=>`mdbase.app.private-bootstrap.v1.${r}.${t}.${a}`));let s=await Promise.all(o.map(pg)),i=globalThis.navigator?.storage;if(typeof i?.getDirectory=="function"){let a=await i.getDirectory();try{await a.removeEntry(`.mdbase-app-${si(n.accountId)}-${si(n.installationId)}-${t}`,{recursive:!0})}catch(c){if(!(c instanceof DOMException&&c.name==="NotFoundError"))return!1}}return s.every(Boolean)}catch{return!1}}async function nE(n){if(!globalThis.indexedDB)return Object.freeze({ledger:!1,complete:!1});let[e,t]=Y8(n),r=await pg(e),o=null;try{o=await J8(n,e,t)}catch{}let s=o?await Promise.all([...o,...n.isolated||n.storageNamespace!==void 0?[]:[IA]].map(pg)):[!1],i=n.storageNamespace===void 0?!0:await dg(QR(n),!1),a=n.accountId&&n.installationId?await X8(n.accountId,n.installationId).catch(()=>!1):!0;return Object.freeze({ledger:r,complete:r&&i&&a&&s.every(Boolean)})}var H8,G8,si,f0=I(()=>{"use strict";OA();ve();H8=5e3,G8=n=>Array.from(N(n),e=>e.toString(16).padStart(2,"0")).join(""),si=n=>(N(n),n.toLowerCase())});var ze,hu,Pc,h0=I(()=>{"use strict";Ye();ve();ze=()=>new Error("app Noise custody unavailable; preserve storage and reopen"),hu=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]),Pc=class{constructor(e,t,r){this.pin=e;this.key=t;this.store=r;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(N);if(o.some(s=>s.every(i=>i===0))||t.type!=="secret"||t.extractable||t.algorithm.name!=="AES-GCM"||t.algorithm.length!==256||!t.usages.includes("encrypt")||!t.usages.includes("decrypt"))throw ze();this.namespace=`mdbase.app-noise.v1:${this.scope.connectorId}:${this.scope.deviceId}:${this.scope.installationId}`,this.aad=ue(["mdbase/v1/app-noise-platform",...o]),this.check(new AbortController().signal)}catch{throw ze()}}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 ze()}catch{throw ze()}}receiptValue(e){if(e.connectorId!==this.scope.connectorId||e.deviceId!==this.scope.deviceId||e.installationId!==this.scope.installationId)throw ze();let t=[e.signPublicKey,e.kemPublicKey,e.noisePublicKey];if(t.some(r=>!(r instanceof Uint8Array)||r.length!==32||r.every(o=>o===0)))throw ze();return t.map(r=>new Uint8Array(r))}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(r=>r===0)))throw ze();return Object.freeze({...this.scope,signPublicKey:new Uint8Array(e[0]),kemPublicKey:new Uint8Array(e[1]),noisePublicKey:new Uint8Array(e[2])})}markerValue(e){let t=N(e.collection);if(t.every(r=>r===0)||typeof e.acknowledged!="boolean"||!(e.sasCommitment instanceof Uint8Array)||e.sasCommitment.length!==32||e.sasCommitment.every(r=>r===0))throw ze();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(i=>i===0)||typeof e[5]!="boolean")throw ze();let r=this.receipt(e.slice(1,4));for(let i of["signPublicKey","kemPublicKey","noisePublicKey"])if(!hu(r[i],t[i]))throw ze();let o=e[4];if(!(o instanceof Uint8Array)||o.length!==32||o.every(i=>i===0))throw ze();let s=Array.from(e[0],i=>i.toString(16).padStart(2,"0")).join("");return Object.freeze({...r,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,r=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 ze();t=new Uint8Array(o);let s=we(t);if(!(s instanceof Map))throw ze();let i=s,a=i.get(1),c=i.get(2);if(i.size!==3||i.get(0)!==1||!(a instanceof Uint8Array)||a.length!==12||!(c instanceof Uint8Array)||c.length<16||c.length>2064||(r=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(c))),this.check(e.signal),r.length>2048))throw ze();let l=we(r);if(!(l instanceof Map))throw ze();let p=l,d=p.get(1);if(!(p.get(0)===1&&p.size===3||p.get(0)===2&&p.size===4&&p.has(3))||!(d instanceof Uint8Array)||d.length===0||d.length>1024||!p.has(2))throw ze();let u=this.receipt(p.get(2)),f=p.get(0)===2?this.marker(p.get(3),u):null;return{value:Object.freeze({envelope:new Uint8Array(d),receipt:u,privateEnrolMarker:f}),encrypted:new Uint8Array(t)}}catch{throw ze()}finally{t?.fill(0),r?.fill(0)}}async write(e,t,r,o,s=null){let i=null,a=null;try{if(this.check(o.signal),!(e instanceof Uint8Array)||!e.length||e.length>1024)throw ze();let c=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),c.set(3,u)}if(i=ue(c),i.length>2048)throw ze();let l=globalThis.crypto.getRandomValues(new Uint8Array(12)),p=new Uint8Array(await globalThis.crypto.subtle.encrypt({name:"AES-GCM",iv:l,additionalData:new Uint8Array(this.aad),tagLength:128},this.key,new Uint8Array(i)));this.check(o.signal),a=ue(new Map([[0,1],[1,l],[2,p]]));let d=await this.store.compareAndSet(this.namespace,r,a,o);if(this.check(o.signal),d!==!0)throw ze()}catch{throw ze()}finally{i?.fill(0),a?.fill(0)}}async pending(e,t){let r=await this.read(t);if(this.check(t.signal),r){if(!hu(r.value.envelope,e))throw ze();return}await this.write(e,null,null,t),this.check(t.signal)}async privateEnrolPending(e,t){try{if(e.acknowledged!==!1)throw ze();await this.writePrivateMarker(e,!1,t)}catch{throw ze()}}async privateEnrolAcknowledged(e,t){try{await this.writePrivateMarker(e,!0,t)}catch{throw ze()}}async writePrivateMarker(e,t,r){this.check(r.signal);let o=this.marker(this.markerValue(e),e),s=await this.read(r);if(this.check(r.signal),!s?.value.receipt)throw ze();for(let a of["signPublicKey","kemPublicKey","noisePublicKey"])if(!hu(o[a],s.value.receipt[a]))throw ze();let i=s.value.privateEnrolMarker;if(i){if(i.collection!==o.collection||!hu(i.sasCommitment,o.sasCommitment))throw ze();if(i.acknowledged){if(!t)throw ze();return}if(!t)return}else if(t)throw ze();await this.write(s.value.envelope,s.value.receipt,s.encrypted,r,Object.freeze({...o,acknowledged:t})),this.check(r.signal)}async registered(e,t){let r=await this.read(t);if(this.check(t.signal),!r)throw ze();if(r.value.receipt){for(let o of["signPublicKey","kemPublicKey","noisePublicKey"])if(!hu(r.value.receipt[o],e[o]))throw ze();this.receiptValue(e);return}await this.write(r.value.envelope,e,r.encrypted,t),this.check(t.signal)}}});var va,Ut,ug,xc,m0=I(()=>{"use strict";At();ve();va=class extends Error{constructor(t){super(`app device registration: ${t}`);this.reason=t;this.name="AppDeviceRegistrationError"}reason},Ut=n=>new va(n),ug=n=>Array.from(n,e=>e.toString(16).padStart(2,"0")).join(""),xc=class{constructor(e,t,r,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(N(a).every(c=>c===0))throw Ut("binding");if(t.kind!=="mobile"&&t.kind!=="app-runtime")throw Ut("binding");this.rawOrigin=t.cpOrigin;let i=new URL(this.rawOrigin);if(i.username||i.password||i.pathname!=="/"||i.search||i.hash||i.protocol!=="https:"&&!(s.allowLoopbackHttp===!0&&Ze(this.rawOrigin))||(this.origin=i.origin,this.now=s.now??Date.now,this.fetchImpl=s.fetch??globalThis.fetch,!(r.envelope instanceof Uint8Array)||!r.envelope.length||r.envelope.length>1024)||!e.deviceCustodyCurrent(t,r)||(this.custody=Object.freeze({signPublicKey:new Uint8Array(r.signPublicKey),kemPublicKey:new Uint8Array(r.kemPublicKey),noisePublicKey:new Uint8Array(r.noisePublicKey),envelope:new Uint8Array(r.envelope)}),!this.current()))throw Ut("binding")}catch{throw e.retireLog(),Ut("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(),Ut("fenced")}async json(e,t,r,o){this.check(o);let s=new AbortController,i=()=>s.abort(),a=setTimeout(i,15e3);a.unref?.(),o.addEventListener("abort",i,{once:!0}),this.lifetime.signal.addEventListener("abort",i,{once:!0});let c=new Uint8Array(32*1024),l=0,p=null,d=null;try{let u=this.fetchImpl;if(p=await u(`${this.origin}${e}`,{method:"POST",headers:{authorization:`Bearer ${t}`,...r===void 0?{}:{"content-type":"application/json"}},body:r,signal:s.signal,redirect:"error",credentials:"omit",cache:"default",referrerPolicy:"no-referrer"}),this.check(o),s.signal.aborted||!p.ok)throw Ut("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(),Ut("response");if(!p.body)throw Ut("response");for(d=p.body.getReader();;){let{done:m,value:w}=await d.read();try{if(this.check(o),s.signal.aborted)throw Ut("unavailable");if(m)break;if(l+w.length>c.length)throw s.abort(),Ut("response");c.set(w,l),l+=w.length}finally{w?.fill(0)}}let h=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c.subarray(0,l)));if(!h||typeof h!="object"||Array.isArray(h))throw Ut("response");return h}catch(u){throw this.check(o),u instanceof va?u:Ut("unavailable")}finally{c.fill(0),(d?.cancel()??p?.body?.cancel())?.catch(()=>{}),d?.releaseLock(),clearTimeout(a),o.removeEventListener("abort",i),this.lifetime.signal.removeEventListener("abort",i)}}async register(e){let t=null,r=null;try{if(this.check(e.signal),this.attempted)throw Ut("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 Ut("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 Ut("response");t=Uint8Array.from(s.challenge.match(/../g).map(l=>parseInt(l,16)));let i=this.runtime.signCpEnrol(t);this.check(e.signal),r=i.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_v2"],challenge:s.challenge,sign_pk:ug(i.signPublicKey),kem_pk:ug(i.kemPublicKey),noise_pk:ug(i.noisePublicKey),sig:ug(r)}),e.signal);if(this.check(e.signal),a.device_id!==this.scope.deviceId)throw Ut("response");let c=Object.freeze({connectorId:this.scope.connectorId,deviceId:this.scope.deviceId,installationId:this.scope.installationId,signPublicKey:new Uint8Array(i.signPublicKey),kemPublicKey:new Uint8Array(i.kemPublicKey),noisePublicKey:new Uint8Array(i.noisePublicKey)});return await this.persistence.registered(c,e),this.check(e.signal),this.runtime.acknowledgeDeviceRegistration(c),c}catch(o){throw this.close(),o instanceof va?o:Ut("unavailable")}finally{t?.fill(0),r?.fill(0)}}close(){this.lifetime.signal.aborted||(this.lifetime.abort(),this.custody.envelope.fill(0),this.runtime.retireLog())}}});var fr,Q8,Z8,be,rE,Cc,mu=I(()=>{"use strict";OA();jy();tn();ve();Vs();Es();ie();$m();Cd();e2();RA();TA();nr();xd();c2();Fm();Id();jA();p2();VA();KA();u2();fu();s0();a0();l0();u0();vc();f0();h0();m0();Hm();fr=class extends Error{constructor(t,r,o){super(`app cloud copy host: ${t}`,o);this.reason=t;this.stage=r;this.name="AppCloudCopyHostError"}reason;stage},Q8=32,Z8=8,be=(n,e)=>new fr(n,e),rE=(n,e)=>n.length===e.length&&n.every((t,r)=>t===e[r]),Cc=class n{constructor(e,t,r,o,s){this.source=e;this.installation=t;this.originalRelease=r;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 i of[e.accountId,e.connectorId,e.deviceId,e.installationId])if(N(i).every(a=>a===0))throw be("binding");if(e.kind!=="app-runtime"&&e.kind!=="mobile"||r.schema!=="mdbn-app-trust/release/1"||r.cpOrigin!==e.cpOrigin||r.logOrigin!==e.logOrigin||!/^[0-9a-f]{64}$/.test(r.assetSha256)||!r.trustedRoots.length||r.trustedRoots.length>64||!r.policyPins.length||r.policyPins.length>65536)throw be("binding");if(this.trust=Object.freeze({...r,source:Object.freeze({...r.source}),trustedRoots:Object.freeze(r.trustedRoots.map(i=>{if(!(i instanceof Uint8Array)||i.length!==32||i.every(a=>a===0))throw be("binding");return new Uint8Array(i)})),policyPins:new Uint8Array(r.policyPins)}),this.pin=Object.freeze({...this.selected,isCurrent:()=>this.current(),installationOwned:()=>this.current(),connectorBearer:async({signal:i})=>{this.check(i);let a=await this.bearerCallback.call(this.source,Object.freeze({signal:i}));return this.check(i),a}}),e.approvalMode==="strict")throw new Mt;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;restoredPrivateMarker=null;privateStore=null;privateBootstrap=null;privateMetadata=null;accountKeyPin=null;accountKeyWork=!1;accountKeySealed=new bc;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;readWake=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(([r,o])=>this.source[r]===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((r,o)=>rE(r,t.trustedRoots[o]))&&rE(e.policyPins,t.policyPins)}catch{return!1}}check(e){if(e.aborted||!this.current())throw be("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:r,release:o,origin:s,mode:i,signal:a,loadRuntime:c,fetch:l,allowLoopbackHttp:p}=e,d=null;try{if(!["fresh","existing"].includes(i))throw be("binding");d=new n(t,r,o,s,a);let{custody:u,restored:f}=await d.openOwnedDevice({mode:i,signal:a,loadRuntime:c,requireReceipt:!0});if(i==="existing")d.native.acknowledgeDeviceRegistration(f.receipt),d.check(a),d.publicReceipt=d.native.registeredDeviceReceipt();else{let h=await new xc(d.native,d.pin,u,d.noise,{fetch:l,allowLoopbackHttp:p}).register(Object.freeze({signal:a}));d.check(a),d.publicReceipt=h}return d}catch(u){throw await d?.close(),u instanceof fr||u instanceof Mt?u:new fr("unavailable","device_open",{cause:u})}}static async openInstallationDevice(e){let{signIn:t,installation:r,release:o,origin:s,signal:i,loadRuntime:a,allowLoopbackHttp:c}=e,l=null;try{let p=t.confirmedHostSession(o.logOrigin,o.environment);l=new n(p,r,o,s,i),l.signIn=t;let d=await t.prepareOriginalDevice(r);if(l.check(i),d.mode==="fresh"&&!await eE(d.pin))throw new Lr("an unfinished device creation could not be cleared");l.check(i);let{custody:u,restored:f}=await l.openOwnedDevice({mode:d.mode,signal:i,loadRuntime:a,requireReceipt:!1});if(l.originalCustody=u,f?.receipt&&t.view().state!=="paired")throw be("recovery_required");return await l.noise.pending(new Uint8Array(u.envelope),{signal:i}),l.check(i),t.view().state==="paired"&&await l.completeInstallationSignIn(),l}catch(p){throw await l?.close(),p}}async attestInstallation(){if(this.check(this.lifetime),!this.signIn||!this.native||!this.originalCustody||!this.noise)throw be("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 be("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:r,loadRuntime:o,requireReceipt:s}=e;this.check(r),this.provider=await _c.open({source:this.pin,origin:this.origin,mode:t,signal:r}),this.check(r),this.key=this.provider.deviceCustodyKek({signal:r}),this.check(r),this.keys=await Ac.open({source:this.pin,origin:this.origin,mode:t,signal:r}),this.check(r),this.noiseStore=await Sc.open({source:this.pin,origin:this.origin,mode:t,signal:r}),this.check(r),this.noise=new Pc(this.pin,this.key,this.noiseStore);let i=await this.noise.restore({signal:r});if(this.check(r),t==="existing"?!i||s&&!i.receipt:i!==null)throw be("recovery_required");this.restoredPrivateMarker=i?.privateEnrolMarker??null;let a=await o(Object.freeze({signal:r}));if(this.check(r),!(a instanceof Uint8Array)||!a.length)throw be("binding");this.native=await Ql.createDevice(new Uint8Array(a)),this.check(r);let c=await new kc(this.pin,this.key,this.keys).openNativeDevice(this.native,{signal:r,mode:t,noise:t==="fresh"?{mode:"fresh"}:{mode:"existing",envelope:i.envelope}});return this.check(r),{custody:c,restored:i}}async bootstrapCloudCopy(e){let{scope:t,collectionCurrent:r,purpose:o,outcomeMode:s,signal:i,reconcile:a,fetch:c,allowLoopbackHttp:l}=e,p=this.operationSignal(i),d=e.displayName,u=d===void 0?void 0:sr(d);if(u!==void 0&&o!=="create"||(this.check(p),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)||N(t.collection).every(w=>w===0)))throw be("binding");let f=Object.freeze({account:t.account,installation:t.installation,collection:t.collection}),h=()=>{try{return this.current()&&!p.aborted&&e.scope===t&&e.collectionCurrent===r&&Object.entries(f).every(([w,b])=>t[w]===b)&&r.call(e)===!0&&this.outcomeStore?.fenced!==!0}catch{return!1}};if(!h())throw be("fenced");this.collectionAttempted=!0,this.collectionSignal=p,this.collectionCurrent=h,this.collectionScope=f;let m=Object.freeze({...this.pin,collection:f.collection,purpose:o,assetSha256:this.trust.assetSha256,...u===void 0?{}:{displayName:u},isCurrent:h});this.collectionSession=m;try{this.outcomeStore=await Vy.open({source:m,origin:this.origin,mode:s,signal:p}),this.checkCollection(p),this.outcome=new $y(m,this.publicReceipt,this.key,this.outcomeStore,{mode:s,signal:p}),this.native.prepareCloudCopyCollection(m),this.checkCollection(p),this.bootstrap=new Vl(this.native,m,this.trust,this.outcome,{fetch:c,allowLoopbackHttp:l,...u===void 0?{}:{displayName:u}});let w=await this.bootstrap.bootstrap(Object.freeze({signal:p,...a?{reconcile:a}:{}}));return this.checkCollection(p),this.bootstrapConfirmed=!0,w}catch(w){throw await this.close(),w}}async bootstrapPrivateDevice(e){let{scope:t,collectionCurrent:r,signal:o,fetch:s,allowLoopbackHttp:i}=e,a=this.operationSignal(o);if(this.check(a),this.collectionAttempted||!this.native||!this.key||!this.noise||!this.publicReceipt||t.account!==this.selected.accountId||t.installation!==this.selected.installationId||N(t.collection).every(u=>u===0))throw be("binding");let c=this.restoredPrivateMarker;if(c&&c.collection!==t.collection)throw be("private_device_limit");let l=Object.freeze({account:t.account,installation:t.installation,collection:t.collection}),p=()=>{try{return this.current()&&!a.aborted&&e.scope===t&&e.collectionCurrent===r&&Object.entries(l).every(([u,f])=>t[u]===f)&&r.call(e)===!0}catch{return!1}};if(!p())throw be("fenced");this.collectionAttempted=!0,this.collectionSignal=a,this.collectionCurrent=p,this.collectionScope=l;let d=Object.freeze({...this.pin,collection:l.collection,purpose:"enrol",rootPublicKey:new Uint8Array(this.trust.trustedRoots[0]),isCurrent:p});this.collectionSession=d;try{this.privateStore=await Gy.open({source:d,origin:this.origin,mode:c?"existing":"fresh",signal:a}),this.checkCollection(a);let u=new Wy(d,this.publicReceipt,this.key,this.privateStore,this.noise,{allowLoopbackHttp:i});this.native.preparePrivateCollection(d,c?{mode:"existing",marker:c}:{mode:"fresh"}),this.checkCollection(a),this.privateBootstrap=new Fy(this.native,d,u,{fetch:s,allowLoopbackHttp:i}),this.privateMetadata=await this.privateBootstrap.bootstrap(Object.freeze({signal:a})),this.checkCollection(a),this.bootstrapConfirmed=!0}catch(u){throw await this.close(),u}}adoptPrivateDevice(e,t){let r=this.operationSignal(e.signal);this.checkCollection(r);let o=this.privateMetadata,s=this.publicReceipt;if(!this.native||!this.privateBootstrap||!o||!s||!this.bootstrapConfirmed||this.adoptedEndpoint!==null)throw be("fenced");let i=o.collection;this.native.adoptDevice({replicaId:e.replicaId,endpoint:e.endpoint,opened:e.opened,sqliteVersion:e.sqliteVersion,collection:i,deviceId:o.deviceId,state:"e2e",cloudCopyOptIn:!1,trustedRoots:this.trust.trustedRoots.map(a=>new Uint8Array(a)),policyPins:new Uint8Array(this.trust.policyPins),trustedSigners:[],expectedGenesis:o.expectedGenesis},t),this.checkCollection(r),this.adoptedEndpoint=e.endpoint,this.accountKeyPin=Object.freeze({connectorId:s.connectorId,deviceId:s.deviceId,installationId:s.installationId,collection:i,approvalMode:"password-ak1",isCurrent:()=>this.collectionCurrent?.()===!0})}checkCollection(e){if(this.check(e),this.collectionCurrent?.()!==!0)throw be("fenced")}adoptCloudCopy(e,t){let r=this.operationSignal(e.signal);if(this.checkCollection(r),!this.bootstrap||!this.bootstrapConfirmed||this.adoptedEndpoint!==null)throw be("fenced");let o=e.endpoint;this.bootstrap.adoptCollection({...e,signal:this.collectionSignal},t),this.checkCollection(r),this.adoptedEndpoint=o}async openCollectionSql(e){let{replicaId:t,endpoint:r,openSql:o}=e,s=this.operationSignal(e.signal);if(this.checkCollection(s),!this.bootstrapConfirmed||!this.collectionScope||this.sqlAttempted||this.adoptedEndpoint!==null||N(t).every(i=>i===0)||typeof r!="bigint"&&!Number.isSafeInteger(r)||BigInt(r)<0n||BigInt(r)>(1n<<64n)-1n)throw be("binding");this.sqlAttempted=!0;try{let i=await o.call(e,Object.freeze({scope:this.collectionScope,signal:s})),a=i.close;if(this.sqlClose=async()=>{await a.call(i)},this.collectionSql=i.sql,this.checkCollection(s),e.openSql!==o)throw be("fenced");this.privateBootstrap?this.adoptPrivateDevice({signal:s,replicaId:t,endpoint:r,opened:i.opened,sqliteVersion:i.sqliteVersion},i.sql):this.adoptCloudCopy({signal:s,replicaId:t,endpoint:r,opened:i.opened,sqliteVersion:i.sqliteVersion,cloudCopyOptIn:!0},i.sql)}catch(i){throw await this.close(),i}}async startCollectionLog(e){let{fetch:t,allowLoopbackHttp:r}=e,o=this.operationSignal(e.signal);if(this.checkCollection(o),!this.native||!this.collectionSession||this.adoptedEndpoint===null)throw be("binding");let s=t??globalThis.fetch,i=r===!0;if(this.authority&&(s!==this.logRequest||i!==this.logLoopback))throw be("fenced");if(this.pump)return;if(this.logWork){await this.logWork,this.checkCollection(o);return}this.authority||(this.logRequest=s,this.logLoopback=i,this.authority=new Bl(this.native,Object.freeze({...this.collectionSession,endpoint:this.adoptedEndpoint,directOrigins:Object.freeze([])}),{fetch:s,allowLoopbackHttp:r,tokenCache:XR()}));let a=this.authority,c=(async()=>{await a.accessToken(Object.freeze({signal:o})),this.checkCollection(o),this.pump=this.native.bindLogTransport(a.logTransport())})();this.logWork=c;try{await c}finally{this.logWork===c&&(this.logWork=null)}}peopleAuthority(){if(this.checkCollection(this.lifetime),!this.collectionSession||this.adoptedEndpoint===null||!this.logRequest||this.accountKeyPin)throw be("binding");if(!this.peopleMetadata){let e=this.adoptedEndpoint,t=this.collectionSession,r=new fc(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 i=await t.connectorBearer({signal:this.lifetime});return this.checkCollection(this.lifetime),s.throwIfAborted(),i}}),{fetch:this.logRequest,allowLoopbackHttp:this.logLoopback}),o=Object.freeze({collection:r.collection,isCurrent:()=>r.isCurrent(),request:(s,i)=>r.request(s,i)});this.peopleMetadata={authority:r,view:o}}return this.peopleMetadata.view}timerConsentKey(e){let t=this.timerGrant(e);return t?JSON.stringify(t.consent):null}timerGrant(e){let t=this.source.timerConsent,r=t?.call(this.source);if(!r?.approved)return null;let o=r.grants.find(s=>s.collectionId===e);return o?{callback:t,consent:r,grant:o}:null}openTimersPort(e){if(this.checkCollection(this.lifetime),!this.readVerified||!this.logRequest||!this.collectionScope||e.signal.aborted)throw be("binding");let{scope:t,generation:r,signal:o}=e,s=this.collectionScope;if(t.account!==s.account||t.installation!==s.installation||t.collection!==s.collection||N(r).every(m=>m===0))throw be("binding");let i=this.timerGrant(t.collection);if(!i)return null;let{callback:a,consent:c,grant:l}=i,p=globalThis.WorkerGlobalScope;if(typeof p!="function"||!(globalThis instanceof p)||N(l.grantId).every(m=>m===0)||!/^[0-9a-f]{64}$/.test(l.declarationDigest))throw be("binding");let d=JSON.stringify(c),u=new MessageChannel,f=()=>{try{return!o.aborted&&e.signal===o&&e.scope===t&&e.generation===r&&this.collectionCurrent?.()===!0&&this.current()&&t.account===s.account&&t.installation===s.installation&&t.collection===s.collection&&this.source.timerConsent===a&&JSON.stringify(a?.call(this.source))===d}catch{return!1}},h=o2(u.port1,{scope:s,generation:r,grantId:l.grantId,cpOrigin:new URL(this.selected.cpOrigin).origin,signal:o,isCurrent:f,fetch:this.logRequest,...this.signIn?{journal:{read:()=>this.signIn.originalTimerChannel(l.grantId),write:m=>this.signIn.retainTimerChannel(l.grantId,m)}}:{},bearer:async()=>{if(!f())throw be("fenced");let m=await this.bearerCallback.call(this.source,{signal:this.lifetime});if(!f())throw be("fenced");return m}});return this.timerPorts.add(h),Object.freeze({port:u.port2,close:async()=>{await h.close(),u.port2.close(),this.timerPorts.delete(h)}})}serverProblem(){return this.pump?.serverProblem??null}transportHealth(){return this.pump?.transportHealth??null}initialSync(){try{return this.native?hc(this.native.observations().status):"unavailable"}catch{return"unavailable"}}holdsLog(){try{if(!this.native)return!1;let e=this.native.observations().status;return e.mode==="local_only"||e.headKnown>0}catch{return!1}}keyWaitDetail(){try{return this.native?Dy(this.native.observations().status):null}catch{return null}}keyringSettled(){if(!this.native)throw be("binding");let e=this.native.observations();return e.requiresReopen||e.keyringRebuildFailed?"failed":e.keyringRebuilding?"pending":"settled"}pendingWrites(){try{return this.native?.observations().status.pending??0}catch{return 0}}pushLog(e){try{let t=this.native?.pushLog(e)===!0;return t&&this.readWake?.(),t}catch{return!1}}openLogPush(e){this.checkCollection(this.lifetime);let t=this.native,r=this.authority,o=this.collectionSession,s=this.logRequest;if(!t||!this.pump||!r||!o||!s)throw be("binding");if(!t.supportsLogPush||typeof WebSocket!="function")return null;let i=this.logLoopback,a=r.origin,c=()=>{try{return this.collectionCurrent?.()===!0&&this.current()&&this.authority===r&&r.isCurrent()}catch{return!1}};return new Uy({origin:a,collection:r.collection,deviceId:o.deviceId,isCurrent:c,accessToken:l=>r.accessToken(l),invalidateToken:l=>r.invalidateToken(l),nonce:async({signal:l})=>{let p=await s(`${a}/v1/nonce`,{signal:l,cache:"no-store",credentials:"omit",redirect:"error",referrerPolicy:"no-referrer"}),d=(await p.text()).trim();if(!p.ok||!/^[0-9a-f]{64}$/.test(d))throw be("unavailable","push_nonce");return Uint8Array.from(d.match(/../g).map(u=>parseInt(u,16)))},signHello:(l,p)=>c()?t.signLogHello(l,p):null},e,{allowLoopbackHttp:i})}async driveCollection(e){let t=this.operationSignal(e.signal);if(this.checkCollection(t),!this.native||!this.pump||this.adoptedEndpoint===null)throw be("binding");for(let r=0;r<Z8;r++){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 be("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:r=!1,local:o=!1}=e,s=this.operationSignal(e.signal);if(this.checkCollection(s),!this.native||!this.collectionScope||this.adoptedEndpoint===null||!Number.isSafeInteger(t)||t<1||t>15e3||typeof r!="boolean"||typeof o!="boolean"||r&&(o||!this.pump))throw be("binding");if(o&&!this.holdsLog())return Promise.reject(be("unavailable","local_read_without_log"));if(this.readWork)return this.readWork.then(()=>{this.checkCollection(s)});let i=this.verifyRead(s,t,r,o,e.onProgress);return this.readWork=i,i.finally(()=>{this.readWork===i&&(this.readWork=null)}).catch(()=>{}),i}async verifyRead(e,t,r,o,s){let i=new AbortController,a=()=>i.abort(),c=()=>o?null:this.pump;this.readAbort=i;let l=!1,p=null;c()&&(this.readWake=()=>{l=!0,p?.()});let d=v=>l?(l=!1,Promise.resolve()):c()?new Promise((k,S)=>{if(i.signal.aborted){S(i.signal.reason);return}let x=()=>{clearTimeout(R),i.signal.removeEventListener("abort",C),p===P&&(p=null)},P=()=>{x(),l=!1,k()},C=()=>{x(),S(i.signal.reason)},R=setTimeout(()=>{x(),k()},v);p=P,i.signal.addEventListener("abort",C,{once:!0})}):fa(v,i.signal);e.addEventListener("abort",a,{once:!0});let u=null,f="read_connect",h=null,m=()=>h??=be(r?"sync_stalled":"unavailable",f),w,b=new Promise((v,k)=>{w=()=>k(m()),i.signal.addEventListener("abort",w,{once:!0})});b.catch(()=>{});let g=null,y=v=>{if(v!==g){g=v;try{s?.(v)}catch{}}},_=()=>{this.checkCollection(e);let v=r?c().terminalProblem:null;if(pn(v))throw new On(It(v)??"unavailable",v);let k=this.native.observations();if(k.requiresReopen||k.keyringRebuildFailed)throw be("recovery_required");let S=hc(k.status);return y(S==="installing"?"loading_snapshot":S==="waiting_for_key"?"waiting_for_key":S==="behind"?"replaying":S===null?"verifying_read":"syncing"),k};this.readVerified=!1;try{if(c()){let k=!1,S=()=>{let E=_();return k=r&&l2(E.status),[E.status.confirmedThrough,E.status.installing?.done??0,E.status.installing?.total??0,c().readProgress]},x=S(),P=Date.now(),C=new Map,R=null,O=()=>{try{let E=Date.now(),j=S();j.some((V,U)=>V>x[U])&&(P=E,R=null),x=j.map((V,U)=>Math.max(V,x[U]));let B=c().responseProgress(),D=new Set(B.map(V=>V.id));for(let V of C.keys())D.has(V)||C.delete(V);for(let V of B){let U=C.get(V.id);V.bytes>(U?.bytes??0)&&C.set(V.id,{bytes:V.bytes,at:E})}let J=(k?Math.max(t,a2):t)-(E-P);J<=0&&(R??=new Set(C.keys()),J=Math.max(0,...[...R].map(V=>{let U=C.get(V);return U?t-(E-U.at):0}))),J<=0?a():u=setTimeout(O,Math.min(250,J))}catch(E){h=E,a()}};u=setTimeout(O,Math.min(250,t))}else u=setTimeout(a,t);this.readClient=await Promise.race([yi.connect({app:{name:"app-local-read-gate",version:"1"},connector:Jl(this.native,{collection:this.collectionScope.collection}),reconnect:!1,signal:i.signal}).then(k=>{if(i.signal.aborted)throw k.close(),m();return k}),b]),this.checkCollection(e);let v=250;for(;!i.signal.aborted;){f="read_catch_up",l=!1,this.native.tick();let k=c();k&&await Promise.race([k.pump(),b]),this.checkCollection(e);let S=_();if(r&&hc(S.status)!==null){await d(v),v=Math.min(1e3,v*2);continue}f="read_query";try{if(await Promise.race([this.readClient.query({limit:1},{signal:i.signal}),b]),this.checkCollection(e),i.signal.aborted)throw m();this.readVerified=!0;return}catch(x){if(this.checkCollection(e),!(x instanceof oe)||x.code!=="unavailable"||!c()||i.signal.aborted)throw x}await d(v),v=Math.min(1e3,v*2)}throw m()}catch(v){throw this.checkCollection(e),i.signal.aborted?m():v}finally{u!==null&&clearTimeout(u),e.removeEventListener("abort",a),i.signal.removeEventListener("abort",w),this.readWake=null,p=null,this.readClient?.close(),this.readClient=null,this.readAbort=null}}get privateDevice(){return this.accountKeyPin!==null}accountKeyState(){if(!this.native||!this.accountKeyPin||this.adoptedEndpoint===null)throw be("binding");return this.native.accountKeyStatus(this.accountKeyPin)}async settlePrivateKey(e){let{timeoutMs:t=15e3}=e,r=this.operationSignal(e.signal);if(this.checkCollection(r),!this.native||!this.pump||!this.accountKeyPin||this.adoptedEndpoint===null||!Number.isSafeInteger(t)||t<1||t>15e3)throw be("binding");let o=null,s=Date.now(),i=100,a=!1,c=async()=>a?!0:(a=!0,await this.wakeCollectionLog({signal:r}),!1);for(;;){let l=this.accountKeyState();if(l.state==="keyed")return"keyed";if(l.state==="refused"&&l.reason==="outcome_unknown")throw be("recovery_required");await this.driveCollection({signal:r});let p=this.pump?.terminalProblem;if(pn(p))throw new On(It(p)??"unavailable",p);if(this.accountKeyState().state==="keyed")return"keyed";let d=this.native.observations();if(d.requiresReopen||d.keyringRebuildFailed)throw be("recovery_required");let u=hc(d.status);if(u==="offline"||this.pump?.transportHealth?.kind==="offline")throw be("unavailable","key_wait_offline");let f=u==="waiting_for_key"?Dy(d.status)?.key:void 0;if(u===null||f!==void 0&&f!=="reading"){if(await c())return"locked";continue}let h=Date.now(),m=[d.status.confirmedThrough,d.status.headKnown,this.pump.readProgress];if((o===null||m.some((w,b)=>w>o[b]))&&(s=h),o=o===null?m:m.map((w,b)=>Math.max(w,o[b])),h-s>=t)throw be("sync_stalled");await fa(i,r),this.checkCollection(r),i=Math.min(1e3,i*2)}}accountKeySession(e){let t=this.collectionSession;if(!t)throw be("binding");return Object.freeze({accountId:this.selected.accountId,connectorId:e.connectorId,deviceId:e.deviceId,collection:e.collection,cpOrigin:this.selected.cpOrigin,isCurrent:()=>this.collectionCurrent?.()===!0&&this.accountKeyPin===e,connectorBearer:async({signal:r})=>{r.throwIfAborted(),this.checkCollection(this.lifetime);let o=await t.connectorBearer({signal:this.lifetime});return this.checkCollection(this.lifetime),r.throwIfAborted(),o}})}async accountKeyMode(e){let t=this.operationSignal(e.signal);this.checkCollection(t);let r=this.accountKeyPin;if(!r||!this.logRequest)throw be("binding");return ig(this.accountKeySession(r),{signal:t,fetch:this.logRequest,allowLoopbackHttp:this.logLoopback})}async unlockAccountKey(e,t){let r=this.operationSignal(t.signal);this.checkCollection(r);let o=this.native,s=this.accountKeyPin,i=this.logRequest;if(!o||!s||!i||!this.pump||this.adoptedEndpoint===null||this.accountKeyWork)throw be("binding");let a=Object.freeze({supportsFetchProof:()=>o.supportsAccountKeyFetchProof,signFetch:c=>o.signAccountKeyFetch(s,this.selected.accountId,c),unlockConsuming:c=>o.unlockAccountKeyConsuming(s,c),status:()=>o.accountKeyStatus(s),drive:c=>this.driveCollection({signal:c.signal}),headKnown:()=>o.observations().status.headKnown});this.accountKeyWork=!0;try{await og(this.accountKeySession(s),a,e,{signal:r,fetch:i,allowLoopbackHttp:this.logLoopback,sealed:this.accountKeySealed,...t.onMode?{onMode:t.onMode}:{}}),this.checkCollection(r)}finally{this.accountKeyWork=!1}}onLogWork(e){this.logWorkListener=e}attachDataFacade(e){if(this.checkCollection(this.lifetime),!this.native||!this.collectionScope||!this.readVerified||this.facades.size>=Q8||this.facades.has(e))throw be("fenced");let t=Object.freeze({...this.collectionScope,isCurrent:()=>{try{return this.checkCollection(this.lifetime),!0}catch{return!1}}}),r=Bm(this.native,e,t,()=>this.logWorkListener?.());return this.facades.set(e,r),r.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 be("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 r of this.facades.values())r.close();this.facades.clear()},()=>this.peopleMetadata?.authority.close(),()=>this.bootstrap?.close(),()=>this.outcome?.close(),()=>this.accountKeySealed.clear()])try{t()}catch{e=!0}return this.closeResult??=(async()=>{try{await Promise.all([...this.timerPorts].map(async r=>{try{await r.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 be("unavailable","close_fence")}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.privateStore?.close(),this.noiseStore?.close(),this.keys?.close(),this.provider?.close()}})()}}});var Ic,eD,tD,fs,Ln,Oc,fg=I(()=>{"use strict";Ic="original-join",eD=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,tD="00000000-0000-0000-0000-000000000000",fs=class extends Error{constructor(t){super(`app collection join: ${t}`);this.reason=t;this.name="AppCollectionJoinError"}reason},Ln=(n="recovery_required")=>new fs(n),Oc=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(r=>typeof r!="string"||!eD.test(r)||r===tD)||typeof e.databaseName!="string"||!e.databaseName.length||e.databaseName.length>256||/[\u0000-\u001f\u007f]/.test(e.databaseName)||typeof e.isCurrent!="function")throw Ln("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 Ln("fenced")}marker(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).sort().join()!=="account,collection,installation,phase,version")throw Ln();let t=e;if(t.version!==1||t.phase!=="attempted"&&t.phase!=="completed"||Object.entries(this.options.scope).some(([r,o])=>t[r]!==o))throw Ln();return t}open(e){if(this.check(e),!globalThis.indexedDB)throw Ln();return new Promise((t,r)=>{let o=indexedDB.open(this.options.databaseName,1),s=!1,i=()=>e.removeEventListener("abort",a),a=()=>{s=!0,i();try{o.transaction?.abort()}catch{}r(Ln())};e.addEventListener("abort",a,{once:!0}),o.onblocked=o.onerror=a,o.onupgradeneeded=()=>{try{if(this.check(e),s||o.result.objectStoreNames.length)throw Ln();o.result.createObjectStore(Ic)}catch{try{o.transaction?.abort()}catch{}}},o.onsuccess=()=>{i();try{if(this.check(e),s||o.result.objectStoreNames.length!==1||!o.result.objectStoreNames.contains(Ic))throw Ln();t(o.result)}catch{o.result.close(),r(Ln())}}})}async change(e,t){if(this.check(t),this.busy)throw Ln("busy");this.busy=!0;let r=null;try{return r=await this.open(t),this.check(t),await new Promise((o,s)=>{this.check(t);let i=r.transaction(Ic,"readwrite",{durability:"strict"}),a=null,c,l=()=>{try{i.abort()}catch{}},p=()=>t.removeEventListener("abort",l);t.addEventListener("abort",l,{once:!0}),i.onabort=i.onerror=()=>{p(),s(c??Ln())},i.oncomplete=()=>{p();try{if(this.check(t),!a)throw Ln();o(Object.freeze(a))}catch{s(Ln())}};let d=i.objectStore(Ic),u=d.get(this.key);u.onsuccess=()=>{try{this.check(t);let f=u.result;if(f===void 0){if(e!=="prepare")throw Ln();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){c=f,l()}}})}catch(o){throw o instanceof fs?o:Ln()}finally{r?.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 r=null;try{r=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 i=r.transaction(Ic,e==="mark"?"readwrite":"readonly"),a=!1;i.onabort=i.onerror=()=>s(!1),i.oncomplete=()=>s(e==="mark"||a);let c=i.objectStore(Ic);if(e==="mark")c.put({version:1,synced:!0},o);else{let l=c.get(o);l.onsuccess=()=>{let p=l.result;a=!!p&&p.version===1&&p.synced===!0}}})}catch{return!1}finally{r?.close()}}async complete(e){await this.change("complete",e.signal)}}});function oE(n){let e=Object.freeze({...n,setupJournal:Object.freeze({...n.setupJournal})}),t=RI(e.sql);if(typeof e.handoff!="function")throw ai("binding");let r=new Set;return async o=>{let s=JSON.stringify([o.scope.account,o.scope.installation,o.scope.collection]);if(r.has(s))throw ai("fenced");r.add(s);let{host:i,installation:a,signal:c,collection:l,setupPolicy:p}=o,d=a.isCurrent,u=l.displayName,f=l.mode==="private",h=de=>{if(re())try{o.onProgress?.(de)}catch{}},m=Object.freeze({account:o.scope.account,installation:o.scope.installation,collection:o.scope.collection}),w=JSON.stringify([m.account,m.installation,m.collection]),b=new AbortController,g=!1,y=!0,_=null,v=null,k=null,S=null,x=null,P=null,C=null,R=null,O="setup_required",E=null,j=!1,B=!1,D=null,J=null,V="settled",U=null,ce=!1,ee=null,te=!1,Ce=null,et=null,$=new Map,Y=new Map,K=()=>{try{return i.timerConsentKey(m.collection)}catch{return}},Z=null,_e=new Set,re=()=>{try{return!g&&!b.signal.aborted&&!c.aborted&&o.signal===c&&o.host===i&&o.installation===a&&a.isCurrent===d&&d.call(a)===!0&&o.collection===l&&o.setupPolicy===p&&a.scope.account===m.account&&a.scope.installation===m.installation&&JSON.stringify([o.scope.account,o.scope.installation,o.scope.collection])===w&&l.collectionId===m.collection}catch{return!1}},ne=()=>{if(!re())throw ai("fenced")},Ke=()=>{for(let de of[..._e])try{de()}catch{}},Ve=()=>{if(k)return k;g=!0,O="setup_required",_!==null&&clearTimeout(_),_=null,ee!==null&&clearTimeout(ee),ee=null,et=null;try{U?.close()}catch{}U=null;try{i.onLogWork?.(null)}catch{}c.removeEventListener("abort",Ft);let de=[...$.values()];return $.clear(),k=Promise.resolve().then(async()=>{let Ie=!1;try{await x?.close()}catch{Ie=!0}try{await S?.close()}catch{Ie=!0}for(let st of de){try{await st.timers?.close()}catch{Ie=!0}try{await st.control.close()}catch{Ie=!0}try{st.data.port1.postMessage([1,JSON.stringify([m.account,m.installation,m.collection]),"close"])}catch{Ie=!0}for(let hr of[st.data.port1,st.data.port2,st.command.port1,st.command.port2])try{hr.close()}catch{Ie=!0}}try{C?.port1.postMessage([1,JSON.stringify([m.account,m.installation,m.collection]),"close"])}catch{Ie=!0}for(let st of[C?.port1,C?.port2,R?.port1,R?.port2])try{st?.close()}catch{Ie=!0}await v?.catch(()=>{});try{P?.close()}catch{Ie=!0}if(Ie)throw ai("unavailable");_e.clear(),r.delete(s)}),b.abort(),Ke(),k},Ft=()=>{Ve().catch(()=>{})},Re=null,nt=0,ci=()=>{let de=It(Z);if(de!==null)return de==="collection_migrating"?Math.min(6e5,Math.max(5e3,Z?.retryAfterMs??3e4)):3e5;let Ie=Math.min(6e4,1e3*2**Math.min(Math.max(nt,Di),6));return Re?.kind==="offline"?Un?Ie:null:Re?.kind==="server_busy"||Re?.kind==="rate_limited"?Re.retryAfterMs??Ie:Di||Re?Ie:250},yo=()=>{let de=null;try{de=i.serverProblem()}catch{de=null}let Ie=null;try{Ie=i.transportHealth()}catch{Ie=null}nt=Ie?nt+1:0;let st=JSON.stringify(Ie)===JSON.stringify(Re);(de!==Z||!st)&&(Z=de,Re=Ie,Ke())},go=Number.POSITIVE_INFINITY,Di=0,bo=0,hs=!1,Un=null,cn=de=>{let Ie=de&&typeof de=="object"&&typeof de.code=="string"?de.code:null;try{console.debug("mdbase: sync turn failed",{reason:Re?.kind??It(Z)??Ie??"unknown",failures:Di})}catch{}},wo=()=>{if(y||Date.now()-bo>=nD)return!1;try{return i.pendingWrites()>0}catch{return!1}},zc=()=>i.startCollectionLog({signal:b.signal,fetch:e.fetch,allowLoopbackHttp:e.allowLoopbackHttp}),Aa=de=>{Ce=de,Cg(),$c(!1),Un?.(),Ke()},ms=()=>{if(!(U||!re())){try{U=typeof i.openLogPush=="function"?i.openLogPush({push:de=>{re()&&(i.pushLog(de),Cg())},live:$c,ended:de=>{if(!j){et??=de,$c(!1);return}Aa(de)}}):null}catch{U=null}if(U){try{U.start()}catch{try{U.close()}catch{}U=null,ka(!0);return}$c(!1)}else ka(!0)}},jr=async()=>{let de=D;D=null,await(de??zc()),ne(),B=!0,ms()},V0=()=>{if(!(V!=="pending"||!B)){try{V=i.keyringSettled?.()??"settled"}catch{return}V==="failed"&&F0(new fr("recovery_required"))}},F0=de=>{J=de,j=!1,_!==null&&clearTimeout(_),_=null,Ke()},HE=de=>{let Ie=null;try{Ie=de.server}catch{Ie=null}let st=pn(Ie)&&It(Ie)!==null?Ie:null,hr=!pn(Ie)&&de instanceof lr&&de.reason==="response",wn=st?null:hr?{kind:"unreachable"}:Ld(de);if(!st&&(wn===null||wn.kind==="auth")){F0(de);return}nt=wn?nt+1:0,(st!==Z||JSON.stringify(wn)!==JSON.stringify(Re))&&(Z=st,Re=wn,Ke())},ys=()=>{if(!j||!re())return;if(!y&&!wo()&&!te){v||U?.suspend();return}if(_!==null||v)return;let de=te?0:ci();te=!1,de!==null&&(_=setTimeout(()=>{if(_=null,!re())return;let Ie=y&&Date.now()>=go;Ie&&(go=Number.POSITIVE_INFINITY);let st=v=B?Ie?i.wakeCollectionLog({signal:b.signal}):i.driveCollection({signal:b.signal}):jr().then(()=>i.driveCollection({signal:b.signal}));st.then(()=>{v===st&&(v=null),Di=0,hs=!0,re()&&(yo(),V0()),Un?.(),ys()},hr=>{v===st&&(v=null),Di++,re()&&(B?(yo(),V0()):HE(hr)),cn(hr),Un?.(),ys()})},de))},Cg=()=>{re()&&(te=!0,_!==null&&clearTimeout(_),_=null,ys())},ka=de=>{ce!==de&&(ce=de,Ke())},$c=de=>{if(ee!==null&&clearTimeout(ee),ee=null,de){ka(!1);return}if(!U?.available){ka(Ce===null);return}U.suspended||(ee=setTimeout(()=>{ee=null,re()&&!U?.live&&ka(!0)},iE))},K0=de=>{if(ne(),de){(!U?.live||Re?.kind==="offline")&&(go=0),Di=0,nt=0,Re?.kind==="offline"&&(te=!0);try{U?.resume(),U&&!U.live&&$c(!1)}catch{}}else y&&(bo=Date.now());y=de,_!==null&&clearTimeout(_),_=null,ys()},GE=()=>new Promise((de,Ie)=>{let st,hr=null,wn=Qn=>{Un=null,hr!==null&&clearTimeout(hr),b.signal.removeEventListener("abort",Sa),Qn?Ie(Qn):de()},Sa=()=>wn(ai("fenced"));b.signal.addEventListener("abort",Sa,{once:!0}),Un=()=>{if(!re()){wn(ai("fenced"));return}if(Ce!==null){wn();return}let Qn="first_turn";if(hs)try{Qn=typeof i.initialSync=="function"?i.initialSync():null}catch{Qn="unavailable"}if(Qn===null||Qn==="offline"||Re?.kind==="offline"){wn();return}let mr=null;if(Qn==="waiting_for_key"&&typeof i.keyWaitDetail=="function")try{mr=i.keyWaitDetail()}catch{mr=null}let Pa=Qn+(mr?JSON.stringify(mr):"");if(Pa!==st){st=Pa;try{console.debug("mdbase: waiting for the first sync",{...mr,reason:Qn})}catch{}}},hr=setTimeout(()=>wn(),rD),Un()});c.addEventListener("abort",Ft,{once:!0});try{ne(),P=new Wl({...e.setupJournal,scope:m,isCurrent:re});let de=new Oc({databaseName:e.joinDatabaseName,scope:m,isCurrent:re});if(f)h("joining"),await i.bootstrapPrivateDevice({scope:m,collectionCurrent:re,signal:b.signal,fetch:e.fetch,allowLoopbackHttp:e.allowLoopbackHttp}),ne();else{let Ct=await de.prepare({signal:b.signal});ne(),h("joining"),await i.bootstrapCloudCopy({scope:m,collectionCurrent:re,purpose:"join",outcomeMode:Ct.outcomeMode,signal:b.signal,...Ct.outcomeMode==="existing"?{reconcile:"explicit-unknown-outcome"}:{},fetch:e.fetch,allowLoopbackHttp:e.allowLoopbackHttp}),ne(),await de.complete({signal:b.signal}),ne()}let Ie=i.registeredReceipt();if(Ie.installationId!==m.installation)throw ai("binding");let st=null,hr=async Ct=>{let qt=await t(Ct);return st=qt.ledger??null,qt};h("opening_store"),await i.openCollectionSql({signal:b.signal,replicaId:Ie.deviceId,endpoint:0,openSql:hr}),ne();let wn=!0;try{wn=i.holdsLog?.()??!0}catch{wn=!1}let Sa=!f&&wn&&await de.syncedBefore({signal:b.signal});ne();let Qn=async()=>{h("connecting_log");let Ct=Date.now()+oD;for(let qt=0;;qt++)try{await zc(),ne();break}catch(yr){ne();let zi=yr instanceof lr&&yr.reason==="unavailable"?yr.server:null;if(!pn(zi)||zi.status!==503||zi.code!=="busy"||It(zi)!==null||qt+1>=sD)throw yr;let Bc=zi.retryAfterMs??1e3*2**qt;if(Date.now()+Bc>=Ct||(await fa(Bc,b.signal),ne(),Date.now()>=Ct))throw yr}B=!0};Sa?(D=zc(),D.catch(()=>{})):await Qn();let mr=crypto.randomUUID(),Pa=null,W0=null,Ig=null;if(f){h("syncing");let Ct=await i.settlePrivateKey({signal:b.signal});if(ne(),Ct==="locked"){let qt=await i.accountKeyMode({signal:b.signal});ne(),E={mode:qt,unlocking:!1,problem:null}}}let H0=async()=>{let Ct=f?await de.syncedBefore({signal:b.signal}):Sa;ne();let qt=!1;if(Sa&&!B)try{await i.waitForVerifiedRead({signal:b.signal,local:!0,timeoutMs:iD,onProgress:h}),ne(),qt=!0}catch{ne();let Kt=D;D=null;let wt=Kt?await Kt.then(()=>!0,()=>!1):!1;ne(),wt?B=!0:await Qn()}if(qt||(ms(),h("syncing"),await i.waitForVerifiedRead({signal:b.signal,cold:!Ct,onProgress:h}),ne()),j=!0,i.onLogWork?.(Cg),et!==null){let Kt=et;et=null,Aa(Kt)}qt?(V="pending",te=!0,ys(),ee=setTimeout(()=>{ee=null,re()&&!U?.live&&ka(!0)},iE)):(ys(),Ct&&(h("syncing"),await GE()),ne()),h("checking_setup"),de.markSynced({signal:b.signal}).catch(()=>{});let yr=await P.load(b.signal);ne();let zi=yr&&yr.version!==1&&(yr.phase==="attempted"||yr.phase==="confirmed")?"reconcile-original":yr===null&&p==="approved-new-collection"?"approved-new":"inspect",Bc=e.people===!0&&!f,G0=Bc?{people:!0}:f?{privateDevice:!0}:{},XE={owner:null},Y0=(Kt,wt,Wt,$i)=>zI(wt,{scope:m,generation:mr},{journal:P,resourceSetup:i.attachDataFacade(Kt),signal:b.signal,isCurrent:re,ledger:()=>re()?st:null,setupTurn:XE,assess(Vc){ne(),O=Vc,Ke()},foreground:Wt,onProtocolFailure:$i,...Bc?{peopleAuthority:i.peopleAuthority()}:{}});x=i.openTimersPort({scope:m,generation:mr,signal:b.signal}),ne();let QE=K()??null;C=new MessageChannel,R=new MessageChannel,S=Y0(C.port1,R.port1,K0,Ft),ne();let Og=Kt=>{if(Y.delete(Kt.dataPort),C&&R&&Kt.dataPort===C.port2){let Wt={data:C,command:R,control:S,timers:x};C=null,R=null,S=null,x=null;try{i.detachDataFacade(Wt.data.port1)}catch{}Wt.timers?.close().catch(()=>{}),Wt.control?.close().catch(()=>{});for(let $i of[Wt.data.port1,Wt.command.port1])try{$i.close()}catch{}return}let wt=$.get(Kt.dataPort);if(wt){$.delete(Kt.dataPort);try{i.detachDataFacade(wt.data.port1)}catch{}wt.timers?.close().catch(()=>{}),wt.control.close().catch(()=>{});for(let Wt of[wt.data.port1,wt.command.port1])try{Wt.close()}catch{}}},J0=(Kt=zi==="reconcile-original"?zi:"inspect")=>{if(!re()||Ce!==null)return null;let wt=new MessageChannel,Wt=new MessageChannel,$i=null,Vc=null;try{$i=i.openTimersPort({scope:m,generation:mr,signal:b.signal});let xa=null,eq=K()??null;return Vc=Y0(wt.port1,Wt.port1,()=>{},()=>{xa&&Og(xa)}),xa=Object.freeze({schema:"mdbn-app-collection/1",scope:m,generation:mr,displayName:u,setupMode:Kt,dataPort:wt.port2,controlPort:Wt.port2,...G0,...$i?{timerPort:$i.port}:{}}),$.set(wt.port2,{data:wt,command:Wt,control:Vc,timers:$i}),Y.set(wt.port2,eq),xa}catch{try{i.detachDataFacade(wt.port1)}catch{}$i?.close().catch(()=>{}),Vc?.close().catch(()=>{});for(let xa of[wt.port1,wt.port2,Wt.port1,Wt.port2])xa.close();return null}},ZE=Kt=>{if(!re()||!Y.has(Kt.dataPort))return null;let wt=K();if(wt===void 0||wt===Y.get(Kt.dataPort))return null;let Wt=J0(Kt.setupMode);return Wt&&Og(Kt),Wt};Pa=J0,W0=Og,Ig=ZE,Y.set(C.port2,QE),e.handoff(Object.freeze({schema:"mdbn-app-collection/1",scope:m,generation:mr,displayName:u,setupMode:zi,dataPort:C.port2,controlPort:R.port2,...G0,...x?{timerPort:x.port}:{}})),ne(),ys()},YE=Object.freeze({scope:m,generation:mr,isCurrent:re,setForeground:K0,attach:()=>Pa?Pa():null,detach:Ct=>{W0?.(Ct)},renewTimers:Ct=>Ig?Ig(Ct):null}),JE={get state(){return re()?E?"needs_unlock":O:"setup_required"},get locked(){return re()&&E?Object.freeze({...E}):null},get problem(){return re()?Z:null},get health(){return re()?Re:null},get live(){return re()?!ce:null},get ended(){return re()?Ce:null},get failure(){return re()?J:null},connection:YE,close:Ve,subscribe(Ct){return ne(),_e.add(Ct),()=>{_e.delete(Ct)}},...f?{unlock:async Ct=>{if(ne(),!E||E.unlocking)throw ai("binding");E={mode:E.mode,unlocking:!0,problem:null},Ke();try{await i.unlockAccountKey(Ct,{signal:b.signal,onMode:qt=>{E&&re()&&(E={...E,mode:qt})}}),ne()}catch(qt){if(qt instanceof pt&&re()&&E){E={mode:E.mode,unlocking:!1,problem:qt.reason},Ke();return}throw await Ve(),qt}try{await H0(),ne()}catch(qt){throw await Ve(),qt}E=null,Ke()}}:{}};return E||await H0(),ne(),Object.freeze(JE)}catch(de){throw await Ve(),de}}}async function hg(n,e){if(n.schema!=="mdbn-app-collection/1"||Rc.has(n.dataPort)||Rc.has(n.controlPort)||n.dataPort===n.controlPort||!["inspect","approved-new","reconcile-original"].includes(n.setupMode)||n.people!==void 0&&n.people!==!0||n.privateDevice!==void 0&&(n.privateDevice!==!0||n.people!==void 0)||e.signal.aborted||n.timerPort&&(Rc.has(n.timerPort)||n.timerPort===n.dataPort||n.timerPort===n.controlPort))throw ai("binding");Rc.add(n.dataPort),Rc.add(n.controlPort),n.timerPort&&Rc.add(n.timerPort);let t=Object.freeze({...n.scope}),r=n.generation,o=n.setupMode,s=n.people===!0,i=n.dataPort,a=n.controlPort,c=e.signal,l=!1,p=null,d=null,u=null,f,h=()=>{if(!l){l=!0,c.removeEventListener("abort",h);for(let m of[()=>f?.close(),()=>d?.close(),()=>p?.close(),()=>u?.close(),()=>i.close(),()=>a.close()])try{m()}catch{}}};c.addEventListener("abort",h,{once:!0});try{if(u=Vm(i,{...t,isCurrent:()=>!l&&!c.aborted}),d=zm(a,{scope:t,generation:r},{signal:c,isCurrent:()=>!l,onClose:h,...s?{people:!0}:{}}),n.timerPort&&(f=new Fa(s2(n.timerPort,{scope:t,generation:r},{signal:c,onClose:()=>{}}),{criteria:e.timerCriteria??[]})),p=await yi.connect({app:e.app,connector:u,reconnect:!1,signal:c,ledger:d.ledger}),l||c.aborted)throw p.close(),ai("fenced");let m=s?Nm(p,d):void 0;return Object.freeze({client:p,resourceSetup:d.resourceSetup,...m?{people:m}:{},journal:d.journal,scope:t,setupMode:o,close:h,...f?{timers:f}:{},assess:(w,b)=>d.assess(w,b),setForeground:(w,b)=>d.setForeground(w,b)})}catch(m){throw h(),m}}var iE,nD,rD,iD,oD,sD,yu,ai,Rc,y0=I(()=>{"use strict";nr();Cd();mu();jy();Wm();Es();fw();TA();EI();fg();Js();es();Fm();fu();qd();iE=1e4,nD=12e4,rD=2e3,iD=5e3,oD=15e3,sD=3,yu=class extends Error{constructor(t){super(`app web collection: ${t}`);this.reason=t;this.name="AppWebCollectionError"}reason},ai=n=>new yu(n);Rc=new WeakSet});function aD(n,e){return Object.freeze({collection:n,isCurrent:e,request:()=>Promise.reject(A("upgrade_required","People is not available for a Private collection opened by this app","people_unsupported"))})}var ln,mg,lD,Ec,g0=I(()=>{"use strict";y0();ie();Sp();ln=class extends Error{constructor(t){super("SDK application connection unavailable");this.code=t;this.name="ApplicationUiConnectionError"}code},mg=new WeakSet;lD=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,Ec=class{app;signal;current=null;pending=null;opening=null;retiring=null;closing=null;epoch=0;timerCriteria;constructor(e,t,r=[]){this.app=Object.freeze({...e}),this.signal=t,this.timerCriteria=Object.freeze([...r]),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 r=t.caller,o=t.isCurrent,s=[e.dataPort,e.controlPort,...e.timerPort?[e.timerPort]:[]];if(s.some(y=>!(y instanceof MessagePort))||new Set(s).size!==s.length||s.some(y=>mg.has(y))){for(let y of new Set(s))y instanceof MessagePort&&!mg.has(y)&&(mg.add(y),y.close());return Promise.reject(new ln("application_connection_binding"))}for(let y of s)mg.add(y);let i=y=>{for(let _ of s)_.close();return Promise.reject(new ln(y))};if(this.pending||this.current||this.retiring)return i("application_connection_busy");if(this.closing||this.signal.aborted||r.aborted||!o())return i("application_connection_fenced");let a=Object.freeze({...e.scope}),c=e.generation,l=e.displayName;if(e.schema!=="mdbn-app-collection/1"||Object.keys(a).sort().join()!=="account,collection,installation"||Object.values(a).some(y=>!lD.test(y)||y==="00000000-0000-0000-0000-000000000000")||typeof c!="string"||!c||c.length>256||typeof l!="string"||!l.trim()||new TextEncoder().encode(l).length>4096||!["inspect","approved-new","reconcile-original"].includes(e.setupMode))return i("application_connection_binding");let p=e.privateDevice===!0;if(e.privateDevice!==void 0&&(!p||e.people!==void 0))return i("application_connection_binding");if(e.people!==!0&&!p)return i("application_connection_people_unavailable");let d=Object.freeze({...e,scope:a,generation:c,displayName:l}),u=new AbortController,f=this.epoch;this.opening=u;let h=()=>u.abort();r.addEventListener("abort",h,{once:!0});let m=AbortSignal.any([this.signal,u.signal]),w=()=>!m.aborted&&!this.closing&&!this.retiring&&this.epoch===f&&o(),b=null,g=Promise.resolve().then(async()=>{if(!w()||r.aborted)throw new ln("application_connection_fenced");if(b=await hg(d,{app:this.app,signal:m,timerCriteria:this.timerCriteria}),!w()||r.aborted)throw new ln("application_connection_fenced");if(b.client.collection!==a.collection||b.client.link!=="open")throw new ln("application_connection_binding");if(p?b.people!==void 0:!b.people)throw new ln(p?"application_connection_binding":"application_connection_people_unavailable");let y=b,_=b.people??new gi(y.client,aD(a.collection,()=>w()&&this.current?.ui===y&&y.client.link==="open")),v=Object.freeze({id:a.collection,scope:a,generation:c,displayName:l,records:y.client,files:y.client.files,people:_,...y.timers?{timers:y.timers}:{},isCurrent:()=>w()&&this.current?.ui===y&&y.client.link==="open"});return this.current={public:v,ui:y,lifetime:u},v}).catch(y=>{u.abort(),b?.close();for(let _ of s)_.close();throw y}).finally(()=>{r.removeEventListener("abort",h),this.pending===g&&(this.pending=null,this.opening=null)});return this.pending=g,g}retire(){if(this.retiring)return this.retiring;++this.epoch;let e=this.current,t=this.pending;this.opening?.abort(),e?.lifetime.abort();let r=Promise.resolve().then(async()=>{await t?.catch(()=>{}),e?.ui.close(),this.current===e&&(this.current=null)});return this.retiring=r,r.then(()=>{this.retiring===r&&(this.retiring=null)},()=>{}),r}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 hD(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 Vt("unsupported");let e=n.contracts.map(r=>{if(!r||!Tc(r.id,256)||!Tc(r.version,128)||!fD.test(r.digest))throw Vt("unsupported");return Object.freeze({id:r.id,version:r.version,digest:r.digest})}),t=n.requiredNativeCapabilities.map(r=>{if(!Tc(r,128))throw Vt("unsupported");return r});if(new Set(e.map(r=>JSON.stringify([r.id,r.version]))).size!==e.length||new Set(t).size!==t.length||n.typeIssues!==void 0&&n.typeIssues!=="block"&&n.typeIssues!=="degrade")throw Vt("unsupported");return Object.freeze({capabilityContractVersion:2,typeIssues:n.typeIssues??"block",contracts:Object.freeze(e),requiredNativeCapabilities:Object.freeze(t)})}function mD(n){let e=fe(n,"path");return typeof e=="string"&&e?e:null}function qc(n,e){return Object.freeze({reason:n,...n==="fenced"&&e?{detail:e}:{}})}function b0(n){if(!X(n))return;let e=fe(n.details,"condition"),t=cD.find(r=>r===e);if(t)return t;if(n.code==="unauthenticated")return"read_unauthenticated";if(n.code==="cancelled")return"read_cancelled"}function w0(n){try{if(X(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 _0(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 A0(n){return n.mode==="local_only"}function Mc(n){return JSON.stringify(n,(e,t)=>typeof t=="bigint"?`${t}n`:t instanceof Uint8Array?[...t]:t)}function aE(n,e,t){return new v0(n,e,t)}var cD,pD,dD,uD,sE,fD,Tc,Vt,v0,k0=I(()=>{"use strict";ie();vn();cD=["binding_invalid","binding_aborted","binding_not_current","readiness_closed","read_aborted","session_closed","session_replaced","session_collection_mismatch","read_unauthenticated","read_cancelled"],pD=4096,dD=2*1024*1024,uD=64,sE=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,fD=/^sha256:[0-9a-f]{64}$/,Tc=(n,e=4096)=>typeof n=="string"&&!!n.trim()&&new TextEncoder().encode(n).length<=e,Vt=(n,e)=>A(n==="fenced"?"unauthenticated":n==="budget"?"too_large":"unavailable","collection readiness unavailable",{reason:`readiness_${n}`,...e?{details:{condition:e}}:{}});v0=class{constructor(e,t,r){this.client=e;if(this.declared=hD(t),!sE.test(r.collection)||r.collection==="00000000-0000-0000-0000-000000000000"||!sE.test(r.generation))throw Vt("fenced","binding_invalid");this.binding=Object.freeze({collection:r.collection,generation:r.generation,signal:r.signal,isCurrent:r.isCurrent.bind(r)}),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=w0(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:qc(t,b0(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,r){e?.throwIfAborted();let o=this.fenceDetail(e);if(o)throw Vt("fenced",o);if(t?.closed)throw Vt("fenced","session_closed");if(t&&t!==this.client.currentSession())throw Vt("fenced","session_replaced");if(t&&t.hello.collection!==this.binding.collection)throw Vt("fenced","session_collection_mismatch");if(r!==void 0&&(r!==this.epoch||this.watch?.state!=="active"))throw Vt("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,r=this.client.describe({signal:this.readSignal}).then(o=>{this.closed||this.snapshotValue.assessment!==e||Mc(o)!==t&&this.recheck()},()=>{this.closed||this.recheck()});this.probing=r.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:qc("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(this.invalidate),this.stops.push(this.watch.subscribe(this.invalidate),this.client.onLink(this.invalidate),this.client.onStatus(e=>{let t=_0(this.client);(t!==this.lastStatus||A0(e))&&(this.lastStatus=t,this.invalidate())})))}start(e){return this.refresh(e)}refresh(e,t=!1){try{if(this.check(e),this.pending)throw Vt("busy")}catch(a){return Promise.reject(a)}t||(this.retrySince=null);let r=AbortSignal.any([this.binding.signal,this.lifetime.signal,...e?[e]:[]]),o,s,i=Promise.resolve().then(async()=>{this.check(r),this.attach();let a=await this.client.readyForRead(r);this.check(r,a),await this.watch.ready,this.check(r,a);let c=this.epoch;this.dirty=!1,this.check(r,a,c);let l=await this.inventory(r,a,c),p=await this.client.describe({signal:this.readSignal});this.check(r,a,c);let d=this.evaluate(p,a),u=Mc(p);for(let w of d.paths){let b=l.find(y=>y.path===w);if(!b)throw Vt("changed");let g=await this.client.resources.get(w,{signal:this.readSignal});if(this.check(r,a,c),g.path!==b.path||g.revision!==b.revision||g.size!==b.size||g.state!=="confirmed")throw Vt("changed")}let f=await this.inventory(r,a,c);if(JSON.stringify(l)!==JSON.stringify(f))throw Vt("changed");this.check(r,a,c);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?qc(d.reason):null,witness:h,...d.unavailable.length?{unavailableTypes:Object.freeze(d.unavailable)}:{}});return o=a,s=c,this.retries=0,this.failures=0,this.retrySince=null,this.assessedSession=a,this.assessedEpoch=c,this.assessedCatalog=u,this.publish({checking:!1,assessment:m,problem:m.problem}),this.check(r,a,c),m}).catch(a=>{let c=r.aborted||this.closed?"fenced":w0(a);throw this.retryLater(c,t)||this.publish({checking:!1,assessment:null,problem:qc(c,this.fenceDetail(r)??b0(a))}),a});return this.pending=i,this.publish({checking:!0,assessment:null,problem:null}),i.finally(()=>{this.pending===i&&(this.pending=null),this.schedule()}).catch(()=>{}),i.then(a=>{try{if(this.check(r,o,s),this.snapshotValue.assessment!==a)throw Vt("changed");return a}catch(c){let l=r.aborted?"fenced":w0(c);throw this.snapshotValue.assessment===a&&!this.retryLater(l)&&this.publish({checking:!1,assessment:null,problem:qc(l,this.fenceDetail(r)??b0(c))}),c}})}async inventory(e,t,r){let o=[],s=new Set,i,a="",c=0;for(let l=0;l<uD;l++){this.check(e,t,r);let p=await this.client.resources.list({text:!1,limit:128,...i?{cursor:i}:{},signal:this.readSignal});this.check(e,t,r);for(let d of p.resources){if(!Tc(d.path)||d.path<=a||!Tc(d.revision,128)||!Number.isSafeInteger(d.size)||d.size<0||d.state!=="confirmed")throw Vt("catalog_response");a=d.path;let u=Object.freeze({path:d.path,revision:d.revision,size:d.size,state:d.state});if(c+=new TextEncoder().encode(JSON.stringify(u)).length,o.length>=pD||c>dD)throw Vt("budget");o.push(u)}if(p.complete===!0&&p.cursor===void 0)return o;if(p.complete!==!1||!Tc(p.cursor)||s.has(p.cursor))throw Vt("catalog_response");s.add(p.cursor),i=p.cursor}throw Vt("budget")}evaluate(e,t){let r=e.issues.filter(d=>d.severity==="error"),o=new Set;for(let d of r){let u=mD(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 i=new Set,a=new Set,c=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(c.has(d.name))return{status:"incompatible",reason:"catalog_response",paths:[],unavailable:[]};c.add(d.name)}let l,p=[];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(i.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(i.add(h.path),o.has(h.path)){if(this.declared.typeIssues!=="degrade")return s;p.some(m=>m.name===h.name)||p.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:[...i].sort(),unavailable:p}}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:qc("fenced",this.fenceDetail())})}await this.pending?.catch(()=>{})}}});function gD(n){let e=o=>o?Object.freeze({code:`readiness_${o.reason}`,...o.detail?{detail:o.detail}:{}}):null,t=e(n.problem),r=n.assessment?.unavailableTypes;return Object.freeze({checking:n.checking,assessment:n.assessment?Object.freeze({status:n.assessment.status,problem:e(n.assessment.problem),...r?.length?{unavailableTypes:r}:{}}):null,problem:t})}var lE,yD,gu,Ni,yg,cE=I(()=>{"use strict";Ep();ie();k0();lE=["configuration","files"],yD=["people","notifications"],gu=class extends Error{constructor(t,r){super("SDK application readiness unavailable");this.code=t;this.detail=r;this.name="ApplicationReadinessError"}code;detail},Ni=(n,e=!1,t)=>Object.freeze({checking:e,assessment:null,problem:n?Object.freeze({code:n,...t?{detail:t}:{}}):null});yg=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?aE(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(X(e)){let t=Ts(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=Ni(e?"readiness_unsupported":"readiness_fenced"),r=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;r=h?Ni("readiness_fenced",!1,h):gD(u)}let o=u=>{if(!e)return t;let f=this.sources[u];if(!f)return Ni(`${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 Ni(`${u}_unavailable`)}},s=Object.freeze({capabilities:r,contracts:r,configuration:o("configuration"),files:o("files"),people:o("people"),notifications:o("notifications")}),i=[s.capabilities,s.contracts,s.configuration,s.files],a=e&&(this.checking||i.some(u=>u.checking)),c=null,l=null;if(!e)l=Object.freeze({code:"readiness_fenced"});else if(!a){let u=["capabilities","contracts",...lE].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`})),i.every(f=>f.assessment!==null)){let f=s.configuration.assessment?.status==="setup_required",h=y=>y.assessment?.status==="incompatible"&&!(f&&y===r&&y.assessment.problem?.code==="readiness_contract_mismatch"),m=i.find(h),w=i.find(y=>y.assessment?.status==="setup_required"),b=m??w,g=r.assessment?.unavailableTypes;c=Object.freeze({status:m?"incompatible":w?"setup_required":"ready",problem:b?.assessment?.problem??null,...g?.length?{unavailableTypes:g}:{}})}}let p=this.fenceDetail();if(p)return this.lastReady=null,Object.freeze({checking:!1,assessment:null,problem:Object.freeze({code:this.connectionProblem(),detail:p}),facets:Object.freeze({capabilities:Ni("readiness_fenced",!1,p),contracts:Ni("readiness_fenced",!1,p),configuration:Ni("readiness_fenced",!1,p),files:Ni("readiness_fenced",!1,p),people:Ni("readiness_fenced",!1,p),notifications:Ni("readiness_fenced",!1,p)})});let d=!l||/_(changed|busy)$/.test(l.code);if(l===null&&c!==null&&!a)this.lastReady=Object.freeze({checking:a,assessment:c,problem:l,facets:s});else{if(this.lastReady&&d&&(a||c===null)&&(this.lastReady.assessment?.status==="ready"||!this.checking))return Object.freeze({...this.lastReady,facets:s});this.lastReady=null}return Object.freeze({checking:a,assessment:c,problem:l,facets:s})}refresh(e={}){let t=e.signal,r=this.fenceDetail()??(t?.aborted?"caller_aborted":null);if(r)return Promise.reject(new gu("application_readiness_fenced",r));if(this.pending)return Promise.reject(new gu("application_readiness_busy"));this.checking=!0;let o=Promise.resolve().then(async()=>{if(!this.current())return this.getSnapshot();await this.advisory;let s=[],i=async(c,l)=>{try{await l()}catch(p){let d=!1;try{d=c.getSnapshot().checking===!0}catch{}if(!d||!this.current())throw p;s.push(p)}},a=this.native;a&&await i(a,()=>a.start());for(let c of lE){let l=this.sources[c];if(!this.current())break;l&&await i(l,()=>l.refresh())}if(await this.reassessAfterSetup(),s.length)throw s[0];return this.getSnapshot()}).finally(()=>{if(this.pending!==o)return;this.pending=null,this.checking=!1;let s=(async()=>{for(let i of yD){let a=this.sources[i];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 i=this.fenceDetail()??(t?.aborted?"caller_aborted":null);if(i)throw new gu("application_readiness_fenced",i);return s})}async reassessAfterSetup(){if(!this.native||!this.current())return;let e=this.native.getSnapshot(),t=null;try{t=this.sources.configuration?.getSnapshot()??null}catch{}e.checking||e.assessment?.status!=="setup_required"||t?.checking||t?.assessment?.status!=="ready"||await this.native.start().catch(r=>{if(!(X(r)&&r.reason==="readiness_busy"))throw r})}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 bD(n){let e=new Set,t=[],r=[];for(let o of n.review?.packs??[]){if(o.status!=="conflict"&&o.status!=="downgrade")continue;let s=o.installedVersion?Ms(o.installedVersion,o.version):"unknown";s==="installed_newer"&&!o.resources.some(i=>i.action==="conflict")?(e.add(o.id),r.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(r),compatible:e,major:Object.freeze(t)})}function wD(n,e){let t=n,r=t.provisions?.type_packs;return!e.size||!Array.isArray(r)?n:{...t,provisions:{...t.provisions,type_packs:r.filter(o=>!(typeof o?.manifest?.id=="string"&&e.has(o.manifest.id)))}}}function dE(n){return new Proxy({},{get(e,t){let r=Reflect.get(n,t,n);return typeof r!="function"?r:async(...o)=>{let s=o.find(a=>a instanceof AbortSignal),i=Date.now()+vD;for(let a=25;;a=Math.min(a*2,500))try{return await r.apply(n,o)}catch(c){if(!(c instanceof Rr&&c.reason==="busy")||!s)throw c;if(Date.now()+a>i)throw Je("busy_timeout");await _D(a,s)}}}})}function fE(n,e){let t=Object.freeze({...n,scope:Object.freeze({...n.scope}),journal:dE(n.journal)});if(e&&(e=dE(e)),Object.values(t.scope).some($=>!pE.test($)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/.test($))||!pE.test(t.generation)||!["inspect","approved-new","reconcile-original"].includes(t.setupMode))throw Je("binding");let r=JSON.stringify([t.scope.account,t.scope.installation,t.scope.collection]),o=new AbortController,s=AbortSignal.any([t.signal,o.signal]),i=new Set,a=fo(),c=null,l=null,p=!1,d,u=null,f=!1,h=!1,m=0,w=!1,b=!1,g=null,y=null,_=()=>{try{return JSON.stringify([t.client.link,_0(t.client)])}catch{return null}},v=[],k=new WeakMap;function S($,Y){if($?.throwIfAborted(),p||s.aborted||t.isCurrent()!==!0||JSON.stringify([t.journal.scope.account,t.journal.scope.installation,t.journal.scope.collection])!==r||Y&&(Y.closed||t.client.currentSession()!==Y||Y.hello.collection!==t.scope.collection))throw Je("fenced")}function x($){a=Object.freeze($);for(let Y of i)try{Y()}catch{}}function P(){if(p)return;let $=_();if($!==null&&$===y)return;if(y=$,c||!a.assessment||u===null||t.client.link!=="open"){C();return}if(f){h=!0;return}f=!0;let Y=a,K=u;t.client.describe({signal:s}).then(Z=>{!p&&a===Y&&Mc(Z)!==K&&C()},()=>{p||C()}).finally(()=>{f=!1,h&&!p&&(h=!1,y=null,P())})}function C(){p||(w=!0,c||x(fo(null,!0)),R())}function R(){p||c||b||!w||(b=!0,setTimeout(()=>{if(b=!1,p||c||!w)return;let $=te(!1,{},void 0,!0);g=c,$.catch(()=>{})},m?Math.min(5e3,250*2**m):50))}function O(){if(a.assessment)try{S(void 0,d)}catch{p||s.aborted||t.isCurrent()!==!0?x(fo("configuration_fenced")):(w=!0,y=null,x(fo(null,!0)),R())}return a}async function E($,Y,K){let Z=await t.client.awaitReceipt($.mutationId,{timeoutMs:12e4,signal:s});if(S(Y,K),Z.mutation!==$.mutationId||Z.state!=="confirmed"||Z.status!=="applied"||(Z.conflicts?.length??0)!==0||Z.published==="publishing"||Z.published==="not_published")throw Je("recovery_required");return Z}async function j($,Y,K){let Z,_e=0,re=0,ne=new Set,Ke=new Set,Ve=new TextEncoder;for(let Ft=0;Ft<64;Ft++){S(Y,K);let Re=await t.client.resources.list({text:!1,limit:128,...Z===void 0?{}:{cursor:Z},signal:s});if(S(Y,K),Re.resources.length>128)throw Je("recovery_required");for(let nt of Re.resources){let ci=Ve.encode(nt.path).length;if(_e++,re+=ci+128,!nt.path||ci>4096||Ke.has(nt.path)||nt.state!=="confirmed"||!S0.test(nt.revision)||!Number.isSafeInteger(nt.size)||nt.size<0||_e>4096||re>2*1024*1024||$.has(nt.path))throw Je("recovery_required");Ke.add(nt.path)}if(Re.complete===!0&&Re.cursor===void 0)return;if(Re.complete!==!1||!Re.resources.length||typeof Re.cursor!="string"||!Re.cursor||Ve.encode(Re.cursor).length>4096||ne.has(Re.cursor))throw Je("recovery_required");ne.add(Re.cursor),Z=Re.cursor}throw Je("recovery_required")}async function B($,Y,K){let Z=$.version===2?$.plan.readback:$.plan.resourceReadback,_e=new Set(Z.filter(re=>re.doc===null).map(re=>re.path));_e.size&&await j(_e,Y,K);for(let re of Z){if(re.doc===null)continue;let ne=await t.client.resources.get(re.path,{signal:s});if(S(Y,K),ne.path!==re.path||ne.text!==re.doc||ne.state!=="confirmed")throw Je("recovery_required")}if($.version!==2)for(let re of $.plan.sources){let ne=await t.client.get(re.id,{signal:s});if(S(Y,K),ne.id!==re.id||ne.path!==re.path||ne.state.state!=="confirmed"||ne.state.hold||ne.state.unresolved)throw Je("recovery_required")}}async function D($,Y,K){return await E($,Y,K),$.phase==="attempted"&&($=$.version===2?await t.journal.recordConfirmed($.mutationId,s):await t.journal.recordResourceConfirmed($.mutationId,s),S(Y,K)),$.phase==="verified"||(await B($,Y,K),$.phase==="confirmed"&&($=$.version===2?await t.journal.recordVerified($.mutationId,s):await t.journal.recordResourceVerified($.mutationId,s),S(Y,K))),$}async function J($,Y){let K=await t.journal.load(s);if(S($,Y),!K)return{journaled:!1,previous:null};if(K=Jt(K,t.scope),K.version===1||K.phase==="prepared")throw Je("recovery_required");if(K.phase==="attempted"&&(K.version===3||K.version===4)&&t.journal.recordResourceRejected){let Z=await t.client.awaitReceipt(K.mutationId,{timeoutMs:12e4,signal:s});S($,Y),Z.mutation===K.mutationId&&Z.state==="rejected"&&(K=Jt(await t.journal.recordResourceRejected(K.mutationId,s),t.scope),S($,Y))}if(K.version===1)throw Je("recovery_required");return K.phase==="rejected"?{journaled:!0,previous:K.version===4?K.previous:null}:{journaled:!0,previous:await D(K,$,Y)}}async function V($,Y){let K=t.compiledManifest.manifest,Z=await P0(e.assess(K,s,$),$),_e=Z;Z.status==="conflict"&&!Z.review&&(_e=await e.assess(K,s,Or({})));let re=bD(_e);if(!re.compatible.size)return{assessed:Z,manifest:K,newer:re};let ne=wD(K,re.compatible),Ke=Y?$??Or({}):$;return Z=await P0(e.assess(ne,s,Ke),Ke),{assessed:Z,manifest:ne,newer:re}}async function U($,Y,K={}){S(Y);let Z=await t.client.readyForRead(s);S(Y,Z),v.length||(y=_(),v.push(t.client.onStatus(bo=>{A0(bo)&&(y=null),P()}),t.client.onLink(P))),w=!1;let{journaled:_e,previous:re}=await J(Y,Z);if(!e)throw Je("unsupported");let ne=null;try{ne=Mc(await t.client.describe({signal:s}))}catch{}S(Y,Z);let Ke=await V(K.decisions,!1),Ve=Ke.assessed,Ft=Ke.manifest;if(S(Y,Z),!S0.test(Ve.assessmentDigest)||!["current","provision","conflict"].includes(Ve.status))throw Je("response");if(K.expected!==void 0&&Ve.assessmentDigest!==K.expected)throw x0();let Re=!_e&&t.setupMode==="approved-new";if(Ve.status==="provision"&&($||Re)){if(t.setupMode==="reconcile-original")throw Je("recovery_required");if(!(t.compiledManifest.operations.includes("apply_collection_setup")||t.compiledManifest.operations.includes("apply_type_pack"))||!Z.hello.grant.capabilities.includes("definitions.manage"))throw Je("not_authorized");let bo=K.records??[];if(bo.length&&!Z.hello.grant.capabilities.includes("records.create"))throw Je("not_authorized");let hs=$t(await P0(e.apply(Ft,Ve.assessmentDigest,s,K.decisions),K.decisions));if(S(Y,Z),hs.assessmentDigest!==Ve.assessmentDigest)throw Je("response");if(hs.sources.length)throw Je("unsupported_source_provision");let Un=bo.length?$t({...hs,sources:bo.map(jr=>({id:crypto.randomUUID(),path:jr.path,document:jr.document}))}):hs,cn;if(re){if(!t.journal.prepareResourceRound)throw Je("recovery_required");cn=await t.journal.prepareResourceRound(Un,re.mutationId,s)}else cn=await t.journal.prepareResources(Un,s);if(S(Y,Z),cn=Jt(cn,t.scope),cn.version!==3&&cn.version!==4||cn.phase!=="prepared"||JSON.stringify(cn.plan)!==JSON.stringify(Un))throw Je("recovery_required");let wo=Jt(await t.journal.recordResourceAttempt(cn.mutationId,s),t.scope);if(S(Y,Z),wo.version!==3&&wo.version!==4||wo.mutationId!==cn.mutationId||wo.phase!=="attempted"||JSON.stringify(wo.plan)!==JSON.stringify(Un))throw Je("recovery_required");let zc=[...Un.resourceOps,...Un.sources.map(jr=>({kind:"create",id:jr.id,path:jr.path,document:jr.document}))],Aa=await t.client.submit(zc,{mutationId:cn.mutationId,wait:"confirmed",signal:s});if(S(Y,Z),Aa.mutationId!==cn.mutationId)throw Je("recovery_required");let ms;try{ms=await Aa.confirmed}catch(jr){throw S(Y,Z),Aa.receipt.state!=="rejected"||!t.journal.recordResourceRejected?jr:(await t.journal.recordResourceRejected(cn.mutationId,s),S(Y,Z),x0(cn.mutationId,jr))}if(S(Y,Z),ms.state!=="confirmed"||ms.status!=="applied"||(ms.conflicts?.length??0)!==0)throw Je("recovery_required");await D(wo,Y,Z),w=!1,y=_();try{ne=Mc(await t.client.describe({signal:s}))}catch{ne=null}if(Ve=await e.assess(Ft,s),S(Y,Z),Ve.status!=="current"||!S0.test(Ve.assessmentDigest))throw Je("recovery_required")}let nt=Ve.status==="conflict"&&Ke.newer.major.length>0,ci=Ve.status==="conflict"?nt?"installed_newer":"setup_conflict":null,yo=ci?Object.freeze({code:ci}):null,go=Object.freeze({status:Ve.status==="current"?"ready":nt?"incompatible":"setup_required",problem:yo});d=Z,u=ne;let Di=Object.freeze({checking:!1,assessment:go,problem:yo});return m=0,x(w?fo(null,!0):Di),S(Y,Z),Di}function ce($={}){try{S($.signal)}catch(Z){return Promise.reject(Z)}let Y=c,K=(Y?Y.then(()=>{},()=>{}):Promise.resolve()).then(()=>ee($));return c=K,K.finally(()=>{c===K&&(c=null)}).catch(()=>{}),K}async function ee($){let Y=iy($.records),K=Or($.adopt===void 0?{}:{adopt:$.adopt}),Z=AbortSignal.any([s,...$.signal?[$.signal]:[]]),_e=await t.client.readyForRead(s);if(S(Z,_e),await J(Z,_e),!e)throw Je("unsupported");let{assessed:re,newer:ne}=await V(K,!0);if(S(Z,_e),!re.review)throw Je("response");let Ke=[];if(re.status!=="current")for(let Re of Y){let nt=await t.client.find({path:Re.path},{signal:s});S(Z,_e),Ke.push({path:Re.path,free:nt===null})}let Ve=_e.hello.grant.capabilities,Ft=Nd(re,{records:Ke,canManage:Ve.includes("definitions.manage")&&(t.compiledManifest.operations.includes("apply_collection_setup")||t.compiledManifest.operations.includes("apply_type_pack")),canCreateRecords:Ve.includes("records.create"),newer:ne});return k.set(Ft,Object.freeze({decisions:K,records:Y.filter(Re=>Ke.some(nt=>nt.path===Re.path&&nt.free))})),Ft}function te($,Y={},K,Z=!1){try{S(Y.signal)}catch(ne){return Promise.reject(ne)}if(c&&c===g){let ne=c;return ne.then(()=>{},()=>{}).then(()=>c&&c!==ne?Promise.reject(Je("busy")):te($,Y,K))}if(c)return Promise.reject(Je("busy"));let _e=AbortSignal.any([s,...Y.signal?[Y.signal]:[]]),re=Promise.resolve().then(()=>U($,_e,K)).catch(ne=>{let Ke=s.aborted||_e.aborted,Ve=X(ne)&&ne.reason==="configuration_busy_timeout";Ve&&(w=!1);let Ft=!Ke&&!Ve&&(w||uE(ne));throw Ft&&uE(ne)&&(w=!0,m=Math.min(m+1,4)),!Ke&&!Ve&&!w&&Z&&m<5&&!p&&t.isCurrent()===!0&&(m++,w=!0,Ft=!0),x(Ft?fo(null,!0):fo(Ke?"configuration_fenced":Ve?"configuration_busy_timeout":"configuration_unavailable")),ne});return c=re,x(fo(null,!0)),re.finally(()=>{c===re&&(c=null),g===re&&(g=null),R()}).catch(()=>{}),re.then(ne=>(S(_e,d),ne))}let Ce=()=>{if(!l){p=!0,t.signal.removeEventListener("abort",et),o.abort();for(let Y of v.splice(0))Y();x(fo("configuration_fenced"));let $=c;l=Promise.resolve().then(async()=>{await $})}return l},et=()=>{Ce().catch(()=>{})};return t.signal.addEventListener("abort",et,{once:!0}),Object.freeze({getSnapshot:O,subscribe($){return i.add($),()=>{i.delete($)}},assess:$=>te(!1,$),configure:$=>te(!0,$),plan:ce,async apply($,Y={}){let K=k.get($);if(!K)throw new TypeError("setup.apply needs a plan returned by setup.plan");if($.refusal)throw A($.refusal.code==="setup_conflict"?"conflict":$.refusal.code==="installed_newer"?"upgrade_required":"forbidden",$.refusal.message,$.refusal.code);if($.status==="current"){await te(!1,Y,{decisions:K.decisions,expected:$.digest});return}await te(!0,Y,{decisions:K.decisions,expected:$.digest,records:K.records})},close:Ce})}var pE,S0,Je,x0,P0,vD,_D,uE,fo,hE=I(()=>{"use strict";ie();Js();k0();es();Gf();oy();pE=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,S0=/^sha256:[0-9a-f]{64}$/,Je=n=>A("unavailable","application configuration unavailable",`configuration_${n}`),x0=(n,e)=>new oe(A("conflict","This collection changed since the setup was reviewed. Review it again.","setup_changed").toProblem(),{...n?{mutationId:n}:{},...e===void 0?{}:{cause:e}}),P0=async(n,e)=>{try{return await n}catch(t){throw e?.adopt&&Object.keys(e.adopt).length&&X(t,"unavailable")&&t.reason==="resource_setup_unavailable"?x0(void 0,t):t}};vD=15e3,_D=(n,e)=>new Promise((t,r)=>{if(e.aborted){r(e.reason);return}let o=()=>{clearTimeout(s),r(e.reason)},s=setTimeout(()=>{e.removeEventListener("abort",o),t()},n);e.addEventListener("abort",o,{once:!0})});uE=n=>X(n)&&n.reason==="configuration_busy",fo=(n=null,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n?Object.freeze({code:n}):null})});function mE(n){return{issuer:n.issuer,subject:n.subject,name:n.name,...n.accountId===void 0?{}:{account_id:n.accountId}}}function yE(n){let e=n.scope,t=e.account,r=e.installation,o=e.collection,s=n.generation,i=n.signal,a=n.people,c=n.isCurrent.bind(n),l=typeof a?.current=="function"?a.current.bind(a):void 0,p=typeof a?.members=="function"?a.members.bind(a):void 0,d=new Set,u=_a(null),f=!1,h=!1,m=null;function w(){try{return f||i.aborted||c()!==!0?!1:!f&&!i.aborted&&n.scope===e&&n.generation===s&&n.signal===i&&n.people===a&&!!s&&s.length<=256&&[t,r,o].every(k=>typeof k=="string"&&!!k&&k.length<=128)&&e.account===t&&e.installation===r&&e.collection===o}catch{return!1}}function b(k){u=w()?k:ho;for(let S of[...d])try{S()}catch{}w()||(u=ho)}function g(){return w()||(u=ho),u}function y(){if(!f){f=!0,i.removeEventListener("abort",y),u=ho;for(let k of[...d])try{k()}catch{}d.clear()}}i.addEventListener("abort",y,{once:!0}),i.aborted&&y();function _(k,S){return!w()||S?.aborted?Promise.reject(bu()):new Promise((x,P)=>{let C=!1,R=(j,B)=>{C||(C=!0,S?.removeEventListener("abort",O),i.removeEventListener("abort",O),d.delete(E),B!==void 0?P(B):x(j))},O=()=>R(void 0,bu()),E=()=>{w()||O()};d.add(E),S?.addEventListener("abort",O,{once:!0}),i.addEventListener("abort",O,{once:!0}),k.then(()=>{!w()||S?.aborted?O():R(g())},()=>R(void 0,bu())),(!w()||S?.aborted)&&O()})}function v(k={}){let S=k.signal;if(!w()||S?.aborted)return Promise.reject(bu());if(m)return Promise.reject(A("unavailable","People readiness READ is occupied","people_readiness_busy"));let x=Promise.resolve().then(async()=>{if(!w())return ho;if(!l||!p)return _a("people_unsupported");try{let C=await l({signal:i});if(!w()||(Hl("identity",{...mE(C),...C.personSettingsUrl===void 0?{}:{person_settings_url:C.personSettingsUrl}}),!w()))return ho;let R=await p({signal:i});return w()?!Array.isArray(R)||R.length>1e3?_a("people_response"):(Hl("members",{members:Array.from(R,O=>({...mE(O),role:O.role}))}),w()?AD:ho):ho}catch{return _a(w()?"people_unavailable":"people_fenced")}});m=x,b(_a(null,!0));let P=x.then(C=>(b(C),g()),()=>(b(_a("people_unavailable")),g())).finally(()=>{m===x&&(m=null)});return _(P,S)}return Object.freeze({getSnapshot:g,subscribe(k){return f?()=>{}:(d.add(k),()=>{d.delete(k)})},start(k={}){return h?_(m??Promise.resolve(g()),k.signal):!w()||k.signal?.aborted?Promise.reject(bu()):(h=!0,v(k))},refresh:v,close:y})}var _a,ho,AD,bu,gE=I(()=>{"use strict";qd();ie();_a=(n,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n===null?null:Object.freeze({code:n})}),ho=_a("people_fenced"),AD=Object.freeze({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null}),bu=()=>A("cancelled","People readiness ended","people_readiness_fenced")});function gg(n){if(!n||!Array.isArray(n.criteria))return Object.freeze([]);let e=n.criteria.filter(t=>t?.event?.id===tm.id&&t.event.version===tm.version&&t.event.digest===tm.digest).map(t=>t.id);return Object.freeze([...new Set(e)])}var C0=I(()=>{"use strict";dd()});function bE(n){let e=n.scope,t=e.account,r=e.installation,o=e.collection,s=n.generation,i=n.signal,a=n.isCurrent.bind(n),c=n.notifications,l=c?.declaration,p=c?.timerNamespace,d=n.timers,u=typeof d?.list=="function"?d.list.bind(d):void 0,f=new Set,h=li(null),m=!1,w=!1,b=null;function g(){try{return m||i.aborted||a()!==!0?!1:!m&&!i.aborted&&n.signal===i&&n.scope===e&&n.generation===s&&!!s&&s.length<=256&&[t,r,o].every(x=>typeof x=="string"&&!!x&&x.length<=128)&&e.account===t&&e.installation===r&&e.collection===o&&n.notifications===c&&c?.declaration===l&&c?.timerNamespace===p&&n.timers===d}catch{return!1}}function y(x){h=g()?x:bg;for(let P of[...f])try{P()}catch{}g()||(h=bg)}function _(){return g()||(h=bg),h}function v(){if(!m){m=!0,i.removeEventListener("abort",v),h=bg;for(let x of[...f])try{x()}catch{}f.clear()}}i.addEventListener("abort",v,{once:!0}),i.aborted&&v();function k(x,P){return!g()||P?.aborted?Promise.reject(wu()):new Promise((C,R)=>{let O=!1,E=(D,J)=>{O||(O=!0,P?.removeEventListener("abort",j),i.removeEventListener("abort",j),f.delete(B),J!==void 0?R(J):C(D))},j=()=>E(void 0,wu()),B=()=>{g()||j()};f.add(B),P?.addEventListener("abort",j,{once:!0}),i.addEventListener("abort",j,{once:!0}),x.then(()=>{!g()||P?.aborted?j():E(_())},()=>E(void 0,wu())),(!g()||P?.aborted)&&j()})}function S(x={}){let P=x.signal;if(!g()||P?.aborted)return Promise.reject(wu());if(b)return Promise.reject(A("unavailable","Notification readiness READ is occupied","notification_readiness_busy"));let C=Promise.resolve().then(async()=>{if(!g())return li("notifications_fenced");if(l===null&&c&&Object.hasOwn(c,"declaration"))return Object.freeze({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null});if(!u&&gg(l).length)return li("notifications_consent_required");if(!l||typeof l!="object"||!u||typeof p!="string"||!/^[A-Za-z0-9._-]{1,64}$/.test(p))return li("notifications_unsupported");try{let O=await u(p,{signal:i});return g()?!O||O.namespace!==p||!Array.isArray(O.timers)||O.timers.length>1e4?li("notifications_response"):li("notifications_unsupported"):li("notifications_fenced")}catch{return li(g()?"notifications_unavailable":"notifications_fenced")}});b=C,y(li(null,!0));let R=C.then(O=>(y(O),_()),()=>(y(li("notifications_unavailable")),_())).finally(()=>{b===C&&(b=null)});return k(R,P)}return Object.freeze({getSnapshot:_,subscribe(x){return m?()=>{}:(f.add(x),()=>{f.delete(x)})},start(x={}){return w?k(b??Promise.resolve(_()),x.signal):!g()||x.signal?.aborted?Promise.reject(wu()):(w=!0,S(x))},refresh:S,close:v})}var kD,li,bg,wu,wE=I(()=>{"use strict";ie();C0();kD=n=>Object.freeze({code:n}),li=(n,e=!1)=>Object.freeze({checking:e,assessment:null,problem:n===null?null:kD(n)}),bg=li("notifications_fenced"),wu=()=>A("cancelled","Notification readiness ended","notification_readiness_fenced")});function AE(n){let e=new Set,t=!1,r=()=>{if(t||!n.isCurrent())return vE;let s=n.declaration;if(!s)return I0;let i;try{i=n.grant()}catch{return SD}return i?s.required.some(a=>!i.actions.includes(a))?_E("files_access_missing"):n.scope==="collection"&&i.scope.kind!=="collection"?_E("files_scope_missing"):I0:I0},o=r();return Object.freeze({getSnapshot:()=>t||!n.isCurrent()?vE:o,subscribe(s){return t?()=>{}:(e.add(s),()=>{e.delete(s)})},async refresh(){let s=r();if(s!==o){o=s;for(let i of[...e])try{i()}catch{}}return o},close(){t=!0,e.clear()}})}var wg,I0,vE,SD,_E,kE=I(()=>{"use strict";wg=n=>Object.freeze(n),I0=wg({checking:!1,assessment:Object.freeze({status:"ready",problem:null}),problem:null}),vE=wg({checking:!1,assessment:null,problem:Object.freeze({code:"files_fenced"})}),SD=wg({checking:!1,assessment:null,problem:Object.freeze({code:"files_unavailable"})}),_E=n=>wg({checking:!1,assessment:Object.freeze({status:"incompatible",problem:Object.freeze({code:n})}),problem:null})});var vg,SE=I(()=>{"use strict";g0();cE();hE();gE();wE();C0();yp();Zm();kE();vg=class{constructor(e,t,r,o="block",s=()=>[]){this.typeIssues=o;this.consented=s;this.compiled=e,this.signal=r,this.ui=new Ec(t,r,gg(this.compiled.manifest.notifications)),r.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,r){let o=this.epoch,s=()=>!this.signal.aborted&&!this.closing&&!this.retiring&&this.epoch===o&&r(),i=!!this.opening||!!this.selected||!!this.retiring||!!this.closing,a=this.ui.adopt(e,{caller:t,isCurrent:s});if(i)return a;let c=null,l=[],p=a.then(d=>{if(!s()||t.aborted)throw new ln("application_connection_fenced");let u=this.ui.owned();if(!u)throw new ln("application_connection_binding");let f=Xm(this.compiled);f&&LS(d.files,nO(f,()=>this.consented(d.id)));let h=new AbortController,m=AbortSignal.any([this.signal,h.signal]);c=h;let w=()=>s()&&d.isCurrent(),b={scope:d.scope,generation:d.generation,signal:m,isCurrent:w},g=fE({client:d.records,compiledManifest:this.compiled,journal:u.journal,...b,setupMode:u.setupMode},u.resourceSetup);l.push(()=>g.close());let y={getSnapshot:g.getSnapshot,subscribe:g.subscribe,refresh:g.assess,close:g.close},_=yE({people:d.people,...b});l.push(()=>_.close());let v=this.compiled.manifest.notifications,k=bE({notifications:{declaration:v?.criteria?.length?v:null},timers:d.timers,...b});l.push(()=>k.close());let S=this.compiled.manifest.requirements.files?.scope?.kind,x=AE({declaration:f,scope:typeof S=="string"?S:null,grant:()=>d.files.grant,isCurrent:w});l.push(()=>x.close());let P=this.compiled.nativeCapabilities?{...this.compiled.nativeCapabilities,contracts:this.compiled.manifest.requirements.contracts,typeIssues:this.typeIssues}:null,C=new yg({connection:d,nativeRequirements:P,signal:m,isCurrent:w,configuration:y,files:x,people:_,notifications:k}),R=C.subscribe(this.changed);return this.selected={connection:d,lifetime:h,readiness:C,configuration:g,unsubscribe:R},c=null,l.length=0,this.changed(),d}).catch(async d=>{c?.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===p&&(this.opening=null)});return this.opening=p,p}assess(e={}){return!this.selected||!this.selected.connection.isCurrent()||this.retiring||this.closing?Promise.reject(new ln("application_connection_fenced")):this.selected.readiness.refresh(e)}async configure(e={}){let t=this.selected,r=this.epoch;if(!t||!t.connection.isCurrent()||this.retiring||this.closing)throw new ln("application_connection_fenced");if(await t.configuration.configure(e),e.signal?.aborted||this.epoch!==r||this.selected!==t||!t.connection.isCurrent())throw new ln("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 ln("application_connection_fenced")):t.configuration.plan(e)}async applySetup(e,t={}){let r=this.selected,o=this.epoch;if(!r||!r.connection.isCurrent()||this.retiring||this.closing)throw new ln("application_connection_fenced");if(await r.configuration.apply(e,t),t.signal?.aborted||this.epoch!==o||this.selected!==r||!r.connection.isCurrent())throw new ln("application_connection_fenced");return r.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 r=this.ui.retire(),o=Promise.resolve().then(async()=>{let i=(await Promise.allSettled([r,t?.catch(()=>{}),e?.readiness.close()])).find(a=>a.status==="rejected");if(i?.status==="rejected")throw i.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 O0(n,e){return!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!==e.split(",").sort().join()?Lc():n}function R0(n){(typeof n!="string"||!PD.test(n)||/^0{8}-0{4}-0{4}-0{4}-0{12}$/.test(n))&&Lc()}function PE(n){let e=O0(n,"rpc,action,value");if((!Number.isSafeInteger(e.rpc)||e.rpc<1||e.rpc>4294967295)&&Lc(),e.action==="cancel")e.value!==null&&Lc();else if(e.action==="prepare"){let t=O0(e.value,`requestId,accountId,appId,challenge${Object.hasOwn(e.value,"authorizationId")?",authorizationId":""}`);for(let r of["requestId","accountId","appId"])R0(t[r]);t.authorizationId!==void 0&&R0(t.authorizationId),(typeof t.challenge!="string"||!/^[0-9a-f]{64}$/.test(t.challenge))&&Lc()}else if(e.action==="finish"){let t=O0(e.value,"requestId,authorizationRequestId,collectionId");for(let r of Object.keys(t))R0(t[r])}else Lc();return Object.freeze({...e,value:e.value===null?null:Object.freeze({...e.value})})}var PD,Lc,xE=I(()=>{"use strict";Od();PD=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,Lc=()=>{throw new xe("application_worker_binding")}});function E0(n){if(!n||typeof n!="object"||Array.isArray(n))throw new xe("application_worker_binding");let e=n,t=e.unlock;if(e.status==="needs_unlock"!=(t!=null)||t!=null&&(typeof t!="object"||!["password","strict","none"].includes(t.mode)||typeof t.unlocking!="boolean"||!(t.problem===null||typeof t.problem=="string"&&/^[a-z][a-z0-9_]{0,63}$/.test(t.problem))))throw new xe("application_worker_binding");if(!["not_started","starting","signed_out","authorizing","unselected","opening","setup_required","ready","blocked","closed","needs_unlock"].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))||!(e.unsynced==null||typeof e.unsynced=="object"&&e.unsynced.collectionId===e.selectedCollectionId&&typeof e.unsynced.sessionStatus=="string")||!(e.unsyncedWork==null||typeof e.unsyncedWork=="object"&&Number.isSafeInteger(e.unsyncedWork.since)&&e.unsyncedWork.since>=0))throw new xe("application_worker_binding");return Object.freeze({...e,openingProgress:hm(e.openingProgress)?e.openingProgress:null})}var jc,_g,CE=I(()=>{"use strict";Gv();xE();Od();jc=class extends Error{constructor(t){super("SDK application operation unavailable");this.code=t;this.name="ApplicationWorkerReplyError"}code};_g=class{port;binding;owner;nextId=0;active=null;portal=null;fault=null;stopping=null;stopReply=null;watch=null;closedPortal=null;abandoned=!1;constructor(e,t,r){if(!uI(t))throw new xe("application_worker_binding");this.port=e,this.binding=t,this.owner=Object.freeze({...r}),e.addEventListener("message",this.message),e.addEventListener("messageerror",this.messageError),e.start()}id(){if(this.nextId===Rm)throw new xe("application_worker_stop_failed");return++this.nextId}send(e,t,r){let o=u_([cr,this.binding,e,t,r],this.binding);try{this.port.postMessage(o)}catch{throw this.quarantine("application_worker_unavailable"),this.fault}}request(e,t,r,o){if(this.fault||this.stopping||r.aborted)return Promise.reject(this.fault??new xe("application_worker_fenced"));if(this.active)return Promise.reject(new xe("application_worker_busy"));let s;try{s=this.id(),u_([cr,this.binding,s,e,t],this.binding)}catch(c){return Promise.reject(c)}if(o){if(!["authorize","renewExpiredPairing","requestFileAccess"].includes(e))return Promise.reject(new xe("application_worker_binding"));this.portal?.life.abort(),this.portal&&(this.closedPortal=this.portal.id);try{this.portal?.value.close()}catch{return this.quarantine("application_worker_stop_failed"),Promise.reject(this.fault)}this.portal={id:s,value:o,caller:r,life:new AbortController,lastRpc:0,busy:!1},this.watchPortal()}let i,a=new Promise(c=>{i=c});return new Promise((c,l)=>{let p={id:s,caller:r,done:a,finish:i,resolve:c,reject:l,fenced:!1,reply:!1,handoff:null,cancel:()=>{p.fenced=!0,l(new xe("application_worker_fenced"))}};this.active=p,r.addEventListener("abort",p.cancel,{once:!0});try{this.send(s,e,t)}catch(d){l(d)}r.aborted&&p.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,this.closedPortal=e.id);try{this.send(0,"approvalClosed",!0)}catch{}}},500))}messageError=()=>this.quarantine("application_worker_unavailable");quarantine(e){if(!this.fault){this.fault=new xe(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]!==cr||t[1]!==this.binding||!Number.isInteger(t[3])||t[3]<0||t[3]>Rm)throw new xe("application_worker_binding");if(this.fault)return;let[,,r,o,s]=t;if(r==="nativeSnapshot"){if(o!==0)throw new xe("application_worker_binding");let l=E0(s);this.stopping||this.owner.snapshot(l);return}if(r==="fatal"){if(o!==0)throw new xe("application_worker_binding");this.quarantine("application_worker_stop_failed");return}if(r==="nativeAuthorization"){let l=PE(s),p=this.portal;if(o===this.closedPortal&&p?.id!==o){l.action!=="cancel"&&this.port.postMessage([cr,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!1}]);return}if(!p||p.id!==o||this.stopping||p.caller.aborted||l.rpc<=p.lastRpc)throw new xe("application_worker_fenced");if(p.lastRpc=l.rpc,l.action==="cancel")p.life.abort();else if(p.busy)throw new xe("application_worker_binding");l.action!=="cancel"&&(p.busy=!0);let d=AbortSignal.any([p.caller,p.life.signal]);Promise.resolve().then(()=>{if(!this.owner.nativeAuthorization)throw new xe("application_worker_unavailable");return this.owner.nativeAuthorization(l,p.value,d)}).then(u=>{if(d.aborted||this.portal!==p||this.stopping)throw new xe("application_worker_fenced");this.port.postMessage([cr,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!0,value:u}])},()=>{this.port.postMessage([cr,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!1}])}).catch(()=>{try{this.port.postMessage([cr,this.binding,"nativeAuthorizationReply",o,{rpc:l.rpc,ok:!1}])}catch{}}).finally(()=>{p.busy=!1});return}if(r==="portal"){if(!s||!["navigate","focus","close"].includes(s.action))throw new xe("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(s.action==="focus")try{l.value.focus?.()}catch{}else{if(this.stopping||typeof s.uri!="string"||s.uri.length>8192)throw new xe("application_worker_binding");l.value.navigate(s.uri)}return}if(r==="handoff"&&o===0){if(!s||s.schema!=="mdbn-app-collection/1")throw new xe("application_worker_binding");let l=[s.dataPort,s.controlPort,...s.timerPort?[s.timerPort]:[]];if(l.some(p=>!(p instanceof MessagePort)))throw new xe("application_worker_binding");if(this.stopping||!this.owner.attached){for(let p of l)p.close();return}this.owner.attached(s);return}if(r==="handoff"){let l=this.active;if(!l||l.id!==o||l.reply||l.handoff)throw new xe("application_worker_binding");if(this.stopping){if(!s||s.schema!=="mdbn-app-collection/1")throw new xe("application_worker_binding");for(let p of[s.dataPort,s.controlPort,...s.timerPort?[s.timerPort]:[]]){if(!(p instanceof MessagePort))throw new xe("application_worker_binding");p.close()}l.handoff=Promise.resolve();return}l.handoff=Promise.resolve().then(()=>this.owner.handoff(s,l.caller)),l.handoff.catch(()=>{});return}if(r!=="reply"||!s||typeof s.ok!="boolean"||!s.ok&&(!s.problem||typeof s.problem.code!="string"||s.problem.code.length>128))throw new xe("application_worker_binding");let i=this.stopReply;if(i&&i.id===o){if(s.ok){let l=E0(s.snapshot);if(l.status!=="closed"||l.selectedCollectionId!==null)throw new xe("application_worker_stop_failed");i.resolve()}else i.reject(new xe("application_worker_stop_failed"));return}let a=this.active;if(!a||a.id!==o||a.reply)throw new xe("application_worker_binding");a.reply=!0;let c=s.ok?E0(s.snapshot):null;this.settle(a,c,s.ok?null:Object.freeze({code:s.problem.code}))}catch{this.quarantine("application_worker_binding")}};async settle(e,t,r){try{if(await e.handoff,e.fenced||e.caller.aborted||this.stopping||this.fault)throw this.fault??new xe("application_worker_fenced");if(r)throw new jc(r.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 xe("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 xe("application_worker_fenced"))),this.stopping=Promise.resolve().then(async()=>{if(this.fault)throw new xe("application_worker_stop_failed");this.portal?.life.abort(),this.portal?.value.close(),this.portal=null;let t=this.id();if(await new Promise((r,o)=>{this.stopReply={id:t,resolve:r,reject:o};try{this.send(t,"close",null)}catch(s){o(s)}}),await e?.done,this.fault)throw new xe("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 OE={};Ca(OE,{ApplicationRuntime:()=>T0,ApplicationRuntimeError:()=>jn});function xD(n,e){let t=()=>A("invalid_request","Pass the collection and either { password } or { recoveryKey }.","unlock_secret_invalid");if(typeof n!="string"||!e||typeof e!="object")throw t();let r=Object.hasOwn(e,"password"),o=Object.hasOwn(e,"recoveryKey");if(r===o)throw t();let s=r?e.password:e.recoveryKey;if(typeof s!="string"||!s.length)throw t();let i=new TextEncoder().encode(s);if(i.length>d_)throw i.fill(0),t();return Object.freeze([n,r?"password":"recoveryKey",i])}function IE(n){try{if(!n||!vu.test(String(n.name)))return;let e=o=>typeof o=="string"&&vu.test(o)?o:"-",t=`${n.name}:${e(n.code)}`;typeof n.stage=="string"&&vu.test(n.stage)&&(t+=`@${n.stage}`),n.cause&&vu.test(String(n.cause.name))&&(t+=` cause=${n.cause.name}:${e(n.cause.code)}`);let r=n.server?.status;return Number.isInteger(r)&&r>=100&&r<=599&&(t+=` http=${r}${n.server.code&&vu.test(n.server.code)?`:${n.server.code}`:""}`),t}catch{return}}var jn,vu,q0,T0,RE=I(()=>{"use strict";ie();Od();YR();SE();g0();At();Zm();CE();f_();jn=class extends Error{constructor(t){super("SDK application runtime unavailable");this.code=t;this.name="ApplicationRuntimeError"}code},vu=/^[A-Za-z][A-Za-z0-9_]{0,63}$/;q0=()=>{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})})},T0=class{lifetime=new AbortController;scope;worker;cpOrigin;lab;appName;sourceAdopt=null;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:q0()});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.appName=e.declaration.name,this.lab=ql(e.declaration.environment),this.scope=new vg(e.compiledManifest,{name:e.declaration.name,version:"1"},this.lifetime.signal,e.typeIssues,t=>Qm(this.raw,t)),this.worker=new _g(e.port,e.binding,{snapshot:t=>{this.closed||(this.raw=t,this.followSession(),this.publish())},handoff:(t,r)=>{if(this.sourceAdopt)return this.sourceAdopt(t,r);let o=this.epoch;return this.scope.adopt(t,r,()=>!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,unlock:null}),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 r=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,r,()=>!this.closed&&this.epoch===o).catch(s=>{throw this.portsFailed=e.scope.collection,s}),this.portsFailed=null,this.complete(this.raw,r)},r)).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,r=this.scope.selectedId();if(r!==null&&(r!==t||!e&&this.raw.status!=="opening"&&this.raw.status!=="authorizing")){let o=this.lifetime.signal;this.queue(()=>this.action(async()=>(this.scope.selectedId()===r&&(++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,unlock:null,readiness:q0()});else{let e=this.scope.getReadiness()??q0(),t=this.raw.status,r=this.raw.problem,o,s=this.raw.problemDetail,i=this.raw.selectedCollectionId,a=this.retiring&&e.problem?.code==="readiness_fenced",c=i!==null&&(this.scope.getReadiness()===null||a)&&this.portsFailed!==i;if((t==="ready"||t==="setup_required")&&c)t="opening";else if(t==="ready"||t==="setup_required"){let u=this.assessing&&!e.assessment&&e.problem?.code!=="readiness_fenced";if(t=e.checking||u?"opening":e.assessment?.status==="ready"?"ready":e.assessment?.status==="setup_required"?"setup_required":"blocked",t==="blocked"){let f=e.problem??e.assessment?.problem;r=f?.code??"application_readiness_unavailable",o=f?.detail,s=void 0}}let l=`${r}:${o??IE(s)??""}`;if(t==="blocked"&&r&&l!==this.loggedProblem){this.loggedProblem=l;try{let u=o??IE(s);u?console.error("mdbase application blocked:",r,u):console.error("mdbase application blocked:",r)}catch{}}else t!=="blocked"&&(this.loggedProblem=null);let{problemDetail:p,...d}=this.raw;this.snapshot=Object.freeze({...d,...s?{problemDetail:s}:{},status:t,problem:r,openingProgress:t==="opening"?e.checking?"checking_setup":this.raw.openingProgress??null:null,collections:Object.freeze(this.raw.collections.map(u=>Object.freeze({...u}))),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 jn("application_fenced"));if(this.pending)return Promise.reject(new jn("application_busy"));this.assessing=!0;let r=Promise.resolve().then(async()=>{if(this.closed||t.aborted)throw new jn("application_fenced");let o=await e();if(this.closed||t.aborted)throw new jn("application_fenced");return o}).finally(async()=>{(this.assessing||this.retiring)&&(this.assessing=!1,this.retiring=!1,this.publish()),await this.worker.drain(),this.pending===r&&(this.pending=null)});return this.pending=r,r}async complete(e,t){if(this.closed||t.aborted)throw new jn("application_fenced");let r=!!(e.selectedCollectionId&&this.scope.connection(e.selectedCollectionId));if(this.raw=e,this.assessing=r,this.publish(),r){try{await this.scope.assess({signal:t}).catch(()=>{})}finally{this.assessing=!1}this.publish()}if(this.closed||t.aborted)throw new jn("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={},r=null){let o=this.signal(t);return this.action(async()=>this.complete(await this.worker.request("authorize",r,o,e),o),o).catch(s=>{throw e.close(),s})}authorize(e={}){let t=this.signal(e),r;try{r=Em(qm(this.cpOrigin,t,()=>!this.closed,this.lab))}catch(o){return Promise.reject(o)}return this.authorizeReserved(r,e)}select(e,t={}){let r=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,r):this.snapshot;++this.epoch;let o=this.retireOwn();if(this.publish(),await o,this.closed||r.aborted)throw new jn("application_fenced");return this.complete(await this.worker.request("select",e,r),r)},r)}unlock(e,t,r={}){let o=this.signal(r),s;try{s=xD(e,t)}catch(a){return Promise.reject(a)}let i=()=>{s[2].fill(0)};return this.action(async()=>{if(this.raw.selectedCollectionId!==e||this.raw.status!=="needs_unlock")throw A("invalid_request","This collection is not waiting to be unlocked.","unlock_not_locked");let a;try{a=this.worker.request("unlock",s,o)}finally{i()}return this.complete(await a,o)},o).finally(i)}openUnsynced(e={}){let t=this.signal(e);return this.action(async()=>{let r=this.raw.unsynced?.collectionId??null;if(r!==null&&this.raw.selectedCollectionId===r&&(this.raw.status==="ready"||this.raw.status==="setup_required")&&this.scope.connection(r)?.isCurrent())return this.snapshot.status==="blocked"?this.complete(this.raw,t):this.snapshot;++this.epoch;let o=this.retireOwn();if(this.publish(),await o,this.closed||t.aborted)throw new jn("application_fenced");return this.complete(await this.worker.request("openUnsynced",null,t),t)},t)}async retireUnsynced(e,t,r={}){let o=this.signal(r),s=!0;return await this.queue(()=>this.action(async()=>{try{return this.complete(await this.worker.request("retireUnsynced",[e,t],o),o)}catch(i){if(i instanceof jc&&i.code==="application_worker_busy")return s=!1,this.snapshot;throw i}},o)),s}discardUnsynced(e={}){let t=this.signal(e);return this.action(async()=>{let r=this.raw.unsynced?.collectionId??null,o=r!==null&&this.raw.selectedCollectionId===r;if(o){++this.epoch;let s=this.retireOwn();if(this.publish(),await s,this.closed||t.aborted)throw new jn("application_fenced")}try{return this.complete(await this.worker.request("discardUnsynced",null,t),t)}catch(s){throw o&&s instanceof jc&&s.code==="application_worker_busy"&&!this.closed&&!t.aborted&&this.complete(await this.worker.request("openUnsynced",null,t),t),s}},t)}async withUnsyncedSource(e,t={}){let r=this.signal(t),o=new Ec({name:this.appName,version:"1"},r),s=null;try{if(await this.queue(()=>this.action(async()=>{this.sourceAdopt=(i,a)=>(s=o.adopt(i,{caller:a,isCurrent:()=>!this.closed&&!r.aborted}),s.then(()=>{}));try{await this.worker.request("attachUnsynced",null,r)}finally{this.sourceAdopt=null}return this.snapshot},r)),!s)throw new jn("application_connection_unavailable");return await e(await s,r)}finally{if(await o.close().catch(()=>{}),!this.closed){let i=this.lifetime.signal;await this.queue(()=>this.action(async()=>(await this.worker.request("detachUnsynced",null,i),this.snapshot),i)).catch(()=>{})}}}assess(e={}){let t=this.signal(e);return this.action(async()=>(await this.scope.assess({signal:t}),this.settled()),t).then(r=>r.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 jn("application_fenced")):this.scope.planSetup({...e,signal:t})}applySetup(e,t={}){let r=this.signal(t);return this.action(async()=>(await this.scope.applySetup(e,{signal:r}),this.settled()),r)}cancelAuthorization(e={}){let t=this.signal(e);return this.action(async()=>this.complete(await this.worker.request("cancelAuthorization",null,t),t),t)}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 r=this.signal(t);return this.action(async()=>(this.raw.selectedCollectionId===e&&(++this.epoch,await this.retireOwn()),this.complete(await this.worker.request("forget",e,r),r)),r)}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),r=this.raw.selectedCollectionId,o=e.discard!==!0&&r?HR(this.scope.connection(r)):0;return o>0?Promise.reject(GR(o)):this.action(async()=>(++this.epoch,await this.retireOwn(),this.complete(await this.worker.request("signOut",null,t),t)),t)}deleteCollection(e,t,r={}){let o=this.signal(r);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,r,o,s={}){let i=this.signal(s);return this.action(async()=>(this.raw=await this.worker.request("requestFileAccess",[t,r,o],i,e),this.publish(),this.snapshot),i).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 jn("application_stop_failed")}),this.publish(),this.closing)}}});var GD={};Ca(GD,{ACCOUNT_KEY_STATES:()=>Fb,API_VERSIONS:()=>df,AppHost:()=>B0,COLLECTION_UNAVAILABLE_REASONS:()=>vw,CborError:()=>Me,Client:()=>Tf,DESCRIBE_TYPING_MAX_PATHS:()=>tp,DESCRIBE_TYPING_MAX_TYPES:()=>ep,DEVICE_KINDS:()=>Bb,ERROR_CODES:()=>_u,FilesApi:()=>Na,Float64:()=>vt,HOLD_COMPARE_SCHEME:()=>Rp,HOLD_TITLE:()=>Op,IkInitiator:()=>oc,IkResponder:()=>Iy,LiveQuery:()=>Va,MAX_CONVENIENCE_BYTES:()=>uf,MAX_DEPTH:()=>qg,MDBASE_NOTIFICATION_CLICK:()=>mw,MDBASE_NOTIFICATION_TYPE:()=>Ip,MdbaseClient:()=>yi,MdbaseError:()=>oe,MdbasePeopleClient:()=>gi,NoiseError:()=>gt,PERSON_CONTRACT:()=>cw,PROBLEM_CODES:()=>px,PresenceApi:()=>Ba,READ_MANY_MAX_CONCURRENCY:()=>Hb,READ_MANY_MAX_REFS:()=>Wb,RecordReader:()=>dp,RecordSet:()=>$a,SESSION_LIFETIME_MS:()=>cA,SLOW_OPENING_MS:()=>Jf,SchemaError:()=>ae,Session:()=>Cs,TEMPORAL_HINTS:()=>Wu,TimersApi:()=>Fa,WasmRuntime:()=>Xl,Write:()=>Rs,applicationPhase:()=>qp,approvalReadiness:()=>zS,bytesEqual:()=>Mg,clientPrologue:()=>Ti,collectionUnavailableError:()=>Vn,compareVersions:()=>Sw,connect:()=>lw,controlRouteResolver:()=>BE,createMdbase:()=>ME,createViewSource:()=>kf,decode:()=>we,describeDiagnostic:()=>Wf,describeError:()=>Ts,describeHold:()=>ex,diffEdits:()=>ef,duplexCarrier:()=>uA,effectiveCapabilities:()=>LE,encode:()=>ue,encodeSecret:()=>Nn,fileGrant:()=>$b,formatSas:()=>VS,framedPort:()=>af,fromHex:()=>Bi,generateKeyPair:()=>sc,handleMdbaseNotificationClick:()=>QP,handleMdbasePush:()=>XP,holdCompareLink:()=>ww,holdNotice:()=>tx,inProcessConnector:()=>Jl,indexedDbKeyStorage:()=>D0,isCollectionUnavailableReason:()=>Wa,isConfirmed:()=>DP,isErrorCode:()=>vo,isMdbaseError:()=>X,isProtected:()=>Yi,isReadyPhase:()=>gx,isValid:()=>fq,keyPairFromSecret:()=>_R,loadOrCreateClientKey:()=>$E,localLinkConnector:()=>UE,localLinkFirstPayload:()=>U0,mdbaseError:()=>A,memoryKeyStorage:()=>N0,memoryWriteLedgerStore:()=>Cf,nextRelayConnector:()=>CR,noiseChannel:()=>pA,noiseConnector:()=>Mi,orderTargets:()=>Zd,parseCollectionAvailability:()=>wr,parseHoldCompareLink:()=>ZP,parseMdbaseNativeNotification:()=>yw,parseMdbasePush:()=>Nf,parseVersion:()=>Ja,pipeCloseError:()=>ca,portPair:()=>kS,problemCodeOf:()=>Aw,queryPages:()=>mf,readMany:()=>hf,readMdbaseNotificationData:()=>gw,readViewSourceRecord:()=>Af,recoveryFor:()=>sq,relayConnector:()=>jE,relayPipeCarrier:()=>cc,resolveRecordLinks:()=>ZS,revisionOf:()=>Dr,routeFromControl:()=>z0,sameIdentity:()=>jf,showMdbaseNotification:()=>bw,staticKeyOf:()=>xy,streamCarrier:()=>kR,structMap:()=>Tg,summarizeSync:()=>Mf,syncStatusText:()=>nx,toHex:()=>ut,toPlain:()=>gr,toValue:()=>Xe,updateViewSource:()=>Sf,uuidv7:()=>zr,valueEquals:()=>Io,versionRelation:()=>Ms,webSocketCarrier:()=>ac,wire:()=>wb});ie();Zt();Zt();Es();gf();Gb();Xb();Zb();yp();yp();ew();Ye();mi();ff();var ST=["collection_not_yet_migrated","collection_migrating","update_required","account_suspended"];function Mf(n){let e=n.status,t=e.mode==="local_only",r=n.writes??null,o=Math.max(e.pending,r?.pending.length??0),s=!t&&n.transport?n.transport.kind:null,i=n.link===void 0||n.link==="open",a=i?t?"local":n.online===!1||s==="offline"?"offline":s?"reconnecting":e.connection==="offline"?"offline":e.connection==="connecting"?"reconnecting":"online":"reconnecting",c=[],l=t?void 0:ST.find(f=>f===n.problem);l&&c.push(l),r?.rejected.length&&c.push("rejected"),e.unresolved>0&&c.push("conflicts"),e.holds>0&&c.push("held"),e.incidents.length&&c.push("incident"),o>0&&n.storageWarning&&c.push("storage_may_be_evicted");let p=a==="offline"||s!==null||!i,d=c.length?"attention":o>0&&p?"saved_on_device":a==="offline"?"offline":a==="reconnecting"?"reconnecting":o>0?"saving":!t&&(e.installing!==void 0||e.resyncing!==void 0||e.confirmedThrough<e.headKnown)?"catching_up":"saved",u=n.pendingForMs;return{state:d,connection:a,health:s,live:t||typeof n.live!="boolean"?null:n.live,pending:o,pendingFor:o===0?null:u===void 0?"while":u<2e3?"moment":u<3e4?"while":"long",writes:r,attention:c,conflicts:e.unresolved,holds:e.holds,incidents:e.incidents}}function DP(n){return n.state==="confirmed"}iw();Sp();fw();ie();var Ip="mdbase.notification",mw="mdbase.notification.click",WP=/^[\x21-\x7e]{1,256}$/,qT=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/,Eo=n=>A("invalid_request",n,"invalid_push_payload"),TT=()=>A("upgrade_required","The push uses an envelope version this SDK does not support.","unsupported_push_version");function GP(n){if(typeof n=="string")try{n=JSON.parse(n)}catch{throw Eo("The push payload is not JSON.")}else if(n&&typeof n=="object"&&typeof n.json=="function")try{n=n.json()}catch{throw Eo("The push payload is not JSON.")}if(!n||typeof n!="object"||Array.isArray(n))throw Eo("The push payload is not an object.");return n}function Ka(n,e,t){return typeof n=="string"&&n.length>=e&&n.length<=t}function YP(n){if(!n||typeof n!="object"||Array.isArray(n))return null;let e=n;return!Ka(e.title,1,80)||e.body!==void 0&&!Ka(e.body,0,160)||e.tag!==void 0&&!Ka(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 JP(n,e,t){if(n.type!==Ip)throw Eo("The payload is not an mdbase notification.");if(e!==1)throw typeof e=="number"&&Number.isSafeInteger(e)&&e>1?TT():Eo("The payload has no valid envelope version.");if(!Ka(n.signal_id,1,256)||!WP.test(n.signal_id)||!Ka(n.cursor,1,256)||!WP.test(n.cursor)||!Ka(n.criterion_id,1,100)||!qT.test(n.criterion_id))throw Eo("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 Nf(n){let e=GP(n),t=JP(e,e.version,YP(e.presentation));if(!t.presentation)throw Eo("The push has no valid presentation.");return t}function yw(n){if(!n||typeof n!="object"||Array.isArray(n))throw Eo("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 JP(e,t,null)}function gw(n){try{return yw(n)}catch{return null}}function MT(n){return{type:Ip,version:n.version,signal_id:n.signalId,criterion_id:n.criterionId,cursor:n.cursor}}async function bw(n,e,t={}){let r=Nf(e),o=r.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:MT(r)}),r}function hw(n){return globalThis[n]}function LT(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 HP(n,e,t){let r=()=>A("invalid_request",`The notification click ${t} must be on the app's own origin.`,"click_target_cross_origin");if(typeof n!="string")throw r();if(e===null){if(!n.startsWith("/")||n.startsWith("//")||n.startsWith("/\\"))throw r();return n}let o;try{o=new URL(n,`${e}/`)}catch{throw r()}if(o.origin!==e)throw r();return o.href}function XP(n,e={}){let t;try{t=GP(n.data?.text()??null)}catch{return!1}if(t.type!==Ip)return!1;let r=e.registration??hw("registration");if(!r)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{Nf(t)}catch(s){let i=s instanceof oe&&s.reason==="unsupported_push_version"?YP(t.presentation):null;if(!i)throw s;return await r.showNotification(i.title,{...i.body?{body:i.body}:{},...i.tag?{tag:i.tag}:{},...o}),null}return bw(r,t,o)})()),!0}function QP(n,e={}){let t=gw(n.notification.data);if(!t)return!1;n.notification.close();let r=e.clients??hw("clients"),o=hw("registration")?.scope,s=LT(o),i=e.scope===void 0?o:HP(e.scope,s,"scope"),a=e.url===void 0?i??"/":HP(e.url,s,"url");return r&&n.waitUntil((async()=>{let l=(await r.matchAll({type:"window",includeUncontrolled:!0})).find(d=>!i||d.url.startsWith(i));if(!l)return r.openWindow(a);await l.focus();let p={type:mw,notification:t};return l.postMessage(p),l})()),!0}var Op="mdbase protected your edit",jT={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."}},UT={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}},NT={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"]},Rp="mdbase://hold/compare",Df=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ww(n,e){if(!Df.test(n)||!Df.test(e))throw new Error("holdCompareLink: collection and id are UUIDs");return`${Rp}?collection=${n.toLowerCase()}&id=${e.toLowerCase()}`}function ZP(n){if(typeof n!="string"||n.length>512||!n.startsWith(`${Rp}?`))return null;let e=new URLSearchParams(n.slice(Rp.length+1)),t=e.get("collection")??"",r=e.get("id")??"";return!Df.test(t)||!Df.test(r)?null:{collectionId:t.toLowerCase(),id:r.toLowerCase()}}function ex(n,e){let t=n.reason==="read_only",r=n.theirs!==void 0,o=(e.canCompare??!0)&&r,s=c=>!c||!e.capabilities||e.capabilities.includes(c),i=NT[n.reason].filter(c=>c==="compare"?o:(!t||e.host===!0)&&(c!=="take_theirs"||r||t)).map(c=>{let l={action:c,...UT[c]};return t&&c==="take_theirs"&&(l.label="Discard local changes",l.description="Discard unsynced changes on this device.",l.needs="collection.read"),l}).filter(c=>s(c.needs)),a=jT[n.reason];return{id:n.id,path:n.path,reason:n.reason,title:Op,cause:a.cause,detail:a.detail,since:n.since,saves:n.saves,hasTheirs:r,actions:i,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?ww(e.collectionId,n.id):null}}function tx(n){return n.length?n.length===1?`${Op}: ${n[0].path} is waiting for your choice.`:`${Op}: ${n.length} files are waiting for your choice.`:null}function nx(n){let e=(r,o)=>`${r} ${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}`}Ep();Gf();Ep();var Jf=15e3,Yf=(n,e)=>{try{return!!n&&n.id===e&&n.isCurrent()}catch{return!1}},Ls=(n,e)=>Ts(n,e),Zi=(n,e)=>Ls(n,e);function qp(n,e={}){let t=oM(n,e),r=sM(t,n,e);return r.kind==="opening"&&n.status==="opening"&&n.selectedCollectionId===r.collectionId&&n.openingProgress?{...r,progress:n.openingProgress}:r}function oM(n,e){let t={...e.cpOrigin?{cpOrigin:e.cpOrigin}:{},...e.messages?{messages:e.messages}:{}},r=n.selection,o=r?.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:Zi(n.problem,t)};if(r?.state==="invalid")return{kind:"problem",collectionId:null,problem:Zi(r.problem??"application_selection_invalid",t)};let s=n.signIn?.state==="paired";if(r?.state==="approving"||n.status==="authorizing"){let p=r?.approval??null;return s?p?.kind==="add"?{kind:"authorizing",purpose:"add",collectionId:null}:{kind:"authorizing",purpose:"approve",collectionId:p?.collectionId??o?.collectionId??null}:{kind:"authorizing",purpose:"sign_in",collectionId:p?.collectionId??o?.collectionId??null}}let i=n.unsynced??null;if(i&&n.selectedCollectionId===i.collectionId){let p=i.collectionId;return n.status==="ready"&&Yf(e.connection,p)?{kind:"unsynced",collectionId:p,connection:e.connection,rechecking:n.readiness.checking}:n.status==="blocked"||n.status==="setup_required"&&!n.readiness.checking&&n.readiness.assessment?{kind:"problem",collectionId:p,problem:(n.status==="blocked"?Ls(n,t):Ls(n.readiness,t))??Zi("open_failed",t)}:{kind:"opening",collectionId:p,displayName:null,slow:!!e.slow}}if(n.status==="not_started"||n.status==="starting"){let p=o?.collectionId??null;return p&&n.status==="starting"?{kind:"opening",collectionId:p,displayName:o?.displayName??null,slow:!!e.slow}:{kind:"starting"}}if(n.status==="signed_out")return e.openingUnsynced&&!n.problem?{kind:"starting"}:{kind:"signed_out",notice:n.problem?Ls(n,t):null};if(n.status==="blocked"){let p=n.selectedCollectionId??o?.collectionId??null;return n.problem==="recovery_account_mismatch"?{kind:"problem",collectionId:p,problem:Ts(n,{...t,recoveryAccountLabel:n.recoveryAccountLabel})}:{kind:"problem",collectionId:p,problem:p&&n.removedScopeIds?.includes(p)?Zi("installation_scope_removed",t):Ls(n,t)??Zi("open_failed",t)}}if(n.status==="needs_unlock"&&n.selectedCollectionId){let p=n.selectedCollectionId,d=n.unlock??null;return d?{kind:"needs_unlock",collectionId:p,displayName:n.collections.find(u=>u.collectionId===p)?.displayName??o?.displayName??null,mode:d.mode,unlocking:d.unlocking,problem:d.problem===null?null:Ls(d.problem,t)??Zi("unlock_failed",t)}:{kind:"problem",collectionId:p,problem:Zi("open_failed",t)}}if(r?.state==="approval_required"&&o?.collectionId&&n.removedScopeIds?.includes(o.collectionId))return{kind:"problem",collectionId:o.collectionId,problem:Zi("installation_scope_removed",t)};if(r?.state==="approval_required"&&o?.collectionId)return{kind:"needs_approval",collectionId:o.collectionId,displayName:o.displayName,declined:r.problem==="application_selection_not_approved"};if(r?.state==="pending"&&o?.collectionId)return{kind:"opening",collectionId:o.collectionId,displayName:o.displayName,slow:!!e.slow};let a=r?.usable??(n.status==="ready"||n.status==="setup_required"?n.collections.find(p=>p.collectionId===n.selectedCollectionId)??null:null);if(n.status==="setup_required"&&a)return n.readiness.assessment?.status==="incompatible"?{kind:"problem",collectionId:a.collectionId,problem:Ls(n.readiness,t)??Zi("incompatible",t)}:{kind:"needs_setup",collectionId:a.collectionId,collection:a};if(n.status==="ready"&&a&&Yf(e.connection,a.collectionId))return{kind:"ready",collectionId:a.collectionId,collection:a,connection:e.connection,rechecking:n.readiness.checking,problem:null,unavailableTypes:n.readiness.assessment?.unavailableTypes??[]};let c=n.status==="opening"||n.status==="ready"||r?.state==="opening"||r?.state==="usable",l=n.selectedCollectionId??o?.collectionId??null;if(c&&l){let p=n.collections.find(d=>d.collectionId===l)?.displayName??o?.displayName??null;return{kind:"opening",collectionId:l,displayName:p,slow:!!e.slow}}return e.startPending&&s&&n.status==="unselected"&&!n.problem&&r?.state==="none"?{kind:"starting"}:{kind:"choosing",lastApproval:r?.lastApproval??null}}function sM(n,e,t){let r=t.previous;return r?.kind==="needs_setup"&&n.kind==="opening"&&n.collectionId===r.collectionId&&e.selectedCollectionId===r.collectionId&&e.readiness.checking?r:r?.kind==="unsynced"&&n.kind==="opening"&&n.collectionId===r.collectionId&&e.selectedCollectionId===r.collectionId&&Yf(t.connection,r.collectionId)?{...r,connection:t.connection,rechecking:!0}:!r||r.kind!=="ready"||n.kind==="ready"||!Yf(t.connection,r.collectionId)||e.selectedCollectionId!==r.collectionId?n:n.kind==="opening"&&n.collectionId===r.collectionId?{...r,connection:t.connection,rechecking:!0,problem:null}:n.kind==="problem"&&n.problem.transient?{...r,connection:t.connection,rechecking:!0,problem:n.problem}:n}function gx(n,e){return n?.kind==="ready"&&(e===void 0||n.collectionId===e)}Tl();Ep();tn();am();At();var UL=["http","https","file","javascript","data","blob","about","capacitor","chrome-extension","moz-extension"];function Vv(n,e){if(typeof n!="string"||!n||n.length>2048||n.includes("*"))return!1;let t=e&&typeof e=="object"?e.redirect_uris:void 0;if(!Array.isArray(t)||!t.includes(n))return!1;let{id:r,homepage:o}=e,s;try{s=new URL(n)}catch{return!1}if(s.username||s.password||s.hash)return!1;if(s.protocol==="https:"||s.protocol==="http:"){let a;try{a=new URL(String(o))}catch{return!1}return s.origin===a.origin&&(s.protocol==="https:"||Ze(s.origin))}let i=s.protocol.slice(0,-1);return typeof r=="string"&&i.includes(".")&&/^[a-z][a-z0-9+.-]*$/.test(i)&&!UL.includes(i)&&(i===r||i.startsWith(`${r}.`))&&s.hostname.length>0}um();tn();ie();At();var Ir=n=>A("unavailable","application asset unavailable",n),BL=()=>A("cancelled","application asset read fenced","application_asset_fenced");function xi(n){if(n.aborted)throw BL()}function q1(n,e){let t=Object.freeze({...n}),r=Object.freeze({...e}),o,s;try{o=new URL(t.url),s=new URL(r.origin)}catch{throw Ir("application_asset_binding")}if(!dt(r.origin)||s.protocol!==o.protocol||!Go(r.environment)||Pi(r.environment)&&!Yo(r.origin)||kt(o)!==r.origin||o.username||o.password||o.search||o.hash||!/^[0-9a-f]{64}$/.test(t.sha256)||!Number.isSafeInteger(t.bytes)||t.bytes<1||!Number.isSafeInteger(t.maxBytes)||t.maxBytes<t.bytes||t.maxBytes>4*1024*1024)throw Ir("application_asset_binding");let i=r.fetch??globalThis.fetch;if(typeof i!="function")throw Ir("application_asset_unavailable");let a=new URL(o.href);return a.searchParams.set("mdbase-sdk-asset",t.sha256),async({signal:c})=>{xi(c);let l=null,p;try{globalThis.caches&&(l=await globalThis.caches.open("mdbase.sdk.application-assets.v1"),p=await l.match(a.href))}catch{}let d=p!==void 0;if(!p){xi(c);try{p=await i(o.href,{signal:c,credentials:"omit",cache:"force-cache",redirect:"error"})}catch{throw xi(c),Ir("application_asset_fetch")}}let u=p.body?.getReader();if(!u)throw xi(c),Ir("application_asset_response");let f=!1,h=null,m=()=>h??=Promise.resolve().then(async()=>{try{await u.cancel()}catch{throw Ir("application_asset_stop_failed")}}),w=()=>{m().catch(()=>{})};c.addEventListener("abort",w,{once:!0});try{if(xi(c),!p.ok||p.redirected||p.url&&p.url!==o.href)throw Ir("application_asset_response");let b=p.headers.get("content-length"),g=p.headers.get("content-encoding");if(b!==null&&(g===null||g.trim().toLowerCase()==="identity")&&(!/^(?:0|[1-9][0-9]*)$/.test(b)||Number(b)!==t.bytes))throw Ir("application_asset_binding");let y=new Uint8Array(t.bytes),_=0;for(;;){let k=await u.read();if(xi(c),k.done){f=!0;break}if(!(k.value instanceof Uint8Array)||k.value.byteLength>t.bytes-_)throw Ir("application_asset_binding");y.set(k.value,_),_+=k.value.byteLength}if(_!==t.bytes)throw Ir("application_asset_binding");let v=new Uint8Array(await crypto.subtle.digest("SHA-256",y));if(xi(c),Array.from(v,k=>k.toString(16).padStart(2,"0")).join("")!==t.sha256)throw Ir("application_asset_binding");if(xi(c),l&&!d)try{await l.put(a.href,new Response(y))}catch{}return xi(c),y}catch(b){throw xi(c),X(b)?b:Ir("application_asset_response")}finally{c.removeEventListener("abort",w);try{(!f||c.aborted)&&await m()}finally{u.releaseLock()}}}}Xo();tn();ie();lm();At();var Bs={runtime:{sha256:"4f663f240720f2198024cd50f375614fc49e0db203570359d1b1dadee83d1fca",bytes:4070905,maxBytes:4070905,source:{repository:"mdbase-dev/mdbase-connect",commit:"7eecb8284a0b1c7ceeda4bee46fe4b3be8526fb0"}},sqlite:{sha256:"2ee8f3dab694532afc8840e07703127287662d08b74e6ff50491ce63f00d5752",bytes:868907,maxBytes:11e5,initializer:{sha256:"a6d3fe46aa3f924e7686329f97b0564549ef1f787e0c19924179aef7f72bcc01",bytes:642742},asyncProxy:{sha256:"9f1970e05ee07a79332498858740b705eeb1dcee03bc150f6f690bc0fb5f0a06",bytes:32505}}};var fm={},FL=Object.freeze({sha256:Bs.runtime.sha256,bytes:Bs.runtime.bytes,maxBytes:Bs.runtime.maxBytes}),KL=Object.freeze({sha256:Bs.sqlite.sha256,bytes:Bs.sqlite.bytes,maxBytes:Bs.sqlite.maxBytes}),gd=()=>A("unavailable","SDK packaged application assets unavailable","application_packaged_assets_unavailable");function T1(n,e,t){if(!Go(n))throw gd();let r=$s();Cr({environment:n,appOrigin:e,release:r});let o,s;try{let c=new URL(t??fm.url);if(kt(c)!==e||c.username||c.password||(o=t===void 0?new URL("../native/runtime.wasm",fm.url):new URL("../native/runtime.wasm",c),s=t===void 0?new URL("../native/sqlite3.wasm",fm.url):new URL("../native/sqlite3.wasm",c),kt(o)!==e||kt(s)!==e))throw gd()}catch{throw gd()}let i=(c,l)=>Object.freeze({url:c.href,...l}),a=async c=>{let l=globalThis.WorkerGlobalScope;if(typeof l!="function"||!(globalThis instanceof l))throw gd();let p=t===void 0?new URL("../native/sqlite3.js",fm.url):new URL("../native/sqlite3.js",t),{default:d}=await import(p.href);return globalThis.sqlite3ApiConfig={disable:{vfs:{opfs:!0,"opfs-wl":!0}}},d(c)};return Object.freeze({release:()=>$s(),runtime:i(o,FL),sqlite:i(s,KL),initializeSqlite:a})}Gv();vb();var HL="mdbase:startup:",GL=new Set(["signed_out","authorizing","choosing","needs_approval","needs_setup","problem","unavailable","closed"]);function YL(){let n=globalThis.performance;return typeof n?.now=="function"&&typeof n.measure=="function"?n:null}var mm=class{clock=YL();began=this.clock?.now()??0;stage=null;since=this.began;done=this.clock===null;measure(e,t,r){try{this.clock?.measure(`${HL}${e}`,{start:t,end:r})}catch{}}async time(e,t){if(this.done)return t();let r=this.clock.now();try{return await t()}finally{this.measure(e,r,this.clock.now())}}observe(e){if(this.done)return;let t=e.kind==="opening"&&e.progress?`opening:${e.progress}`:e.kind;if(t===this.stage)return;let r=this.clock.now();this.stage!==null&&this.measure(this.stage,this.since,r),this.stage=t,this.since=r;let o=e.kind==="ready"||e.kind==="unsynced";o&&this.measure("total",this.began,r),(o||GL.has(e.kind))&&(this.done=!0)}};function M1(n,e,t){if(n.requested.collectionId!==null){let r=n.requested.collectionId!==t?.selection.requested.collectionId;r&&vs("mdbase:open:requested"),n.requested.approved&&(r||!t?.selection.requested.approved)&&vs("mdbase:open:approved")}e.kind==="opening"&&hm(e.progress)&&(t?.phase.kind==="opening"&&t.phase.collectionId===e.collectionId?t.phase.progress:null)!==e.progress&&vs(`mdbase:open:stage:${e.progress}`),e.kind==="ready"&&(t?.phase.kind!=="ready"||t.phase.connection!==e.connection)&&vs("mdbase:open:ready")}lm();At();Xo();tn();var hn=class extends Error{constructor(t){super("SDK collection selection unavailable");this.code=t;this.name="ApplicationSelectionError"}code},bd=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",fn=(n,e,t=null)=>Object.freeze({requestedCollectionId:n,source:e,problem:t});function L1(n,e){return n.source!=="none"?n:e.storedId!==void 0&&e.storedId!==null?bd(e.storedId)?fn(e.storedId,"stored"):fn(null,"stored","application_selection_invalid"):e.collections.length>1024||e.collections.some(t=>!bd(t.collectionId))||new Set(e.collections.map(t=>t.collectionId)).size!==e.collections.length?fn(null,"none","application_selection_metadata"):e.preferredId!==void 0&&e.preferredId!==null?bd(e.preferredId)&&e.collections.some(t=>t.collectionId===e.preferredId)?fn(e.preferredId,"preferred"):fn(null,"preferred","application_selection_metadata"):e.collections.length===1?fn(e.collections[0].collectionId,"sole"):fn(null,"none")}var ym=class{port;origin;parameter;fallback;listeners=new Set;snapshot=fn(null,"none");stopListening=null;started=!1;closed=!1;constructor(e,t={},r=null){let o,s;try{o=new URL(e),s=new URL(t.fallbackPath??"/",o)}catch{throw new hn("application_selection_binding")}let i=t.parameter??"collection";if(!dt(e)||kt(o)!==e||kt(s)!==e||s.username||s.password||s.search||s.hash||typeof i!="string"||!/^[a-z][a-zA-Z0-9_.-]{0,63}$/.test(i)||["code","state","error","error_description"].includes(i))throw new hn("application_selection_binding");this.origin=e,this.parameter=i,this.fallback=s.href,this.port=r}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 hn("application_selection_fenced")}url(){let e;try{e=new URL(this.port.href())}catch{throw new hn("application_selection_binding")}if(kt(e)!==this.origin||e.username||e.password)throw new hn("application_selection_binding");return e}read(){if(!this.port)return fn(null,"none");let e;try{e=this.url().searchParams.getAll(this.parameter)}catch{return fn(null,"url","application_selection_binding")}return e.length===0?fn(null,"none"):e.length!==1?fn(null,"url","application_selection_duplicate"):e[0]===""?fn(null,"url","application_selection_empty"):bd(e[0])?fn(e[0],"url"):fn(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&&!bd(e))throw new hn("application_selection_invalid");let r=t.history??"replace";if(r!=="push"&&r!=="replace")throw new hn("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,r)}return this.publish(fn(e,e===null?"none":"user")),this.snapshot}returnUrl(e){this.check();try{let t=new URL(e,this.origin);if(kt(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 j1(){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 JL=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",Ml=n=>n.status==="ready"||n.status==="setup_required",Ll=n=>n.status==="needs_unlock",U1=n=>n.signIn?.state==="paired"&&(n.status==="unselected"||n.status==="blocked"||Ml(n)||Ll(n)),XL=n=>n.status==="not_started"||n.status==="starting"||n.status==="signed_out"||n.status==="authorizing",Ci=(n,e)=>e===null?null:n.collections.find(t=>t.collectionId===e)??null,gm=class{browser;session;memory;preferredId;schedule;listeners=new Set;stops=[];value;key="";startTarget=null;startApplied=!1;startHeld=!0;failed=null;before=null;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=this.keyOf(this.value)}startPending(){return this.startHeld}keyOf(e){return JSON.stringify(e)+(this.startHeld?"|start":"")}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 r=this.session.getSnapshot();return e!==null&&r.selectedCollectionId===e&&r.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&&(Ml(o)||Ll(o))||!Ci(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&&!JL(e))return Promise.reject(new hn("application_selection_invalid"));if(this.approval&&!this.approval.settled)return Promise.reject(new hn("application_selection_busy"));e!=null&&e!==this.requested().requestedCollectionId&&(this.startTarget=null,this.browser.select(e,t.history?{history:t.history}:{}));let r=this.session.getSnapshot().signIn,o=r?.nativeSelection?.requestId??r?.collectionSelection?.requestId??null,s,i=e===null?null:this.requested().requestedCollectionId;try{s=this.session.authorize({...t.signal?{signal:t.signal}:{},collectionHint:i})}catch(p){return Promise.reject(p)}let a=i===null?"add":"collection",c=new Set(this.session.getSnapshot().collections.map(p=>p.collectionId)),l={receipt:o,kind:a,collectionId:i,before:c,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),p=>{if(this.approval===l){this.approval=null;let d=p?.code;(d==="cancelled"||d==="aborted")&&(this.lastApproval=Object.freeze({kind:a,outcome:"closed",collectionId:i}))}throw this.changed(),p})}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 hn("application_selection_empty")):this.approve(t,e)}resync(){this.closed||(this.attempted=void 0,this.failed=null,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 hn("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;if(e!==this.lastRequested&&(this.lastRequested=e,this.attempted=void 0,this.failed=null,this.declined!==e&&(this.declined=null)),e!==null&&this.attempted===e){let o=this.session.getSnapshot();o!==this.before&&(o.status==="blocked"?o.selectedCollectionId===e:o.status==="unselected"&&o.problem!==null)&&(this.failed=e)}let t=this.derive(),r=this.keyOf(t);if(t.state==="usable"&&this.remember(t.usable.collectionId),r!==this.key){this.key=r,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(),r=t.requestedCollectionId,o=Ci(e,r),s=Ml(e)?Ci(e,e.selectedCollectionId):null,i,a=null;t.problem?(i="invalid",a=t.problem):this.approval?i="approving":r===null?i="none":s?.collectionId===r?i="usable":e.selectedCollectionId===r&&(e.status==="blocked"||e.status==="opening"||Ll(e))?i=e.status==="blocked"?"blocked":"opening":U1(e)?o?i="opening":this.session.listing?.()?i="pending":(i="approval_required",this.declined===r&&(a="application_selection_not_approved")):i="pending";let c=this.approval?Object.freeze({kind:this.approval.kind,collectionId:this.approval.collectionId,reopenable:this.approval.settled}):null;return Object.freeze({state:i,problem:a,approval:c,lastApproval:this.lastApproval,usable:s?Object.freeze({...s}):null,requested:Object.freeze({collectionId:r,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={},r=!1){this.attempted=e,this.failed=null,this.before=this.session.getSnapshot();let o=t.signal?{signal:t.signal}:{},s=Promise.resolve().then(()=>e===null?this.session.clear(o):this.session.open(e,o)),i=s.then(()=>{},()=>{}).finally(()=>{this.opening===i&&(this.opening=null,this.changed())});return this.opening=i,r?s.then(()=>{}):i}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||e.approval?.outcome==="closed")){let o=this.approval;this.approval=null,this.attempted=void 0,this.lastApproval=Object.freeze({kind:o.kind,outcome:e.problem==="approval_window_closed"||e.approval?.outcome==="closed"?"closed":"declined",collectionId:o.collectionId}),this.refresh()}else{if(!this.approval.settled||XL(e))return;let o=e.signIn?.nativeSelection;if(o&&o.requestId!==this.approval.receipt&&!Ci(e,o.collectionId)&&this.session.listing?.())return;this.finishApproval(e)}if(!U1(e))return;if(!this.startApplied){if(this.browser.getSnapshot().source==="none"){let o=null;try{o=this.memory?.read()??null}catch{}if(o!==null&&!Ci(e,o)&&this.session.listing?.()){this.startHeld=!1,this.refresh();return}this.startApplied=!0;let s=L1(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)}else this.startApplied=!0;this.startHeld=!1,this.refresh()}let t=this.requested(),r=t.requestedCollectionId;if(!t.problem){if(r===null){this.attempted!==null&&e.selectedCollectionId!==null&&(Ml(e)||Ll(e))&&this.run(null);return}if(e.selectedCollectionId===r&&(Ml(e)||Ll(e)||e.status==="opening")){this.attempted=r,this.failed=null;return}if(e.selectedCollectionId===r&&e.status==="blocked"){this.failed=r;return}Ci(e,r)&&(this.attempted===r&&(this.failed!==r||e.status!=="unselected"||e.problem!==null)||(this.failed=null,this.run(r)))}}finishApproval(e){let t=this.approval,r=t.receipt;this.approval=null,this.attempted=void 0;let o=u=>u!==null&&Ci(e,u)?t.before.has(u)?"unchanged":"added":e.approval?.outcome==="closed"?"closed":"declined",s=e.signIn?.collectionSelection,i=e.signIn?.nativeSelection,c=(i&&i.requestId!==r&&Ci(e,i.collectionId)?i.collectionId:null)??(s&&s.requestId!==r&&Ci(e,s.selectedCollectionId)?s.selectedCollectionId:null);if(c!==null){c!==this.requested().requestedCollectionId&&(this.startTarget=null,this.browser.select(c,{history:"replace"})),this.lastApproval=Object.freeze({kind:t.kind,outcome:o(c),collectionId:c}),this.refresh(),e.selectedCollectionId===c&&(Ml(e)||Ll(e)||e.status==="opening")?this.attempted=c:this.run(c);return}let l=this.requested().requestedCollectionId;l!==null&&!Ci(e,l)&&(this.declined=l);let p=t.kind==="add"?e.collections.find(u=>!t.before.has(u.collectionId))?.collectionId??null:null,d=t.kind==="add"?p:t.collectionId??l;this.lastApproval=Object.freeze({kind:t.kind,outcome:o(d),collectionId:d}),this.refresh()}};Od();f_();ie();var Zl="unsynced",Wj="current";var C_="moved.",Gm=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/;var I_=class extends Error{constructor(t){super(`app unsynced collection: ${t}`);this.reason=t;this.name="AppUnsyncedCollectionError"}reason},pr=(n="unavailable")=>new I_(n);function Hj(n){if(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).sort().join()!=="account,collection,device,installation,replica,version")throw pr();let e=n,t=[e.account,e.installation,e.collection,e.replica,e.device];if(e.version!==1||t.some(r=>typeof r!="string"||!Gm.test(r))||new Set(t).size!==t.length)throw pr();return Object.freeze({...e})}function GI(n,e){if(e.throwIfAborted(),!globalThis.indexedDB)throw pr();return new Promise((t,r)=>{let o=indexedDB.open(n,1),s=!1,i=()=>e.removeEventListener("abort",a),a=()=>{s=!0,i();try{o.transaction?.abort()}catch{}r(pr("fenced"))};e.addEventListener("abort",a,{once:!0}),o.onblocked=o.onerror=a,o.onupgradeneeded=()=>{try{if(s||o.result.objectStoreNames.length)throw pr();o.result.createObjectStore(Zl)}catch{try{o.transaction?.abort()}catch{}}},o.onsuccess=()=>{if(i(),s||o.result.objectStoreNames.length!==1||!o.result.objectStoreNames.contains(Zl)){o.result.close(),r(pr());return}t(o.result)}})}async function Gj(n,e,t,r,o){let s=await GI(n,o);try{return await new Promise((i,a)=>{let c=s.transaction(Zl,r?"readwrite":"readonly",{durability:"strict"}),l=null,p=null;c.onabort=c.onerror=()=>a(p??pr()),c.oncomplete=()=>i(l);let d=c.objectStore(Zl),u=d.get(e);u.onsuccess=()=>{try{if(u.result!==void 0){l=t(u.result);return}if(!r)return;let f=t(r());d.add(f,e),l=f}catch(f){p=f,c.abort()}}})}finally{s.close()}}async function Yj(n,e,t){let r=await GI(n,e);try{return await new Promise((o,s)=>{let i=r.transaction(Zl,"readwrite",{durability:"strict"}),a,c=null;i.onabort=i.onerror=()=>s(c??pr()),i.oncomplete=()=>o(a),t(i.objectStore(Zl),l=>{a=l},l=>{c=l,i.abort()})})}finally{r.close()}}var YI=/^sha256:[0-9a-f]{64}$/;function JI(n){let e=n;if(!e||e.version!==1||!e.revisions||typeof e.revisions!="object"||Array.isArray(e.revisions))throw pr();let t=new Map;for(let[r,o]of Object.entries(e.revisions)){if(!Gm.test(r)||typeof o!="string"||!YI.test(o))throw pr();t.set(r,o)}return t}async function XI(n,e,t){if(!Gm.test(e))throw pr("binding");return await Gj(n,C_+e,JI,null,t)??new Map}function QI(n,e,t,r){for(let[o,s]of t)if(!Gm.test(o)||!YI.test(s))return Promise.reject(pr("binding"));return Yj(n,r,(o,s,i)=>{let a=o.get(Wj),c=o.get(C_+e);c.onsuccess=()=>{try{if(a.result===void 0||Hj(a.result).collection!==e){i(pr());return}let l=c.result===void 0?new Map:JI(c.result);for(let[p,d]of t)l.set(p,d);o.put({version:1,revisions:Object.fromEntries(l)},C_+e),s()}catch(l){i(l)}}})}var V7=720*60*60*1e3;ie();var O_=new WeakMap,Jj=100,Xj=(n,e)=>`unsynced/1\0${n}\0${e}`;async function Ym(n,e,t){try{return await n.get(e,{signal:t})}catch(r){if(X(r,"not_found"))return null;throw r}}function Qj(n,e){let t=n.lastIndexOf("/"),r=n.lastIndexOf("."),o=r>t+1?r:n.length;return`${n.slice(0,o)} ${e}${n.slice(o)}`}async function Zj(n,e){let t=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`unsynced/1\0copy\0${n}\0${e}`))).slice(0,16);t[6]=t[6]&15|128,t[8]=t[8]&63|128;let r=[...t].map(o=>o.toString(16).padStart(2,"0")).join("");return`${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function eU(n){if(n.document===void 0)throw A("invalid_request","the source record has no document");return{path:n.path,document:n.document}}async function R_(n,e,t={}){let{signal:r}=t,o=t.map??eU;if(n.collection===e.collection)throw A("invalid_request","a collection cannot be transferred into itself");let s=t.ledger?await t.ledger.read(n.collection,r):new Map,i=new Map,a=await e.describe(r?{signal:r}:{}),c=new Set(a.types.map(b=>b.name.toLowerCase())),l=[],p=new Map,d=new Set,u=new Set,f=0;for await(let b of n.pages({},{include:{body:!0,document:!0},signal:r}))for(let g of b.records){r?.throwIfAborted();let y=null;if(await Ym(e,g.id,r)){let S=s.get(g.id);if(S===void 0&&i.set(g.id,g.revision),S===void 0||S===g.revision){l.push(Object.freeze({sourceId:g.id,sourcePath:g.path,outcome:"present"}));continue}if(y=await Zj(g.id,g.revision),await Ym(e,y,r)){i.set(g.id,g.revision),l.push(Object.freeze({sourceId:g.id,sourcePath:g.path,outcome:"present"}));continue}}let _=await o(g);if(_===null){l.push(Object.freeze({sourceId:g.id,sourcePath:g.path,outcome:"skipped"}));continue}if(!_||typeof _!="object"||_.id!==void 0&&_.id!==g.id)throw A("invalid_request","the transfer map must keep the record ID");i.set(g.id,g.revision);let v=_.path??g.path,k=v;for(let S=2;d.has(k.toLowerCase())||await Ym(e,{path:k},r);S++){if(S>Jj)throw A("conflict",`no free path beside ${v}`,"path_taken");k=Qj(v,S)}d.add(k.toLowerCase());for(let S of _.type?[_.type]:g.types)c.has(S.toLowerCase())||u.add(S);p.set(g.id,Object.freeze({..._,id:y??g.id,path:k})),k!==v&&!y&&f++,l.push(Object.freeze({sourceId:g.id,sourcePath:g.path,outcome:y?"changed":"create",path:k,...y?{copyId:y}:k!==v?{renamedFrom:v}:{}}))}let h=new Map;if(t.addTypes&&u.size){let b=new Map((await n.describe(r?{signal:r}:{})).types.map(g=>[g.name.toLowerCase(),g]));for(let g of[...u].sort()){let y=b.get(g.toLowerCase());if(!y?.revision)continue;let _;try{_=(await n.resources.get(y.path,{signal:r})).text}catch(v){if(X(v,"not_found"))continue;throw v}typeof _=="string"&&(h.set(y.name,_),u.delete(g))}}let m=b=>l.filter(g=>g.outcome===b).length,w=Object.freeze({source:n.collection,destination:e.collection,items:Object.freeze(l),missingTypes:Object.freeze([...u].sort()),addTypes:Object.freeze([...h.keys()].sort()),counts:Object.freeze({create:m("create"),present:m("present"),skipped:m("skipped"),renamed:f,changed:m("changed")})});return O_.set(w,Object.freeze({inputs:p,types:h,map:t.map,ledger:t.ledger,settle:i})),w}async function ZI(n,e,t,r){let o=O_.get(n);if(!o)throw A("invalid_request","plan the transfer first");if(e.collection!==n.source||t.collection!==n.destination)return!1;let s=await R_(e,t,{...o.map?{map:o.map}:{},...o.ledger?{ledger:o.ledger}:{},...r?{signal:r}:{}});return s.counts.create===0&&s.counts.changed===0}async function eO(n,e,t={}){let r=O_.get(n),{signal:o}=t;if(!r)throw A("invalid_request","plan the transfer first");let{inputs:s}=r;if(e.collection!==n.destination)throw A("invalid_request","the plan is for another collection");let i=n.items.filter(m=>m.outcome==="create"||m.outcome==="changed"),a=[],c=[],l=0,p=n.counts.present,d=0,u=()=>{try{t.onProgress?.(Object.freeze({done:d,total:i.length}))}catch{}};r.ledger&&r.settle.size&&await r.ledger.record(n.source,r.settle,o);let f=[],h=[];for(let[m,w]of r.types){o?.throwIfAborted();try{await e.createType(w,o?{signal:o}:{}),f.push(m)}catch(b){o?.throwIfAborted(),X(b,"conflict")?f.push(m):h.push(Object.freeze({name:m,code:X(b)?b.code:"unavailable"}))}}u();for(let m of i){o?.throwIfAborted();try{let w=await e.create(s.get(m.sourceId),{intent:Xj(n.source,m.copyId??m.sourceId),...o?{signal:o}:{}});c.push(w.mutationId),l++}catch(w){o?.throwIfAborted(),await Ym(e,m.copyId??m.sourceId,o).catch(()=>null)?p++:a.push(Object.freeze({sourceId:m.sourceId,code:X(w)?w.code:"unavailable"}))}d++,u()}return Object.freeze({source:n.source,destination:n.destination,created:l,present:p,skipped:n.counts.skipped,failed:Object.freeze(a),addedTypes:Object.freeze(f),failedTypes:Object.freeze(h),mutations:Object.freeze(c),retired:!1})}Zm();$f();Qo();Qf();var sO="mdbn-app-tabs/1",E_="\0mdbn-port";var Ud=n=>typeof n=="string"&&/^[0-9a-f-]{36}$/.test(n);function iU(n){if(!n||typeof n!="object")return null;let e=n;switch(e.k){case"join":case"leave":return Ud(e.tab)?e:null;case"leader":case"bye":case"fault":case"signedOut":case"signedIn":return Ud(e.leader)?e:null;case"joined":return Ud(e.tab)&&Ud(e.leader)&&typeof e.binding=="string"?e:null;case"m":return Ud(e.tab)&&typeof e.up=="boolean"&&Number.isSafeInteger(e.s)&&e.s>=0?e:null;default:return null}}function q_(n){if(!n||typeof n!="object")return!1;let e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function T_(n,e,t=0){return n instanceof MessagePort?{[E_]:e(n)}:t>=6?n:Array.isArray(n)?n.map(r=>T_(r,e,t+1)):q_(n)?Object.fromEntries(Object.entries(n).map(([r,o])=>[r,T_(o,e,t+1)])):n}function M_(n,e,t,r=0){if(q_(n)&&Object.keys(n).length===1&&Number.isSafeInteger(n[E_])){let o=e(n[E_]);return t.push(o),o}return r>=6?n:Array.isArray(n)?n.map(o=>M_(o,e,t,r+1)):q_(n)?Object.fromEntries(Object.entries(n).map(([o,s])=>[o,M_(s,e,t,r+1)])):n}var ey=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=r=>{let o=r.ports.length?T_(r.data,s=>{let i=this.next;return this.next+=2,this.bridge(s,i),i}):r.data;try{this.send(t,o)}catch{}}}deliver(e,t){let r=this.streams.get(e);if(!r)return;let o=[],s=M_(t,i=>{let a=new MessageChannel;return this.bridge(a.port1,i),a.port2},o);try{r.postMessage(s,o)}catch{for(let i of o)i.close()}}close(){for(let e of this.streams.values()){e.onmessage=null;try{e.close()}catch{}}this.streams.clear()}},ty=class{constructor(e,t,r,o=()=>{},s={}){this.env=t;this.lost=r;this.signedInElsewhere=o;this.role=s;this.base=e.storageNamespace===void 0?`${sO}/${e.cpOrigin}/${e.appId}/${e.build}`:`${sO}/namespace/${JSON.stringify([e.cpOrigin,e.appId,e.build,e.storageNamespace])}`}env;lost;signedInElsewhere;role;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(iU(t.data)),this.channel=e,e}post(e){this.channel?.postMessage(e)}hold(e,t,r){return new Promise((o,s)=>{let i=c=>{if(!c){o(null);return}return new Promise(l=>o(l))};(t?this.env.locks.request(e,{ifAvailable:!0},i):this.env.locks.request(e,{signal:r},i)).catch(s)})}async elect(e){e.throwIfAborted(),this.open(),this.presence??=await this.hold(`${this.base}/tab/${this.tab}`,!0),e.throwIfAborted();let t=this.role.lead!==!1;if(t&&!this.leading&&(this.leading=await this.hold(`${this.base}/leader`,!0)),this.leading)return e.aborted&&(this.resign(),e.throwIfAborted()),{kind:"leader"};let r=new AbortController,o=()=>r.abort();e.addEventListener("abort",o,{once:!0});let s=t?this.hold(`${this.base}/leader`,!1,r.signal):null,i;try{i=await new Promise((d,u)=>{s?.then(f=>{f&&d({release:f})},()=>{}),this.joining={resolve:d,reject:u},e.addEventListener("abort",()=>u(e.reason),{once:!0}),this.join()})}catch(d){throw this.joining=null,r.abort(),d}finally{e.removeEventListener("abort",o)}if(this.joining=null,"release"in i)return this.leading=i.release,e.aborted&&(this.resign(),e.throwIfAborted()),{kind:"leader"};e.aborted&&(r.abort(),e.throwIfAborted());let a=new MessageChannel,c=this.tab,l=new ey((d,u)=>this.post({k:"m",tab:c,up:!0,s:d,d:u}),!0);l.bridge(a.port2,0);let p={leader:i.leader,tunnel:l,wait:r,port:a.port1,left:!1,signedOut:!1};return this.follower=p,(s??this.hold(`${this.base}/leader`,!1,r.signal)).then(d=>{if(!d)return;let u=this.follower===p&&!p.left;u&&t?this.leading=d:d(),u&&this.departed(p)},()=>{}),{kind:"follower",port:a.port1,binding:i.binding,leave:()=>this.leave(p)}}join(){this.post({k:"join",tab:this.tab,...this.role.lead===!1?{needsLeader:!0}:{}})}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 r=this.leading;if(this.leading=null,r?.(),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,r=this.follower;switch(e.k){case"join":{if(!t&&e.needsLeader===!0&&this.role.lead!==!1&&!this.leading&&!r&&!this.joining&&this.hold(`${this.base}/leader`,!0).then(l=>{l&&(l(),this.role.wanted?.())},()=>{}),!t||t.followers.has(e.tab)||e.tab===this.tab)return;let o=crypto.randomUUID(),s=new MessageChannel,i=e.tab,a=new ey((l,p)=>this.post({k:"m",tab:i,up:!1,s:l,d:p}),!1);a.bridge(s.port1,0);let c=new AbortController;t.followers.set(i,{binding:o,tunnel:a,watch:c});try{t.worker.attach(s.port2,o)}catch{t.followers.delete(i),a.close();return}this.post({k:"joined",tab:i,binding:o,leader:this.tab}),t.faulted&&this.post({k:"fault",leader:this.tab}),this.hold(`${this.base}/tab/${i}`,!1,c.signal).then(l=>{l?.(),this.drop(t,i)},()=>{});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.join();return;case"bye":r&&r.leader===e.leader&&this.departed(r,e.signedOut===!0);return;case"signedOut":r&&r.leader===e.leader&&(r.signedOut=!0);return;case"signedIn":!t&&!r&&!this.joining&&e.leader!==this.tab&&this.signedInElsewhere();return;case"fault":r&&!r.left&&r.leader===e.leader&&r.port.dispatchEvent(new MessageEvent("messageerror"));return;case"m":e.up&&t?t.followers.get(e.tab)?.tunnel.deliver(e.s,e.d):!e.up&&r&&e.tab===this.tab&&r.tunnel.deliver(e.s,e.d);return}}drop(e,t){let r=e.followers.get(t);if(r){e.followers.delete(t),r.watch.abort(),r.tunnel.close();try{e.worker.detach(r.binding)}catch{}}}};function Ri(n){try{return n()}catch{return}}function oU(){let n=Ri(()=>globalThis.crypto?.subtle),e=Ri(()=>globalThis.navigator?.storage),t=Ri(()=>typeof e?.getDirectory=="function"?()=>e.getDirectory.call(e):void 0);return{subtle:n,abortSignalAny:Ri(()=>typeof AbortSignal=="function"&&typeof AbortSignal.any=="function")===!0,randomUUID:Ri(()=>typeof globalThis.crypto?.randomUUID=="function")===!0,worker:Ri(()=>typeof Worker=="function")===!0,messageChannel:Ri(()=>typeof MessageChannel=="function")===!0,locks:Ri(()=>typeof globalThis.navigator?.locks?.request=="function")===!0,broadcastChannel:Ri(()=>typeof BroadcastChannel=="function")===!0,indexedDB:Ri(()=>typeof globalThis.indexedDB<"u")===!0,getDirectory:t}}async function aO(n=oU(),e=!0){let t=[];if(n.subtle||t.push("web_crypto"),n.abortSignalAny||t.push("abort_signal_any"),n.randomUUID||t.push("random_uuid"),e&&!n.worker&&t.push("worker"),n.messageChannel||t.push("message_channel"),n.locks||t.push("web_locks"),n.broadcastChannel||t.push("broadcast_channel"),n.indexedDB||t.push("indexed_db"),n.subtle)try{await n.subtle.generateKey({name:"X25519"},!1,["deriveBits"])}catch{t.push("x25519")}if(t.length)return{ok:!1,problem:"browser_unsupported",missing:Object.freeze(t)};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 ny(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 lO(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 cO="Some changes are only on this device. Stay online so they can sync.";async function ry(n,e,t=!1){let r=!1;try{r=await n?.persisted()===!0,!r&&t&&(r=await n?.persist?.()===!0)}catch{}return{persistent:r,installed:e}}oy();var fO=Object.freeze(new Set);function hO(n,e){let t=`mdbase.${n}.forgotten-collections.v1.${encodeURIComponent(e)}`,r=()=>{try{return globalThis.localStorage??null}catch{return null}},o=null,s=()=>{let a=null;try{a=r()?.getItem(t)??null}catch{}if(o&&o.raw===a)return o;let c=null,l=fO;try{let p=a?JSON.parse(a):null;p?.v===1&&typeof p.account=="string"&&p.account.length<=64&&Array.isArray(p.ids)&&p.ids.length<=1024&&p.ids.every(d=>typeof d=="string"&&d.length>0&&d.length<=64)&&(c=p.account,l=Object.freeze(new Set(p.ids)))}catch{}return o={raw:a,account:c,ids:l},o},i=(a,c)=>{try{c.size?r()?.setItem(t,JSON.stringify({v:1,account:a,ids:[...c].slice(-1024)})):r()?.removeItem(t)}catch{}o=null};return Object.freeze({read(a){let c=s();return a&&c.account===a?c.ids:fO},add(a,c){let l=s(),p=new Set(l.account===a?l.ids:[]);p.has(c)||(p.add(c),i(a,p))},remove(a,c){let l=s();if(l.account!==a||!l.ids.has(c))return!1;let p=new Set(l.ids);return p.delete(c),i(a,p),!0},clear(){try{r()?.removeItem(t)}catch{}o=null}})}var uU=new Set(["owner","editor","viewer"]),ns=(n,e=512)=>typeof n=="string"&&n.length>0&&n.length<=e,fU=new Set(["unselected","opening","setup_required","ready"]);function mO(n){let e=n;return!e||typeof e!="object"||!ns(e.collectionId,64)||typeof e.displayName!="string"||e.displayName.length>512||!uU.has(e.role)?null:Object.freeze({collectionId:e.collectionId,displayName:e.displayName,role:e.role})}function yO(n){let e=n;return!e||typeof e!="object"||e.state!=="paired"||!ns(e.requestId,64)||!ns(e.installationId,64)||!ns(e.deviceId,64)||!ns(e.appId,64)||e.kind!=="app-runtime"&&e.kind!=="mobile"||!ns(e.verificationUri,2048)||!ns(e.accountId,64)||!Array.isArray(e.collectionIds)||e.collectionIds.length>1024||!e.collectionIds.every(t=>ns(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 gO(n,e){let t=`mdbase.${n}.session-hint.v1.${encodeURIComponent(e)}`,r=null,o=null,s=()=>{try{return globalThis.localStorage??null}catch{return null}},i=()=>{let c=null;try{c=s()?.getItem(t)??null}catch{return null}if(r&&r.raw===c)return r.value;let l=null;try{let p=c?JSON.parse(c):null,d=p?.v===1?yO(p.signIn):null,u=Array.isArray(p?.collections)&&p.collections.length<=1024?p.collections.map(mO):null;d&&u&&u.every(f=>f!==null)&&(l=Object.freeze({signIn:d,collections:Object.freeze(u)}))}catch{l=null}return r={raw:c,value:l},l},a=()=>{o=null;try{s()?.removeItem(t)}catch{}};return Object.freeze({read:i,clear:a,observe(c){if(c.status==="signed_out"&&c.signIn===null){o!==""&&(a(),o="");return}if(!fU.has(c.status)||c.signIn?.state!=="paired")return;let l=yO(c.signIn),p=c.collections.map(mO);if(!l||!p.every(u=>u!==null))return;let d=JSON.stringify({v:1,signIn:l,collections:p});if(d!==o){o=d;try{s()?.setItem(t,d)}catch{}}}})}j_();ie();tn();vn();function jN(n,e){return new Promise((t,r)=>{let o=()=>{clearTimeout(s),r(A("cancelled","The original collection closed."))};if(n.aborted){r(A("cancelled","The original collection closed."));return}let s=setTimeout(()=>{n.removeEventListener("abort",o),t()},e);n.addEventListener("abort",o,{once:!0})})}var UN=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,dc=Object.freeze({checking:!1,assessment:null,problem:null}),NN=Object.freeze({capabilities:dc,contracts:dc,configuration:dc,files:dc,people:dc,notifications:dc}),Ui=(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({...NN,configuration:Object.freeze({checking:n,assessment:t,problem:null})})})},My=n=>n==="approval_required"?"device_approval_required":n,DN=n=>n.state==="opening"||n.state==="unavailable"&&n.reason!=="sync_required"&&n.reason!=="access_removed"&&n.reason!=="collection_deleted",PA=n=>{if(X(n)){let e=fe(n.details,"availability");return typeof e=="string"?My(e):n.reason??n.code}return"open_failed"},xA=n=>{if(!X(n))return;let e=bO(n.details);return Object.freeze({name:"MdbaseError",code:n.code,...e?{relay:e}:{}})};function zN(n){let e=n.manifest?.redirect_uris;return(Array.isArray(e)?e.filter(r=>typeof r=="string"):[]).find(r=>{try{return kt(new URL(r))===n.origin}catch{return!1}})??new URL("/",n.origin).href}function WR(n,e,t){if(n.signIn?.state!=="paired"||!e.length&&!t)return n;let r=new Set(n.collections.map(c=>c.collectionId)),o=e.filter(c=>!r.has(c.collectionId)),s=o.length?Object.freeze([...n.collections,...o]):n.collections;if(!t||n.status!=="unselected"||r.has(t.collectionId))return s===n.collections?n:Object.freeze({...n,collections:s});let{problemDetail:i,...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 Ly=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(()=>(KR(),FR));return new t({declaration:this.options.declaration,redirectUri:this.options.grantRedirectUri??zN(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 r=t.filter(i=>i.account_id===e);if(this.bindingsAccount===e&&JSON.stringify(r)===JSON.stringify(this.bindings))return;let o=this.bindings;this.bindingsAccount=e,this.bindings=Object.freeze([...r]),this.settled=null,this.listed=null;let s=this.open;if(s){let i=o?.find(c=>c.collection_id===s.id),a=r.find(c=>c.collection_id===s.id);!a||e!==s.scope.account?this.close(!1):(a.grant_id!==i?.grant_id||a.client_noise_public_key!==i?.client_noise_public_key)&&this.openCollection(s.id,s.scope).catch(()=>{})}this.setList([])}async nativeAuthorization(e,t,r){if(e.action==="cancel")return this.native?.life.abort(),this.native?.prepared?.cancel(),this.native=null,null;if(this.closed||r.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 c=AbortSignal.any([r,a.life.signal]),l=await this.grants();if(!l.prepareAuthorization)throw A("unavailable","Native authorization unavailable");let p=btoa(String.fromCharCode(...Uint8Array.from(e.value.challenge.match(/../g),u=>parseInt(u,16)))).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,""),d=await l.prepareAuthorization({authorizationNonce:p,expectedAccountId:e.value.accountId,signal:c});if(a.prepared=d,this.native!==a||c.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 i=await s.finish({popup:t,collection:e.value.collectionId,signal:AbortSignal.any([r,o.life.signal])});if(this.native!==o||r.aborted||!i.nativeCompletion)throw A("unauthenticated","Original Native completion unavailable");return i.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 r=await this.grants(),o=this.bindings,s=[];if(o)for(let a of o)a.account_id===e&&await r.verifiedStoredNativeGrant?.(a)&&s.push(a);let i=await r.collections(o===null?{}:{bindings:s});if(this.closed||o!==this.bindings)return;this.listed=e,this.setList(i)}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(r=>UN.test(r.collectionId)).map(r=>Object.freeze({collectionId:r.collectionId,displayName:r.displayName,role:r.role??"editor",availability:r.availability,kind:"private"})));JSON.stringify(t)!==JSON.stringify(this.list)&&(this.list=t,this.changed())}setAvailability(e,t){this.list.some(r=>r.collectionId===e&&JSON.stringify(r.availability)!==JSON.stringify(t))&&(this.list=Object.freeze(this.list.map(r=>r.collectionId===e?Object.freeze({...r,availability:t}):r)),this.changed())}set(e,t){if(this.open!==e||e.life.signal.aborted)return;let{problemDetail:r,...o}=e.state,{problemDetail:s,...i}=t,a=i.problem===null?void 0:s??(i.problem===void 0?r:void 0);e.state=Object.freeze({...o,...i,...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 r={id:e,scope:t,life:new AbortController,client:null,setup:null,connection:null,stopLink:null,state:Object.freeze({collectionId:e,status:"opening",problem:null,readiness:Ui(!0,null)})};this.open=r,this.changed();let o=r.life.signal;try{let s=await this.grants(),i=this.bindings?.find(d=>d.account_id===t.account&&d.collection_id===e),a=async()=>{if(this.bindings!==null&&(!i||this.bindingsAccount!==t.account||!this.bindings.includes(i)||!await s.verifiedStoredNativeGrant?.(i)))throw A("unauthenticated","Original account-bound Native grant unavailable");if(o.aborted)throw A("cancelled","Original Native open fenced")};await a();let c=await s.availability(e,{signal:o});if(this.setAvailability(e,c),DN(c)&&(c.state==="unavailable"&&this.set(r,{status:"blocked",problem:My(c.reason),readiness:Ui(!1,null)}),c=await s.waitForAvailable(e,{signal:o,timeoutMs:this.options.waitMs??10*6e4,onAvailability:d=>{this.setAvailability(e,d),d.state==="unavailable"?this.set(r,{status:"blocked",problem:My(d.reason)}):this.set(r,{status:"opening",problem:null,readiness:Ui(!0,null)})}})),c.state!=="available"){if(c.state==="opening")throw A("unavailable","The collection is still getting ready","collection_unavailable");this.set(r,{status:"blocked",problem:My(c.reason),readiness:Ui(!1,null)});return}this.set(r,{status:"opening",problem:null}),await a();let l=await(this.options.connect??$N(this.options.declaration))(s,e,o,d=>{this.open===r&&!o.aborted&&(d.reason==="not_served"||d.reason==="device_not_serving"||d.reason==="no_device_online")&&this.set(r,{status:"blocked",problem:PA(d),problemDetail:xA(d),readiness:Ui(!1,null)})});if(this.open!==r||o.aborted||l.collection!==e){if(l.close(),this.open===r&&!o.aborted)throw A("invalid_request","a different collection opened","collection_mismatch");return}r.client=l,r.state.status==="blocked"&&this.set(r,{status:"opening",problem:null,readiness:Ui(!0,null)}),r.setup=s.setup(l),r.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===r&&!o.aborted&&!this.closed}),await this.assessOpen(r);let p=0;r.stopLink=l.onLink((d,u)=>{u?this.set(r,{problem:PA(u),problemDetail:xA(u)}):d==="open"&&this.set(r,{problem:null});let f=++p;s.availability(e,{signal:o}).then(h=>{this.open===r&&!o.aborted&&f===p&&this.setAvailability(e,h)}).catch(()=>{})})}catch(s){throw this.open===r&&!o.aborted&&this.set(r,{status:"blocked",problem:PA(s),problemDetail:xA(s),readiness:Ui(!1,null)}),s}}async assessOpen(e){this.set(e,{readiness:Ui(!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 r;try{r=await e.setup.assess({signal:e.life.signal})}catch(o){if(!X(o)||o.code!=="rate_limited")throw o;let s=o.retryAfterMs;await jN(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:r==="ready"?"ready":"setup_required",problem:null,readiness:Ui(!1,r)}),r}}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 r=this.current(),o=await r.setup.apply(e,t);this.set(r,{status:o==="ready"?"ready":"setup_required",problem:null,readiness:Ui(!1,o)})}async configure(e={}){let r=await this.current().setup.plan(e.signal?{signal:e.signal}:{});await this.apply(r,e)}async add(e,t,r){let o;try{o=await this.grants()}catch(i){throw e.close(),i}let s=await o.authorize({popup:e,...t?{collection:t}:{},...r?{signal:r}:{}});return await this.refresh().catch(()=>{}),s.collectionId}async forget(e){this.open?.id===e&&this.close();let t=await this.grants(),r=this.bindings?.find(o=>o.collection_id===e&&o.account_id===this.bindingsAccount);(this.bindings===null||r&&await t.verifiedStoredNativeGrant?.(r))&&await(r?t.forget(e,{expectedNoisePublicKey:r.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 $N(n){return async(e,t,r,o)=>{let{connect:s}=await Promise.resolve().then(()=>(Es(),Tf));return s({connector:e.connector(t),app:{name:n.id,version:"1"},signal:r,waitForDevice:!0,onWaiting:o})}}var kg={};function ID(n){let e=globalThis.document;return!e||typeof e.addEventListener!="function"||e.visibilityState!=="hidden"?Promise.resolve():new Promise((t,r)=>{let o=()=>{e.visibilityState!=="hidden"&&(e.removeEventListener("visibilitychange",o),n.removeEventListener("abort",s),t())},s=()=>{e.removeEventListener("visibilitychange",o),r(n.reason)};e.addEventListener("visibilitychange",o),n.addEventListener("abort",s,{once:!0})})}var qE=new WeakMap;function OD(n){let e=n.unsynced;if(!e)return n;let t=qE.get(n);return t||(t=Object.freeze({...n,status:e.sessionStatus,selectedCollectionId:null,unsynced:null}),qE.set(n,t)),t}var M0=class extends Error{code="application_not_yet_available";constructor(){super("mdbase cannot run in this context"),this.name="MdbaseApplicationUnavailableError"}},j0=Object.freeze({code:"application_not_yet_available"}),Uc=Object.freeze({checking:!1,assessment:null,problem:j0}),RD=Object.freeze({checking:!1,assessment:null,problem:j0,facets:Object.freeze({capabilities:Uc,contracts:Uc,configuration:Uc,files:Uc,people:Uc,notifications:Uc})}),Nc=Object.freeze({checking:!1,assessment:null,problem:null}),Ag=Object.freeze({checking:!1,assessment:null,problem:null,facets:Object.freeze({capabilities:Nc,contracts:Nc,configuration:Nc,files:Nc,people:Nc,notifications:Nc})}),L0=()=>new M0,TE=Object.freeze({state:"none",problem:null,usable:null,requested:Object.freeze({collectionId:null,source:"none",displayName:null,approved:!1})});function ED(n){let e={status:"blocked",signIn:null,collections:Object.freeze([]),selectedCollectionId:null,problem:j0.code,timing:null,readiness:RD,selection:TE},t=Object.freeze({...e,phase:qp(e,n?{messages:n}:{}),sync:null,writes:null,links:null}),r=()=>Promise.reject(L0());return Object.freeze({getSnapshot:()=>t,subscribe:()=>()=>{},start:r,signIn:r,addCollection:r,cancelAuthorization:r,select:r,approve:r,reauthorize:r,refreshCollectionList:r,requestAccess:r,chooseAnother:r,assess:r,configure:r,setup:Object.freeze({plan:r,apply:r}),forget:r,deleteCollection:r,unlock:r,connection:()=>null,setForeground(){throw L0()},close:r,signOut:r,unsynced:Object.freeze({open:r,planTransfer:r,transfer:r,discard:r})})}var qD=n=>typeof n=="object"&&n!==null&&["postMessage","terminate","addEventListener","removeEventListener"].every(e=>typeof n[e]=="function"),TD=(n,e)=>(!e||typeof Worker=="function")&&typeof MessageChannel=="function"&&Rt()!==null&&dt(n);function MD(n){if(n===void 0)return{build:null,host:!0};if(!n||typeof n!="object"||typeof n.build!="string"||!n.build||n.build.length>128||/[\u0000-\u001f\u007f]/.test(n.build))throw new TypeError("session.build must be a short non-empty string");if(n.host!==void 0&&typeof n.host!="boolean")throw new TypeError("session.host must be a boolean");return{build:n.build,host:n.host!==!1}}function LD(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 r=n.returnUrl,o=n.grantReturnUrl;r!==void 0&&(Vv(r,e.manifest)||t()),o!==void 0&&(!Vv(o,e.manifest)||new URL(o).origin!==e.origin)&&t();let s=n.open.bind(n),i=n.close?.bind(n);return Object.freeze({open:s,...i?{close:i}:{},...r!==void 0?{returnUrl:r}:{},...o!==void 0?{grantReturnUrl:o}:{}})}async function jD(n){let e=!0;if(n.webPush){let t=globalThis.navigator?.serviceWorker,r;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=>{r=setTimeout(()=>o(!1),5e3)})]).finally(()=>clearTimeout(r)))}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 UD(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 Sg=class{mdbase;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:Ag});composed=null;hint=null;forgotten=null;handledApproval=null;refreshing=null;refreshedAt=0;approvalPortal=null;revision=0;links=null;cpOrigin=null;messages;opening=null;syncing=null;storagePolicy=null;pendingSave=null;signIn;typeIssues;createWorker;session;privates=null;unsyncedFirst;unsyncedTried=!1;unsyncedOpening=0;timing=new mm;overlaid=new WeakMap;constructor(e,t={}){this.declaration=so(e),this.compiled=Jo(this.declaration);let r=t.readiness?.typeIssues??"block";if(r!=="block"&&r!=="degrade")throw new TypeError('readiness.typeIssues must be "block" or "degrade"');if(this.typeIssues=r,this.unsyncedFirst=t.unsynced===!0,t.urlSelection!==void 0&&typeof t.urlSelection!="boolean")throw new TypeError("urlSelection must be a boolean");if(t.worker!==void 0&&typeof t.worker!="function")throw new TypeError("worker must be a function");if(this.createWorker=t.worker??null,this.messages=t.messages,this.session=MD(t.session),!this.session.host&&this.createWorker)throw new TypeError("worker has no effect with session.host: false");if(this.signIn=LD(t.signIn,this.declaration),!TD(this.declaration.origin,this.session.host)){this.mdbase=ED(t.messages);return}try{let s=this.environment().cpOrigin;this.cpOrigin=s,this.hint=gO(this.declaration.storage.applicationNamespace,s),this.forgotten=hO(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.followNetwork(),this.memory=UD(this.declaration.storage.applicationNamespace),t.privateCollections!==!1&&(this.privates=new Ly({declaration:this.declaration,...this.signIn?.grantReturnUrl?{grantRedirectUri:this.signIn.grantReturnUrl}:{},onChange:()=>{this.revision++,this.notify()}})),this.selection=new gm({browser:new ym(this.declaration.origin,{},t.urlSelection===!1?null:j1()),session:this.selectionSession(),memory:this.memory}),this.selection.subscribe(()=>{this.unforgetApproved(),this.notify(!1)});let o=()=>this.getSnapshot();this.mdbase=Object.freeze({getSnapshot:o,subscribe:s=>(this.listeners.add(s),()=>{this.listeners.delete(s)}),start:s=>this.track(()=>{let i=this.unsyncedFirst&&(!this.unsyncedTried||this.runtime===null);return i&&(this.unsyncedOpening++,this.revision++,this.notify(!1)),this.call(async a=>{let c=a.getNativeSnapshot();c.status==="blocked"&&c.signIn&&c.selectedCollectionId===null?await a.queue(()=>a.start(s)):await this.timing.time("session",()=>this.started(a,s));let l=this.choose(),p=l.getSnapshot();p.state==="blocked"&&p.requested.approved&&p.requested.collectionId!==null&&await l.select(p.requested.collectionId,s);let d=a.getNativeSnapshot();this.unsyncedFirst&&!this.unsyncedTried&&d.status==="signed_out"&&!d.unsynced&&!d.signOutResult&&l.getSnapshot().requested.collectionId===null&&(this.unsyncedTried=!0,await this.timing.time("unsynced",()=>a.queue(()=>a.openUnsynced(s))))}).catch(a=>{let c=this.runtime?.getNativeSnapshot();if(!(a?.code==="open_in_another_tab"&&c?.status==="blocked"&&c.problem==="open_in_another_tab"))throw a}).finally(()=>{i&&(this.unsyncedOpening--,this.revision++,this.notify(!1))})}),signIn:s=>this.track(()=>this.approve(void 0,s)),approve:(s,i)=>this.track(()=>this.approve(s,i)),reauthorize:s=>this.track(()=>{let i=this.choose(),a=i.getSnapshot(),c=this.privates?.state()?.collectionId??a.usable?.collectionId??a.requested.collectionId;return c?this.approve(c,s):i.reauthorize(s)}),addCollection:s=>this.track(()=>this.approve(null,s)),cancelAuthorization:s=>this.track(()=>this.call(async i=>{await i.queue(()=>i.cancelAuthorization(s));let a=i.getNativeSnapshot();this.unsyncedFirst&&a.status==="signed_out"&&!a.unsynced&&this.choose().getSnapshot().requested.collectionId===null&&await i.queue(()=>i.openUnsynced(s))})),refreshCollectionList:s=>this.track(()=>Promise.all([this.call(i=>i.queue(()=>i.refreshCollections(s))),this.privates?.refresh(this.account()).catch(()=>{})])),requestAccess:(s,i)=>this.requestAccess(s,i),select:(s,i)=>this.track(()=>this.choose().select(s,{...i,history:"push"})),chooseAnother:s=>this.track(()=>this.choose().chooseAnother(s)),forget:(s,i)=>this.track(async()=>{let a=this.choose(),c=this.account();if(this.privates?.has(s)){await this.privates.forget(s),a.getSnapshot().requested.collectionId===s&&await a.select(null,i);return}if(c&&this.forgotten){this.forgotten.add(c,s),this.revision++,(a.getSnapshot().requested.collectionId===s||(this.runtime?.getSnapshot()??this.snapshot).selectedCollectionId===s)&&await a.select(null,i),this.notify(!1);return}await this.call(l=>l.queue(()=>l.forget(s,i))),a.getSnapshot().requested.collectionId===s&&await a.select(null,i)}),deleteCollection:(s,i)=>this.track(async()=>{let a=this.choose(),{confirmName:c,...l}=i??{};await this.call(p=>p.queue(()=>p.deleteCollection(s,c,l))),a.getSnapshot().requested.collectionId===s&&await a.select(null,l)}),unlock:(s,i,a)=>this.track(()=>this.call(c=>c.queue(()=>c.unlock(s,i,a)))),assess:s=>this.privates?.isOpen()?this.privates.assess():this.call(i=>i.queue(()=>i.assess(s))),configure:s=>this.track(()=>this.privates?.isOpen()?this.privates.configure(s):this.call(i=>i.queue(()=>i.configure(s)))),setup:Object.freeze({plan:s=>(this.privates?.isOpen()?this.privates.plan(s):this.call(i=>i.queue(()=>i.planSetup(s)))).then(i=>uO(i,this.getSnapshot().readiness)),apply:(s,i)=>dO(this.track(()=>this.privates?.isOpen()?this.privates.apply(s,i):this.call(a=>a.queue(()=>a.applySetup(s,i)))),o)}),connection:s=>this.connection(s),setForeground:s=>this.setForeground(s),close:()=>this.close(),signOut:s=>this.signOut(s),unsynced:Object.freeze({planTransfer:(s={})=>this.call(i=>{let a=this.transferDestination(null);return i.withUnsyncedSource((c,l)=>R_(c.records,a.records,{...s.map?{map:s.map}:{},...s.addTypes?{addTypes:!0}:{},ledger:this.transferLedger(),signal:l}),s)}),transfer:(s,i={})=>this.call(async a=>{let c=this.transferDestination(s?.destination??null),l=await eO(s,c.records,{...i.signal?{signal:i.signal}:{},...i.onProgress?{onProgress:i.onProgress}:{}});if(l.failed.length||l.failedTypes.length)return l;let p=i.signal?{signal:i.signal}:{};return await a.withUnsyncedSource((d,u)=>ZI(s,d.records,c.records,u),p)?Object.freeze({...l,retired:await a.retireUnsynced(s.source,s.destination,p)}):l}),discard:s=>this.track(async()=>{await this.call(async i=>(await this.started(i,s),i.queue(()=>i.discardUnsynced(s))))}),open:s=>this.track(async()=>{let i=this.choose();this.privates?.close(),i.getSnapshot().requested.collectionId!==null&&await i.select(null,{...s,history:"replace"}),await this.call(async a=>(await this.started(a,s),a.queue(()=>a.openUnsynced(s))))})})})}withPrivate(e){let t=this.privates;if(!t)return e;let r=this.overlaid.get(e);if(r&&r.revision===t.revision)return r.value;let o=WR(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()??TE,r=this.composed,o=e.signIn===null&&(e.status==="starting"||e.status==="blocked"&&e.problem==="open_in_another_tab")?this.hint?.read()??null:null;if(r&&r.base===e&&r.selection===t&&r.revision===this.revision&&r.hint===o)return r.value;let s=o?Object.freeze({...e,signIn:o.signIn,collections:o.collections}):e,i=this.forgotten?.read(s.signIn?.accountId)??null,a=i?.size&&s.collections.some(v=>i.has(v.collectionId)&&v.collectionId!==s.selectedCollectionId)?Object.freeze({...s,collections:Object.freeze(s.collections.filter(v=>!i.has(v.collectionId)||v.collectionId===s.selectedCollectionId))}):s,c=a.selectedCollectionId,l=c&&!this.closed?this.privates?.connection(c)??this.runtime?.connection(c)??null:null,p=this.unsyncedOpening>0&&!a.unsynced&&!a.signOutResult&&t.requested.collectionId===null,d=qp({...a,selection:t},{connection:l,previous:r?.value.phase??null,openingUnsynced:p,startPending:this.selection?.startPending()??!1,...this.cpOrigin?{cpOrigin:this.cpOrigin}:{},...this.messages?{messages:this.messages}:{}});d=this.trackOpening(d),this.timing.observe(d),M1(t,d,r?.value);let u=a.transport??null,f=globalThis.navigator?.onLine,h=this.trackSync(d,u!==null||f===!1),m=this.syncing?.writes()??null,w=this.trackPending(Math.max(h?.pending??0,m?.pending.length??0)),b=h&&w!==null?ny(h.pending,this.storagePolicy??{persistent:!1,installed:!1},{pendingForMs:w,connection:h.connection}).warning:null,g=this.syncing?.link(),y=h?Object.freeze(Mf({status:h,writes:m,problem:a.problem,transport:u,live:a.live??null,storageWarning:b!==null,...g===void 0?{}:{link:g},...typeof f=="boolean"?{online:f}:{},...w===null?{}:{pendingForMs:w}})):null,_=Object.freeze({...a,selection:t,phase:d,sync:y,storage:this.storagePolicy,saveWarning:b,links:this.linksFor(c)});return this.composed={base:e,selection:t,revision:this.revision,hint:o,value:_},_}linksFor(e){return this.links&&e?Object.freeze({...this.links,manageAccess:`${this.cpOrigin}/access?collection=${encodeURIComponent(e)}`}):this.links}trackPending(e){let t=this.syncing;if(this.pendingSave&&(this.closed||this.hidden||!e||this.pendingSave.id!==t?.id)&&this.clearPendingSave(),this.closed||this.hidden||!t||!e)return null;if(!this.pendingSave){let r={id:t.id,since:performance.now(),timer:null},o=s=>()=>{this.pendingSave===r&&(r.timer=s===null?null:setTimeout(o(null),s),this.revision++,this.notify(!1))};r.timer=setTimeout(o(28e3),2e3),this.pendingSave=r}return performance.now()-this.pendingSave.since}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 r={id:t,slow:!1,timer:setTimeout(()=>{this.opening===r&&(r.slow=!0,this.revision++,this.notify(!1))},Jf)};this.opening=r}return e.kind==="opening"&&this.opening.slow?{...e,slow:!0}:e}trackSync(e,t){let r=e.kind==="ready"?e.collectionId:null;if(this.syncing&&this.syncing.id!==r){try{this.syncing.stop()}catch{}this.syncing=null}if(e.kind!=="ready"||this.closed)return null;if(!this.syncing){let o=e.connection.records,s=null;try{s=o.status}catch{}let i={id:e.collectionId,stop:()=>{},status:s,writes:()=>null,link:()=>{}},a=()=>{this.syncing===i&&(this.revision++,this.getSnapshot(),this.notify(!1))},c=()=>{},l=()=>{},p=()=>{};try{c=o.onStatus(d=>{i.status=d,a()})}catch{}try{let d=o.ledger;l=d.subscribe(a),i.writes=()=>{try{return d.getSnapshot()}catch{return null}}}catch{}try{p=o.onLink(a),i.link=()=>{try{return o.link}catch{return}}}catch{}i.stop=()=>{c(),l(),p()},this.syncing=i}try{e.connection.records.setTransportDeferred(t)}catch{}return this.syncing.status}nativeAuthorization(e,t,r){return!this.privates||this.closed||this.hidden?Promise.reject(A("unavailable","Native authorization unavailable")):this.privates.nativeAuthorization(e,t,AbortSignal.any([r,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 r=()=>{t?.visibilityState!=="hidden"&&this.refreshCollections()};e.addEventListener("focus",r,{signal:this.lifetime.signal}),t&&typeof t.addEventListener=="function"&&t.addEventListener("visibilitychange",r,{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 r=e.getNativeSnapshot();r.signIn?.state!=="paired"||r.status!=="unselected"&&r.status!=="ready"&&r.status!=="setup_required"||(this.refreshedAt=t,this.privates?.refresh(r.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}},r=(s=!1)=>{this.closed||ry(e,t(),s).then(i=>{this.closed||this.storagePolicy?.persistent===i.persistent&&this.storagePolicy?.installed===i.installed||(this.storagePolicy=i,this.revision++,this.notify(!1))}).catch(()=>{})},o=globalThis.document;o&&typeof o.addEventListener=="function"&&o.addEventListener("visibilitychange",()=>{o.visibilityState!=="hidden"&&r()},{signal:this.lifetime.signal}),r(!0)}notify(e=!0){let t=this.runtime?.getSnapshot(),r=t?.signIn?.state==="paired"?t.signIn.accountId:null;if(r&&!this.closed&&!this.hidden&&(this.privates?.bind(r,t?.signIn?.nativeGrants??[]),this.privates?.ensure(r)),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(OD(this.runtime?.getNativeSnapshot()??this.snapshot)),subscribe:e=>(this.nativeListeners.add(e),()=>{this.nativeListeners.delete(e)}),open:(e,t={})=>this.call(async r=>{let o=this.privates,s=r.getNativeSnapshot().collections.some(c=>c.collectionId===e);if(!o||s||!o.has(e))return o?.close(),r.queue(()=>r.select(e,t));r.getNativeSnapshot().selectedCollectionId!==null&&await r.queue(()=>r.clearSelection(t));let i=r.getNativeSnapshot().signIn?.accountId,a=r.getNativeSnapshot().signIn?.installationId;if(!i||!a)throw A("unauthenticated","Sign in before opening a collection");o.openCollection(e,{account:i,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 Cr({environment:this.declaration.environment,appOrigin:this.declaration.origin,release:$s()})}initialize(){if(this.initialization)return this.initialization;let e=this.incarnation,t=Promise.resolve().then(async()=>{if(this.check(),typeof kg.url!="string")throw L0();let r=new URL(kg.url);if(kt(r)!==this.declaration.origin||Rt()!==this.declaration.origin)throw A("unavailable","Application module binding unavailable","application_worker_module_binding");let o=this.environment(),s=T1(this.declaration.environment,this.declaration.origin),i=await this.timing.time("capabilities",()=>aO(void 0,this.session.host));if(this.check(),!i.ok)throw A("unavailable","This browser can't run mdbase",{reason:i.problem,details:{missing:i.missing.join(",")}});let a=()=>{if(!this.unsyncedFirst)return;let P={origin:this.declaration.origin,environment:this.declaration.environment};for(let C of[s.runtime,s.sqlite])try{q1(C,P)({signal:this.lifetime.signal}).catch(()=>{})}catch{}},c=Promise.resolve().then(()=>(RE(),OE));c.catch(()=>{});let{registered:l,ApplicationRuntime:p}=await this.timing.time("registration",async()=>({registered:await dm({declaration:this.declaration,signal:this.lifetime.signal,isCurrent:()=>!this.closed,onRequest:a}),ApplicationRuntime:(await c).ApplicationRuntime}));if(this.check(),e!==this.incarnation)throw A("cancelled","Application entry fenced","application_entry_fenced");let d=P1(this.declaration,l);l.supersededDeclaredId&&console.info(`mdbase: ${Wf("application_registration_id_superseded")}`);let u=Xf(this.declaration),f=Object.freeze({cpOrigin:o.cpOrigin,appId:d.id,...u===null?{}:{storageNamespace:u}}),h=P=>(this.runtime=P,this.unsyncedTried=!1,P.subscribe(()=>{this.hint?.observe(P.getNativeSnapshot()),this.observeSignOut(P),P.getNativeSnapshot().signIn?.state==="paired"&&this.tabs?.signedIn(),this.notify(),this.awaitOtherTab(P,f)}),P.setForeground(this.foreground),this.notify(),P),m=this.tabsFor(f),w=new AbortController;this.election?.abort(),this.election=w;let b=await this.timing.time("election",()=>m.elect(AbortSignal.any([this.lifetime.signal,w.signal])));if(this.closed||this.hidden||e!==this.incarnation||w.signal.aborted)throw b.kind==="follower"?b.leave():m.resign(),A("cancelled","Application entry fenced","application_entry_fenced");if(b.kind==="follower")return h(new p({declaration:d,compiledManifest:this.compiled,typeIssues:this.typeIssues,cpOrigin:o.cpOrigin,port:b.port,binding:b.binding,releaseWorker:()=>b.leave(),nativeAuthorization:(P,C,R)=>this.nativeAuthorization(P,C,R)}));let g=new MessageChannel,y=crypto.randomUUID(),_,v=this.createWorker,k=v?new URL("./worker.js",r).href:null;try{if(!v)_=new Worker(new URL("./worker.js",kg.url),{type:"module"});else if(_=v(k),!qD(_))throw new TypeError("not a Worker")}catch{throw m.resign(),g.port1.close(),g.port2.close(),A("unavailable","Application Worker construction unavailable","application_worker_unavailable")}let S=P=>{P.preventDefault(),g.port1.dispatchEvent(new MessageEvent("messageerror")),m.fault()};_.addEventListener("error",S);let x=new p({declaration:d,compiledManifest:this.compiled,typeIssues:this.typeIssues,cpOrigin:o.cpOrigin,port:g.port1,binding:y,releaseWorker:()=>{_.removeEventListener("error",S),_.terminate(),m.resign()},nativeAuthorization:(P,C,R)=>this.nativeAuthorization(P,C,R)});try{_.postMessage([cr,y,d,...k!==null?[u,k]:u===null?[]:[u]],[g.port2])}catch{throw _.removeEventListener("error",S),_.terminate(),m.resign(),g.port1.close(),g.port2.close(),A("unavailable","Application bootstrap unavailable","application_worker_binding")}return m.lead({attach:(P,C)=>_.postMessage([cr,y,"attach",C],[P]),detach:P=>_.postMessage([cr,y,"detach",P])}),h(x)}).catch(r=>{let o=this.initialization===t;if(o&&(this.initialization=null),!this.closed&&o){let{problemDetail:s,...i}=this.snapshot,a=r instanceof oe&&r.reason==="application_registration_refused"?qs(r.details):null;this.snapshot=Object.freeze({...i,status:"blocked",problem:typeof r?.reason=="string"?r.reason:typeof r?.code=="string"?r.code:"application_entry_unavailable",...a?{problemDetail:Object.freeze({name:"MdbaseError",code:r.code,registration:a})}:{}}),this.notify()}throw r});this.initialization=t;{let{problemDetail:r,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 r=e.getNativeSnapshot().status;return r==="not_started"||r==="starting"||r==="blocked"&&!e.getNativeSnapshot().signIn?e.queue(()=>e.start(t)):Promise.resolve()}reservePortal(e){this.check();let t=this.environment(),r=e.signal?AbortSignal.any([this.lifetime.signal,e.signal]):this.lifetime.signal,o=ql(this.declaration.environment),s=()=>!this.closed,i=this.signIn?gI(t.cpOrigin,r,s,this.signIn,o):qm(t.cpOrigin,r,s,o);return{portal:Em(i),signal:r}}requestAccess(e,t){try{this.check();let r=this.runtime,o=r?.getNativeSnapshot(),s=o?.selectedCollectionId??null,i=Xm(this.compiled),a=()=>s&&r?Qm(r.getNativeSnapshot(),s):[],c=rO(i,e,t,a()),l=s?r.connection(s):null;if(!r||!s||!l)throw A("invalid_request","requestAccess needs an open collection","access_no_collection");let p=()=>iO(l.files,i,a());if(!c.length)return Promise.resolve(p());let{portal:d,signal:u}=this.reservePortal(t);return oO({granted:p,native:()=>r.getNativeSnapshot(),start:()=>r.queue(()=>r.requestFileAccess(d,s,c,t.reason,{signal:u})),poll:f=>r.queue(()=>r.pollFileAccess(f))},d,u)}catch(r){return Promise.reject(r)}}approve(e,t={}){let r=this.choose(),o=r.getSnapshot(),s=this.approvalPortal;if(s&&o.approval){if((e===void 0?o.requested.collectionId:e)!==o.approval.collectionId)return Promise.reject(new hn("application_selection_busy"));if(t.signal?.aborted)throw A("cancelled","Application entry fenced","application_entry_fenced");return s.closed||s.focus(),Promise.resolve()}return r.approve(e,t)}authorize(e={},t=null){let r;try{r=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(r,e,t)))).catch(o=>{try{r.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 r=t.getNativeSnapshot().signOutResult??null;await this.signedOut(t,r);let o=this.snapshot.signOutResult??r;return o&&await jD(o),this.getSnapshot()}async signedOut(e,t,r=!1){r||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:Ag,...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(),r){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){return this.tabs??=new ty({...e,build:this.session.build===null?kg.url:`app-build/${this.session.build}`},{locks:globalThis.navigator.locks,BroadcastChannel:globalThis.BroadcastChannel},this.leaderLost,this.signedInElsewhere,{lead:this.session.host,wanted:this.hostWanted})}leaderLost=e=>{if(this.closed||this.hidden)return;let t=this.runtime,r=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&&r&&(++this.incarnation,this.initialization=null),!r||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:Ag}),this.notify(),this.selection?.resync(),this.mdbase.start().catch(()=>{})};hostWanted=()=>{this.closed||this.hidden||this.signingOut||this.runtime!==null||this.initialization!==null||(this.selection?.resync(),this.mdbase.start().catch(()=>{}))};signedInElsewhere=()=>{this.closed||this.hidden||this.signingOut||this.runtime!==null||this.initialization!==null||this.snapshot.status!=="signed_out"||(this.selection?.resync(),this.mdbase.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")},r=()=>{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",r,{signal:this.lifetime.signal}),o.addEventListener("online",r,{signal:this.lifetime.signal})),t()}followNetwork(){let e=typeof window>"u"?globalThis:window;if(typeof e.addEventListener!="function")return;let t=()=>{this.closed||(this.revision++,this.notify(!1))};e.addEventListener("online",t,{signal:this.lifetime.signal}),e.addEventListener("offline",t,{signal:this.lifetime.signal})}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,r=this.signIn?.returnUrl!==void 0&&!/^https?:/i.test(this.signIn.returnUrl);t&&typeof t.addEventListener=="function"&&!r&&(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:r,...o}=this.snapshot;this.snapshot=Object.freeze({...o,status:t?"starting":this.snapshot.status,problem:null,selectedCollectionId:null,readiness:Ag})};pageShown=e=>{let t=this.hidden;this.closed||!t||!e.persisted||(this.hidden=null,this.notify(),t.resume&&(this.selection?.resync(),this.mdbase.start().catch(()=>{})))};awaitingOtherTab=!1;awaitOtherTab(e,t){let r=e.getNativeSnapshot(),o=globalThis.navigator?.locks;if(this.awaitingOtherTab||this.closed||r.status!=="blocked"||r.problem!=="open_in_another_tab"||!o)return;this.awaitingOtherTab=!0;let s=this.incarnation,i=this.lifetime.signal,a=()=>!this.closed&&!this.hidden&&s===this.incarnation&&this.runtime===e;W1(o,t,i).then(()=>ID(i)).then(()=>{this.awaitingOtherTab=!1,a()&&(this.selection?.resync(),this.mdbase.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}transferLedger(){let e=this.declaration.storage.unsyncedDatabaseName,t=new AbortController().signal;return Object.freeze({read:(r,o)=>XI(e,r,o??t),record:(r,o,s)=>QI(e,r,o,s??t)})}transferDestination(e){let t=this.getSnapshot().phase;if(t.kind!=="ready")throw A("invalid_request","Open the collection to bring this work into first.","unsynced_transfer_needs_collection");if(e!==null&&t.collectionId!==e)throw A("invalid_request","This plan is for another collection. Plan the transfer again.","unsynced_transfer_plan_stale");return t.connection}connection(e){return this.closed?null:this.privates?.connection(e)??this.runtime?.connection(e)??null}};function ME(n,e={}){return new Sg(n,e).mdbase}Tl();am();ie();function LE(n,e){let t=Jo(so(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 r=new Set(e.records.hello.grant.capabilities),o=new Set(t.required),s=Object.freeze([...new Set([...t.required,...t.optional??[]])].map(i=>Object.freeze({id:i,requirement:o.has(i)?"required":"optional",state:r.has(i)?"available":"missing"})));return Object.freeze({values:s,requiredAvailable:s.every(i=>i.requirement==="optional"||i.state==="available"),missing:Object.freeze(s.filter(i=>i.state==="missing").map(i=>i.id))})}Ye();ve();Es();Ua();up();ve();ie();la();lc();Qd();function jE(n){let e=N(n.collection),t=n.grant?N(n.grant):null;return Mi({description:`relay:${n.collection}`,staticKey:n.staticKey,target:async()=>{let r=await n.resolveRoute();if(!r)throw A("unavailable","no device of this collection is online","no_device_online");let o=Ti(e,t,N(r.targetDevice));return{prologue:o,...r.prologueFirst&&!r.pipe?{preamble:o}:{},remoteStatic:r.noisePublicKey,device:r.targetDevice,openCarrier:s=>r.pipe?cc(r.url,{accessToken:r.pipe.accessToken,collection:r.pipe.collection,grant:n.grant??"",device:r.targetDevice,devicePublicKey:r.noisePublicKey},n.webSocket,s):ac(r.url,n.webSocket,s)}}})}mA();lc();la();Ye();ve();ie();Zt();la();lc();var ND=new Uint8Array(16);function U0(n,e){if(n.length!==32)throw A("invalid_request","the link token is 32 bytes");let t=Ki.dec(e);if(t.kind!=="request"||t.method!=="hello")throw A("internal","expected the hello request");return ue(new Map([[0,n],[1,t.params]]))}function UE(n){let e=N(n.collection),t=n.staticKey??sc(),r=null;return Mi({description:"localhost-link",staticKey:t,firstPayload:o=>U0(r.token,o),target:async()=>{r=typeof n.link=="function"?await n.link():n.link;let o=r;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?ND:N(o.device));return{prologue:s,preamble:s,remoteStatic:o.noisePublicKey,openCarrier:i=>ac(`ws://127.0.0.1:${o.port}/v1/plugin`,n.webSocket,i)}}})}ky();ie();function N0(){let n=new Map;return{get:async e=>n.get(e),put:async(e,t)=>{n.set(e,t)},putIfAbsent:async(e,t)=>{let r=n.get(e);return r||(n.set(e,t),t)},delete:async e=>{n.delete(e)}}}function D0(n="mdbase-keys",e="keys"){let t=globalThis.indexedDB;if(!t)throw A("invalid_request","IndexedDB is not available here; pass another KeyStorage");let r=()=>new Promise((i,a)=>{let c=t.open(n,1);c.onupgradeneeded=()=>c.result.createObjectStore(e),c.onsuccess=()=>i(c.result),c.onerror=()=>a(c.error)}),o=async(i,a)=>{let c=await r();try{return await new Promise((l,p)=>{let d=c.transaction(e,i),u,f=!1;d.oncomplete=()=>f?l(u):p(A("unavailable","key storage transaction completed without a result","key_storage")),d.onabort=()=>p(d.error??A("unavailable","key storage transaction aborted","key_storage")),d.onerror=()=>p(d.error??A("unavailable","key storage transaction failed","key_storage"));try{a(d.objectStore(e),h=>{u=h,f=!0})}catch(h){d.abort(),p(h)}})}finally{c.close()}},s=(i,a)=>o(i,(c,l)=>{let p=a(c);p.onsuccess=()=>l(p.result)});return{get:i=>s("readonly",a=>a.get(i)),put:(i,a)=>s("readwrite",c=>c.put(a,i)).then(()=>{}),putIfAbsent:(i,a)=>o("readwrite",(c,l)=>{let p=c.get(i);p.onsuccess=()=>{if(p.result!==void 0){l(p.result);return}try{let d=c.add(a,i);d.onsuccess=()=>l(a)}catch{c.transaction.abort()}}}),delete:i=>s("readwrite",a=>a.delete(i)).then(()=>{})}}function zE(){return globalThis.crypto?.subtle}async function DD(){let n=zE();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 zD(n){return n.kind==="raw"?{publicKey:n.publicKey,nonExtractable:!1,dh:e=>ni.getSharedSecret(n.secretKey,e)}:{publicKey:n.publicKey,nonExtractable:!n.privateKey.extractable,dh:async e=>{let t=zE(),r=await t.importKey("raw",e,{name:"X25519"},!1,[]),o=await t.deriveBits({name:"X25519",public:r},n.privateKey,256);return new Uint8Array(o)}}}var $D=N0(),NE=new WeakMap;function DE(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 $E(n,e={}){let t=e.storage??(globalThis.indexedDB?D0():$D),r=e.requireNonExtractable,o=NE.get(t);o||(o=new Map,NE.set(t,o));let s=o.get(n);s||(s=(async()=>{let i=await t.get(n);if(i)return i;let a=await DD();if(!a){if(r)throw A("invalid_request","this platform cannot keep a non-extractable X25519 key","key_storage");let c=ni.utils.randomSecretKey();a={kind:"raw",secretKey:c,publicKey:ni.getPublicKey(c)}}return DE(a,r),t.putIfAbsent?t.putIfAbsent(n,a):(await t.put(n,a),a)})(),o.set(n,s));try{let i=await s;return DE(i,r),zD(i)}finally{o.get(n)===s&&o.delete(n)}}Qd();om();Ye();qo();ie();function z0(n,e){for(let t of n.targets??[]){if(!/^[0-9a-f]{64}$/i.test(t.noise_pk)||!t.url||!t.device)continue;let r={url:t.url,targetDevice:t.device,noisePublicKey:Bi(t.noise_pk)};return t.relay_collection?r.pipe={collection:t.relay_collection,accessToken:e}:t.kind==="hosted"&&(r.prologueFirst=!0),r}return null}function BE(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`,r=n.fetch??globalThis.fetch.bind(globalThis);return async()=>{let o=await n.accessToken(),s;try{s=await r(t,{headers:{authorization:`Bearer ${o}`},redirect:"error",credentials:"omit"})}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 i=await s.json(),a=wr(i.availability);if(a?.state==="unavailable")throw Vn(a.reason);let c=z0(i,o);if(!c&&i.reason==="no_device_registered")throw A("unavailable","this collection has no device set up to serve it","no_device_registered");return c}}$m();x_();qo();Es();var B0={};Ca(B0,{APP_BASES_PROFILE:()=>jb,APP_COLLECTION_SETUP_LIMITS:()=>lo,AppAccountKeyProofUnavailableError:()=>ts,AppAccountKeySealedBundle:()=>bc,AppAccountKeyUnlockError:()=>pt,AppCloudCopyBootstrapError:()=>Rn,AppCloudCopyHostError:()=>fr,AppCollectionControlError:()=>Rr,AppCollectionJoinError:()=>fs,AppCollectionJoinLedger:()=>Oc,AppCollectionSetupError:()=>qn,AppCollectionSetupJournal:()=>Wl,AppCpAccountKeyControl:()=>wc,AppCpAuthorityError:()=>lr,AppCpCloudCopyBootstrap:()=>Vl,AppCpDeviceRegistration:()=>xc,AppCpLogAuthority:()=>Bl,AppCpPeopleAuthority:()=>fc,AppDeviceRegistrationError:()=>va,AppHttpLogError:()=>On,AppHttpLogTransport:()=>$l,AppIndexedDbDeviceKeyProtectedStore:()=>Ac,AppIndexedDbDeviceKeyProvider:()=>_c,AppIndexedDbNoiseProtectedStore:()=>Sc,AppInstallationSignInError:()=>tt,AppLogHostError:()=>Pt,AppLogPump:()=>ea,AppProtectedInstallationSignIn:()=>Dl,AppReplicaOwnerError:()=>it,AppStrictDeviceApprovalError:()=>Mt,AppWasmRuntime:()=>Ql,AppWebCloudCopyHost:()=>Cc,AppWebCollectionError:()=>yu,AppWebDeviceKeyCustody:()=>kc,AppWebNoiseCustody:()=>Pc,AppWebSignInSession:()=>xg,UNSYNCED_STORAGE_WARNING:()=>cO,acquireAppInstallationLease:()=>_d,acquireAppReplicaLease:()=>vd,appBrowserDirectAccess:()=>Pg,appCollectionControlClient:()=>zm,appInstallationLockName:()=>Xv,appLocalConnector:()=>Vm,appLogHealth:()=>Ld,appModelPackPlan:()=>Ys,appModelResourcePlan:()=>$t,appMutationSaveState:()=>lO,appReplicaLockName:()=>wm,appSaveState:()=>ny,appStoragePolicy:()=>ry,attachAppLocalFacade:()=>Bm,createAppCollectionPeople:()=>Nm,createAppWebCollectionAdapter:()=>oE,decodeAppBasesCell:()=>Ps,decodeAppBasesDiscoveryResult:()=>of,decodeAppBasesResult:()=>nf,decodeAppBasesSourceResult:()=>sf,decodeAppCollectionSetupIntent:()=>Jt,encodeAppBasesDiscoveryRequest:()=>pp,encodeAppBasesRequest:()=>tf,encodeAppBasesSourceRequest:()=>rf,openAppWebCollectionClient:()=>hg,openOwnedAppWorker:()=>H1,probeAppStorage:()=>KE,readAccountKeyMode:()=>ig,selectAppEnvironment:()=>Cr,unlockPrivateDevice:()=>og,verifyAppHandover:()=>FE});Fm();Ub();function VE(n,e){return n.seq===e.seq&&n.chain===e.chain&&n.policyGeneration===e.policyGeneration&&n.catalogGeneration===e.catalogGeneration}async function FE(n,e){let t=null;try{let{runtime:r,localPort:o,localClient:s,hostedClient:i,source:a}=n,c=i.hello,l=s.hello,p=a.collection,d=a.deviceId,u=i.authenticatedDevice;if(!(P=>typeof P=="string"&&P.replace(/-/g,"").toLowerCase()===d.replace(/-/g,"").toLowerCase())(u))return null;let h=c.status.confirmedHead,m=h?Object.freeze({...h}):void 0;if(!m||!c.headWitness||c.headWitness.length>64*1024||m.seq===0||c.collection!==p||l.collection!==p)return null;t=new Uint8Array(c.headWitness);let w=t,b=()=>{try{return!e.aborted&&n.isCurrent()===!0&&a.isCurrent()===!0&&l.collection===p&&a.collection===p&&a.deviceId===d&&s.hello===l}catch{return!1}},g=()=>{try{let P=r.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(!b()||!g())return!1;let P=r.verifyHandover(o,a,w);return P!==null&&VE(P,m)},_=()=>{try{return!e.aborted&&b()&&i.hello===c&&i.authenticatedDevice===u}catch{return!1}};if(!_()||!y())return null;let v=await s.appliedPrefix(m.seq,{signal:e});if(!_()||!y()||v.seq!==m.seq||v.appliedThrough<m.seq||v.chain!==m.chain)return null;let k=Object.freeze({...m}),S=!1,x={head:k,appliedThrough:v.appliedThrough,isCurrent:()=>{if(S)return!1;try{return y()&&VE(k,m)}catch{return!1}},dispose:()=>{S=!0,w.fill(0)}};return t=null,x}catch{return null}finally{t?.fill(0)}}m0();l0();s0();a0();h0();u0();Id();Cd();RA();xd();Hm();Wm();async function KE(n){if(!n.worker)return{supported:!1,reason:"worker_required"};if(!n.storage?.getDirectory)return{supported:!1,reason:"opfs_unavailable"};let e,t,r=!1,o,s={supported:!1,reason:"probe_failed"};try{let i=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(i))return s;t=i.toLowerCase(),e=await(await n.storage.getDirectory()).getDirectoryHandle(".mdbase-app-probes",{create:!0});let a=await e.getFileHandle(t,{create:!0});if(r=!0,!a.createSyncAccessHandle)s={supported:!1,reason:"sync_handle_unavailable"};else{o=await a.createSyncAccessHandle();let c=new Uint8Array([109,100,98,110]),l=new Uint8Array(c.length);if(o.write(c,{at:0})!==c.length)throw new Error("short probe write");if(o.flush(),o.read(l,{at:0})!==c.length||l.some((p,d)=>p!==c[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 i=!0;try{o?.close()}catch{i=!1,s={supported:!1,reason:"cleanup_failed"}}if(r&&i&&e&&t)try{await e.removeEntry(t)}catch{s={supported:!1,reason:"cleanup_failed"}}}return s}Qo();Xo();y0();es();qd();Js();v_();fg();Sd();var $0=Object.freeze({status:"unsupported"}),Pg=Object.freeze({snapshot(){return $0},async check(n={}){return n.signal?.throwIfAborted(),$0},async request(n={}){return n.signal?.throwIfAborted(),$0},disable(){}});nr();Sd();mu();dI();ie();Sd();mu();Id();Js();es();fg();Cd();xd();VA();fu();Qo();vc();nr();var BD=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","private_device_limit","private_device_not_allowed"]),VD=new Set(["AbortError","ConstraintError","DataCloneError","InvalidStateError","NotAllowedError","NotFoundError","NotReadableError","OperationError","QuotaExceededError","SecurityError","TimeoutError","TransactionInactiveError","UnknownError","VersionError"]),FD=new Set(["device_open","push_nonce","local_read_without_log","read_connect","read_catch_up","read_query","key_wait_offline","close_fence"]),mo=(n,e,t,r={})=>Object.freeze({problem:n,detail:Object.freeze({name:e,code:t,...Object.fromEntries(Object.entries(r).filter(([,o])=>o!==void 0))})});function KD(n){let e=FD.has(n.stage)?n.stage:void 0;if(e!=="device_open"||n.cause instanceof fr)return{stage:e};let{name:t,code:r}=Dc(n.cause).detail;return{stage:e,cause:Object.freeze({name:t,code:r})}}function Dc(n){try{for(let[e,t]of[[tt,"AppInstallationSignInError"],[fr,"AppCloudCopyHostError"],[Rn,"AppCloudCopyBootstrapError"],[qn,"AppCollectionSetupError"],[Rr,"AppCollectionControlError"],[fs,"AppCollectionJoinError"],[lr,"AppCpAuthorityError"],[On,"AppHttpLogError"],[ha,"AppPrivateBootstrapError"],[pt,"AppAccountKeyUnlockError"]])if(n instanceof e){let r=n.reason,s={server:("server"in n?To(n.server):null)??void 0,...n instanceof fr?KD(n):{}};return r==="sync_stalled"?mo("unavailable",t,r,s):BD.has(r)?mo(r,t,r,s):mo("open_failed",t,null,s)}if(n instanceof Lr)return mo(n.reason,"AppDeviceCustodyError",n.reason);if(n instanceof it&&n.reason==="busy")return mo("open_in_another_tab","AppReplicaOwnerError","busy");if(n instanceof oe){let e=vo(n.code)?n.code:null;return mo(e==="outcome_unknown"?e:"open_failed","MdbaseError",e)}if(typeof DOMException<"u"&&n instanceof DOMException){let e=VD.has(n.name)?n.name:null;return mo("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 mo("open_failed",t,null)}catch{}return mo("open_failed","UnknownError",null)}Id();Xo();Qo();f0();ie();var WD=Object.freeze({status:"unselected",problem:null,transport:null,live:null}),mt=n=>new tt(n),WE=(n,e,t)=>n.problem===void 0||n.problem===e?t:void 0,HD=new Set(["collection_not_yet_migrated","collection_migrating","account_suspended","update_required"]),xg=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;restoredPending=!1;acknowledged=!1;consentPending=!1;listCached=!1;fileAccess=null;freshApproval=!1;approvalWindow=null;leftForApproval=!1;nativePending=null;forgotten=new Set;removedScopes=new Set;onAbort=()=>{this.close().catch(()=>{})};constructor(e){this.options=Object.freeze({...e}),this.environment=Cr({environment:e.environment,appOrigin:e.origin,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 r=this.base,o=e===null?void 0:this.slots.get(e);if(!o)return r;if(r.status!=="unselected"&&!t)return Object.freeze({...r,selectedCollectionId:o.id,transport:o.view.transport,live:o.view.live});let{problemDetail:s,...i}=r,{problemDetail:a,...c}=o.view;return Object.freeze({...i,...t?{status:"unselected",problem:null,approval:null}:{},...c,selectedCollectionId:o.id,...a?{problemDetail:a}:{}})}connection(e=this.focus){let t=e===null?void 0:this.slots.get(e),r=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()||!r||!["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=Pg;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 mt("fenced")}publish(e){this.check(),this.setBase(e),this.changed()}setBase(e){let{problemDetail:t,...r}=this.base,o=e.problemDetail??WE(e,r.problem,t);this.base=Object.freeze({...r,...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 r=this.base.timing;if(this.authorizationStartedAt!==null&&(t.status==="ready"||t.status==="setup_required")){let u=Math.max(0,performance.now()-this.authorizationStartedAt);r=Object.freeze({firstScreenMs:r?.firstScreenMs??u,readyMs:t.status==="ready"?r?.readyMs??u:r?.readyMs??null})}this.setBase({timing:r});let{problemDetail:o,unlock:s,...i}=e.view,{unlock:a,...c}=t,l=t.problemDetail??WE(t,i.problem,o),p=(t.status??i.status)==="opening"?"openingProgress"in t?t.openingProgress??null:i.openingProgress??null:null,d=(t.status??i.status)==="needs_unlock"?a??s??null:null;e.view=Object.freeze({...i,...c,openingProgress:p,...d?{unlock:d}:{},...l?{problemDetail:l}:{}}),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(mt("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:i,detail:a}=Dc(s);if(i==="open_failed")try{console.error("mdbase web sign-in open failed",a.name,a.code)}catch{}let c=this.openingSlot;if(this.openingSlot=null,c&&this.slots.get(c.id)===c){let l=!1;try{l=s instanceof Rn&&s.reason==="unavailable"&&s.retryable===!0&&c.view.status==="opening"&&this.base.collections.some(p=>p.collectionId===c.id)&&this.flow?.view().state==="paired"&&this.installation?.isCurrent()===!0}catch{}if(l){try{await this.closeSlot(c),this.check()}catch(p){throw!this.closing&&!this.options.signal.aborted&&this.publishSlot(c,{status:"blocked",problem:"recovery_required",problemDetail:Dc(p).detail}),p}this.publishSlot(c,{status:"unselected",problem:i,problemDetail:a})}else this.publishSlot(c,{status:"blocked",problem:i,problemDetail:a})}else this.publish({status:"blocked",problem:i,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 Dl.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(await this.openDevice(!1,this.options.recoveryFor!==void 0),await this.abandonUnfinishedNativeChoice(),this.flow.collectionConsentView()?.state==="pending")this.consentPending=!0,this.publish({status:"authorizing"});else{let r=null;try{r=this.flow.cachedApprovedCollections(this.installation)}catch{r=null}await this.refreshCollections(r)}else this.restoredPending=t.state==="pending"&&this.flow.requestSent(),this.publish({status:t.state==="pending"&&!this.restoredPending?"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(mt("busy"));let r=this.options.openPortal();return t?t.catch(()=>{}).then(()=>{try{this.check()}catch(s){throw r.close(),s}if(this.pending)throw r.close(),mt("busy");let o=this.base.status;return o!=="authorizing"&&o!=="signed_out"?(r.close(),this.getSnapshot()):this.beginAuthorization(r,e)}):this.beginAuthorization(r,e)}beginAuthorization(e,t){let r={collectionHint:t.collectionHint??null},o=this.flow.view();return this.restoredPending=!1,this.authorizationStartedAt=performance.now(),this.publish({timing:Object.freeze({firstScreenMs:null,readyMs:null}),approval:null}),this.operation(async()=>{try{if(o.state==="paired"){await this.openDevice(),this.check(),await this.abandonUnfinishedNativeChoice();let s=await this.flow.startCollectionConsent(this.installation,this.options.requestedCreateCollections??this.options.freshRequestedCreateCollections??!1,r,this.options.freshRequestedPrivateDevice===!0);this.check(),this.consentPending=!0,e.navigate(s.verificationUri)}else{let s=await this.flow.start(r).catch(i=>this.renewFromGesture(i));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 tt&&s.server?.status===429&&(this.authorizationRateLimit=s,this.authorizationRetryAt=Date.now()+Math.min(Ya,Math.max(Ga,s.server.retryAfterMs??3e4))),e.close(),s}})}requestFileAccess(e,t,r){if(this.check(),!this.flow||this.pending)return Promise.reject(mt("busy"));let o=this.options.openPortal();return this.operation(async()=>{try{if(this.flow.view().state!=="paired"||!this.installation||!this.base.collections.some(i=>i.collectionId===e))throw mt("refused");let s=await this.flow.startFileAccess(this.installation,e,t,r);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 r={state:"pending"};try{r=await this.flow.exchangeFileAccess(this.installation,t)}catch{}if(this.check(),this.fileAccess!==t||r.state==="pending"&&Date.now()<t.expiresAt)return this.getSnapshot();this.fileAccess=null,this.closeApprovalWindow();let o=r.state==="granted"?r.actions:null,s=o?Object.freeze(this.base.collections.map(i=>i.collectionId!==t.collectionId?i:Object.freeze({...i,fileActions:Object.freeze([...new Set([...i.fileActions??[],...o])])}))):this.base.collections;return this.publish({collections:s,fileAccess:Object.freeze({requestId:e,collectionId:t.collectionId,actions:o??t.actions,state:r.state==="pending"?"expired":r.state})}),this.getSnapshot()},!0)}async renewFromGesture(e){if(!(e instanceof tt)||e.reason!=="expired"&&e.reason!=="refused")throw e;try{return await this.flow.renewExpiredPairing()}catch(t){throw t instanceof tt&&t.reason==="recovery_required"?e:t}}renewExpiredPairing(){return this.operation(async()=>{if(!this.flow)throw mt("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(),r=this.consentPending?e.collectionConsentView():null;return(this.consentPending?r?.state!=="pending":!["pending","awaiting_approval"].includes(t.state))?null:JSON.stringify([t.requestId,t.installationId,t.deviceId,t.accountId,t.state,this.consentPending,r?.requestId,r?.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,r=this.pending,o=t?this.receiptGeneration(t):null,s=t&&r&&o!==null?Object.freeze({flow:t,operation:r,generation:o,caller:this.options.signal,installation:this.installation,attested:this.attested,acknowledged:this.acknowledged}):null;this.receiptRead=s;let i=!1;try{let a=await e();return i=a!=null,a}catch(a){if(a instanceof tt&&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&&(!i||!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(r){if(!(r instanceof tt)||r.reason!=="refused"&&r.reason!=="expired")throw r;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 mt("account_confirmation_required");let r=this.flow.pendingNativeSelection?.();if(r?.requestId===t.requestId){if(!await this.settleNativeChoice(r)){this.consentPending=!1,this.closeApprovalWindow(),this.publish({status:"unselected",problem:null,approval:Object.freeze({outcome:"closed"})}),await this.refreshCollections();return}}else if(this.flow.view().collectionSelection?.requestId!==t.requestId&&!this.deviceAccessWithoutPick(t.requestedPrivateDevice===!0?t.addedCollectionIds:[]))throw mt("response");this.consentPending=!1,this.freshApproval=!0,this.closeApprovalWindow(),await this.refreshCollections()}else await this.prepareNativeChoice(),this.resumeApprovalWindow(),this.publish({status:"authorizing",problem:null});return}let e;try{e=await this.exchangeReceipt(()=>this.flow.exchange())}catch(t){if(!this.restoredPending||!(t instanceof tt)||t.reason!=="expired"&&t.reason!=="refused")throw t;this.check(),this.restoredPending=!1,this.publish({status:"signed_out",problem:null});return}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(),this.resumeApprovalWindow()),e.state==="paired"){let t=this.flow.pendingNativeSelection?.(),r=t?.requestId===e.requestId&&!await this.settleNativeChoice(t);if(t?.requestId!==e.requestId&&e.collectionSelection?.requestId!==e.requestId&&!this.deviceAccessWithoutPick(e.privateDeviceCollectionIds??[]))throw mt("response");this.freshApproval=!0,this.closeApprovalWindow(),await this.openDevice(),this.check(),r&&this.publish({approval:Object.freeze({outcome:"closed"})}),await this.refreshCollections()}else this.publish({status:"authorizing",problem:null})}deviceAccessWithoutPick(e){let t=this.flow.view(),r=t.privateDeviceCollectionIds??[];return(t.collectionSelection??null)===null&&e.some(o=>r.includes(o))}resumeApprovalWindow(){if(!(!this.leftForApproval||!this.foreground||!this.approvalWindow||!this.appPartDone())){this.leftForApproval=!1;try{this.approvalWindow.focus?.()}catch{}}}appPartDone(){if(!this.attested)return!1;if(!this.approvalWindow?.nativeAuthorization||!this.installation||!this.flow.nativeAuthorizationContext(this.installation))return!0;let e=this.nativePending;return e!==null&&(e.attempted||e.failed)}async prepareNativeChoice(){let e=this.approvalWindow?.nativeAuthorization;if(!e||!this.installation)return;let t=this.flow.nativeAuthorizationContext(this.installation);if(!t)return;let r=this.nativePending;if(!r){if(r={context:t,port:e,life:new AbortController,prepared:null,failed:!1,attempted:!1},this.nativePending=r,t.authorizationId){r.failed=!0;return}let o=r,s=AbortSignal.any([this.lifetime.signal,this.flowLifetime.signal,r.life.signal]);e.prepare(t,s).then(i=>{this.nativePending!==o||s.aborted||(o.prepared=Object.freeze({...i}))},()=>{o.failed=!0})}if(r.context.requestId!==t.requestId||r.context.accountId!==t.accountId||r.context.challenge!==t.challenge)throw mt("fenced");if(r.prepared&&!r.attempted){r.attempted=!0;try{await this.flow.attachNativeAuthorization(this.installation,r.context,r.prepared),this.check()}catch{r.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 mt("recovery_required");let r=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 mt("fenced");await this.flow.completeNativeAuthorization(this.installation,r),this.check()}async settleNativeChoice(e){await this.openDevice(),this.check();try{return await this.finishNativeChoice(e),!0}catch(t){this.check();let r=!1;try{r=this.installation!==null&&await this.flow.abandonNativeSelection?.(this.installation)===!0}catch{r=!1}if(this.check(),!r)throw t;try{console.warn("mdbase: a Private collection pick was not finished",Dc(t).detail.code)}catch{}return!1}}async abandonUnfinishedNativeChoice(){let e=this.flow;if(!e.pendingNativeSelection?.()||e.view().nativeSelection)return;if(!this.installation||!e.abandonNativeSelection)throw mt("recovery_required");let t=await e.abandonNativeSelection(this.installation);if(this.check(),!t)throw mt("recovery_required")}holdApprovalWindow(e){this.approvalWindow!==e&&this.closeApprovalWindow(),this.approvalWindow=e,this.leftForApproval=!1}closeApprovalWindow(){let e=this.approvalWindow;this.approvalWindow=null,this.leftForApproval=!1;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 r=this.flow.confirmedSelection(),o=Object.freeze({account:r.accountId,installation:r.installationId});this.installationLease=await _d(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(r=>r.host!==null)||(this.host?!this.acknowledged&&this.flow.view().state==="paired"&&(await this.host.completeInstallationSignIn(),this.check(),this.acknowledged=!0):(this.host=await Cc.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}),this.check(),this.acknowledged=this.flow.view().state==="paired"))}async refreshCollections(e=null){let t=e??await this.flow.listApprovedCollections(this.installation);if(this.check(),this.listCached=e!==null,!e)for(let s of this.flow.view().collectionIds)t.some(i=>i.collectionId===s)||this.removedScopes.add(s);let r=Object.freeze(t.filter(s=>!this.forgotten.has(s.collectionId)));for(let s of this.slots.values()){if(s.usable&&s.selected&&!r.some(p=>p.collectionId===s.id)){s.usable=!1,s.lifetime?.abort(),await this.closeSlot(s),this.check(),this.deleteSlot(s);continue}let i=s.usable&&s.selected!==null&&r.some(p=>p.collectionId===s.id),{problemDetail:a,unlock:c,...l}=s.view;s.view=Object.freeze({...l,...i?this.assessed(s.selected):{status:"unselected"},problem:null})}this.publish({status:"unselected",collections:r,problem:null});let o=this.flow.view().collectionSelection?.selectedCollectionId;(this.options.autoSelect??"only")==="only"&&(this.freshApproval&&o&&r.some(s=>s.collectionId===o)?await this.openSlot(o,!0):r.length===1&&await this.openSlot(r[0].collectionId,!0))}schedulePoll(){if(this.pending&&!this.closing&&!this.options.signal.aborted)return;let e=this.foregroundRead;this.foregroundRead=null;for(let r of this.closing||this.options.signal.aborted?[]:this.slots.values()){let o=this.retryAfterMs(r);o===null||r.timer!==null||r.view.status!=="blocked"||(r.timer=setTimeout(()=>{r.timer=null,!(this.slots.get(r.id)!==r||r.view.status!=="blocked"||r.view.problem!=="collection_migrating"||this.flow?.view().state!=="paired")&&this.operation(()=>this.openSlot(r.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 r=null;try{r=To(t.problemDetail?.server)?.retryAfterMs??null}catch{r=null}return Math.min(Ya,Math.max(Ga,r??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,this.approvalWindow&&!this.appPartDone()&&(this.leftForApproval=!0)),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 cancelAuthorization(){for(this.check();this.pending;)await this.pending.catch(()=>{}),this.check();return this.operation(async()=>{if(this.base.status!=="authorizing")return this.getSnapshot();this.closeApprovalWindow();let e=Object.freeze({outcome:"closed"});return this.consentPending?(this.consentPending=!1,this.publish({status:"unselected",problem:null,approval:e}),await this.refreshCollections()):(await this.flow.forgetSentRequest(),this.check(),this.restoredPending=!1,this.publish({status:"signed_out",problem:null,approval:e})),this.getSnapshot()})}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 r=this.base.collections.find(h=>h.collectionId===e);if(!r||this.flow?.view().state!=="paired"||!this.installation)throw mt("refused");let o=t?[...this.slots.values()].filter(h=>h.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 h of o)h.usable=!1,h.lifetime?.abort();this.focus=e,this.settleBase(),this.publishSlot(s,{...this.assessed(s.selected),problem:null});for(let h of o)await this.closeSlot(h),this.check(),this.deleteSlot(h),this.changed();return}for(let h of o)h.usable=!1,h.lifetime?.abort();let i=s??{id:e,host:null,lease:null,leaseScope:null,selected:null,scope:null,lifetime:null,usable:!1,stopAssessment:null,timer:null,view:WD};i.usable=!1,i.lifetime?.abort(),this.slots.set(e,i),this.focus=e,this.openingSlot=i,this.settleBase(),this.publishSlot(i,{status:"opening",problem:null,openingProgress:null});for(let h of o)await this.closeSlot(h),this.check(),this.deleteSlot(h),this.changed();(i.lease||i.selected||i.host)&&await this.closeSlot(i),this.check(),await this.openDevice(!0),this.check(),i.host=this.host,this.host=null;let a=Object.freeze({...this.installation.scope,collection:e});i.lease=await vd(this.options.locks,a,this.lifetime.signal),i.leaseScope=a,this.check(),i.lifetime=new AbortController;let c=this.freshApproval&&this.flow.view().collectionSelection?.createdCollectionIds.includes(e)===!0,l=i.lifetime,p=await this.options.openCollection({host:i.host,installation:this.installation,scope:a,collection:r,setupPolicy:c?"approved-new-collection":"explicit",signal:l.signal,onProgress:h=>{this.closing||this.slots.get(i.id)!==i||i.lifetime!==l||l.signal.aborted||i.view.status!=="opening"||i.view.openingProgress!==h&&this.publishSlot(i,{openingProgress:h})}});i.selected=p,i.scope=a,this.check();let d=this.assessed(p);i.usable=!0,this.openingSlot===i&&(this.openingSlot=null),i.stopAssessment=p.subscribe?.(()=>{if(this.closing||this.slots.get(i.id)!==i||!i.usable||i.selected!==p||i.lifetime?.signal.aborted||!this.sameScope(i.scope,i.leaseScope)||i.scope?.collection!==i.id)return;let h=null;try{h=p.ended??null}catch{h=null}if(h){this.accessEnded(i,p,h);return}let m=null;try{m=p.failure??null}catch{m=null}if(m!==null){this.openFailedLate(i,p,m);return}let w;try{w=this.assessed(p)}catch{return}this.publishSlot(i,w.status==="needs_unlock"?{...w,problem:null,transport:null,live:null}:{...w,...this.liveProblem(i,p)})})??null;let u=null;try{u=p.ended??null}catch{u=null}let f=null;try{f=p.failure??null}catch{f=null}if(u){this.accessEnded(i,p,u);return}if(f!==null){this.openFailedLate(i,p,f);return}this.publishSlot(i,{...d,transport:null,live:null,openingProgress:null})}assessed(e){let t=e.state;if(t==="ready"||t==="setup_required")return{status:t};if(t!=="needs_unlock"||typeof e.unlock!="function")throw mt("response");let r=e.locked;if(!r||typeof r!="object"||!["password","strict","none"].includes(r.mode)||typeof r.unlocking!="boolean"||r.problem!==null&&(typeof r.problem!="string"||!/^[a-z][a-z0-9_]{0,63}$/.test(r.problem)))throw mt("response");return{status:t,unlock:Object.freeze({mode:r.mode,unlocking:r.unlocking,problem:r.problem})}}unlockCollection(e,t){let r=()=>{let o=this.slots.get(e);return o&&o.usable&&o.selected&&typeof o.selected.unlock=="function"&&o.view.status==="needs_unlock"&&!o.lifetime?.signal.aborted&&this.base.status==="unselected"&&this.installation?.isCurrent()===!0&&this.sameScope(o.scope,o.leaseScope)&&o.scope?.collection===e?o:null};return!this.closing&&!this.options.signal.aborted&&!this.pending&&!r()?Promise.reject(mt("refused")):this.operation(async()=>{let o=r();if(!o)throw mt("refused");let s=o.selected;this.openingSlot=o;try{await s.unlock(t),this.check()}catch(a){throw o.usable=!1,o.lifetime?.abort(),a}if(this.slots.get(o.id)!==o||o.selected!==s||!o.usable)throw mt("fenced");this.openingSlot===o&&(this.openingSlot=null);let i=this.assessed(s);return this.publishSlot(o,i.status==="needs_unlock"?{...i,problem:null}:{...i,...this.liveProblem(o,s)}),this.viewFor(e)})}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,r){if(e.selected!==t||!e.usable)return;let o=r==="gone"?"collection_deleted":r==="revoked"?"unauthenticated":"access_removed";r!=="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 i=await this.flow.listApprovedCollections(this.installation);this.check(),this.publish({collections:Object.freeze(i.filter(a=>!this.forgotten.has(a.collectionId)))})}catch{}}).catch(()=>{})}};s()}openFailedLate(e,t,r){if(e.selected!==t||!e.usable)return;let{problem:o,detail:s}=Dc(r);if(o==="open_failed")try{console.error("mdbase web sign-in open failed",s.name,s.code)}catch{}e.usable=!1,this.publishSlot(e,{status:"blocked",problem:o,problemDetail:s,transport:null,live:null});let i=()=>{if(!(this.closing||this.options.signal.aborted||e.selected!==t||this.slots.get(e.id)!==e)){if(this.pending){this.pending.catch(()=>{}).then(i);return}this.operation(async()=>{await this.closeSlot(e),this.publishSlot(e,{status:"blocked",problem:o,problemDetail:s})},!0).catch(()=>{})}};i()}liveProblem(e,t){let r=null;try{r=t.problem??null}catch{r=null}let o=null;try{o=t.health??null}catch{o=null}let s=o?Object.freeze({...o}):null,i=null;try{let c=t.live;i=typeof c=="boolean"?c:null}catch{i=null}let a=pn(r)?It(r):null;return a&&r?{problem:a,problemDetail:Object.freeze({name:"AppHttpLogError",code:a,server:r}),transport:s,live:i}:{...HD.has(e.view.problem??"")?{problem:null}:{},transport:s,live:i}}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)}collectionListCached(){return this.listCached}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 mt("binding");let r=this.flow.collectionRecoveries(),o=this.slots.get(e);if(t===void 0&&!Object.hasOwn(r,e)&&!this.scopeWasRemoved(e))throw mt("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(),i=this.options;if(!await tE({cpOrigin:i.cpOrigin,appId:i.appId,accountId:s.accountId,connectorId:s.connectorId,installationId:s.installationId,deviceId:s.deviceId,collectionIds:[e],databases:[]},e))throw mt("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(r=>r.collectionId!==e))}),this.getSnapshot()})}deleteCollection(e,t){let r=null;return this.operation(async()=>{let o=this.base.collections.find(s=>s.collectionId===e);if(!this.flow||!this.installation||!o)r=new ei("collection_delete_not_found");else if(o.role!=="owner")r=new ei("collection_delete_not_owner");else{try{await this.flow.deleteApprovedCollection(this.installation,e,t)}catch(s){r=pI(s)}this.check()}return this.getSnapshot()}).then(o=>{if(r)throw r;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,r=null,o=null,s=!1;try{r=t?.view()??null}catch{r=null}try{o=t?.confirmedSelection().connectorId??null}catch{o=null}try{s=t?.hasWebPushChannel()===!0}catch{s=!1}let i=[...new Set([...r?.collectionIds??[],...this.base.collections.map(p=>p.collectionId)])];this.closeApprovalWindow(),this.fileAccess=null,this.consentPending=!1;try{await this.closeSlots()}catch(p){throw this.failSignOut(),p}this.check();let a="not_paired";if(t&&r?.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 c=this.options,l=await nE({cpOrigin:c.cpOrigin,appId:c.appId,...c.owner===void 0?{}:{owner:c.owner},...c.storageNamespace===void 0?{}:{storageNamespace:c.storageNamespace},accountId:r?.accountId??null,connectorId:o,installationId:r?.installationId??null,deviceId:r?.deviceId??null,collectionIds:i,databases:c.localDatabases??[],...c.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,...r}=this.base;this.focus=null,this.emit(Object.freeze({...r,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}};fu();mu();return oq(GD);})();