@mdbase-dev/connect 0.1.0-beta.95 → 0.1.0-beta.97

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- "use strict";var MdbaseConnect=(()=>{var mn=Object.defineProperty;var Vr=Object.getOwnPropertyDescriptor;var Gr=Object.getOwnPropertyNames;var Hr=Object.prototype.hasOwnProperty;var $r=(t,e)=>{for(var n in e)mn(t,n,{get:e[n],enumerable:!0})},Wr=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Gr(e))!Hr.call(t,o)&&o!==n&&mn(t,o,{get:()=>e[o],enumerable:!(i=Vr(e,o))||i.enumerable});return t};var Jr=t=>Wr(mn({},"__esModule",{value:!0}),t);var uc={};$r(uc,{ApplicationIdentityStoreError:()=>Ae,FileTransferCryptoError:()=>se,GrantFileTransferCipher:()=>He,IndexedDbApplicationIdentityStore:()=>je,IndexedDbGrantKeyStore:()=>Ee,MDBASE_RECORD_CREATED_CONTRACT:()=>Ii,MDBASE_TIMER_FIRED_CONTRACT:()=>Mi,MdbaseApplicationSession:()=>Ne,MdbaseBrowserSelection:()=>hn,MdbaseCollectionClient:()=>Ge,MdbaseConnect:()=>fn,MdbaseConnectError:()=>b,MdbaseConnection:()=>Ye,MdbaseFileClient:()=>Qe,MdbaseMemorySelection:()=>yn,MdbaseMemoryVerificationStore:()=>mt,MdbaseSession:()=>Le,MemoryApplicationIdentityStore:()=>Ke,MemoryGrantKeyStore:()=>qe,RelayCryptoError:()=>x,applicationIdentity:()=>Bt,applicationInstallationId:()=>Ve,authorityProofMessage:()=>zn,connectError:()=>d,connectFailure:()=>g,connectProblem:()=>w,connectSuccess:()=>I,createPkce:()=>dt,decryptRelayResponse:()=>ze,deriveFileTransferKey:()=>Vn,deriveP256SharedSecret:()=>st,effectiveCapabilities:()=>kt,encryptRelayRequest:()=>oe,externalStore:()=>jr,isRetryableConnectError:()=>zi,operationProblem:()=>ke,operationsForApplicationCapabilities:()=>wi,parseMdbaseNativeNotificationData:()=>Nr,parseMdbasePushPayload:()=>si,showMdbasePushNotification:()=>Br,signApplicationAuthorization:()=>gt,signAuthorityRequest:()=>Et,validateGrantEncryption:()=>re});var be={access_denied:{category:"authorization",recovery:"reauthorize"},access_paused:{category:"availability",recovery:"resume_connector_access"},application_declaration_mismatch:{category:"authorization",recovery:"reauthorize"},application_identity_unavailable:{category:"compatibility",recovery:"upgrade_application"},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_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_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_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_request:{category:"validation",recovery:"fix_request"},invalid_token_response:{category:"integrity",recovery:"contact_support"},legacy_scope_reauthorization_required:{category:"authorization",recovery:"reauthorize"},managed_fcm_not_declared:{category:"compatibility",recovery:"fix_request"},manifest_load_failed:{category:"availability",recovery:"retry"},manifest_required:{category:"validation",recovery:"fix_request"},missing_grant_key:{category:"authorization",recovery:"reauthorize"},mutation_recovery_expired:{category:"compatibility",recovery:"none"},mutation_request_conflict:{category:"conflict",recovery:"resolve_conflict"},no_pending_mutation:{category:"conflict",recovery:"refresh"},not_authorized:{category:"authorization",recovery:"reauthorize"},not_remote_authority:{category:"compatibility",recovery:"choose_collection"},notification_criterion_not_declared:{category:"validation",recovery:"fix_request"},notification_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"},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"},sandbox_unsupported:{category:"compatibility",recovery:"fix_request"},scope_denied:{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"},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"}},Qr={access_denied:{type:"object",required:[],properties:{return_to:{type:"string"}}},approval_window_blocked:{type:"object",required:["user_code","verification_uri","verification_uri_complete","expires_at","interval_seconds"],properties:{user_code:{type:"string"},verification_uri:{type:"string"},verification_uri_complete:{type:"string"},expires_at:{type:"integer"},interval_seconds:{type:"integer"}}},authorization_binding_incompatible:{type:"object",required:["contract","required","supported","peer"],properties:{contract:{type:"string"},required:{type:"array",items:{type:"integer"}},supported:{type:"array",items:{type:"integer"}},peer:{type:"string"},operation:{type:"string"}}},capability_contract_incompatible:{type:"object",required:["contract","required","supported","peer"],properties:{contract:{type:"string"},required:{type:"array",items:{type:"integer"}},supported:{type:"array",items:{type:"integer"}},peer:{type:"string"},operation:{type:"string"}}},collection_configuration_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_contracts_missing:{type:"object",required:["contracts"],properties:{contracts:{type:"array",items:{type:"object",required:["id","version"],properties:{id:{type:"string"},version:{type:"string"}}}}}},collection_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_type_registry_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_version_unsupported:{type:"object",required:["current_version","required_version"],properties:{current_version:{type:"string"},required_version:{type:"string"}}},connector_offline:{type:"object",required:[],properties:{connector_name:{type:"string"}}},durable_mutation_unsupported:{type:"object",required:["contract","required","supported","peer"],properties:{contract:{type:"string"},required:{type:"array",items:{type:"integer"}},supported:{type:"array",items:{type:"integer"}},peer:{type:"string"},operation:{type:"string"}}},insufficient_access:{type:"object",required:["required_operations","granted_operations","missing_operations"],properties:{required_operations:{type:"array",items:{type:"string"}},granted_operations:{type:"array",items:{type:"string"}},missing_operations:{type:"array",items:{type:"string"}}}},invalid_application_manifest:{type:"object",required:["issues"],properties:{issues:{type:"array",items:{type:"object",required:["path","keyword","message","params"],properties:{path:{type:"string"},keyword:{type:"string"},message:{type:"string"},params:{type:"object"}}}}}},mutation_request_conflict:{type:"object",required:["request_id"],properties:{request_id:{type:"string"}}},operation_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}},partial_result:{}}},operation_outcome_unknown:{type:"object",required:["request_id"],properties:{request_id:{type:"string"}}},rate_limited:{type:"object",required:[],properties:{retry_after_ms:{type:"integer"}}},transport_protocol_incompatible:{type:"object",required:["contract","required","supported","peer"],properties:{contract:{type:"string"},required:{type:"array",items:{type:"integer"}},supported:{type:"array",items:{type:"integer"}},peer:{type:"string"},operation:{type:"string"}}}};function ci(t){return Object.hasOwn(be,t)}function Xe(t){if(!li(t))return!1;let e=t;if(e.problem_version!==1||typeof e.message!="string"||e.message.length===0||e.operation_outcome!==void 0&&e.operation_outcome!=="not_sent"&&e.operation_outcome!=="rejected"&&e.operation_outcome!=="unknown"||e.trace_id!==void 0&&(typeof e.trace_id!="string"||e.trace_id.length===0))return!1;if(e.code==="unknown")return typeof e.server_code=="string"&&e.server_code.length>0&&e.category==="unknown"&&e.recovery==="none";if(typeof e.code!="string"||!ci(e.code)||e.server_code!==void 0)return!1;let n=be[e.code],i=Qr[e.code],o=i===void 0?e.details===void 0:e.details===void 0?(i.required?.length??0)===0:gn(e.details,i);return e.category===n.category&&e.recovery===n.recovery&&o}function gn(t,e){if(e.type===void 0)return!0;if(e.type==="string")return typeof t=="string";if(e.type==="integer")return typeof t=="number"&&Number.isInteger(t);if(e.type==="number")return typeof t=="number"&&Number.isFinite(t);if(e.type==="boolean")return typeof t=="boolean";if(e.type==="array")return Array.isArray(t)&&t.every(i=>gn(i,e.items??{}));if(!li(t))return!1;if(!e.properties)return!0;let n=t;return!Object.keys(n).every(i=>Object.hasOwn(e.properties,i))||!(e.required??[]).every(i=>Object.hasOwn(n,i))?!1:Object.entries(n).every(([i,o])=>gn(o,e.properties[i]))}function li(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function _n(t,e,n={}){if(ci(t)){let i=be[t],o={problem_version:1,code:t,category:i.category,recovery:i.recovery,message:e,...n.details===void 0?{}:{details:n.details},...n.operation_outcome===void 0?{}:{operation_outcome:n.operation_outcome},...n.trace_id===void 0?{}:{trace_id:n.trace_id}};if(Xe(o))return o}return{problem_version:1,code:"unknown",server_code:t,category:"unknown",recovery:"none",message:e,...n.details===void 0?{}:{details:n.details},...n.operation_outcome===void 0?{}:{operation_outcome:n.operation_outcome},...n.trace_id===void 0?{}:{trace_id:n.trace_id}}}var di=new Uint8Array([77,68,66,70]),ui=1,pi=0,yc=new Uint8Array([77,68,66,82]);var fi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function hi(t,e={}){return{actions:[...new Set([...t.required,...e.includeOptional===!1?[]:t.optional??[]])],scope:structuredClone(t.scope)}}var k=class extends Error{code;constructor(e,n){super(n),this.code=e,this.name="FileFrameError"}};function Yr(t){return t==="upload_chunk"?1:2}function Xr(t){if(t===1)return"upload_chunk";if(t===2)return"download_chunk";throw new k("invalid_kind",`Unknown file frame kind ${t}`)}function Zr(t){if(!t||typeof t!="object"||Array.isArray(t))throw new k("invalid_header","File frame header must be a JSON object");return t}function Ct(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new k("invalid_header",`File frame header ${e} must be a non-empty string`);return n}function bt(t,e){let n=Ct(t,e);if(!fi.test(n))throw new k("invalid_header",`File frame header ${e} must be a UUID`);return n}function Ce(t,e,n=Number.MAX_SAFE_INTEGER){let i=t[e];if(!Number.isSafeInteger(i)||i<0||i>n)throw new k("invalid_header",`File frame header ${e} is outside its allowed range`);return i}function bn(t){if(t.protocol_version!==1)throw new k("unsupported_version",`Unsupported file transfer protocol ${t.protocol_version}`);if(t.protection!=="grant_aead_v1"&&t.protection!=="transport_tls")throw new k("invalid_header","Unknown file transfer protection");if(t.direction!=="upload"&&t.direction!=="download")throw new k("invalid_header","Unknown file transfer direction");for(let[e,n]of[["grant_id",t.grant_id],["authority_id",t.authority_id],["collection_id",t.collection_id],["transfer_id",t.transfer_id]])if(!fi.test(n))throw new k("invalid_header",`File frame header ${e} must be a UUID`);for(let[e,n,i]of[["chunk_size",t.chunk_size,4194304],["chunk_index",t.chunk_index,Number.MAX_SAFE_INTEGER],["offset",t.offset,Number.MAX_SAFE_INTEGER],["plaintext_length",t.plaintext_length,4194304],["total_size",t.total_size,Number.MAX_SAFE_INTEGER]])if(!Number.isSafeInteger(n)||n<0||n>i)throw new k("invalid_header",`File frame header ${e} is outside its allowed range`);if(t.chunk_size<64*1024)throw new k("invalid_header","File frame chunk_size is below the protocol minimum");if(!Number.isSafeInteger(t.scope_epoch)||t.scope_epoch<1)throw new k("invalid_header","File frame header scope_epoch must be a positive integer");if(t.protection==="grant_aead_v1"&&!t.key_id)throw new k("invalid_header","AEAD-protected file frames require key_id");return{protocol_version:1,protection:t.protection,grant_id:t.grant_id,authority_id:t.authority_id,collection_id:t.collection_id,transfer_id:t.transfer_id,direction:t.direction,chunk_size:t.chunk_size,chunk_index:t.chunk_index,offset:t.offset,plaintext_length:t.plaintext_length,total_size:t.total_size,scope_epoch:t.scope_epoch,...t.key_id===void 0?{}:{key_id:t.key_id}}}function ea(t){let e;try{e=new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{throw new k("invalid_header","File frame header is not valid UTF-8")}let n;try{n=Zr(JSON.parse(e))}catch(l){throw l instanceof k?l:new k("invalid_header","File frame header is not valid JSON")}let i=new Set(["protocol_version","protection","grant_id","authority_id","collection_id","transfer_id","direction","chunk_size","chunk_index","offset","plaintext_length","total_size","scope_epoch","key_id"]);if(Object.keys(n).some(l=>!i.has(l)))throw new k("invalid_header","File frame header contains an unknown field");let o=Ce(n,"protocol_version");if(o!==1)throw new k("unsupported_version",`Unsupported file transfer protocol ${o}`);let r=Ct(n,"protection"),a=Ct(n,"direction"),s=n.key_id===void 0?void 0:Ct(n,"key_id"),c=bn({protocol_version:1,protection:r,grant_id:bt(n,"grant_id"),authority_id:bt(n,"authority_id"),collection_id:bt(n,"collection_id"),transfer_id:bt(n,"transfer_id"),direction:a,chunk_size:Ce(n,"chunk_size",4194304),chunk_index:Ce(n,"chunk_index"),offset:Ce(n,"offset"),plaintext_length:Ce(n,"plaintext_length",4194304),total_size:Ce(n,"total_size"),scope_epoch:Ce(n,"scope_epoch"),...s===void 0?{}:{key_id:s}});if(JSON.stringify(c)!==e)throw new k("invalid_header","File frame header must use the canonical field order without duplicate fields or whitespace");return c}function Cn(t,e,n){let i=t==="upload_chunk"?"upload":"download";if(e.direction!==i)throw new k("invalid_header",`Frame kind ${t} requires direction ${i}`);let o=e.chunk_index*e.chunk_size;if(!Number.isSafeInteger(o)||e.offset!==o)throw new k("invalid_header","Chunk offset does not match its index and protocol chunk size");if(e.offset+e.plaintext_length>e.total_size)throw new k("invalid_header","Chunk extends past the declared transfer size");let r=e.protection==="grant_aead_v1"?e.plaintext_length+16:e.plaintext_length;if(n!==r)throw new k("invalid_length","Payload length does not match the protected plaintext length")}function ta(t){return t.plaintext_length+(t.protection==="grant_aead_v1"?16:0)}function vt(t,e){let n=bn(e),i=ta(n);Cn(t,n,i);let o=new TextEncoder().encode(JSON.stringify(n));if(o.byteLength>16384)throw new k("limit_exceeded","File frame header exceeds the protocol limit");let r=new Uint8Array(16+o.byteLength);r.set(di,0);let a=new DataView(r.buffer,r.byteOffset,r.byteLength);return a.setUint8(4,ui),a.setUint8(5,Yr(t)),a.setUint16(6,pi,!1),a.setUint32(8,o.byteLength,!1),a.setUint32(12,i,!1),r.set(o,16),r}function yi(t){let e=bn(t.header);if(Cn(t.kind,e,t.payload.byteLength),t.payload.byteLength>4194320)throw new k("limit_exceeded","File frame payload exceeds the protocol limit");let n=vt(t.kind,e),i=new Uint8Array(n.byteLength+t.payload.byteLength);return i.set(n,0),i.set(t.payload,n.byteLength),i}function wt(t,e={}){if(t.byteLength<16)throw new k("invalid_length","File frame is shorter than its fixed prefix");if(!di.every((f,h)=>t[h]===f))throw new k("invalid_magic","File frame magic is not MDBF");let n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=n.getUint8(4);if(i!==ui)throw new k("unsupported_version",`Unsupported file frame version ${i}`);let o=Xr(n.getUint8(5));if(n.getUint16(6,!1)!==pi)throw new k("unsupported_flags","File frame uses unsupported flags");let r=n.getUint32(8,!1),a=n.getUint32(12,!1),s=e.maxHeaderBytes??16384,c=e.maxPayloadBytes??4194320;if(r===0)throw new k("invalid_length","File frame header must not be empty");if(r>s||a>c)throw new k("limit_exceeded","File frame exceeds the configured decode limits");let l=16+r+a;if(!Number.isSafeInteger(l)||l!==t.byteLength)throw new k("invalid_length","File frame lengths do not match the supplied bytes");let u=16+r,p=ea(t.subarray(16,u));return Cn(o,p,a),{kind:o,header:p,payload:t.slice(u)}}var na=["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"],ia=["list_files","open_file_upload","open_file_download","move_file","delete_file","get_file_transfer_status","commit_file_upload","abort_file_transfer"],oa={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"},ra={describe:1,changes:1,read:1,query:1,list_views:1,execute_view:1,read_view_source:1,create_view_source:1,update_view_source:1,delete_view_source:1,validate:1,create:1,update:1,delete:1,rename:1,read_type:1,create_type:1,update_type:1,assess_type_pack:1,apply_type_pack:1,assess_collection_setup:1,apply_collection_setup:1,list_timers:1,put_timer:1,cancel_timer:1,reconcile_timers:1,sync:1},aa={list_files:1,open_file_upload:1,open_file_download:1,move_file:1,delete_file:1,get_file_transfer_status:1,commit_file_upload:1,abort_file_transfer:1},sa=new Set(["open_file_upload","move_file","delete_file","commit_file_upload","abort_file_transfer"]),ca=new Set(["delete","rename"]);var la=new Set(na),da=new Set(ia);function mi(t){return la.has(t)}function ua(t){return da.has(t)}function gi(t,e){if(t==="file_control"){let n=_i(e)&&typeof e.type=="string"?e.type:"";if(!ua(n))throw new Error(`Unknown file-control message: ${n}`);return aa[n]}return ra[t]}function de(t,e){let n=_i(e)?e:{};if(n.dry_run===!0&&ca.has(t))return null;if(t==="file_control"){let o=typeof n.type=="string"?n.type:"";return sa.has(o)?`file_control:${o}`:null}let i=oa[t];return i==="always"?t:i==="sync_action"&&n.action==="mutate"?"sync:mutate":null}function ue(t,e){return de(t,e)!==null}function _i(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var pa=1,fa="mdbase-connect mutation fingerprint v1\0",vn=new TextEncoder;function ha(t){return wn(t,new Set)}function ya(t,e){let n=de(t,e);if(n===null)throw new TypeError("The operation is not a canonical mutation.");let i=vn.encode(n),o=vn.encode(ha(e)),r=vn.encode(fa),a=new Uint8Array(r.length+4+8+i.length+4+8+o.length),s=new DataView(a.buffer),c=0;return a.set(r,c),c+=r.length,s.setUint32(c,pa,!1),c+=4,c=Ci(a,s,c,i),s.setUint32(c,gi(t,e),!1),c+=4,Ci(a,s,c,o),a}async function vi(t,e){let n=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",ya(t,e).buffer));return ma(n)}function wn(t,e){if(t===null)return"null";if(t===!0)return"true";if(t===!1)return"false";if(typeof t=="string")return bi(t),JSON.stringify(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError("Mutation input numbers must be finite.");return JSON.stringify(t)}if(typeof t!="object")throw new TypeError(`Mutation input contains unsupported ${typeof t}.`);if(e.has(t))throw new TypeError("Mutation input must not contain cycles.");e.add(t);try{if(Array.isArray(t)){if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("Mutation input must not contain symbol properties.");let o=[];for(let r=0;r<t.length;r+=1){if(!Object.hasOwn(t,r))throw new TypeError("Mutation input arrays must not be sparse.");o.push(wn(t[r],e))}return`[${o.join(",")}]`}let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new TypeError("Mutation input objects must be plain JSON objects.");if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("Mutation input must not contain symbol properties.");let i=Object.entries(t);for(let[o]of i)bi(o);return i.sort(([o],[r])=>o<r?-1:o>r?1:0),`{${i.map(([o,r])=>{let a=Object.getOwnPropertyDescriptor(t,o);if(!a||a.get||a.set)throw new TypeError("Mutation input must not contain accessor properties.");return`${JSON.stringify(o)}:${wn(r,e)}`}).join(",")}}`}finally{e.delete(t)}}function bi(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n>=55296&&n<=56319){let i=t.charCodeAt(e+1);if(!(i>=56320&&i<=57343))throw new TypeError("Mutation input strings must not contain lone surrogates.");e+=1}else if(n>=56320&&n<=57343)throw new TypeError("Mutation input strings must not contain lone surrogates.")}}function Ci(t,e,n,i){return e.setBigUint64(n,BigInt(i.length),!1),n+=8,t.set(i,n),n+i.length}function ma(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}var St={"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"]},Rt=["assess_collection_setup","apply_collection_setup"];function wi(t,e={}){let n=e.includeOptional===!1?t.required:[...t.required,...t.optional??[]];return[...new Set(n.flatMap(i=>St[i]))]}var ga=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([])});function W(t,e){let n=t===1?ga:t===2?St:void 0;if(!(!n||!Object.hasOwn(n,e)))return[...n[e]]}var Cc=Object.freeze([1]);var $=3,ba=2,Si=[$,ba],ee=5,Sn=4,Ri=[ee,Sn],Ca=2,va=1,Sc={operation_transport:[...Si],authorization_binding:[...Ri],semantic_capabilities:[Ca,1],durable_mutation:[va]};function Rn(t,e,n=[],i=2){let o={operation_transport:$,authorization_binding:ee,semantic_capabilities:i},r=[...new Set(n)].filter(a=>a!==$).sort((a,s)=>s-a);return r.length>0&&(o.operation_transport_recovery=r),(t.some(a=>ue(a,{action:"mutate"}))||e?.actions.some(a=>a!=="list"&&a!=="read")===!0)&&(o.durable_mutation=1),o}function Ze(t){return Si.includes(t)}function Ai(t){return Ri.includes(t)}var wa=new TextEncoder().encode("mdbase-connect application installation id v2\0"),Sa=new TextEncoder().encode("mdbase-connect application authorization proof v4\0"),Ra=new TextEncoder().encode("mdbase-connect application authorization proof v5\0");async function Oi(t){let e=At(t),i=new Uint8Array(await crypto.subtle.digest("SHA-256",ve([wa,N(e)]))).slice(0,16);return i[6]=i[6]&15|128,i[8]=i[8]&63|128,[et(i.slice(0,4)),et(i.slice(4,6)),et(i.slice(6,8)),et(i.slice(8,10)),et(i.slice(10,16))].join("-")}function Ti(t){let e=[At(t.installation_signing_public_key),At(t.grant_agreement_public_key),At(t.grant_signing_public_key)];if(e.some((c,l)=>e.slice(l+1).some(u=>Ia(c,u))))throw new Error("Application authorization keys must be distinct.");let n=An(t.authorization_nonce),i=An(t.code_challenge),o=t.contracts,r=o.operation_transport_recovery??[],a=t.requested_operations.some(c=>ue(c,{action:"mutate"}))||t.requested_files?.actions.some(c=>!["list","read"].includes(c))===!0;if(!Ai(t.protocol_version)||n.byteLength!==32||!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(t.application_declaration_id)||!/^[0-9a-f]{64}$/u.test(t.application_manifest_digest)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(t.issued_at)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(t.expires_at)||i.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!==t.protocol_version||!Ze(o.operation_transport)||t.protocol_version===ee&&o.operation_transport!==$||r.some(c=>!Ze(c)||c===o.operation_transport)||new Set(r).size!==r.length||t.protocol_version===Sn&&r.length>0||r.length>0&&!a||(a?o.durable_mutation!==1:o.durable_mutation!==void 0)||t.requested_operations.length===0&&t.requested_files===void 0||new Set(t.requested_operations).size!==t.requested_operations.length||t.requested_operations.some(c=>!c||c.includes("\0"))||(t.flow==="authorization_code"?t.redirect_uri===void 0||t.state===void 0:t.flow!=="device_code"||t.redirect_uri!==void 0||t.state!==void 0))throw new Error("Application authorization binding is invalid.");Pa(t.requested_files);let s=t.requested_operations.map(c=>N(new TextEncoder().encode(c)));return ve([t.protocol_version===ee?Ra:Sa,Q(t.protocol_version),N(Pt(t.application_id)),N(Pt(t.authorization_id)),N(new TextEncoder().encode(t.application_declaration_id)),N(ki(t.application_manifest_digest)),N(Pt(t.application_installation_id)),...e.map(N),N(new TextEncoder().encode(t.flow)),N(n),N(new TextEncoder().encode(t.issued_at)),N(new TextEncoder().encode(t.expires_at)),Pi(t.redirect_uri),Pi(t.state),N(new TextEncoder().encode(t.code_challenge)),Q(o.operation_transport),...t.protocol_version===ee?[Q(r.length),...r.map(Q)]:[],Q(o.authorization_binding),Q(o.semantic_capabilities),Aa(o.durable_mutation),Q(s.length),...s,Oa(t.requested_files),Ta(t.collection_id)])}function Aa(t){return t===void 0?new Uint8Array(1):ve([new Uint8Array([1]),Q(t)])}function Pa(t){if(t!==void 0&&(t.actions.length===0||new Set(t.actions).size!==t.actions.length||t.scope.kind==="selected_folders"&&(t.scope.folders.length===0||new Set(t.scope.folders).size!==t.scope.folders.length||t.scope.folders.some(e=>!e||e.includes("\0")))))throw new Error("Application authorization file request is invalid.")}function Oa(t){if(t===void 0)return new Uint8Array(1);let e=t.actions.map(n=>N(new TextEncoder().encode(n)));return ve([new Uint8Array([1]),Q(e.length),...e,N(new TextEncoder().encode(t.scope.kind)),...t.scope.kind==="selected_folders"?[Q(t.scope.folders.length),...t.scope.folders.map(n=>N(new TextEncoder().encode(n)))]:[]])}function Pi(t){return t===void 0?new Uint8Array(1):ve([new Uint8Array([1]),N(new TextEncoder().encode(t))])}function Ta(t){return t===void 0?new Uint8Array(1):ve([new Uint8Array([1]),N(Pt(t))])}function At(t){let e=An(t);if(e.byteLength!==65||e[0]!==4)throw new Error("Application authorization public key is invalid.");return e}function An(t){if(!/^[A-Za-z0-9_-]+$/u.test(t))throw new Error("Invalid base64url value.");let e=t.replaceAll("-","+").replaceAll("_","/"),n=e.padEnd(Math.ceil(e.length/4)*4,"="),i=Uint8Array.from(atob(n),o=>o.charCodeAt(0));if(ka(i)!==t)throw new Error("Non-canonical base64url value.");return i}function Pt(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(t))throw new Error("Invalid UUID value.");let e=t.replaceAll("-","");return ki(e)}function ki(t){if(!/^[0-9a-f]+$/u.test(t)||t.length%2!==0)throw new Error("Invalid hexadecimal value.");return Uint8Array.from({length:t.length/2},(e,n)=>Number.parseInt(t.slice(n*2,n*2+2),16))}function N(t){return ve([Q(t.byteLength),t])}function Q(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!1),e}function ve(t){let e=new Uint8Array(t.reduce((i,o)=>i+o.byteLength,0)),n=0;for(let i of t)e.set(i,n),n+=i.byteLength;return e}function ka(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function Ia(t,e){return t.byteLength===e.byteLength&&t.every((n,i)=>n===e[i])}function et(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}var Ii={id:"mdbase.record.created",version:"1.0.0",digest:"sha256:7f3bed6baa356ee9389e977ae7b77a102e2bee871a7c1d9f2026fc21cacdbfc9"};var Mi={id:"mdbase.runtime.timer.fired",version:"1.0.0",digest:"sha256:41105be7a7abf33b31ced47e1e1965242236e40ccaea286b959b0a8c591f5642"};var xi=28485,tt="P256-HKDF-SHA256-AES256GCM",Ot=1;var Ma="contract-setup-v1",xa="file-relay-v1",Ea="protocol-usage-report-v1",qa="policy-freshness-lease-v1",za=["application-authorization-v4","authorization-activation","encrypted-relay","policy-ack"];var Fa=["durable-mutation-journal-v1","durable-file-lifecycle-v1"],Da="candidate-b-activation-v1",kc=[...Fa,"mutation-replay-after-credential-retirement-v1",Da],Ua="application-declaration-evidence-v1",Ic=[Ua,...za,qa,"application-authorization-v5",Ma,xa,Ea],Pn=1;var Ei="mdbase-authority-request-proof-v1",nt={version:"x-mdbase-proof-version",timestamp:"x-mdbase-proof-timestamp",nonce:"x-mdbase-proof-nonce",signature:"x-mdbase-proof-signature"};var b=class extends Error{constructor(n,i={}){super(n.message,i.cause===void 0?void 0:{cause:i.cause});this.problem=n;this.name="MdbaseConnectError",this.code=n.code,this.status=i.status}problem;code;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 w(t,e,...[n={}]){let i=be[t];return{problem_version:1,code:t,category:i.category,recovery:i.recovery,message:e,...n.details===void 0?{}:{details:n.details},...n.operationOutcome===void 0?{}:{operation_outcome:n.operationOutcome},...n.traceId===void 0?{}:{trace_id:n.traceId}}}function qi(t,e,n={}){return _n(t,e,{details:n.details,operation_outcome:n.operationOutcome,trace_id:n.traceId})}function d(t,e,...n){let i=n[0];return new b(w(t,e,...n),{status:i?.status,cause:i?.cause})}function U(t,e,n={}){let{status:i,cause:o,...r}=n;return new b(_n(t,e,{details:r.details,operation_outcome:r.operationOutcome,trace_id:r.traceId}),{status:i,cause:o})}function ke(t){let e=Na(t.diagnostics),n=Ka(t.diagnostics);if(e==="collection_version_unsupported"){let i=Ba(t.diagnostics);return w(e,n,{operationOutcome:"rejected",details:i})}return e!=="operation_invalid"?w(e,n,{operationOutcome:"rejected",details:{diagnostics:t.diagnostics}}):w(e,n,{operationOutcome:"rejected",details:{diagnostics:t.diagnostics,partial_result:t.result}})}function Na(t){let e=new Set(t.filter(n=>n.severity==="error").map(n=>n.code));return["migration_required","migration_lossy","unsupported_version"].some(n=>e.has(n))?"collection_version_unsupported":["invalid_config","invalid_configuration","missing_config","missing_spec_version"].some(n=>e.has(n))?"collection_configuration_invalid":["duplicate_type","invalid_contract_definition","invalid_data_contract","invalid_type_definition","invalid_type_path"].some(n=>e.has(n))?"collection_type_registry_invalid":["collection_invalid","collection_open_failed"].some(n=>e.has(n))?"collection_invalid":"operation_invalid"}function Ba(t){let e=t.map(n=>n.details).find(n=>ja(n));return{current_version:typeof e?.current_version=="string"?e.current_version:"0.2.x",required_version:typeof e?.required_version=="string"?e.required_version:"0.3.0"}}function ja(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function zi(t){return t instanceof b&&t.retryable}function Ka(t){return t.filter(e=>e.severity==="error").map(e=>e.message).join(" ")||t.map(e=>e.message).join(" ")||"The collection rejected this operation."}var we=["describe","changes","read","query"];function B(t){let e=t.capabilities===void 0?1:t.capabilities?.contract_version;return e!==1&&e!==2&&Ie("Unsupported declared capability contract version."),e}function Ie(t){throw d("invalid_application_manifest",t,{details:{issues:[{path:"/requirements/capabilities",keyword:"authorizationSelection",message:t,params:{}}]}})}function Y(t,e){if(e.operations!==void 0&&e.capabilities!==void 0&&Ie("Specify operations or capabilities, not both."),e.operations!==void 0&&B(t)!==1&&Ie("Exact operations authorization is only supported for legacy v1 declarations."),e.capabilities!==void 0){let n=new Set([...t.capabilities?.required??[],...t.capabilities?.optional??[]]);e.capabilities.some(i=>!n.has(i)||W(B(t),i)===void 0)&&Ie("Authorization can only include capabilities declared by the application.")}}function Fi(t){let e=t.capabilities;return e?[...new Set([...e.required,...e.optional??[]].flatMap(n=>W(e.contract_version,n)??[]))]:[...we]}function On(t,e){let{requirements:n}=t;if(Y(n,e),B(n)===1){if(e.operations!==void 0)return[...new Set(e.operations)];if(e.capabilities===void 0)return[...we]}let i=n.capabilities,r=[...i?.required??[],...e.capabilities??i?.optional??[]].flatMap(s=>W(B(n),s)??[]),a=(t.provisions?.type_packs.length??0)>0||(t.provisions?.configuration?.length??0)>0;return[...new Set([...r,...B(n)===2&&a?Rt:[]])]}function Tt(t,e){return[...t.capabilities?.required??[],...t.capabilities?.optional??[]].filter(n=>(W(B(t),n)??[]).every(i=>e.includes(i)))}function Tn(t){let e=t.files;if(e)return B(t)===1?((!("actions"in e)||"required"in e||"optional"in e)&&Ie("Legacy file declarations must use exact files.actions."),{actions:[...e.actions],scope:structuredClone(e.scope)}):("actions"in e&&Ie("V2 file declarations must use required/optional file actions."),hi(e))}function kt(t,e,n){let i=new Set(t.required),o=[...new Set([...t.required,...t.optional??[]])],r={};for(let a of o)r[a]=Va(a,i.has(a),n,t.contract_version,e);return{contractVersion:t.contract_version,values:r,requiredAvailable:t.required.every(a=>r[a]?.state==="available")}}function Va(t,e,n,i,o){let r=W(i,t)??[],a=r.filter(c=>!n.operations.includes(c)),s={id:t,requirement:e?"required":"optional",operations:r,missingOperations:a,evidence:[{source:"application",fact:`${e?"Required":"Optional"} in capability contract v${i}.`}]};if(a.length>0)return{...s,state:"requires_authorization",evidence:[...s.evidence,{source:"authorization",fact:`Missing ${a.join(", ")}.`}],reason:"The current grant does not include every operation for this capability."};if(n.scope.access!=="full_collection")return{...s,state:"requires_authorization",reason:"The current grant uses legacy contract scope and must be reauthorized for the entire collection.",evidence:[...s.evidence,{source:"authorization",fact:"Legacy contract scope is compatibility evidence, not active data authority."}]};if(i===1&&t.startsWith("files.")){let c=t.slice(6);if(!n.fileCapability?.actions.includes(c))return{...s,state:n.fileCapability?"requires_authorization":"unsupported",reason:n.fileCapability?`The current file grant does not include ${c}.`:"This connection has no file capability."}}return i===1&&t==="notifications.background-delivery"&&(o.notifications?.criteria.length??0)===0?{...s,state:"requires_setup",reason:"The application manifest declares no notification criteria."}:{...s,state:"available",evidence:[...s.evidence,{source:"authorization",fact:r.length>0?`Granted operations: ${r.join(", ")}.`:"No record operation is required."},{source:"authority",fact:n.authority.kind==="hosted"?"Backed by a durable hosted mdbase authority.":"Backed by a user-operated mdbase connector."}],...t==="offline.replica"||i===1&&t==="sync.offline-replica"?{details:{durability:"device",writes:"queued",authority:n.authority.kind}}:{},...i===1&&t==="notifications.background-delivery"?{details:{delivery:"authority",payload:"opaque"}}:{}}}var Me=3e4,kn=1e4,Ga=10*6e4,Ha=12e4,$a=6e4;function xe(t={}){return{requestMs:it(t.requestMs,Me,"requestMs"),watchStartMs:it(t.watchStartMs,kn,"watchStartMs"),fileIndexMs:it(t.fileIndexMs,Ga,"fileIndexMs"),uploadMs:it(t.uploadMs,Ha,"uploadMs"),syncMs:it(t.syncMs,$a,"syncMs")}}function ot(t,e){return{...t,signal:e.signal,...e.deadline===null?{}:{deadlineUnixMs:e.deadline}}}function pe(t={},e=Me,n=Date.now){let i=t.timeoutMs===void 0?e:t.timeoutMs,o=i===null?null:Wa(i),r=new AbortController,a=o===null?null:n()+o,s=()=>r.abort(t.signal?.reason);t.signal?.aborted?s():t.signal?.addEventListener("abort",s,{once:!0});let c=o===null?void 0:setTimeout(()=>r.abort(d("timeout","The operation exceeded its request deadline.",{operationOutcome:"not_sent"})),o),l=!1;return{signal:r.signal,deadline:a,remainingMs:()=>a===null?null:Math.max(0,a-n()),dispose:()=>{l||(l=!0,c!==void 0&&clearTimeout(c),t.signal?.removeEventListener("abort",s))}}}async function F(t,e,n){let i=pe(t,e),o,r=new Promise((s,c)=>{o=c}),a=()=>o?.(J(i.signal));i.signal.addEventListener("abort",a,{once:!0});try{if(i.signal.aborted)throw J(i.signal);return await Promise.race([n(i),r])}finally{i.signal.removeEventListener("abort",a),i.dispose()}}async function K(t,e,n){let i=pe(t,e);try{if(i.signal.aborted)throw J(i.signal);return await n(i)}finally{i.dispose()}}function J(t){return t.reason instanceof b?t.reason:d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t.reason})}function Wa(t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("timeoutMs must be a positive safe integer or null.");return t}function it(t,e,n){if(t===void 0)return e;if(t===null)return null;if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${n} must be a positive safe integer or null.`);return t}async function Di(t){let{collectionId:e,readiness:n,contracts:i,connection:o,controller:r,options:a,requestMs:s,isCurrent:c,publish:l}=t,u=()=>r.abort(a?.signal?.reason);a?.signal?.aborted?u():a?.signal?.addEventListener("abort",u,{once:!0});try{let p=await F({...a,signal:r.signal},s,h=>o.describe(h));if(!c())return!1;if(!p.ok){let h=["access_denied","collection_access_denied","insufficient_access","not_authorized","authorization_expired","application_declaration_mismatch"].includes(p.problem.code);return n.contracts={state:h?"requires_authorization":"temporarily_unavailable",missing:[],evidence:[{source:"runtime",fact:p.problem.message}]},l(h?{status:"authorization_required"}:{status:"blocked",problem:p.problem}),!1}if(p.value.collectionId!==e)return n.contracts={state:"temporarily_unavailable",missing:[],evidence:[]},l({status:"blocked",problem:{code:"collection_not_ready",message:"Description belongs to a different collection."}}),!1;let f=i.filter(h=>!p.value.contracts.some(y=>y.id===h.id&&y.version===h.version&&y.digest===h.digest));if(n.contracts={state:f.length?"requires_setup":"verified",missing:f,evidence:[{source:"authority",fact:"Exact contract ID, version and digest checked by live describe for this collection."}]},f.length)return l({status:"blocked",problem:{code:"collection_not_ready",message:"The collection is missing required exact contracts."}}),!1}catch(p){if(!c())return!1;if(!(p instanceof b))throw p;return n.contracts={state:"temporarily_unavailable",missing:[],evidence:[{source:"runtime",fact:p.problem.message}]},l({status:"blocked",problem:p.problem}),!1}finally{a?.signal?.removeEventListener("abort",u)}return!0}function Ui(t,e,n){let i=structuredClone(t);return i.setup.state!=="not_required"&&i.setup.state!=="current"&&(i.setup.state=e==="ready"?n==="cached"?"cached":"current":e==="setup_review_required"?"review_required":e==="authorization_required"?"requires_authorization":e==="blocked"?"blocked":"checking",i.setup.evidence=[{source:e==="ready"&&n==="cached"?"runtime":"authority",fact:`Collection setup verification: ${i.setup.state}.`}]),i}function Li(t,e,n,i){return{collectionId:e,info:n,capabilities:kt(t.requirements.capabilities,t,n),...t.requirements?.capabilities?.contract_version===2?{readiness:Qa(t,n)}:{},connections:i}}function It(t,e){return`mdbase-application-session:v1:${t.id}:${e}`}function In(t){return JSON.stringify({capabilities:t.requirements?.capabilities,requirements:t.requirements?.configuration??[],provisions:t.provisions??{}})}function Ni(t,e,n,i){return{applicationId:e,declarationDigest:n,requirements:{configuration:t.requirements?.configuration??[]},provisions:{configuration:t.provisions?.configuration??[],typePacks:t.provisions?.type_packs??[]},...i?{typePackAdoptions:i}:{}}}function Ja(t,e){if(!e||t.kind!==e.kind)return!1;if(t.kind==="collection"||e.kind==="collection")return!0;let n=[...new Set(t.folders)].sort(),i=[...new Set(e.folders)].sort();return JSON.stringify(n)===JSON.stringify(i)}function Qa(t,e){let n=t.requirements?.files,i=n&&"required"in n?n:void 0,o=!i||Ja(i.scope,e.fileCapability?.scope),r=u=>u.filter(p=>!o||!e.fileCapability?.actions.includes(p)),a=r(i?.required??[]),s=r(i?.optional??[]),c=t.requirements?.contracts??[],l=(t.provisions?.type_packs.length??0)>0||(t.provisions?.configuration?.length??0)>0;return{files:{state:i?a.length?"requires_authorization":"available":"not_required",missingRequiredActions:a,missingOptionalActions:s,scopeMatches:o,evidence:[{source:"authorization",fact:"Compared exact file actions and folder scope with connection.info().fileCapability."}]},contracts:{state:c.length?"checking":"not_required",missing:[],evidence:[]},setup:{state:l?"checking":"not_required",evidence:[]},notifications:{state:t.notifications?.criteria.length?"requires_registration":"not_required",registration:"unverified",evidence:[{source:"runtime",fact:"The connection API exposes registration commands but no current delivery-registration query. Manifest criteria do not prove approval or delivery registration."}]}}}var Ya=["access_denied","access_paused","application_declaration_mismatch","authorization_binding_incompatible","authorization_expired","capability_contract_incompatible","collection_access_denied","connector_identity_changed","connector_offline","connector_upgrade_required","direct_operation_rejected","durable_mutation_unsupported","operation_outcome_unknown","encryption_required","encrypted_relay_rejected","hosted_provider_unavailable","insufficient_access","invalid_encrypted_response","invalid_operation_response","invalid_request","missing_grant_key","mutation_recovery_expired","mutation_request_conflict","not_authorized","operation_cancelled","operation_failed","rate_limited","relay_authorization_expired","relay_unavailable","temporarily_unavailable","timeout","transport_protocol_incompatible","unsupported_operation"],Bi=Object.keys(be),Se=["discovery_failed","invalid_operation_response","invalid_application_manifest","invalid_request","manifest_load_failed","rate_limited","temporarily_unavailable","timeout"],fe=[...Se,"access_denied","application_declaration_mismatch","application_identity_unavailable","approval_window_blocked","authorization_binding_incompatible","authorization_cancelled","authorization_replayed","browser_required","capability_contract_incompatible","collection_access_denied","collection_configuration_invalid","collection_contracts_missing","collection_incompatible","collection_invalid","collection_kind_unsupported","collection_mismatch","collection_not_found","collection_type_registry_invalid","collection_version_unsupported","connector_identity_changed","connector_offline","connector_upgrade_required","device_authorization_failed","durable_mutation_unsupported","encryption_required","expired_token","invalid_application_authorization","invalid_callback","invalid_device_authorization_response","invalid_token_response","legacy_scope_reauthorization_required","scope_denied","reconnect_required","token_exchange_failed","transport_protocol_incompatible"],rt=[...Se,"authorization_expired","invalid_operation_response","invalid_push_subscription","managed_fcm_not_declared","not_authorized","notification_criterion_not_declared","notification_reauthorization_required","notification_registration_failed","notification_unregistration_failed","notifications_not_declared","notifications_unavailable"],Mn=["connector_offline","connector_upgrade_required","invalid_operation_response","not_authorized","operation_failed","temporarily_unavailable","timeout"],il=[...fe,"collection_not_ready","collection_not_selected","operation_cancelled","session_destroyed","session_not_started","session_starting","unknown_collection"],Xa=["collection_configuration_invalid","collection_invalid","collection_type_registry_invalid","collection_version_unsupported"],Mt=[...Ya,...Xa],ie=[...Mt,"invalid_path","operation_invalid"],xn=[...ie,"cursor_capacity_exhausted","generation_expired","invalid_read_cursor","query_snapshot_changed","sandbox_unsupported"],j=[...ie,"concurrent_modification","invalid_preflight","pending_mutation_unresolved"],xt=[...Mt,"change_cursor_reset"],he=[...j,"type_pack_provision_failed"];function I(t,e=[]){return{ok:!0,value:t,diagnostics:e}}function g(t){return{ok:!1,problem:t}}async function D(t,e){try{return I(await t())}catch(n){if(!(n instanceof b))throw n;let i=n.problem;return i.code==="unknown"||e.includes(i.code)?g(i):g(qi(i.code,i.message,{details:i.details,operationOutcome:i.operation_outcome,traceId:i.trace_id}))}}var Za="mdbase-connect-keys",ye="grant-keys",qn=18446744073709551615n,es="mdbase-connect relay request key v1",ts="mdbase-connect relay response key v1",ji=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Ee=class{database=null;async create(e){let n=await Gi(e),i=await this.open();return await Vi(i,o=>o.add({...n,counter:"0"})),n}async get(e){let n=await this.open(),i=await rs(n.transaction(ye).objectStore(ye).get(e));return i?{handle:i.handle,agreementPrivateKey:i.agreementPrivateKey,agreementPublicKey:i.agreementPublicKey,signingPrivateKey:i.signingPrivateKey,signingPublicKey:i.signingPublicKey}:null}async nextCounter(e){let n=await this.open();return new Promise((i,o)=>{let r=n.transaction(ye,"readwrite"),a=r.objectStore(ye),s=a.get(e),c=null;s.onerror=()=>o(s.error),s.onsuccess=()=>{let l=s.result;if(!l){r.abort(),o(new x("missing_grant_key","The encrypted grant key is unavailable."));return}let u=BigInt(l.counter)+1n;if(u>qn){r.abort(),o(new x("counter_exhausted","The encrypted grant must be authorized again."));return}c=u.toString(),a.put({...l,counter:c})},r.onerror=()=>o(r.error),r.onabort=()=>o(r.error??new Error("Key counter transaction aborted.")),r.oncomplete=()=>{c&&i(c)}})}async delete(e){let n=await this.open();await Vi(n,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new x("key_storage_unavailable","Encrypted relay authorization requires browser IndexedDB or an injected grant key store.");return this.database||(this.database=new Promise((e,n)=>{let i=indexedDB.open(Za,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(ye)||i.result.createObjectStore(ye,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},qe=class{records=new Map;sequence=Promise.resolve();async create(e){if(this.records.has(e))throw new Error(`Grant key already exists: ${e}`);let n=await Gi(e);return this.records.set(e,{...n,counter:"0"}),n}async get(e){let n=this.records.get(e);return n?{handle:n.handle,agreementPrivateKey:n.agreementPrivateKey,agreementPublicKey:n.agreementPublicKey,signingPrivateKey:n.signingPrivateKey,signingPublicKey:n.signingPublicKey}:null}nextCounter(e){let n,i,o=new Promise((r,a)=>{n=r,i=a});return this.sequence=this.sequence.then(()=>{let r=this.records.get(e);if(!r)throw new x("missing_grant_key","The encrypted grant key is unavailable.");let a=BigInt(r.counter)+1n;if(a>qn)throw new x("counter_exhausted","The encrypted grant must be authorized again.");r.counter=a.toString(),n(r.counter)}).catch(r=>{i(r)}),o}async delete(e){this.records.delete(e)}};async function Et(t,e,n,i){let o=await ns(t,e,n),r=i.timestamp??Math.floor(Date.now()/1e3),a=i.nonce??crypto.randomUUID(),s=await zn({...i,timestamp:r,nonce:a}),c=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},o.signingPrivateKey,new TextEncoder().encode(s));return{[nt.version]:String(Pn),[nt.timestamp]:String(r),[nt.nonce]:a,[nt.signature]:at(new Uint8Array(c))}}async function zn(t){let e=t.method.toUpperCase(),n=await Ki(t.body??""),i=await Ki(t.credential);for(let o of[e,t.target,String(t.timestamp),t.nonce])if(!o||o.includes(`
2
- `)||o.includes("\r"))throw new x("invalid_proof_input","Authority request proof metadata is invalid.");return[Ei,Pn,e,t.target,n,i,t.timestamp,t.nonce].join(`
3
- `)}async function oe(t,e,n,i,o,r=crypto.randomUUID(),a){if(re(n.encryption),a!==void 0&&(!Number.isSafeInteger(a)||a<=0))throw new x("invalid_deadline","The operation deadline is invalid.");let s=await Hi(t,e,n.encryption.application_agreement_public_key),c=await t.nextCounter(e),l={binding:n,protocolVersion:$,requestId:r,operation:i,counter:c},u=await $i(s.agreementPrivateKey,n,l.protocolVersion,"request"),p=new TextEncoder().encode(JSON.stringify(o??{})),f=await crypto.subtle.encrypt({name:"AES-GCM",iv:Qi(c),additionalData:new TextEncoder().encode(Ji(l,"request")),tagLength:128},u,p);return{type:"encrypted_operation_request",...is(l),...a===void 0?{}:{deadline_unix_ms:a},ciphertext:at(new Uint8Array(f))}}async function ze(t,e,n,i,o){if(!os(i,o))throw new x("invalid_encrypted_response","Encrypted response metadata does not match its request.");let r=await Hi(t,e,n.encryption.application_agreement_public_key),a={binding:n,protocolVersion:i.protocol_version,requestId:i.request_id,operation:i.operation,counter:i.counter},s=await $i(r.agreementPrivateKey,n,i.protocol_version,"response");try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:Qi(i.counter),additionalData:new TextEncoder().encode(Ji(a,"response")),tagLength:128},s,Xi(Yi(o.ciphertext))),l=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c));if(l?.ok===!0&&"result"in l||l?.ok===!1&&Xe(l.problem))return l;throw new Error("invalid response body")}catch(c){throw c instanceof x?c:new x("encrypted_response_rejected","The encrypted connector response could not be authenticated.")}}var x=class extends Error{constructor(n,i){super(i);this.code=n}code};async function Gi(t){let e=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),n=at(new Uint8Array(await crypto.subtle.exportKey("raw",e.publicKey))),i=await crypto.subtle.exportKey("pkcs8",e.privateKey),o=await crypto.subtle.importKey("pkcs8",i,{name:"ECDH",namedCurve:"P-256"},!1,["deriveBits"]),r=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),a=at(new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey))),s=await crypto.subtle.exportKey("pkcs8",r.privateKey),c=await crypto.subtle.importKey("pkcs8",s,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]);return{handle:t,agreementPrivateKey:o,agreementPublicKey:n,signingPrivateKey:c,signingPublicKey:a}}async function Hi(t,e,n){let i=await t.get(e);if(!i||i.agreementPublicKey!==n)throw new x("missing_grant_key","The encrypted grant key is unavailable or does not match the grant.");return i}async function ns(t,e,n){let i=await t.get(e);if(!i||i.signingPublicKey!==n)throw new x("missing_grant_key","The remote authority signing key is unavailable or does not match the grant.");return i}async function $i(t,e,n,i){let o=await st(t,e.encryption.connector_agreement_public_key),r=await crypto.subtle.importKey("raw",o,"HKDF",!1,["deriveKey"]),a=new TextEncoder().encode(Wi(e,n)),s=await crypto.subtle.digest("SHA-256",a);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:s,info:new TextEncoder().encode(i==="request"?es:ts)},r,{name:"AES-GCM",length:256},!1,i==="request"?["encrypt"]:["decrypt"])}async function st(t,e){try{let n=await crypto.subtle.importKey("raw",Xi(En(e)),{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveBits({name:"ECDH",public:n},t,256)}catch{throw new x("invalid_public_key","The connector relay public key is invalid.")}}function Wi(t,e){let n=t.encryption;return["mdbase-connect",e,n.suite,t.grantId,t.applicationId,n.connector_id,n.collection_id,n.scope_epoch,n.key_id].join("|")}function Ji(t,e){return[Wi(t.binding,t.protocolVersion),t.requestId,e,t.operation,t.counter].join("|")}function is(t){let e=t.binding.encryption;return{protocol_version:t.protocolVersion,suite:tt,request_id:t.requestId,grant_id:t.binding.grantId,application_id:t.binding.applicationId,connector_id:e.connector_id,collection_id:e.collection_id,operation:t.operation,scope_epoch:e.scope_epoch,key_id:e.key_id,counter:t.counter}}function os(t,e){return e.type==="encrypted_operation_response"&&typeof e.ciphertext=="string"&&t.protocol_version===e.protocol_version&&t.suite===e.suite&&t.request_id===e.request_id&&t.grant_id===e.grant_id&&t.application_id===e.application_id&&t.connector_id===e.connector_id&&t.collection_id===e.collection_id&&t.operation===e.operation&&t.scope_epoch===e.scope_epoch&&t.key_id===e.key_id&&t.counter===e.counter}function re(t){if(t.protocol_version!==Ot||t.suite!==tt||!Number.isSafeInteger(t.scope_epoch)||t.scope_epoch<=0||typeof t.key_id!="string"||t.key_id.length===0||t.key_id.length>200||t.key_id.includes("|"))throw new x("unsupported_encryption","The grant uses an unsupported relay encryption profile.");if(typeof t.connector_id!="string"||!ji.test(t.connector_id)||typeof t.collection_id!="string"||!ji.test(t.collection_id))throw new x("unsupported_encryption","The grant uses invalid encrypted relay identities.");En(t.application_agreement_public_key),En(t.connector_agreement_public_key)}function Qi(t){let e=BigInt(t);if(e<=0n||e>qn||e.toString()!==t)throw new x("invalid_counter","The encrypted relay counter is invalid.");let n=new Uint8Array(new ArrayBuffer(12));return new DataView(n.buffer).setBigUint64(4,e,!1),n}function at(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}async function Ki(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return at(new Uint8Array(e))}function Yi(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw new x("invalid_base64","Encrypted relay data is malformed.");let e="=".repeat((4-t.length%4)%4),n=atob(t.replaceAll("-","+").replaceAll("_","/")+e);return Uint8Array.from(n,i=>i.charCodeAt(0))}function En(t){let e=Yi(t);if(e.length!==65||e[0]!==4)throw new x("invalid_public_key","Encrypted relay public keys must be uncompressed P-256 points.");return e}function Xi(t){return Uint8Array.from(t).buffer}function rs(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function Vi(t,e){return new Promise((n,i)=>{let o=t.transaction(ye,"readwrite"),r=e(o.objectStore(ye));r.onerror=()=>i(r.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Grant key transaction aborted.")),o.oncomplete=()=>n()})}function me(t){return{...t,credentials:"omit",targetAddressSpace:"loopback"}}async function ct(){if(typeof navigator>"u"||!navigator.permissions?.query)return null;try{return(await navigator.permissions.query({name:"local-network-access"})).state}catch{return null}}function Fe(t){return t===404||t===405||t===426||t>=500}function Zi(t,e){return ue(t,e)}function eo(t,e){if(t.deadline_unix_ms===e)return t;let{deadline_unix_ms:n,...i}=t;return{...i,...e===void 0?{}:{deadline_unix_ms:e}}}function lt(t){return[...new Set(t)]}function to(t,e){return t.grantId||e.grantId?t.grantId===e.grantId&&t.keyHandle===e.keyHandle&&t.encryption?.key_id===e.encryption?.key_id:t.accessToken===e.accessToken}function Re(t){if(t?.aborted)throw d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t.reason})}function qt(t,e,n,i){return t instanceof b?t:e?.aborted?n?G(n,t):e.reason instanceof b?e.reason:d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t}):n?G(n,t):t instanceof TypeError?d(i,i==="hosted_provider_unavailable"?"The hosted collection provider is unavailable.":"The Connect relay is unavailable.",{cause:t}):t instanceof Error?t:new Error(String(t))}function no(t){return U(t.code==="unknown"?t.server_code:t.code,t.message,{details:t.details,operationOutcome:t.operation_outcome??"rejected",traceId:t.trace_id})}function io(t,e,n,i,o){return fetch(t,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json",...n},body:i,signal:o})}function Dn(t,e){return e?.aborted===!0||t instanceof b&&t.code==="operation_cancelled"}function oo(t,e){if(e.dryRun!==!0||e.wouldRename!==!0||e.from!==t.from||e.to!==t.to)throw d("invalid_preflight","The rename preview does not match this mutation. Run the preview again.")}function ro(t,e){if(e.dryRun!==!0||e.wouldDelete!==!0||e.path!==t.path)throw d("invalid_preflight","The delete preview does not match this mutation. Run the preview again.")}function ao(t,e){if(t.updateRefs===!1)return{affectedRecords:0,totalUnits:1,warnings:0};let n=e.referencesAffected??[];return{affectedRecords:new Set(n.map(i=>i.path)).size,totalUnits:1+n.length,warnings:e.warnings?.length??0}}function so(t){return{affectedRecords:new Set((t.brokenLinks??[]).map(e=>e.path)).size,totalUnits:1,warnings:0}}async function co(t,e){return vi(t,e??{})}function lo(t){return JSON.stringify(Fn(t))}function Fn(t){return Array.isArray(t)?t.map(e=>Fn(e)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e<n?-1:e>n?1:0).map(([e,n])=>[e,Fn(n)])):t}function G(t,e){return d("operation_outcome_unknown","The write may have completed, but mdbase could not recover its authoritative result. Retry the exact same write to recover safely.",{operationOutcome:"unknown",details:{request_id:t},cause:e})}function X(t){let e=new Uint8Array(t);return crypto.getRandomValues(e),Un(e)}function Un(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function uo(t){let e=t.replaceAll("-","+").replaceAll("_","/").padEnd(Math.ceil(t.length/4)*4,"="),n=atob(e),i=new Uint8Array(new ArrayBuffer(n.length));for(let o=0;o<n.length;o+=1)i[o]=n.charCodeAt(o);return i}function po(t,e){let n=t instanceof URL?t.href:t??ss(),i=typeof n=="string"?n:n.distribution==="portable"?`bundle:${n.id}:${ls(n)}`:`bundle:${n.id}`,o=e===void 0?typeof n!="string"&&n.distribution==="portable"?"":cs():String(e);return{manifest:n,manifestSource:i,redirectUri:o}}async function ae(t,e,n,i){try{return await fetch(t,e)}catch(o){throw d(n,i,{cause:o})}}async function E(t,e,n){let i;try{i=await t.text()}catch(o){throw U(e,n,{status:t.status,cause:o})}if(i.trim()==="")throw U(e,n,{status:t.status});try{return JSON.parse(i)}catch(o){throw U(e,n,{status:t.status,cause:o})}}function fo(t){let e=new URL(t);if(e.protocol!=="http:"||!["127.0.0.1","[::1]"].includes(e.hostname)||e.username||e.password||e.pathname!=="/"||e.search||e.hash)throw d("invalid_loopback_url","loopbackUrl must be an HTTP origin on 127.0.0.1 or ::1.");return e.origin}async function dt(){let t=X(32),e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:Un(new Uint8Array(e))}}function z(t,e,n,i){return U(ut(t)??t?.error?.code??e,t?.error_description??t?.error?.message??n,{status:i,details:t?.error?.details,operationOutcome:t?.error?.operation_outcome,traceId:t?.error?.trace_id})}function ut(t){return typeof t?.error=="string"?t.error:void 0}function pt(t,e){if(!t||typeof t!="object"||Array.isArray(t)||typeof e!="string")return!1;let n=t;if(typeof n.operations_url!="string"||typeof n.sync_url!="string"||typeof n.files_url!="string"||typeof n.replica_id!="string"||n.replica_id.length===0||typeof n.access_token!="string"||n.access_token.length===0||n.proof_public_key!==void 0&&(typeof n.proof_public_key!="string"||n.proof_public_key.length===0))return!1;try{let i=new URL(n.operations_url),o=new URL(n.sync_url),r=new URL(n.files_url);return[i,o,r].every(a=>(a.protocol==="https:"||a.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname))&&!a.username&&!a.password&&!a.search&&!a.hash)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/operations$/i.test(i.pathname)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync$/i.test(o.pathname)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/files$/i.test(r.pathname)&&i.origin===o.origin&&i.origin===r.origin&&i.pathname.split("/")[3]===e&&o.pathname.split("/")[3]===e&&r.pathname.split("/")[3]===e}catch{return!1}}function ho(t,e){return pt({operations_url:t?.operationsUrl,sync_url:t?.syncUrl,files_url:t?.filesUrl,replica_id:t?.replicaId,access_token:t?.accessToken,proof_public_key:t?.proofPublicKey},e)}function zt(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t,n=e.actions;if(e.kind!=="files"||e.protocol_version!==1||!Array.isArray(n)||n.length===0||n.length>6||new Set(n).size!==n.length||n.some(o=>!["list","read","add","replace","move","delete"].includes(o)))return!1;let i=e.scope;return!i||typeof i!="object"||Array.isArray(i)?!1:i.kind==="collection"?Object.keys(i).length===1:i.kind==="selected_folders"&&Object.keys(i).length===2&&Array.isArray(i.folders)&&i.folders.length>0&&i.folders.length<=100&&new Set(i.folders).size===i.folders.length&&i.folders.every(o=>typeof o=="string"&&o.length>0&&o.length<=1024&&as(o))}function as(t){let e=new Set([".mdbase",".git","node_modules","_contracts","_schemas","_types","_views"]);return!t.startsWith("/")&&!t.endsWith("/")&&!t.includes("\\")&&t.split("/").every(n=>{let i=n.split(".")[0]?.toUpperCase()??"";return n!==""&&n!=="."&&n!==".."&&!n.startsWith(".")&&!n.endsWith(" ")&&!n.endsWith(".")&&!/[<>:"|?*]/.test(n)&&!e.has(n.toLowerCase())&&!["CON","PRN","AUX","NUL"].includes(i)&&!/^(COM|LPT)[1-9]$/.test(i)})}function yo(t,e){if(!t||typeof t!="object"||Array.isArray(t)||t.collection_id!==e)return!1;try{return re(t),!0}catch{return!1}}function mo(t){if(typeof t?.device_code!="string"||typeof t?.user_code!="string"||typeof t?.verification_uri!="string"||typeof t?.verification_uri_complete!="string"||!Number.isFinite(t?.expires_in)||!Number.isFinite(t?.interval))throw d("invalid_device_authorization_response","Connect returned an invalid downloaded application authorization response.");return{userCode:t.user_code,verificationUri:t.verification_uri,verificationUriComplete:t.verification_uri_complete,expiresAt:Date.now()+Math.max(1,t.expires_in)*1e3,intervalSeconds:Math.max(1,t.interval)}}function M(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}function Ft(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return e.access!=="contract"&&e.access!=="full_collection"||!Array.isArray(e.contracts)||e.contracts.some(n=>!n||typeof n!="object"||n.contract_type!=="record"||typeof n.id!="string"||typeof n.version!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(n.version)||!/^sha256:[0-9a-f]{64}$/.test(n.digest)||!n.schema||typeof n.schema!="object"||Array.isArray(n.schema)||!Array.isArray(n.implementations)||n.implementations.some(i=>!i||typeof i!="object"||typeof i.type_name!="string"||!Number.isInteger(i.type_version)||!/^sha256:[0-9a-f]{64}$/.test(i.digest)||!i.fields||typeof i.fields!="object"||Array.isArray(i.fields)||Object.values(i.fields).some(o=>typeof o!="string")))?null:e}function Dt(t){return t.access==="full_collection"&&t.contracts.length===0}function go(t){return t.endsWith("/")?t.slice(0,-1):t}function ss(){if(typeof location>"u")throw d("manifest_required","manifest is required outside a browser environment.");if(location.origin==="null")throw d("manifest_required","Downloaded applications must provide their v1 portable manifest inline.");return new URL("/.well-known/mdbase-app.json",location.origin).href}function cs(){if(typeof location>"u")throw d("redirect_uri_required","redirectUri is required outside a browser environment.");return location.href.split(/[?#]/)[0]}function _o(t,e,n,i){if(typeof t!="string"&&t.distribution==="portable"||i)return"null";let o=new URL(n);if(["http:","https:"].includes(o.protocol))return o.origin;if(typeof location<"u")return location.origin;if(typeof t!="string")return new URL(t.homepage).origin;try{return new URL(e).origin}catch{return""}}function bo(t){let e=":token:",n=t.lastIndexOf(e);return n<0?"":t.slice(n+e.length)}function Ut(){if(typeof location>"u")throw d("callback_url_required","callbackUrl is required outside a browser environment.");return location.href}function Co(t){if(t)return new De;if(typeof localStorage>"u")throw d("storage_required","storage is required outside a browser environment.");try{let e=`mdbase-connect:probe:${X(8)}`;return localStorage.setItem(e,"1"),localStorage.removeItem(e),localStorage}catch{return new De}}var De=class{values=new Map;get length(){return this.values.size}clear(){this.values.clear()}getItem(e){return this.values.get(e)??null}key(e){return[...this.values.keys()][e]??null}removeItem(e){this.values.delete(e)}setItem(e,n){this.values.set(String(e),String(n))}};function vo(t){return typeof t=="string"||t.distribution!=="portable"?!1:typeof location>"u"||location.origin==="null"||!["http:","https:"].includes(location.protocol)}function ls(t){let e=lo(t),n=2166136261,i=2654435769;for(let o=0;o<e.length;o+=1){let r=e.charCodeAt(o);n=Math.imul(n^r,16777619),i=Math.imul(i^r,2246822507)}return`${(n>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}function ft(t){let e="bundle:";if(!t.startsWith(e)||t.length===e.length)throw new Error("The registered application has no valid declaration identity.");return t.slice(e.length)}function Ue(t,e,n){return t.reason instanceof b?t.reason:d("authorization_cancelled",e,{cause:n})}function ht(t){for(let e of["code","state","error","error_description"])t.searchParams.delete(e);return t}function Lt(t){let e;try{e=new URL(t)}catch{return!1}return e.searchParams.has("state")&&(e.searchParams.has("code")||e.searchParams.has("error"))}function Nt(t){try{let e=new URL(t).searchParams.get("state");return e&&e.length>0?e:null}catch{return null}}function wo(t){if(!t.details||typeof t.details!="object"||Array.isArray(t.details))return;let e=t.details.return_to;return typeof e=="string"?e:void 0}var Le=class{constructor(e,n){this.connect=e;this.operations=lt(n.operations??we),this.selection=n.selection,this.autoSelect=n.autoSelect??"only",this.snapshot={status:"not_started",connections:[]}}connect;operations;selection;autoSelect;listeners=new Set;snapshot;snapshotKey="";stopConnections;stopSelection;stopActiveConnection;activeCollectionId=null;unavailableReason="not_authorized";started=!1;destroyed=!1;refreshing=!1;refreshQueued=!1;transactionDepth=0;lifecycleGeneration=0;operationControllers=new Set;startOperation=null;callbackCompletions=new Map;start(e){if(this.destroyed)return Promise.resolve(g(w("session_destroyed","This session has been destroyed.")));if(this.started&&!this.startOperation)return Promise.resolve(I(this.snapshot));let n=this.startOperation??this.beginStart();return this.waitForStart(n,e)}beginStart(){let e=new AbortController,n=++this.lifecycleGeneration;this.publish({status:"starting",connections:this.connect.connections()});let i={promise:this.performStart({signal:e.signal,timeoutMs:null},n),controller:e,waiters:0,generation:n};this.startOperation=i;let o=()=>{this.startOperation===i&&(this.startOperation=null)};return i.promise.then(o,o),i}async waitForStart(e,n){e.waiters+=1;try{return await F(n,kn,()=>e.promise)}catch(i){if(i instanceof b)return g(i.problem);throw i}finally{e.waiters-=1,e.waiters===0&&this.startOperation===e&&(e.controller.abort(),this.startOperation=null,this.lifecycleGeneration+=1,this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"not_started",connections:this.connect.connections()}))}}async performStart(e,n){try{this.started=!0,this.stopConnections=this.connect.onConnectionsChange(()=>this.refresh()),this.stopSelection=this.selection.subscribe(()=>{this.unavailableReason="not_authorized",this.refresh()});let i=this.selection.authorizationCallback();if(i){let o=await this.completeAuthorizationCallback(i,e);if(!o.ok)return n===this.lifecycleGeneration&&!this.destroyed&&(this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"start_failed",problem:o.problem,connections:this.connect.connections()})),o}else this.autoSelectOnlyConnection();return n!==this.lifecycleGeneration||this.destroyed?g(w("session_destroyed","This session has been destroyed.")):(this.publishCurrent(),I(this.snapshot))}catch(i){if(i instanceof b){let o=i.problem;return n===this.lifecycleGeneration&&!this.destroyed&&(this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"start_failed",problem:o,connections:this.connect.connections()})),g(o)}throw n===this.lifecycleGeneration&&!this.destroyed&&(this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"not_started",connections:this.connect.connections()})),i}}destroy(){if(!this.destroyed){this.lifecycleGeneration+=1,this.startOperation?.controller.abort(),this.startOperation=null;for(let e of this.operationControllers)e.abort();this.operationControllers.clear(),this.stopLifecycleSubscriptions(),this.started=!1,this.destroyed=!0,this.callbackCompletions.clear(),this.publish({status:"destroyed",connections:[]}),this.listeners.clear()}}stopLifecycleSubscriptions(){this.stopConnections?.(),this.stopSelection?.(),this.stopActiveConnection?.(),this.stopConnections=void 0,this.stopSelection=void 0,this.stopActiveConnection=void 0,this.activeCollectionId=null}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}select(e,n={}){let i=this.lifecycleProblem();if(i)return g(i);let o=this.connect.connection(e);return o?(this.unavailableReason="not_authorized",this.selection.select(e,n),this.refresh(),I(o)):g(w("unknown_collection","This collection is not authorized for this application."))}clearSelection(e={}){let n=this.lifecycleProblem();return n?g(n):(this.unavailableReason="not_authorized",this.selection.select(null,e),this.refresh(),I(void 0))}forget(e){let n=this.lifecycleProblem();if(n)return g(n);this.transactionDepth+=1;try{let i=this.selection.selectedCollectionId()===e;this.connect.connection(e)?.forget(),i&&this.selection.select(null,{history:"replace"})}finally{this.transactionDepth-=1,this.refresh()}return I(void 0)}async authorize(e,n={}){let i=this.lifecycleProblem();if(i)return g(i);let o=this.selection.selectedCollectionId();if(e==="selected"&&!o)return g(w("collection_not_selected","Choose a collection before updating its access."));let r=typeof e=="object"?e.collectionId:e==="selected"?o:null,a=this.beginLifecycleOperation(n);this.transactionDepth+=1;try{let s=await this.connect.manifest?.(a.options);if(s&&!s.ok)return s;if(!this.lifecycleCurrent(a.generation))return this.destroyedOutcome(I(void 0));let c=s?B(s.value.requirements):1,l=await this.connect.authorize({...a.options,...c===1&&n.operations===void 0&&n.capabilities===void 0?{operations:this.operations}:{},target:r===null?{kind:"choose"}:{kind:"collection",collectionId:r},returnTo:this.selection.authorizationReturnTo()});return this.lifecycleCurrent(a.generation)?(l.ok&&l.value.kind==="connected"&&this.selection.finishAuthorization(l.value.returnTo,l.value.connection.collectionId),l):this.destroyedOutcome(l)}finally{a.dispose(),this.transactionDepth-=1,this.refresh()}}ensureOperations(e,n){return this.ensureAuthorization({operations:e},n)}ensureCapabilities(e,n){return this.ensureAuthorization({capabilities:e},n)}async ensureAuthorization(e,n){let i=this.lifecycleProblem();if(i)return g(i);let o=this.snapshot;if(o.status!=="ready")return g(w("collection_not_ready","Choose an authorized collection first."));let r=this.beginLifecycleOperation(n);this.transactionDepth+=1;try{let a=await this.connect.manifest?.(r.options);if(a&&!a.ok)return a;if(!this.lifecycleCurrent(r.generation))return this.destroyedOutcome(I(void 0));let s=a?.value.requirements??("operations"in e?{access:"full_collection",contracts:[]}:{access:"full_collection",contracts:[],capabilities:{contract_version:2,required:[],optional:Object.keys(St)}});Y(s,{...n,...e});let c="operations"in e?e.operations:e.capabilities.flatMap(f=>W(B(s),f)??[]),l=o.connection.authorizationCapabilities(c);if(l.sufficient)return I({kind:"unchanged",connection:o.connection});let u="operations"in e||B(s)===1?{operations:lt([...l.grantedOperations,...c])}:{capabilities:[...new Set([...Tt(s,l.grantedOperations),...e.capabilities])]},p=await this.connect.authorize({...r.options,...u,target:{kind:"collection",collectionId:o.collectionId},returnTo:this.selection.authorizationReturnTo()});return this.lifecycleCurrent(r.generation)?(p.ok&&p.value.kind==="connected"&&this.selection.finishAuthorization(p.value.returnTo,p.value.connection.collectionId),p):this.destroyedOutcome(p)}catch(a){if(a instanceof b)return g(a.problem);throw a}finally{r.dispose(),this.transactionDepth-=1,this.refresh()}}handleAuthorizationCallback(e,n){let i=this.lifecycleProblem();return i?Promise.resolve(g(i)):Lt(e)?this.completeAuthorizationCallback(e,n):Promise.resolve(g(w("invalid_callback","This URL is not an authorization callback.")))}completeAuthorizationCallback(e,n){if(n?.signal?.aborted){let r=J(n.signal);return Promise.resolve(g(r.problem))}let i=Nt(e);if(!i)return Promise.resolve(g(w("invalid_callback","Authorization callback is missing its state.")));let o=this.callbackCompletions.get(i)??this.beginCallbackCompletion(e,i);return this.waitForCallbackCompletion(o,n)}beginCallbackCompletion(e,n){let i=new AbortController,o=this.lifecycleGeneration;this.transactionDepth+=1,this.operationControllers.add(i);let r={state:n,controller:i,waiters:0,settled:!1,abandoned:!1,promise:void 0},a=this.connect.completeAuthorization(e,{signal:i.signal,timeoutMs:null}).catch(s=>{if(s instanceof b)return g(s.problem);throw s});return r.promise=a.then(s=>{if(o!==this.lifecycleGeneration||this.destroyed)return this.destroyedOutcome(s);if(!s.ok){if(!r.abandoned&&s.problem.recovery!=="retry"){let l=wo(s.problem);this.selection.clearAuthorizationCallback(l)}return this.refresh(),s}let c=s.value;return this.unavailableReason="not_authorized",this.selection.finishAuthorization(c.returnTo,c.connection.collectionId),this.refresh(),I(c.connection,s.diagnostics)}).catch(s=>{if(o!==this.lifecycleGeneration||this.destroyed)return g(w("session_destroyed","This session was destroyed before authorization completion finished."));throw r.abandoned||(this.selection.clearAuthorizationCallback(),this.refresh()),s}).finally(()=>{r.settled=!0,this.operationControllers.delete(i),this.transactionDepth-=1,this.refresh(),this.callbackCompletions.get(n)===r&&this.callbackCompletions.delete(n)}),this.callbackCompletions.set(n,r),r}async waitForCallbackCompletion(e,n){e.waiters+=1;try{return await F(n,Me,()=>e.promise)}catch(i){if(i instanceof b)return g(i.problem);throw i}finally{e.waiters-=1,e.waiters===0&&!e.settled&&this.callbackCompletions.get(e.state)===e&&(e.abandoned=!0,this.callbackCompletions.delete(e.state),e.controller.abort())}}lifecycleProblem(){return this.destroyed?w("session_destroyed","This session has been destroyed."):this.snapshot.status==="starting"?w("session_starting","The session is still starting."):this.snapshot.status==="start_failed"?this.snapshot.problem:this.started?null:w("session_not_started","Start the session before using it.")}beginLifecycleOperation(e={}){let n=new AbortController,i=()=>n.abort(e.signal?.reason);return e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0}),this.operationControllers.add(n),{generation:this.lifecycleGeneration,options:{...e,signal:n.signal},dispose:()=>{e.signal?.removeEventListener("abort",i),this.operationControllers.delete(n)}}}lifecycleCurrent(e){return!this.destroyed&&e===this.lifecycleGeneration}destroyedOutcome(e){return!e.ok&&e.problem.code==="operation_outcome_unknown"?e:g(w("session_destroyed","This session was destroyed before the operation finished."))}autoSelectOnlyConnection(){if(this.autoSelect!=="only"||this.selection.selectedCollectionId())return;let e=this.connect.connections();e.length===1&&this.selection.select(e[0].collectionId,{history:"replace"})}refresh(){if(!(!this.started||this.destroyed||this.snapshot.status==="starting"||this.snapshot.status==="start_failed")){if(this.transactionDepth>0){this.refreshQueued=!0;return}if(this.refreshing){this.refreshQueued=!0;return}this.refreshing=!0;try{do this.refreshQueued=!1,this.publishCurrent();while(this.refreshQueued)}finally{this.refreshing=!1}}}publishCurrent(){let e=this.selection.selectedCollectionId(),n=this.connect.connections(),i=e?this.connect.connection(e):null;i?.collectionId!==this.activeCollectionId&&(this.stopActiveConnection?.(),this.activeCollectionId=i?.collectionId??null,this.stopActiveConnection=i?.onConnectionChange(r=>{!r&&this.selection.selectedCollectionId()===i.collectionId&&(this.unavailableReason="authorization_lost"),this.refresh()}));let o;if(!e)o={status:"unselected",connections:n};else if(!i||!i.info())o={status:"unavailable",collectionId:e,reason:this.connect.unavailableReason(e)??this.unavailableReason,connections:n};else{let r=i.info();o={status:"ready",collectionId:e,connection:i,info:r,access:i.authorizationCapabilities(this.operations),connections:n}}this.publish(o)}publish(e){if(this.snapshot.status==="destroyed"&&e.status!=="destroyed")return;let n=ds(e);if(n!==this.snapshotKey){this.snapshot=e,this.snapshotKey=n;for(let i of this.listeners)i()}}};function ds(t){return t.status==="not_started"||t.status==="starting"||t.status==="destroyed"?JSON.stringify(t):t.status==="start_failed"?JSON.stringify({status:t.status,problem:t.problem,connections:t.connections}):t.status==="unselected"?JSON.stringify({status:t.status,connections:t.connections}):t.status==="unavailable"?JSON.stringify({status:t.status,collectionId:t.collectionId,reason:t.reason,connections:t.connections}):JSON.stringify({status:t.status,collectionId:t.collectionId,info:t.info,access:t.access,connections:t.connections})}var mt=class{values=new Map;read(e){return this.values.get(e)??null}write(e,n){this.values.set(e,n)}remove(e){this.values.delete(e)}},Ne=class{constructor(e,n,i=xe()){this.connect=e;this.options=n;this.timeouts=i;this.verificationStore=n.verificationStore??ms()}connect;options;timeouts;listeners=new Set;verificationStore;snapshot={status:"not_started",connections:[]};manifest=null;application=null;base=null;stopBase;setupAssessment=null;setupTypePackAdoptions=null;verificationGeneration=0;readinessController;lifecycleGeneration=0;operationControllers=new Set;startOperation=null;start(e){if(this.snapshot.status==="destroyed")return Promise.resolve(g(w("session_destroyed","This application session has been destroyed.")));if(this.base&&!this.startOperation)return Promise.resolve(I(this.snapshot));let n=this.startOperation??this.beginStart();return this.waitForStart(n,e,this.timeouts.watchStartMs)}async waitForStart(e,n,i){e.waiters+=1;try{return await F(n,i,()=>e.promise)}catch(o){if(o instanceof b)return g(o.problem);throw o}finally{e.waiters-=1,e.waiters===0&&this.startOperation===e&&this.abandonStart(e)}}abandonStart(e){e.controller.abort(),this.readinessController?.abort(),this.startOperation=null,this.lifecycleGeneration+=1,this.verificationGeneration+=1,this.base&&this.cleanupBase(this.base),this.application=null,this.manifest=null,this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"not_started",connections:this.connect.connections()})}beginStart(){this.publish({status:"starting",connections:this.connect.connections()});let e=new AbortController,n=++this.lifecycleGeneration,i={promise:this.startWithinBudget({signal:e.signal,timeoutMs:null},n),controller:e,waiters:0,generation:n};this.startOperation=i;let o=()=>{this.startOperation===i&&(this.startOperation=null)};return i.promise.then(o,o),i}async startWithinBudget(e,n){try{return await this.performStartWithinBudget(e,n)}catch(i){if(i instanceof b)return this.startFailure(i.problem,n);throw n===this.lifecycleGeneration&&(this.verificationGeneration+=1,this.base&&this.cleanupBase(this.base),this.application=null,this.manifest=null,this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"not_started",connections:this.connect.connections()})),i}}async performStartWithinBudget(e,n){let i=await this.connect.register(e);if(!i.ok)return this.startFailure(i.problem,n);let o=await this.connect.manifest(e);if(!o.ok)return this.startFailure(o.problem,n);if(o.value.requirements?.access!=="full_collection")return this.startFailure(w("invalid_application_manifest","Application sessions require explicit full_collection access.",{details:{issues:[{path:"/requirements/access",keyword:"const",message:"must be full_collection",params:{allowedValue:"full_collection"}}]}}),n);let r=o.value.requirements.capabilities;if(!r)return this.startFailure(w("invalid_application_manifest","Application sessions require a versioned semantic capability contract.",{details:{issues:[{path:"/requirements/capabilities",keyword:"required",message:"is required for application sessions",params:{}}]}}),n);if(n!==this.lifecycleGeneration||e.signal?.aborted)return g(w("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}));this.application=i.value,this.manifest=o.value;let a=new Le(this.connect,{selection:this.options.selection,autoSelect:this.options.autoSelect,operations:us(r,o.value)});this.base=a;try{let s=await a.start(e);return s.ok?n!==this.lifecycleGeneration||e.signal?.aborted?(this.cleanupBase(a),g(w("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}))):(this.stopBase=a.subscribe(()=>{this.base===a&&this.refresh()}),await this.refresh(!0,e),n!==this.lifecycleGeneration||e.signal?.aborted?(this.cleanupBase(a),g(w("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}))):I(this.snapshot)):(this.cleanupBase(a),this.startFailure(s.problem,n))}catch(s){throw this.cleanupBase(a),s}}startFailure(e,n){return n===this.lifecycleGeneration&&this.publish({status:"start_failed",problem:e,connections:this.connect.connections()}),g(e)}destroy(){if(this.snapshot.status!=="destroyed"){this.lifecycleGeneration+=1,this.verificationGeneration+=1,this.readinessController?.abort(),this.startOperation?.controller.abort(),this.startOperation=null;for(let e of this.operationControllers)e.abort();this.operationControllers.clear(),this.base&&this.cleanupBase(this.base),this.application=null,this.manifest=null,this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"destroyed",connections:[]}),this.listeners.clear()}}cleanupBase(e){this.base===e&&(this.stopBase?.(),this.stopBase=void 0,e.destroy(),this.base=null)}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}connection(){let e=this.base?.getSnapshot();return e?.status==="ready"?e.connection:null}select(e,n={}){let i=this.lifecycleBase();return i.ok?i.value.select(e,n):i}clearSelection(e={}){let n=this.lifecycleBase();return n.ok?(n.value.clearSelection(e),I(void 0)):n}forget(e){let n=this.lifecycleBase();return n.ok?(n.value.forget(e),I(void 0)):n}authorize(e,n={}){return this.withLifecycleBase(n,async(i,o,r)=>{let a=await i.authorize(e,{...n,...o});return a.ok&&a.value.kind==="connected"&&this.lifecycleCurrent(r)&&await this.refresh(!0,o),a})}handleAuthorizationCallback(e,n){let i=String(e),o=this.startOperation!==null&&this.options.selection.authorizationCallback()===i;return this.withLifecycleBase(n,async(r,a,s)=>{if(o){let l=r.getSnapshot();return l.status==="ready"?I(l.connection):g(w("collection_not_ready","Authorization did not produce a ready collection."))}let c=await r.handleAuthorizationCallback(i,a);return c.ok&&this.lifecycleCurrent(s)&&await this.refresh(!0,a),c})}completeAuthorization(e,n){let i=e===void 0?Ut():String(e),o=this.startOperation!==null&&this.options.selection.authorizationCallback()===i;return this.withLifecycleBase(n,async(r,a,s)=>{if(o){let l=r.getSnapshot();return l.status==="ready"?I(l.connection):g(w("collection_not_ready","Authorization did not produce a ready collection."))}let c=await r.handleAuthorizationCallback(i,a);return c.ok&&this.lifecycleCurrent(s)&&await this.refresh(!0,a),c})}ensureCapabilities(e,n){return this.withLifecycleBase(n,(i,o,r)=>{Y(this.manifest.requirements,{...n,capabilities:e});let a=this.manifest.requirements?.capabilities,s=new Set([...a?.required??[],...a?.optional??[]]);return e.some(c=>!s.has(c))?Promise.resolve(g(w("invalid_application_manifest","Applications may only request capabilities declared in their manifest.",{details:{issues:[{path:"/requirements/capabilities",keyword:"undeclaredCapability",message:"must declare every capability requested by the application",params:{requested:e,declared:[...s]}}]}}))):i.ensureCapabilities(e,o).then(async c=>(c.ok&&c.value.kind==="connected"&&this.lifecycleCurrent(r)&&await this.refresh(!0,o),c))})}ensureOperations(e,n){return this.withLifecycleBase(n,async(i,o,r)=>{Y(this.manifest.requirements,{...n,operations:e});let a=await i.ensureOperations(e,o);return a.ok&&a.value.kind==="connected"&&this.lifecycleCurrent(r)&&await this.refresh(!0,o),a})}applyCollectionSetup(e){return this.withLifecycleBase(e,(n,i,o)=>this.applyCollectionSetupStarted(i,o))}async applyCollectionSetupStarted(e,n){if(this.snapshot.status!=="setup_review_required"||!this.setupAssessment)return g(w("collection_not_ready","There is no reviewed collection setup to apply."));if(!this.setupAssessment.applicable)return g(w("collection_not_ready","Resolve the collection setup conflicts before applying this update."));let i=this.connection();if(!i)return g(w("collection_not_ready","The collection is not ready."));let o=this.verificationGeneration,r=this.setupAssessment,a={...this.collectionSetupInput(this.setupTypePackAdoptions??void 0),expectedAssessmentDigest:r.assessmentDigest,expectedCollectionRevision:r.collectionRevision,expectedProvisionDigest:r.provisionDigest,allowTypePackDowngrades:r.typePacks.filter(c=>c.status==="downgrade").map(c=>c.desired.id)},s=await i.applyCollectionSetup(a,e);return this.lifecycleCurrent(n)?o!==this.verificationGeneration||this.connection()!==i?g(w("collection_not_ready","The selected collection changed during setup.")):s.ok?(this.setupAssessment=null,this.setupTypePackAdoptions=null,await this.verifySetup(this.context(i),++this.verificationGeneration,e),I(this.snapshot)):(s.problem.code==="application_declaration_mismatch"&&(this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"authorization_required",...this.context(i)})),s):!s.ok&&s.problem.code==="operation_outcome_unknown"?g(s.problem):g(w("session_destroyed",yt("session_destroyed")))}async refresh(e=!1,n){if(!this.base||!this.manifest)return;let i=this.base.getSnapshot();this.readinessController?.abort(),this.verificationGeneration+=1;let o=this.verificationGeneration;if(this.setupAssessment=null,this.setupTypePackAdoptions=null,i.status==="unselected"){this.publish({status:"unselected",connections:i.connections});return}if(i.status==="unavailable"){this.publish(i);return}if(i.status!=="ready")return;let r=this.context(i.connection);if(this.connect.connectionApplicationId(i.collectionId)!==this.application?.id){this.publish({status:"authorization_required",...r});return}if(!r.capabilities.requiredAvailable||r.readiness?.files.state==="requires_authorization"||!ys(this.manifest,r.info)){this.publish({status:"authorization_required",...r});return}if(!((this.manifest.provisions?.type_packs.length??0)>0||(this.manifest.provisions?.configuration?.length??0)>0)){let l=this.publishReady(r,o,n);e&&await l;return}let s=It(this.manifest,i.collectionId);r.readiness?.contracts.state!=="checking"&&this.verificationStore.read(s)===In(this.manifest)?this.publish({status:"ready",verification:"cached",...r}):this.publish({status:"checking_setup",...r});let c=this.verifySetup(r,o,n);e&&await c}async verifySetup(e,n,i){let o=this.connection(),r=this.requireManifest();if(!o||o.collectionId!==e.collectionId)return;let a=this.collectionSetupInput(),s=i?await o.assessCollectionSetup(a,i):await o.assessCollectionSetup(a);if(n===this.verificationGeneration){if(!s.ok){this.publish(s.problem.code==="application_declaration_mismatch"?{status:"authorization_required",...e}:{status:"blocked",problem:s.problem,...e});return}if(!s.value.applicable){let c=hs(s.value);if(Object.keys(c).length>0){if(s=i?await o.assessCollectionSetup(this.collectionSetupInput(c),i):await o.assessCollectionSetup(this.collectionSetupInput(c)),n!==this.verificationGeneration)return;if(!s.ok){this.publish(s.problem.code==="application_declaration_mismatch"?{status:"authorization_required",...e}:{status:"blocked",problem:s.problem,...e});return}this.setupTypePackAdoptions=c}}if(n===this.verificationGeneration){if(s.value.status!=="current"){this.setupAssessment=s.value,this.verificationStore.remove(It(r,e.collectionId)),this.publish({status:"setup_review_required",update:fs(s.value,r.provisions?.type_packs??[]),...e});return}this.verificationStore.write(It(r,e.collectionId),In(r)),e.readiness&&(e.readiness.setup={state:"current",evidence:[{source:"authority",fact:"Collection setup assessment is current."}]}),await this.publishReady(e,n,i)}}}async publishReady(e,n,i){let o=this.requireManifest().requirements?.contracts??[];if(e.readiness&&o.length){let r=this.connection();if(!r||r.collectionId!==e.collectionId)return;this.publish({status:"checking_setup",...e});let a=new AbortController;this.readinessController?.abort(),this.readinessController=a;try{if(!await Di({...e,readiness:e.readiness,contracts:o,connection:r,controller:a,options:i,requestMs:this.timeouts.requestMs,isCurrent:()=>n===this.verificationGeneration&&this.connection()===r,publish:s=>this.publish({...s,...e})}))return}finally{this.readinessController===a&&(this.readinessController=void 0)}}n===this.verificationGeneration&&this.publish({status:"ready",verification:"verified",...e})}collectionSetupInput(e){let n=this.requireManifest(),i=this.requireApplication();return Ni(n,ft(i.family_identity),`sha256:${i.manifest_digest}`,e)}context(e){return Li(this.requireManifest(),e.collectionId,e.info(),this.connect.connections())}publish(e){if(!(this.snapshot.status==="destroyed"&&e.status!=="destroyed")&&("readiness"in e&&e.readiness&&(e={...e,readiness:Ui(e.readiness,e.status,e.status==="ready"?e.verification:void 0)}),JSON.stringify(this.snapshot)!==JSON.stringify(e))){this.snapshot=e;for(let n of this.listeners)n()}}lifecycleBase(){let e=this.snapshot.status;if(this.startOperation||e==="starting")return g(w("session_starting","The application session is still starting."));if(this.snapshot.status==="start_failed")return g(this.snapshot.problem);if(this.base)return I(this.base);let n=e==="destroyed"?"session_destroyed":"session_not_started";return g(w(n,yt(n)))}async withLifecycleBase(e,n){let i=this.beginLifecycleOperation(e),o=pe(i.options,this.timeouts.requestMs),r={signal:o.signal,timeoutMs:null};try{let a=this.startOperation;if(a){let l=await this.waitForStart(a,r,null);if(!l.ok)return l}if(!this.lifecycleCurrent(i.generation))return g(w("session_destroyed",yt("session_destroyed")));let s=this.lifecycleBase();if(!s.ok)return s;let c=await n(s.value,r,i.generation);return this.lifecycleCurrent(i.generation)?c:this.destroyedOutcome(c)}catch(a){if(a instanceof b)return this.lifecycleCurrent(i.generation)?g(a.problem):a.problem.code==="operation_outcome_unknown"?g(a.problem):g(w("session_destroyed",yt("session_destroyed")));throw a}finally{o.dispose(),i.dispose()}}beginLifecycleOperation(e={}){let n=new AbortController,i=()=>n.abort(e.signal?.reason);return e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0}),this.operationControllers.add(n),{generation:this.lifecycleGeneration,options:{...e,signal:n.signal},dispose:()=>{e.signal?.removeEventListener("abort",i),this.operationControllers.delete(n)}}}lifecycleCurrent(e){return this.snapshot.status!=="destroyed"&&e===this.lifecycleGeneration}destroyedOutcome(e){return!e.ok&&e.problem.code==="operation_outcome_unknown"?e:g(w("session_destroyed",yt("session_destroyed")))}requireManifest(){if(!this.manifest)throw new Error("Start the application session before using it.");return this.manifest}requireApplication(){if(!this.application)throw new Error("Start the application session before using it.");return this.application}};function us(t,e){let n=(e.provisions?.type_packs.length??0)>0||(e.provisions?.configuration?.length??0)>0;return[...Fi(e.requirements),...t.contract_version===2&&n?Rt:[]]}function ps(t,e){let n=e.status==="conflict"?"Existing user-owned resources conflict with this application definition pack.":e.status==="install"?"This collection needs the application definitions installed.":`This collection has a ${e.status} definition change to review.`;return{id:e.desired.id,name:t.manifest.name??e.desired.id,status:e.status,applicable:e.applicable,assessmentDigest:e.assessmentDigest,...e.current?{currentVersion:e.current.version}:{},desiredVersion:e.desired.version,resources:e.resources,contractSetups:e.contractSetups,canApply:e.applicable,reason:n}}function fs(t,e){let n=t.typePacks.map(r=>{let a=e.find(s=>s.manifest.id===r.desired.id);if(!a)throw new Error(`Collection setup returned undeclared type pack '${r.desired.id}'.`);return ps(a,r)}),i=t.configuration.filter(r=>r.action!=="current").length,o=t.status==="conflict"?"Existing collection policy conflicts with this application's required setup.":`This application requires ${i} configuration change${i===1?"":"s"} and ${n.length} definition update${n.length===1?"":"s"}.`;return{status:t.status,applicable:t.applicable,assessmentDigest:t.assessmentDigest,collectionRevision:t.collectionRevision,provisionDigest:t.provisionDigest,configuration:t.configuration,typePacks:n,canApply:t.applicable,reason:o}}function hs(t){let e={};for(let n of t.typePacks){let i=Object.fromEntries(n.resources.filter(o=>o.action==="conflict"&&o.mode==="managed"&&o.currentDigest!==void 0&&o.installedDigest===void 0).map(o=>[o.target,o.currentDigest]));Object.keys(i).length>0&&(e[n.desired.id]=i)}return e}function ys(t,e){return t.requirements?.access==="full_collection"&&e.scope.access==="full_collection"&&e.scope.contracts.length===0}function yt(t){return t==="session_destroyed"?"This application session has been destroyed.":t==="session_starting"?"The application session is still starting.":"Start the application session before using it."}function ms(){return typeof localStorage<"u"?{read:t=>localStorage.getItem(t),write:(t,e)=>localStorage.setItem(t,e),remove:t=>localStorage.removeItem(t)}:new mt}function Z(t,e){return new Promise((n,i)=>{if(e?.aborted){i(e?.reason??new DOMException("Aborted","AbortError"));return}let o=()=>e?.removeEventListener("abort",a),r=setTimeout(()=>{o(),n()},t),a=()=>{clearTimeout(r),o(),i(e?.reason??new DOMException("Aborted","AbortError"))};e?.addEventListener("abort",a,{once:!0})})}var gs="mdbase-connect-identities",Be="application-identities",Ln=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),_s=Ln/2n,je=class{database=null;async create(e){let n=await Ro(e),i=await this.open();return await So(i,o=>o.add(n)),n}async get(e){let n=await this.open();return await bs(n.transaction(Be).objectStore(Be).get(e))??null}async delete(e){let n=await this.open();await So(n,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new Ae("Persistent application identity requires browser IndexedDB or an injected identity store.");return this.database||(this.database=new Promise((e,n)=>{let i=indexedDB.open(gs,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Be)||i.result.createObjectStore(Be,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},Ke=class{records=new Map;async create(e){if(this.records.has(e))throw new Error(`Application identity already exists: ${e}`);let n=await Ro(e);return this.records.set(e,n),n}async get(e){return this.records.get(e)??null}async delete(e){this.records.delete(e)}},Ae=class extends Error{constructor(e){super(e),this.name="ApplicationIdentityStoreError"}};async function Ve(t){return Oi(t.signingPublicKey)}async function gt(t,e){if(t.installation_signing_public_key!==e.signingPublicKey||t.application_installation_id!==await Ve(e))throw new Error("Application authorization identity does not match its binding.");let n=vs(new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e.signingPrivateKey,Ti(t))));return{binding:t,signature:Ao(n)}}async function Bt(t,e,n){let i=`application-installation:v2:${e}:${n.id}`,o=await t.get(i);if(o)return o;try{return await t.create(i)}catch(r){let a=await t.get(i);if(a)return a;throw r}}async function Ro(t){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),n=Ao(new Uint8Array(await crypto.subtle.exportKey("raw",e.publicKey))),i=await crypto.subtle.exportKey("pkcs8",e.privateKey),o=await crypto.subtle.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]);return{handle:t,signingPrivateKey:o,signingPublicKey:n}}function bs(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function So(t,e){return new Promise((n,i)=>{let o=t.transaction(Be,"readwrite");e(o.objectStore(Be)).onerror=()=>i(o.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Identity transaction aborted.")),o.oncomplete=()=>n()})}function Cs(t){let e=new Uint8Array(t.reduce((i,o)=>i+o.byteLength,0)),n=0;for(let i of t)e.set(i,n),n+=i.byteLength;return e}function Ao(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function vs(t){if(t.byteLength!==64)throw new Error("Application authorization signature is invalid.");let e=ws(t.slice(32));if(e===0n||e>=Ln)throw new Error("Application authorization signature is invalid.");return e<=_s?t:Cs([t.slice(0,32),Ss(Ln-e,32)])}function ws(t){return BigInt(`0x${Rs(t)}`)}function Ss(t,e){let n=t.toString(16).padStart(e*2,"0");return Uint8Array.from({length:e},(i,o)=>Number.parseInt(n.slice(o*2,o*2+2),16))}function Rs(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}async function*Oo(t,e,n={},i={}){let{offset:o,limit:r,cursor:a,pagination:s,snapshot:c,...l}=n,u=As(o,0),p=Po(i.firstPageSize??r,200),f=Po(i.pageSize??r,1e3),h=a,y=a!==void 0,R=a,C=c,m=0,v=0;try{for(;!i.signal?.aborted;){let _=h,A={signal:i.signal,timeoutMs:i.pageTimeoutMs,coordination:{...i.coordination,coalesce:!1}},T=v===0&&a===void 0&&s===void 0&&c===void 0,O=await t({...l,limit:v===0?p:f,...y?_?{cursor:_}:{pagination:"cursor"}:{offset:u,...C?{snapshot:C}:{},...!C&&s==="cursor"?{pagination:"cursor"}:{}},...!y&&!C&&T?{pagination:"cursor"}:{}},A);if(T&&!O.ok&&O.problem.code==="operation_invalid"&&(O=await t({...l,limit:p,offset:u},A)),!O.ok){yield O;return}let S=O.value,P=S.meta?.cursor;if(P?(y=!0,h=P,R=P):y&&(h=void 0,R=_),y&&S.meta?.hasMore&&!P){yield g(w("invalid_operation_response","The collection authority omitted the cursor required for the next query page."));return}let q=S.meta?.snapshot;if(!y&&C&&q&&C!==q){yield g(w("query_snapshot_changed","The collection query snapshot changed while paging. Refresh the query before continuing."));return}!y&&!C&&q&&(C=q),m+=S.results.length;let H=!S.meta?.hasMore||S.results.length===0,ne={results:S.results,...S.meta?{meta:S.meta}:{},page:v,offset:u,loaded:m,complete:H,...P?{cursor:P}:{},...!y&&C?{snapshot:C}:{}};if(i.onProgress?.(ne),yield I(ne,O.diagnostics),H)return;u+=S.results.length,v+=1}}finally{y&&R&&await e(R)}}function As(t,e){return typeof t=="number"&&Number.isFinite(t)?Math.max(0,Math.floor(t)):e}function Po(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):e}async function*ko(t,e,n,i={}){let{offset:o,limit:r,cursor:a,...s}=n,c=Ps(o,0),l=To(i.firstPageSize??r,200),u=To(i.pageSize??r,1e3),p=a,f=a!==void 0,h=a,y=0,R=0;try{for(;!i.signal?.aborted;){let C=p,m=await t({...s,limit:R===0?l:u,...f&&C?{cursor:C}:{offset:c}},{signal:i.signal,timeoutMs:i.pageTimeoutMs,coordination:{...i.coordination,coalesce:!1}});if(!m.ok){yield m;return}let v=m.value,_=v.meta.cursor;if(_?(f=!0,p=_,h=_):f&&(p=void 0,h=C),f&&v.meta.hasMore&&!_){yield g(w("invalid_operation_response","The collection authority omitted the cursor required for the next saved-view page."));return}y+=v.results.length;let A=!v.meta.hasMore||v.results.length===0,T={...v,page:R,offset:c,loaded:y,complete:A,..._?{cursor:_}:{}};if(i.onProgress?.(T),yield I(T,m.diagnostics),A)return;c+=v.results.length,R+=1}}finally{f&&h&&await e(h)}}function Ps(t,e){return typeof t=="number"&&Number.isFinite(t)?Math.max(0,Math.floor(t)):e}function To(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):e}function Io(t){if(t!==!1)return{initialDelayMs:Math.max(0,t?.initialDelayMs??500),maxDelayMs:Math.max(0,t?.maxDelayMs??15e3),multiplier:Math.max(1,t?.multiplier??2),...t?.maxAttempts===void 0?{}:{maxAttempts:Math.max(0,t.maxAttempts)}}}var Ge=class{constructor(e,n=Me){this.transport=e;this.requestTimeoutMs=n}transport;requestTimeoutMs;operation(e,n,i){return D(()=>this.transport.operation(e,n,i),Bi)}async describe(e){let n=await this.rawOperation("describe",{},Mt,e);return L(n,js)}async changes(e={},n){let i=await this.rawOperation("changes",e,xt,n);return L(i,Bs)}async read(e,n){let i=await this.envelopeOperation("read",Os(e),ie,n);return L(i,jt)}async query(e={},n){let i=await this.envelopeOperation("query",Ts(e),xn,n);return L(i,({results:o,meta:r})=>({results:o.map(Bo),...r?{meta:{...typeof r.total_count=="number"?{totalCount:r.total_count}:{},...r.total_count_outcome===void 0?{}:{totalCountOutcome:r.total_count_outcome},hasMore:r.has_more,...r.cursor?{cursor:r.cursor}:{},...r.snapshot?{snapshot:r.snapshot}:{}}}:{}}))}async*queryPages(e={},n={}){yield*Oo((i,o)=>this.query(i,o),i=>this.releaseQueryCursor(i),e,n)}async queryAll(e={},n={}){let i=pe(n,this.requestTimeoutMs),o=[],r,a=[];try{for await(let s of this.queryPages(e,{firstPageSize:n.firstPageSize,pageSize:n.pageSize,signal:i.signal,pageTimeoutMs:null,coordination:n.coordination,onProgress:n.onProgress})){if(!s.ok)return s;let c=s.value;o.push(...c.results),r=c,a.push(...s.diagnostics)}if(i.signal.aborted)throw J(i.signal);return I({results:o,meta:{totalCount:r?.meta?.totalCount??o.length,hasMore:r?!r.complete:!1,...r?.snapshot?{snapshot:r.snapshot}:{}}},a)}catch(s){if(s instanceof b)return g(s.problem);throw s}finally{i.dispose()}}async listViews(e){let n=await this.envelopeOperation("list_views",{},ie,e);return L(n,i=>({views:i.views,meta:{totalCount:i.meta.total_count}}))}async executeView(e,n){let i=await this.envelopeOperation("execute_view",e,ie,n);return L(i,Fs)}async*executeViewPages(e,n={}){yield*ko((i,o)=>this.executeView(i,o),i=>this.releaseQueryCursor(i),e,n)}readViewSource(e,n){return this.envelopeOperation("read_view_source",e,ie,n)}createViewSource(e,n){return this.envelopeOperation("create_view_source",e,j,n)}updateViewSource(e,n){return this.envelopeOperation("update_view_source",Nn(e),j,n)}deleteViewSource(e,n){return this.envelopeOperation("delete_view_source",Nn(e),j,n)}async create(e,n){let i=await this.envelopeOperation("create",ks(e),j,n);return L(i,jt)}async update(e,n){let i=await this.envelopeOperation("update",Is(e),j,n);return L(i,jt)}async delete(e,n){let i=await this.envelopeOperation("delete",Mo(e),j,n);return L(i,Uo)}async preflightDelete(e,n){let i=await this.envelopeOperation("delete",{...Mo(e),check_backlinks:!0,dry_run:!0},j,n);return L(i,Es)}async rename(e,n){let i=await this.envelopeOperation("rename",xo(e),j,n);return L(i,qs)}async preflightRename(e,n){let i=await this.envelopeOperation("rename",{...xo(e),dry_run:!0},j,n);return L(i,zs)}validate(e={},n){return this.envelopeOperation("validate",e,ie,n)}readType(e,n){return this.envelopeOperation("read_type",e,he,n)}createType(e,n){return this.envelopeOperation("create_type",e,he,n)}updateType(e,n){return this.envelopeOperation("update_type",Nn(e),he,n)}async assessTypePack(e,n){let i=await this.envelopeOperation("assess_type_pack",Fo(e),he,n);return L(i,jn)}async applyTypePack(e,n){let i=await this.envelopeOperation("apply_type_pack",Ms(e),he,n);return L(i,Us)}async assessCollectionSetup(e,n){let i=await this.envelopeOperation("assess_collection_setup",Do(e),he,n);return L(i,zo)}async applyCollectionSetup(e,n){let i=await this.envelopeOperation("apply_collection_setup",xs(e),he,n);return L(i,o=>({assessment:zo(o.assessment),receipt:Ls(o.receipt)}))}async listTimers(e,n){let i=await this.rawOperation("list_timers",{namespace:e},ie,n);return L(i,o=>({namespace:o.namespace,timers:o.timers.map(Bn)}))}async putTimer(e,n){let i=await this.rawOperation("put_timer",{namespace:e.namespace,criterion_id:e.criterionId,timer:Eo(e.timer)},j,n);return L(i,Bn)}cancelTimer(e,n){return this.rawOperation("cancel_timer",e,j,n)}async reconcileTimers(e,n){let i=await this.rawOperation("reconcile_timers",{namespace:e.namespace,criterion_id:e.criterionId,timers:e.timers.map(Eo)},j,n);return L(i,o=>({namespace:o.namespace,timers:o.timers.map(Bn),cancelledIds:o.cancelled_ids}))}async*watch(e={}){let n=e.cursor,i=Math.max(100,e.pollIntervalMs??1e3),o=Io(e.retry),r=0,a=!1;for(e.onStatus?.({state:"connecting",...n===void 0?{}:{cursor:n}});!e.signal?.aborted;){let s=await this.changes(n===void 0?{}:{after:n,limit:200},{signal:e.signal,timeoutMs:e.timeoutMs});if(!s.ok){let u=s.problem;if(e.signal?.aborted)return;if(!o||u.recovery!=="retry"){yield s;return}if(a=!1,r+=1,o.maxAttempts!==void 0&&r>o.maxAttempts){yield s;return}let p=Math.min(o.maxDelayMs,Math.round(o.initialDelayMs*o.multiplier**(r-1)));e.onStatus?.({state:"reconnecting",...n===void 0?{}:{cursor:n},attempt:r,retryInMs:p,problem:u});try{await Z(p,e.signal)}catch{if(!e.signal?.aborted)throw d("operation_failed","Watch retry delay failed unexpectedly.")}continue}let c=s.value;if(n===void 0){n=c.cursor;continue}if(c.reset){let u=w("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again.");e.onStatus?.({state:"reset_required",cursor:n,problem:u}),yield g(u);return}let l=r>0;r=0,(!a||l)&&e.onStatus?.({state:"connected",cursor:n,recovered:l}),a=!0;for(let u of c.events)yield I(u);if(n=c.cursor,!c.hasMore)try{await Z(i,e.signal)}catch{if(!e.signal?.aborted)throw d("operation_failed","Watch polling delay failed unexpectedly.")}}}rawOperation(e,n,i,o){return D(()=>this.transport.operation(e,n,o),i)}async releaseQueryCursor(e){try{await this.envelopeOperation("query",{release_cursor:e},xn,{timeoutMs:2e3,coordination:{coalesce:!1}})}catch{}}async envelopeOperation(e,n,i,o){let r=await D(()=>this.transport.operation(e,n,o),i);if(!r.ok)return r;let a=r.value;return a.valid?I(a.result,a.diagnostics):g(ke(a))}};function L(t,e){return t.ok?I(e(t.value),t.diagnostics):t}function Os(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function Ts(t){return{...t.types?{types:t.types}:{},...t.timezone?{timezone:t.timezone}:{},...t.context?{context:t.context}:{},...t.projections?{projections:Object.fromEntries(Object.entries(t.projections).map(([e,n])=>[e,{expr:n.expression,...n.description?{description:n.description}:{}}]))}:{},...t.where?{where:t.where}:{},...t.select?{select:t.select.map(e=>typeof e=="string"?e:{name:e.name,expr:e.expression,...e.label?{label:e.label}:{},...e.description?{description:e.description}:{}})}:{},...t.orderBy?{order_by:t.orderBy}:{},...t.groupBy?{group_by:t.groupBy}:{},...t.summaryFunctions?{summary_functions:Object.fromEntries(Object.entries(t.summaryFunctions).map(([e,n])=>[e,{expr:n.expression,...n.description?{description:n.description}:{}}]))}:{},...t.summaries?{summaries:t.summaries}:{},...t.limit===void 0?{}:{limit:t.limit},...t.offset===void 0?{}:{offset:t.offset},...t.pagination?{pagination:t.pagination}:{},...t.cursor?{cursor:t.cursor}:{},...t.snapshot?{snapshot:t.snapshot}:{},...t.includeBody===void 0?{}:{include_body:t.includeBody},...t.frontmatterMode?{frontmatter_mode:t.frontmatterMode}:{},...t.contract?{contract:t.contract}:{}}}function ks(t){return{...t.path?{path:t.path}:{},...t.type?{type:t.type}:{},...t.contract?{contract:t.contract}:{},...t.frontmatter?{frontmatter:t.frontmatter}:{},...t.body===void 0?{}:{body:t.body},...t.ifRevision?{if_revision:t.ifRevision}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function Is(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.ifRevision?{if_revision:t.ifRevision}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument},...t.document===void 0?{patch:t.patch,...t.body===void 0?{}:{body:t.body}}:{document:t.document}}}function Mo(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.checkBacklinks===void 0?{}:{check_backlinks:t.checkBacklinks},...t.ifRevision?{if_revision:t.ifRevision}:{}}}function xo(t){return{from:t.from,to:t.to,...t.contract?{contract:t.contract}:{},...t.updateRefs===void 0?{}:{update_refs:t.updateRefs},...t.ifRevision?{if_revision:t.ifRevision}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function Nn(t){let{ifRevision:e,...n}=t;return{...n,...e?{if_revision:e}:{}}}function Fo(t){return{provision:t.provision,installed_by:t.installedBy,...t.adoptResources?{adopt_resources:t.adoptResources}:{},...t.preserveSeedTargets?{preserve_seed_targets:t.preserveSeedTargets}:{},...t.targetOverrides?{target_overrides:t.targetOverrides}:{},...t.contractSetups?{contract_setups:t.contractSetups.map(Lo)}:{}}}function Ms(t){return{...Fo(t),expected_assessment_digest:t.expectedAssessmentDigest,...t.allowDowngrade===void 0?{}:{allow_downgrade:t.allowDowngrade}}}function Do(t){return{application_id:t.applicationId,declaration_digest:t.declarationDigest,requirements:t.requirements,provisions:{configuration:t.provisions.configuration,type_packs:t.provisions.typePacks},...t.contractSetups?{contract_setups:t.contractSetups.map(Lo)}:{},...t.typePackAdoptions?{type_pack_adoptions:t.typePackAdoptions}:{}}}function xs(t){return{...Do(t),expected_assessment_digest:t.expectedAssessmentDigest,expected_collection_revision:t.expectedCollectionRevision,expected_provision_digest:t.expectedProvisionDigest,...t.allowTypePackDowngrades?{allow_type_pack_downgrades:t.allowTypePackDowngrades}:{}}}function Uo(t){return{path:t.path,deleted:t.deleted,...t.broken_links?{brokenLinks:t.broken_links}:{}}}function Es(t){return{...Uo(t),deleted:!1,dryRun:!0,wouldDelete:!0}}function qs(t){let{references_updated:e,...n}=t;return{...jt(n),from:t.from,to:t.to,...e?{referencesUpdated:e}:{}}}function zs(t){return{from:t.from,to:t.to,dryRun:!0,wouldRename:!0,...t.references_affected?{referencesAffected:t.references_affected}:{},...t.warnings?{warnings:t.warnings}:{}}}function Eo(t){return{id:t.id,fire_at:t.fireAt,...t.data===void 0?{}:{data:t.data}}}function Bn(t){return{id:t.id,fireAt:t.fire_at,...t.data===void 0?{}:{data:t.data},criterionId:t.criterion_id,generation:t.generation,status:t.status,createdAt:t.created_at,updatedAt:t.updated_at,firedAt:t.fired_at}}function Lo(t){return t.mode==="starter"?t:{contract:t.contract,mode:"existing",type_name:t.typeName,type_revision:t.typeRevision,fields:t.fields,...t.binding?{binding:t.binding}:{}}}function No(t){return{id:t.id,version:t.version,digest:t.digest,type:t.type,implementationDigest:t.implementation_digest}}function Bo(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,...e===void 0?{}:{effectiveFrontmatter:e},...n?{contract:No(n)}:{}}}function jt(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,effectiveFrontmatter:e,...n?{contract:No(n)}:{}}}function Fs(t){return{results:t.results.map(e=>{let n=Bo(e);if(!n.effectiveFrontmatter)throw new Error("Saved view result omitted canonical effective frontmatter.");return{...n,effectiveFrontmatter:n.effectiveFrontmatter}}),meta:{totalCount:t.meta.total_count,hasMore:t.meta.has_more,...t.meta.cursor?{cursor:t.meta.cursor}:{},view:t.meta.view,...t.meta.context?{context:t.meta.context}:{},...t.meta.groups?{groups:t.meta.groups}:{}}}}function qo(t){return{source:t.source,target:t.target,kind:t.kind,mode:t.mode,action:t.action,digest:t.digest,...t.current_digest?{currentDigest:t.current_digest}:{},...t.installed_digest?{installedDigest:t.installed_digest}:{},...t.adopted_from_digest?{adoptedFromDigest:t.adopted_from_digest}:{},...t.reason?{reason:t.reason}:{}}}function Kt(t){return{id:t.id,version:t.version,digest:t.digest,installedBy:t.installed_by,resources:t.resources.map(e=>({source:e.source,target:e.target,kind:e.kind,mode:e.mode,digest:e.digest,...e.adopted_from_digest?{adoptedFromDigest:e.adopted_from_digest}:{}}))}}function Ds(t){return t.mode==="starter"?t:{contract:t.contract,mode:"existing",typeName:t.type_name,typeRevision:t.type_revision,fields:t.fields,...t.binding?{binding:t.binding}:{}}}function jn(t){return{status:t.status,applicable:t.applicable,assessmentDigest:t.assessment_digest,...t.current?{current:Kt(t.current)}:{},desired:Kt(t.desired),resources:t.resources.map(qo),lock:t.lock,contractSetups:{choices:t.contract_setups.choices.map(Ds),resources:t.contract_setups.resources.map(qo)}}}function Us(t){return{...jn(t),receipt:Kt(t.receipt),cleanupDeferred:t.cleanup_deferred}}function zo(t){return{status:t.status,applicable:t.applicable,applicationId:t.application_id,declarationDigest:t.declaration_digest,provisionDigest:t.provision_digest,collectionRevision:t.collection_revision,finalCollectionRevision:t.final_collection_revision,baselineDiagnosticCount:t.baseline_diagnostic_count,finalDiagnosticCount:t.final_diagnostic_count,resolvedDiagnosticCount:t.resolved_diagnostic_count,introducedDiagnosticCount:t.introduced_diagnostic_count,baselineDiagnosticDigest:t.baseline_diagnostic_digest,configuration:t.configuration,typePacks:t.type_packs.map(jn),finalResourceRevisions:t.final_resource_revisions,assessmentDigest:t.assessment_digest}}function Ls(t){return{applicationId:t.application_id,declarationDigest:t.declaration_digest,provisionDigest:t.provision_digest,assessmentDigest:t.assessment_digest,collectionRevision:t.collection_revision,configuration:t.configuration,typePacks:t.type_packs.map(Kt),cleanupDeferred:t.cleanup_deferred}}function Ns(t){return{cursor:t.cursor,type:t.type,occurredAt:t.occurred_at,payload:t.payload}}function Bs(t){return{events:t.events.map(Ns),cursor:t.cursor,hasMore:t.has_more,reset:t.reset}}function js(t){return{protocolVersion:t.protocol_version,collectionId:t.collection_id,displayName:t.display_name,specVersion:t.spec_version,operations:t.operations,changeCursor:t.change_cursor,types:t.types,contracts:t.contracts.map(e=>({contractType:e.contract_type,id:e.id,version:e.version,digest:e.digest,schema:e.schema,...e.binding_schema?{bindingSchema:e.binding_schema}:{},implementations:e.implementations.map(n=>({typeName:n.type_name,typeVersion:n.type_version,...n.type_path?{typePath:n.type_path}:{},digest:n.digest,fields:n.fields,...n.binding?{binding:n.binding}:{}}))})),...t.configuration?{configuration:t.configuration}:{}}}var Vt=class{constructor(e){this.context=e}context;async registerNotifications(e){return F(e,this.context.requestTimeoutMs,n=>this.registerNotificationsWithinBudget(e,n.signal))}async registerNotificationsWithinBudget(e,n){let i=await this.context.authorizedToken(n);if(!i)throw d("not_authorized","Connect this application before enabling notifications.");let r=(await this.context.register(n)).notifications?.criteria.map(m=>m.id)??[],a=[...new Set(e.criteria??r)],s=a.find(m=>!r.includes(m));if(s)throw d("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${s}.`);if(a.length===0)throw d("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=await ae(`${this.context.serverUrl}/v1/notifications/vapid-public-key`,{signal:n},"notifications_unavailable","Push notifications are unavailable."),l=await E(c,"invalid_operation_response","Connect returned an invalid notification key response.");if(!c.ok)throw z(l,"notifications_unavailable","Push notifications are unavailable.",c.status);let u=await e.serviceWorker.pushManager.getSubscription();u||(u=await e.serviceWorker.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:uo(l.public_key)}));let p=u.toJSON();if(!p.endpoint||!p.keys?.p256dh||!p.keys.auth)throw d("invalid_push_subscription","The browser returned an incomplete push subscription.");let f=M(this.context.storage.getItem(this.context.notificationKey())),h=e.installationId??f?.installationId??X(24),y=await ae(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${i.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:h,criteria:a,subscription:{endpoint:p.endpoint,expirationTime:p.expirationTime??null,keys:p.keys}}),signal:n},"notification_registration_failed","Could not register push notifications."),R=await E(y,"invalid_operation_response","Connect returned an invalid notification registration response.");if(!y.ok)throw z(R,"notification_registration_failed","Could not register push notifications.",y.status);f?.channelId&&f.channelId!==R.channel_id&&fetch(`${this.context.serverUrl}/v1/notifications/channels/${f.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${i.accessToken}`},signal:n}).catch(()=>{});let C={channelId:R.channel_id,installationId:h,criteria:a};return this.context.storage.setItem(this.context.notificationKey(),JSON.stringify(C)),C}async registerNativeNotifications(e){return F(e,this.context.requestTimeoutMs,n=>this.registerNativeNotificationsWithinBudget(e,n.signal))}async registerNativeNotificationsWithinBudget(e,n){let i=await this.context.authorizedToken(n);if(!i)throw d("not_authorized","Connect this application before enabling notifications.");let o=await this.context.register(n);if(o.notifications?.native_delivery?.mode!=="managed_fcm")throw d("managed_fcm_not_declared","This application does not declare Connect-managed native notifications.");let r=o.notifications.criteria.map(y=>y.id),a=[...new Set(e.criteria??r)],s=a.find(y=>!r.includes(y));if(s)throw d("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${s}.`);if(a.length===0)throw d("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=this.context.notificationKey("fcm"),l=M(this.context.storage.getItem(c)),u=e.installationId??l?.installationId??X(24),p=await ae(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${i.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:u,criteria:a,transport:"fcm",token:e.token}),signal:n},"notification_registration_failed","Could not register native notifications."),f=await E(p,"invalid_operation_response","Connect returned an invalid native notification response.");if(!p.ok)throw z(f,"notification_registration_failed","Could not register native notifications.",p.status);l?.channelId&&l.channelId!==f.channel_id&&this.deleteNotificationChannel(l.channelId,i.accessToken,n).catch(()=>{});let h={channelId:f.channel_id,installationId:u,transport:"fcm",criteria:a};return this.context.storage.setItem(c,JSON.stringify(h)),h}async unregisterNativeNotifications(e={}){return F(e,this.context.requestTimeoutMs,n=>this.unregisterNativeNotificationsWithinBudget(n.signal))}async unregisterNativeNotificationsWithinBudget(e){let n=this.context.notificationKey("fcm"),i=M(this.context.storage.getItem(n)),o=await this.context.authorizedToken(e);if(i?.channelId&&!o)throw d("not_authorized","Reconnect this application before disabling native notifications.");i?.channelId&&o&&await this.deleteNotificationChannel(i.channelId,o.accessToken,e),this.context.storage.removeItem(n)}async unregisterNotifications(e,n={}){return F(n,this.context.requestTimeoutMs,i=>this.unregisterNotificationsWithinBudget(e,i.signal))}async unregisterNotificationsWithinBudget(e,n){let i=M(this.context.storage.getItem(this.context.notificationKey())),o=await this.context.authorizedToken(n);if(i?.channelId&&!o)throw d("not_authorized","Reconnect this application before disabling push notifications.");if(i?.channelId&&o){let a=await ae(`${this.context.serverUrl}/v1/notifications/channels/${i.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${o.accessToken}`},signal:n},"notification_unregistration_failed","Could not unregister push notifications.");if(!a.ok&&a.status!==404){let s=await E(a,"invalid_operation_response","Connect returned an invalid notification response.");throw z(s,"notification_unregistration_failed","Could not unregister push notifications.",a.status)}}this.context.storage.removeItem(this.context.notificationKey()),await(await e?.pushManager.getSubscription())?.unsubscribe()}async deleteNotificationChannel(e,n,i){let o=await ae(`${this.context.serverUrl}/v1/notifications/channels/${e}`,{method:"DELETE",headers:{authorization:`Bearer ${n}`},signal:i},"notification_unregistration_failed","Could not unregister push notifications.");if(!o.ok&&o.status!==404){let r=await E(o,"invalid_operation_response","Connect returned an invalid notification response.");throw z(r,"notification_unregistration_failed","Could not unregister push notifications.",o.status)}}};async function Gt(t,e,n,i,o,r){if(!t.authority)throw d("not_remote_authority","This authorization has no remote authority endpoint.");let a=n===""||n.startsWith("?")?n:`/${n}`,s=`${t.authority.filesUrl}${a}`,c=i===void 0?void 0:JSON.stringify(i),l=await r(t,e,s,c,t.authority.accessToken);return fetch(s,{method:e,redirect:"error",headers:{authorization:`Bearer ${t.authority.accessToken}`,...c===void 0?{}:{"content-type":"application/json"},...l},...c===void 0?{}:{body:c},...o?{signal:o}:{}})}async function jo(t,e,n,i,o,r,a,s=async c=>c){let c=t,l=await Gt(c,e,n,i,o,a);if(l.status===401&&c.refreshToken){if(c=await s(await r(o)),!c.authority||!c.fileCapability)throw d("authority_authorization_changed","Reconnect this collection before accessing its files.");l=await Gt(c,e,n,i,o,a)}let u=await E(l,"invalid_operation_response","The hosted authority returned an invalid file response.");if(!l.ok)throw z(u,"operation_failed","Collection file request failed.",l.status);return u}async function Ko(t,e,n,i,o,r,a=async s=>s){let s=t,c=await Gt(s,"GET",e,void 0,i,r);if(c.status===401&&s.refreshToken){if(s=await a(await o(i)),!s.authority||!s.fileCapability)throw d("authority_authorization_changed","Reconnect this collection before accessing its files.");c=await Gt(s,"GET",e,void 0,i,r)}if(!c.ok){let u=await E(c,"invalid_operation_response","The hosted authority returned an invalid file range error response.");throw z(u,"operation_failed","Collection file range request failed.",c.status)}let l=c.headers.get("content-length");if(l===null||!/^(0|[1-9][0-9]*)$/u.test(l)||Number(l)!==n)throw await c.body?.cancel().catch(()=>{}),d("invalid_operation_response","The hosted file response declared an unexpected byte length.");if(!c.body)throw d("invalid_operation_response","The hosted file response did not contain a byte stream.");return c.body}var Ht=class{constructor(e,n){this.namespace=e;this.onFinalRelease=n}namespace;onFinalRelease;leases=new Map;locks=Ks();retainAutomaticallyRetiredKeys=this.locks===null;async acquire(e,n,i){let o=this.acquireLocal(e,n);if(!this.locks)return o;try{let r=await Vs(this.locks,this.lockName(e,n),i);return Kn(()=>{r(),o()})}catch(r){throw o(),r}}deleteExclusive(e,n,i){this.retainAutomaticallyRetiredKeys||(this.locks?this.locks.request(this.lockName(e,n),{mode:"exclusive"},i).catch(()=>{}):this.has(e,n)||Promise.resolve().then(i).catch(()=>{}))}has(e,n){return this.leases.get(e)?.has(n)??!1}handles(e){return this.leases.get(e)?.keys()??[]}acquireLocal(e,n){let i=this.leases.get(e)??new Map;return i.set(n,(i.get(n)??0)+1),this.leases.set(e,i),Kn(()=>{let o=(i.get(n)??1)-1;o>0?i.set(n,o):(i.delete(n),i.size===0&&this.leases.delete(e),this.onFinalRelease(e,n))})}lockName(e,n){return`mdbase-connect:grant-key:${this.namespace}:${e}:${n}`}},ge=class{constructor(e,n){this.collectionId=e;this.acquire=n}collectionId;acquire;releases=new Map;async retain(e,n){let i=typeof e=="string"?e:e?.keyHandle;if(!i)return;let o=this.releases.get(i);o||(o=this.acquire(this.collectionId,i,n),this.releases.set(i,o));try{await o}catch(r){throw this.releases.get(i)===o&&this.releases.delete(i),this.release(),r}}release(){for(let e of this.releases.values())e.then(n=>n());this.releases.clear()}};async function V(t,e,n){for(;;){let i=t();if(!i)return null;await e.retain(i,n);let o=t();if(!o)return null;if(o.keyHandle===i.keyHandle)return o}}function Ks(){let t=typeof navigator>"u"?void 0:navigator.locks;return t||(typeof window<"u"||typeof globalThis.importScripts=="function"?null:void 0)}async function Vs(t,e,n){let i,o,r,a=new Promise((l,u)=>{i=l,o=u}),s=new Promise(l=>{r=l});return t.request(e,{mode:"shared",...n?{signal:n}:{}},async()=>{i(),await s}).catch(o),await a,Kn(r)}function Kn(t){let e=!1;return()=>{e||(e=!0,t())}}var Gs="mdbase-connect file chunk key v1",$t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,se=class extends Error{constructor(n,i){super(i);this.code=n;this.name="FileTransferCryptoError"}code},He=class t{constructor(e,n){this.binding=e;this.key=n}binding;key;static async open(e,n,i){Vo(i);let o=await e.get(n);if(!o||o.agreementPublicKey!==i.encryption.application_agreement_public_key)throw new x("missing_grant_key","The encrypted grant key is unavailable or does not match the file transfer grant.");let r=await st(o.agreementPrivateKey,i.encryption.connector_agreement_public_key);return t.fromSharedSecret(r,i)}static async fromSharedSecret(e,n){Vo(n);let i=await Vn(e,n);return new t(n,i)}async encryptChunk(e,n,i){if(this.validateHeader(n),i.byteLength!==n.plaintext_length)throw new se("plaintext_length_mismatch","File chunk plaintext length does not match its authenticated header.");let o=vt(e,n),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:Go(n.chunk_index),additionalData:Wt(o),tagLength:128},this.key,Wt(i));return yi({kind:e,header:n,payload:new Uint8Array(r)})}async decryptChunk(e){let n=wt(e);this.validateHeader(n.header);let i=vt(n.kind,n.header);try{let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:Go(n.header.chunk_index),additionalData:Wt(i),tagLength:128},this.key,Wt(n.payload));return new Uint8Array(o)}catch{throw new se("authentication_failed","The encrypted file chunk could not be authenticated.")}}validateHeader(e){let n=this.binding.encryption;if(e.protocol_version!==1||e.protection!=="grant_aead_v1"||e.grant_id!==this.binding.grantId||e.authority_id!==this.binding.authorityId||e.collection_id!==n.collection_id||e.transfer_id!==this.binding.transferId||e.direction!==this.binding.direction||e.scope_epoch!==n.scope_epoch||e.key_id!==n.key_id)throw new se("header_binding_mismatch","The file frame does not match its transfer encryption binding.")}};async function Vn(t,e){let n=new TextEncoder().encode(Hs(e)),i=await crypto.subtle.digest("SHA-256",n),o=await crypto.subtle.importKey("raw",t,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:i,info:new TextEncoder().encode(Gs)},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function Vo(t){if(re(t.encryption),!$t.test(t.grantId)||!$t.test(t.applicationId)||!$t.test(t.authorityId)||!$t.test(t.transferId)||t.direction!=="upload"&&t.direction!=="download")throw new se("invalid_binding","The file transfer encryption binding is invalid.")}function Hs(t){let e=t.encryption;return["mdbase-connect","file-transfer",1,e.suite,t.grantId,t.applicationId,e.connector_id,t.authorityId,e.collection_id,e.scope_epoch,e.key_id,t.transferId,t.direction].join("|")}function Go(t){if(!Number.isSafeInteger(t)||t<0)throw new se("invalid_chunk_index","The file chunk index is invalid.");let e=new Uint8Array(new ArrayBuffer(12));return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}function Wt(t){return Uint8Array.from(t).buffer}var Qt=8,Gn=10;function Yt(t){return t instanceof b&&t.code==="connector_busy"}async function Ho(t){if(!Yt(t.error)||t.completedRetries>=Qt)return{retried:!1};try{await Xt(t.completedRetries,t.signal)}catch(e){throw t.attempt.pendingMutation&&(t.knownRejectedMutationRetry||!t.attempt.resumingMutation)&&t.clearPending(t.attempt.requestId),e}return{retried:!0,result:await t.retry(t.attempt.pendingMutationRecord,t.knownRejectedMutationRetry||t.attempt.pendingMutation===!0&&!t.attempt.resumingMutation)}}async function $e(t){if(t.status!==502&&t.status!==503)return!1;let e=await t.clone().json().catch(()=>null);return e?.error==="connector_busy"||typeof e?.error=="object"&&e.error?.code==="connector_busy"}function Xt(t,e){return Wo(Jo(50,800,t),e)}function $o(t,e){return Wo(Jo(100,1e3,t-1),e)}async function Wo(t,e){try{await Z(t,e)}catch(n){throw e?.aborted?e.reason instanceof b?e.reason:d("operation_cancelled","The operation was cancelled while waiting for connector capacity.",{operationOutcome:"not_sent",cause:n}):n}}function Jo(t,e,n){let i=Math.min(e,t*2**Math.max(0,n));return Math.max(1,Math.round(i*(.75+Math.random()*.5)))}var en=class{constructor(e){this.options=e}options;async control(e,n,i,o,r){let a=this.grantKeyLeases(e.collectionId);try{return e=await this.retainEntryToken(e,a,r),await this.controlAttempt(e,n,i,o,r,!1,0,a)}finally{a.release()}}async controlAttempt(e,n,i,o,r,a,s,c){We(e);let l=Xs(n,i,o),u=await this.encryptControl(e,l),p,f=await this.options.shouldAttemptDirect(e);if(f){try{p=await fetch(`${this.options.loopbackUrl}/v1/files/control`,me({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(u),signal:r}))}catch(h){if(r?.aborted)throw h;this.options.onDirectUnavailable()}if(p&&(!Fe(p.status)||await $e(p)))return p.ok&&this.options.onDirectAvailable(),this.decryptControlResponse(e,n,i,o,r,u,p,a,s,c);p&&this.options.onDirectUnavailable()}return f&&n==="GET"&&(e=e.expiresAt>Date.now()+3e4?e:await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,c,r),Zt(e),u=await this.encryptControl(e,l)),p=await this.sendRelayControl(e,u,r),await Ws(p,e)&&(e=await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,c,r),Zt(e),u=await this.encryptControl(e,l),p=await this.sendRelayControl(e,u,r)),p.ok&&this.options.onRelayAvailable(),this.decryptControlResponse(e,n,i,o,r,u,p,a,s,c)}async decryptControlResponse(e,n,i,o,r,a,s,c,l,u){let p=await E(s,"invalid_operation_response","The collection authority returned an invalid file control response.");if(!s.ok){let y=z(p,"operation_failed","Collection file request failed.",s.status);if(Yt(y)&&l<Qt)return await Xt(l,r),this.controlAttempt(e,n,i,o,r,c,l+1,u);if(y.code==="fresh_request_required"&&n==="GET"&&!c)return this.controlAttempt(e,n,i,o,r,!0,l,u);throw y}let f=p?.envelope;if(!f)throw d("invalid_encrypted_response","The connector omitted its encrypted file response.");let h=await ze(this.options.keyStore,e.keyHandle,$n(e),a,f);if(!h.ok&&h.problem.code==="fresh_request_required"&&n==="GET"&&!c)return this.controlAttempt(e,n,i,o,r,!0,l,u);if(!h.ok){let y=Ys(h.problem);if(Yt(y)&&l<Qt)return await Xt(l,r),this.controlAttempt(e,n,i,o,r,c,l+1,u);throw y}return h.result}async uploadChunk(e,n,i,o,r){let a=r??await this.localFileToken(e,"upload",o),s=this.grantKeyLeases(a.collectionId);try{let c=await this.retainEntryToken(a,s,o);return Hn(c,e,"upload"),await this.uploadChunkWithLease(c,s,e,n,i,o)}finally{s.release()}}async uploadChunkWithLease(e,n,i,o,r,a){let s=e,c=await Qo(this.options.keyStore,s,i,o,r),l;if(await this.options.shouldAttemptDirect(s)){try{l=await fetch(`${this.options.loopbackUrl}/v1/files/upload`,me(Yo(c,a)))}catch(u){if(a?.aborted)throw u;this.options.onDirectUnavailable()}if(l&&(!Fe(l.status)||await $e(l)))return l.ok&&this.options.onDirectAvailable(),$s(l,"Encrypted file chunk upload failed.");l&&this.options.onDirectUnavailable()}if(l=await this.sendRelayUpload(s,c,a),l.status===401&&s.refreshToken&&(s=await this.options.refreshAuthorization(a),s=await this.retainEntryToken(s,n,a),Zt(s),c=await Qo(this.options.keyStore,s,i,o,r),l=await this.sendRelayUpload(s,c,a)),!l.ok){let u=await E(l,"invalid_operation_response","The collection authority returned an invalid file upload response.");throw z(u,"operation_failed","Encrypted file chunk upload failed.",l.status)}this.options.onRelayAvailable()}async downloadChunk(e,n,i,o){let r=o??await this.localFileToken(e,"download",i),a=this.grantKeyLeases(r.collectionId);try{return r=await this.retainEntryToken(r,a,i),Hn(r,e,"download"),await this.downloadChunkWithLease(r,a,e,n,i)}finally{a.release()}}async downloadChunkWithLease(e,n,i,o,r){let a;if(await this.options.shouldAttemptDirect(e)){try{a=await fetch(`${this.options.loopbackUrl}/v1/files/download/${encodeURIComponent(e.grantId)}/${encodeURIComponent(i.transfer_id)}/${o}`,me({method:"GET",signal:r}))}catch(s){if(r?.aborted)throw s;this.options.onDirectUnavailable()}if(a&&(!Fe(a.status)||await $e(a)))return a.ok&&this.options.onDirectAvailable(),this.decryptDownloadResponse(e,i,o,a);a&&this.options.onDirectUnavailable()}return a=await this.sendRelayDownload(e,i,o,r),a.status===401&&e.refreshToken&&(e=await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,n,r),Zt(e),a=await this.sendRelayDownload(e,i,o,r)),a.ok&&this.options.onRelayAvailable(),this.decryptDownloadResponse(e,i,o,a)}async decryptDownloadResponse(e,n,i,o){if(!o.ok){let s=await E(o,"invalid_operation_response","The collection authority returned an invalid file download response.");throw z(s,"operation_failed","Encrypted file chunk download failed.",o.status)}if(o.headers.get("content-type")?.split(";",1)[0]!=="application/mdbase-connect-file")throw d("invalid_operation_response","The connector returned an invalid file response media type.");let r=new Uint8Array(await o.arrayBuffer()),a;try{Qs(n,i,r),a=await(await Zo(this.options.keyStore,e,n)).decryptChunk(r)}catch(s){throw s instanceof b?s:d("invalid_operation_response","The connector returned an invalid encrypted file frame.",{cause:s})}if(a.byteLength!==Wn(n,i))throw d("invalid_operation_response","The connector returned a truncated file chunk.");return a}encryptControl(e,n){return We(e),oe(this.options.keyStore,e.keyHandle,$n(e),"file_control",n)}sendRelayControl(e,n,i){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/control`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify(n),signal:i})}sendRelayUpload(e,n,i){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/upload`,{...Yo(n,i),headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/mdbase-connect-file"}})}sendRelayDownload(e,n,i,o){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/download/${encodeURIComponent(n.transfer_id)}/${i}`,{method:"GET",headers:{authorization:`Bearer ${e.accessToken}`},signal:o})}async localFileToken(e,n,i){let o=await this.options.authorizedToken(i);return Hn(o,e,n),o}grantKeyLeases(e){return new ge(e,this.options.acquireGrantKeyLease??(()=>Promise.resolve(()=>{})))}async retainEntryToken(e,n,i){if(!this.options.currentToken)return await n.retain(e,i),e;let o=await V(this.options.currentToken,n,i);if(o)return o;throw d("not_authorized","Reconnect this application to continue.")}};function Hn(t,e,n){if(!t||t.authority||!t.fileCapability||!t.encryption||!t.grantId||!t.keyHandle||e.direction!==n||e.protection!=="grant_aead_v1")throw d("not_authorized","This connection cannot use encrypted local file delivery.");tn(e)}function Zt(t){if(t.authority||!t.fileCapability)throw d("not_authorized","This connection cannot use encrypted local file delivery.");We(t)}async function Qo(t,e,n,i,o){let r=Js(e,n,i,o.byteLength);return(await Zo(t,e,n)).encryptChunk("upload_chunk",r,o)}function Yo(t,e){return{method:"POST",headers:{"content-type":"application/mdbase-connect-file"},body:Uint8Array.from(t).buffer,signal:e}}async function $s(t,e){if(t.ok)return;let n=await E(t,"invalid_operation_response","The collection authority returned an invalid file transfer response.");throw z(n,"operation_failed",e,t.status)}async function Ws(t,e){return e.refreshToken?t.status===401?!0:t.status!==409?!1:(await E(t.clone(),"invalid_operation_response","The collection authority returned an invalid file response.").catch(()=>null))?.error?.code==="encryption_binding_stale":!1}function We(t){if(!t.encryption||!t.grantId||!t.keyHandle)throw d("missing_grant_key","Reconnect this application to restore encrypted file access.")}function $n(t){return We(t),{grantId:t.grantId,applicationId:t.clientId,encryption:t.encryption}}function Zo(t,e,n){return We(e),He.open(t,e.keyHandle,{...$n(e),authorityId:e.encryption.connector_id,transferId:n.transfer_id,direction:n.direction})}function Js(t,e,n,i){We(t);let o=tn(e),r=Wn(e,n);if(i!==r)throw d("invalid_request","The file chunk has the wrong byte length.");return{protocol_version:1,protection:"grant_aead_v1",grant_id:t.grantId,authority_id:t.encryption.connector_id,collection_id:t.collectionId,transfer_id:e.transfer_id,direction:e.direction,chunk_size:o,chunk_index:n,offset:n*o,plaintext_length:i,total_size:e.total_size,scope_epoch:t.encryption.scope_epoch,key_id:t.encryption.key_id}}function Qs(t,e,n){let i=wt(n),o=Wn(t,e),r=tn(t);if(i.kind!=="download_chunk"||i.header.chunk_index!==e||i.header.chunk_size!==r||i.header.offset!==e*r||i.header.plaintext_length!==o||i.header.total_size!==t.total_size)throw d("invalid_operation_response","The connector returned a file frame for a different chunk.")}function Ys(t){return U(t.code==="unknown"?t.server_code:t.code,t.message,{details:t.details,operationOutcome:t.operation_outcome??"rejected",traceId:t.trace_id})}function Xs(t,e,n){if(t==="GET"&&(e===""||e.startsWith("?"))){let o=new URLSearchParams(e.startsWith("?")?e.slice(1):e),r=o.get("limit");return{protocol_version:1,type:"list_files",...o.get("folder")?{folder:o.get("folder")}:{},...o.get("after")?{after:o.get("after")}:{},...r?{limit:Number(r)}:{}}}let i=e.split("/");if(t==="GET"&&i.length===2&&i[0]==="transfers")return Xo("get_file_transfer_status",i[1]);if(t==="DELETE"&&i.length===2&&i[0]==="transfers")return Xo("abort_file_transfer",i[1]);if(t==="POST"&&Zs(n)){let o=e==="uploads"?"open_file_upload":e==="downloads"?"open_file_download":i.length===3&&i[0]==="uploads"&&i[2]==="commit"?"commit_file_upload":i.length===2&&i[1]==="move"&&n.file_id===decodeURIComponent(i[0])?"move_file":i.length===2&&i[1]==="delete"&&n.file_id===decodeURIComponent(i[0])?"delete_file":null;if(o&&n.type===o)return{...n}}throw d("invalid_request","The file control request path is invalid.")}function Xo(t,e){return{protocol_version:1,type:t,transfer_id:decodeURIComponent(e)}}function tn(t){if(t.strategy.kind!=="framed_chunks"||!Number.isSafeInteger(t.strategy.chunk_size)||t.strategy.chunk_size<=0)throw d("invalid_operation_response","The connector returned an invalid framed transfer strategy.");return t.strategy.chunk_size}function Wn(t,e){let n=tn(t);if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t.total_size)||t.total_size<0)throw d("invalid_request","The file chunk index is invalid.");let i=e*n;if(!Number.isSafeInteger(i)||i>=t.total_size)throw d("invalid_request","The file chunk index is outside the transfer.");return Math.min(n,t.total_size-i)}function Zs(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var nn=class{constructor(e){this.options=e;this.local=new en(e)}options;local;async control(e,n="",i,o){let r=await this.requireFileToken(o),a=r.token;try{return a.authority?await jo(a,e,n,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders,r.retain):await this.local.control(a,e,n,i,o)}finally{r.release()}}async uploadChunk(e,n,i,o){let r=await this.requireFileToken(o);try{return await this.local.uploadChunk(e,n,i,o,r.token)}finally{r.release()}}async downloadChunk(e,n,i){let o=await this.requireFileToken(i);try{return await this.local.downloadChunk(e,n,i,o.token)}finally{o.release()}}async downloadHostedPart(e,n,i,o){let r=await this.requireFileToken(o),a=r.token;try{if(!a.authority)throw d("not_remote_authority","Hosted file delivery requires a remote authority endpoint.");return await Ko(a,`downloads/${encodeURIComponent(e.transfer_id)}/parts/${n}`,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders,r.retain)}finally{r.release()}}async requireFileToken(e){let n=new ge(this.options.collectionId,this.options.acquireGrantKeyLease);try{await V(this.options.currentToken,n,e),await this.options.authorizedToken(e);let i=await V(this.options.currentToken,n,e);if(!i?.fileCapability)throw d("not_authorized","This connection has no file capability.");return{token:i,retain:async o=>{let r=await V(this.options.currentToken,n,e);if(r)return r;throw d("not_authorized","Reconnect this application to continue.")},release:()=>n.release()}}catch(i){throw n.release(),i}}};async function Pe(t,e,n,i,o,r){if(!e.authority?.proofPublicKey)return{};if(!e.keyHandle)throw d("missing_grant_key","Reconnect this application to restore remote authority request signing.");try{let a=new URL(i);return await Et(t,e.keyHandle,e.authority.proofPublicKey,{method:n,target:`${a.pathname}${a.search}`,body:o,credential:r})}catch(a){throw a instanceof x?U(a.code,a.message):a}}async function er(t){let e=t.current;if(!e?.refreshToken)throw d("not_authorized","Reconnect this application to continue.");if((e.refreshExpiresAt??0)<=Date.now())throw d("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");let n=e.refreshToken,i=`${t.serverUrl}/oauth/token`,o=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId}).toString(),r=e.authority?await Pe(t.keyStore,e,"POST",i,o,e.refreshToken):{},a=await fetch(i,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...r},body:o,signal:t.signal}),s=await E(a,"invalid_token_response","The authorization service returned an invalid token response.");if(!a.ok){let c=t.currentToken();if(c?.refreshToken&&c.refreshToken!==n)return c;throw t.directCapable(e)||t.removeToken(e.keyHandle),(ut(s)??s?.error?.code)==="invalid_grant"?d("authorization_expired",s?.error_description??s?.error?.message??"Reconnect this application to continue.",{status:a.status}):z(s,"authorization_expired","Reconnect this application to continue.",a.status)}return t.storeTokenResponse(s,e.clientId,e.keyHandle)}var on=class{constructor(e,n){this.storage=e;this.baseKey=n}storage;baseKey;list(e){if(!e)return[];let n=M(this.storage.getItem(this.baseKey));if(tr(n)&&n.collectionId===e){let o=this.key(n.requestId);this.storage.getItem(o)||this.storage.setItem(o,JSON.stringify(n)),this.storage.removeItem(this.baseKey)}let i=[];for(let o=0;o<this.storage.length;o+=1){let r=this.storage.key(o);r?.startsWith(`${this.baseKey}:`)&&i.push(r)}return i.map(o=>M(this.storage.getItem(o))).filter(o=>tr(o)&&o.collectionId===e).sort((o,r)=>o.createdAt-r.createdAt||o.requestId.localeCompare(r.requestId))}find(e,n){return this.list(e).find(i=>i.requestId===n)??null}identifier(e){return e.mutation??de(e.operation,e.request?.input??(e.operation==="sync"?{action:"mutate"}:{}))??(e.operation==="sync"?"sync:mutate":e.operation)}store(e){this.storage.setItem(this.key(e.requestId),JSON.stringify(e))}take(e){let n=this.key(e),i=M(this.storage.getItem(n));return this.storage.removeItem(n),i}key(e){return`${this.baseKey}:${encodeURIComponent(e)}`}};function tr(t){return!!(t&&typeof t.collectionId=="string"&&typeof t.requestId=="string"&&t.requestId.length>0&&mi(t.operation)&&typeof t.inputFingerprint=="string"&&Number.isFinite(t.createdAt)&&t.createdAt>0&&(t.envelope||t.request)&&(t.operation==="sync"||de(t.operation,t.request?.input??{})!==null))}function nr({stored:t,collectionId:e,relayEncryption:n,invalidate:i,directCapable:o}){let r=M(t),a=(c,l="invalid_stored_grant")=>(i(typeof c=="string"?c:void 0,l),null);if(!r)return t&&a(),null;if(r.version!==1||typeof r.accessToken!="string"||r.accessToken.length===0||typeof r.clientId!="string"||r.clientId.length===0||r.collectionId!==e||typeof r.collectionName!="string"||r.collectionName.length===0||!Array.isArray(r.operations)||r.operations.some(c=>typeof c!="string")||typeof r.expiresAt!="number"||!Number.isFinite(r.expiresAt)||r.refreshToken!==void 0&&(typeof r.refreshToken!="string"||r.refreshToken.length===0)||r.refreshExpiresAt!==void 0&&(typeof r.refreshExpiresAt!="number"||!Number.isFinite(r.refreshExpiresAt)))return a(r.keyHandle);let s=Ft(r.scope);if(!s)return a(r.keyHandle);if(!Dt(s))return a(r.keyHandle,"legacy_scope_reauthorization_required");if(r.fileCapability&&!zt(r.fileCapability)||r.authority&&!ho(r.authority,r.collectionId))return a(r.keyHandle);if(n==="required"){if(r.authority){if(!r.keyHandle||!r.authority.proofPublicKey)return a(r.keyHandle)}else if(!r.grantId||!r.keyHandle||!yo(r.encryption,r.collectionId))return a(r.keyHandle)}return r.expiresAt<=Date.now()&&(!r.refreshToken||(r.refreshExpiresAt??0)<=Date.now())?o(r)?r:(i(r.keyHandle),null):r}async function Jn(t,e,n,i,o,r){if(!e.authority)throw d("not_remote_authority","This authorization has no remote authority endpoint.");let a=`${e.authority.syncUrl}/${i}`,s=o===void 0?void 0:JSON.stringify(o),c=await Pe(t,e,n,a,s,e.authority.accessToken);return fetch(a,{method:n,headers:{authorization:`Bearer ${e.authority.accessToken}`,...o===void 0?{}:{"content-type":"application/json"},...c},...s===void 0?{}:{body:s},signal:r})}async function ir(t,e,n,i,o){if(!e.encryption||!e.grantId||!e.keyHandle)throw d("authorization_binding_incompatible","The refreshed authorization no longer supports encrypted connector operations.",{details:{contract:"grant_encryption",required:[1],supported:e.encryption?[e.encryption.protocol_version]:[],peer:"connector",operation:n}});try{return await oe(t,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,void 0,o)}catch(r){throw r instanceof x?U(r.code,r.message):r}}var Je=class{operations=new Map;run(e,n,i,o){if(n?.signal?.aborted)return Promise.reject(J(n.signal));let r=this.operations.get(e)??this.begin(e,o);return this.wait(e,r,n,i)}begin(e,n){let i=new AbortController,o={controller:i,waiters:0,settled:!1,promise:void 0};return o.promise=Promise.resolve().then(()=>n(i.signal)).finally(()=>{o.settled=!0,this.operations.get(e)===o&&this.operations.delete(e)}),this.operations.set(e,o),o}async wait(e,n,i,o){n.waiters+=1;try{return await F(i,o,()=>n.promise)}finally{n.waiters-=1,n.waiters===0&&!n.settled&&this.operations.get(e)===n&&(this.operations.delete(e),n.controller.abort())}}};function or(t,e){return!t||t.authority||!t.encryption||!t.grantId||!t.keyHandle||e==="disabled"?!1:typeof location>"u"||!t.applicationOrigin||t.applicationOrigin===location.origin}async function rr(t,e,n){try{let i=await fetch(`${t}/v1/ready`,me({method:"GET",cache:"no-store",signal:n})),o=await E(i,"invalid_operation_response","The connector returned an invalid readiness response.").catch(()=>null);return i.ok&&o?.service==="mdbase-connect"&&o?.loopback_protocol_version===1&&o?.operation_transport_protocol_version===e}catch{return!1}}async function ar(t,e){try{return{body:await E(t,"invalid_operation_response","The collection authority returned a response that is not valid JSON.")}}catch(n){if(!t.ok&&e&&ec(t.status))return{body:void 0,httpError:U("operation_failed","Collection operation failed.",{status:t.status,operationOutcome:"rejected"})};throw d("invalid_operation_response","The collection authority returned a response that is not valid JSON.",{cause:n})}}function ec(t){return t>=400&&t<500&&![408,425,429].includes(t)}var rn=class{serverUrl;storage;keyStore;directAccessMode;loopbackUrl;collectionId;internals;onChange;timeouts;pendingMutationStore;files;refreshOperations=new Je;directStatus;currentRoute="relay";directFailures=0;directRetryAt=0;constructor(e){this.serverUrl=e.serverUrl,this.storage=e.storage,this.keyStore=e.keyStore,this.directAccessMode=e.directAccessMode,this.loopbackUrl=e.loopbackUrl,this.collectionId=e.collectionId,this.internals=e.internals,this.onChange=e.onChange,this.timeouts=e.timeouts,this.pendingMutationStore=new on(this.storage,this.internals.pendingMutationKey(this.collectionId)),this.files=new nn({keyStore:this.keyStore,serverUrl:this.serverUrl,loopbackUrl:this.loopbackUrl,collectionId:this.collectionId,currentToken:()=>this.currentToken(),authorizedToken:n=>this.authorizedToken({signal:n,timeoutMs:null}),refreshAuthorization:n=>this.refreshAuthorization({signal:n,timeoutMs:null}),shouldAttemptDirect:n=>this.shouldAttemptDirect(n),onDirectAvailable:()=>{this.markDirectAvailable(),this.setRoute("direct")},onDirectUnavailable:()=>this.markDirectUnavailable(),onRelayAvailable:()=>this.setRoute("relay"),acquireGrantKeyLease:(n,i,o)=>this.internals.acquireGrantKeyLease(n,i,o),authorityProofHeaders:(n,i,o,r,a)=>Pe(this.keyStore,n,i,o,r,a)}),this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable"}get directAccess(){return this.currentToken()?.authority?"disabled":this.directStatus}get route(){return this.currentToken()?.authority?"remote":this.currentRoute}notifyStorageChanged(){this.emitConnection()}async checkDirectAccess(e={}){return F(e,this.timeouts.watchStartMs,n=>this.checkDirectAccessWithinBudget(n.signal))}async checkDirectAccessWithinBudget(e){let n=this.currentToken();if(!this.directEligible(n))return this.setDirectStatus("disabled");let i=await ct();return i==="denied"?this.setDirectStatus("denied"):(i==="prompt"||i===null)&&this.storage.getItem(this.internals.directPreferenceKey())!=="enabled"?this.setDirectStatus("permission_required"):this.probeDirectAccess(e)}async requestDirectAccess(e={}){return F(e,this.timeouts.watchStartMs,n=>this.requestDirectAccessWithinBudget(n.signal))}async requestDirectAccessWithinBudget(e){let n=this.currentToken();return this.directCapable(n)?(this.storage.setItem(this.internals.directPreferenceKey(),"enabled"),this.directRetryAt=0,this.probeDirectAccess(e)):this.setDirectStatus("disabled")}disableDirectAccess(){this.storage.setItem(this.internals.directPreferenceKey(),"disabled"),this.setDirectStatus("disabled"),this.setRoute("relay")}pendingMutations(){return this.storedPendingMutations().map(e=>({requestId:e.requestId,operation:this.pendingMutationStore.identifier(e),fingerprint:e.inputFingerprint,status:"outcome_unknown",createdAt:new Date(e.createdAt).toISOString()}))}pendingMutation(e){let n=this.storedPendingMutation(e);return n?{requestId:n.requestId,operation:this.pendingMutationStore.identifier(n),fingerprint:n.inputFingerprint,status:"outcome_unknown",createdAt:new Date(n.createdAt).toISOString()}:null}async recoverPendingMutation(e,n){let i=this.storedPendingMutation(e);if(!i)throw d("no_pending_mutation","There is no interrupted mutation to resume.");return K(n,this.timeouts.requestMs,o=>this.performOperationWithinBudget(i.operation,i.request?.input??{},ot(n??{},o),i))}async performOperation(e,n,i={}){return K(i,this.timeouts.requestMs,o=>this.performOperationWithinBudget(e,n,ot(i,o)))}async performOperationWithinBudget(e,n,i,o,r=!1,a=0,s=!1){Re(i.signal);let c=this.grantKeyLeases();try{let l=await V(()=>this.currentToken(),c,i.signal);if(!l)throw d("not_authorized","Connect this application before accessing a collection.");return await c.retain(o?.keyHandle,i.signal),await this.performLeasedOperation(l,e,n,i,c,o,r,a,s)}finally{c.release()}}async performLeasedOperation(e,n,i,o,r,a,s=!1,c=0,l=!1){if(!e.operations.includes(n))throw d("insufficient_access",`This connection does not allow ${n}.`,{details:{required_operations:[n],granted_operations:[...e.operations],missing_operations:[n]}});let u=await this.shouldAttemptDirect(e);if(!u){if(!await this.authorizedToken({signal:o.signal,timeoutMs:null}))throw d("not_authorized","Reconnect this application to continue.");let A=await V(()=>this.currentToken(),r,o.signal);if(!A)throw d("not_authorized","Reconnect this application to continue.");e=A}let p=a?.requestId??(Zi(n,i)?crypto.randomUUID():void 0),f;try{f=await this.sendOperation(e,n,i,u,r,o,p,l)}catch(_){throw qt(_,o.signal,p!==void 0&&this.storedPendingMutation(p)!==null?p:void 0,e.authority?"hosted_provider_unavailable":"relay_unavailable")}let h=f.response,y=h.status===409&&(await E(h.clone(),"invalid_operation_response","The collection authority returned an invalid operation response.").catch(()=>null))?.error?.code==="encryption_binding_stale";if((h.status===401||y)&&e.refreshToken){if(f.pendingMutation&&(f.directDeliveryUncertain||f.encryptedRequest&&f.resumingMutation))throw d("operation_outcome_unknown","The direct operation may have completed, but its encrypted grant changed before the response could be recovered. Refresh before making another change.",{operationOutcome:"unknown",details:{request_id:f.requestId}});f.pendingMutation&&this.clearPendingMutation(f.requestId),e=await this.refreshAuthorization({signal:o.signal,timeoutMs:null});let _=await V(()=>this.currentToken(),r,o.signal);if(!_)throw d("not_authorized","Reconnect this application to continue.");e=_,u=await this.shouldAttemptDirect(e);try{f=await this.sendOperation(e,n,i,u,r,o,p,l)}catch(A){throw qt(A,o.signal,p!==void 0&&this.storedPendingMutation(p)!==null?p:void 0,e.authority?"hosted_provider_unavailable":"relay_unavailable")}h=f.response}let R=_=>Ho({error:_,attempt:f,completedRetries:c,signal:o.signal,knownRejectedMutationRetry:l,clearPending:A=>this.clearPendingMutation(A),retry:(A,T)=>this.performOperationWithinBudget(n,i,o,A,s,c+1,T)}),C;try{C=await ar(h,e.authority!==void 0)}catch(_){throw f.pendingMutation?G(f.requestId,_):_}let m=C.body;if(!h.ok){let _=C.httpError??z(m,"operation_failed","Collection operation failed.",h.status),A=await R(_);if(A.retried)return A.result;if(_.code==="fresh_request_required"&&!f.pendingMutation&&!s)return this.performOperationWithinBudget(n,i,o,void 0,!0);throw f.pendingMutation&&_.outcomeUnknown?_:f.pendingMutation&&(f.directDeliveryUncertain||f.encryptedRequest&&f.resumingMutation)?G(f.requestId,_):(f.pendingMutation&&!f.directDeliveryUncertain&&this.clearPendingMutation(f.requestId),_.code==="direct_operation_rejected"&&_.status===403&&this.invalidateRejectedAuthorization(e),_)}if(f.encryptedRequest){let _=m?.envelope,A=f.pendingMutationRecord,T=A?.encryption??e.encryption,O=A?.grantId??e.grantId,S=A?.applicationId??e.clientId,P=A?.keyHandle??e.keyHandle;if(!_||!T||!O||!P)throw f.pendingMutation?G(f.requestId,new Error("Encrypted operation response was missing its envelope.")):d("invalid_encrypted_response","The relay did not return an encrypted connector response.");try{let q=await ze(this.keyStore,P,{grantId:O,applicationId:S,encryption:T},f.encryptedRequest,_);if(!q.ok&&q.problem.code==="fresh_request_required"&&!f.pendingMutation&&!s)return this.performOperationWithinBudget(n,i,o,void 0,!0);if(!q.ok){let H=no(q.problem);throw f.pendingMutation&&!H.outcomeUnknown&&this.clearPendingMutation(f.requestId),H}return f.pendingMutation&&this.clearPendingMutation(f.requestId),q.result}catch(q){throw q instanceof b?q:q instanceof x?f.pendingMutation?G(f.requestId,q):U(q.code,q.message):q}}let v=f.pendingMutationRecord?.request?.protocol_version??$;if(m?.protocol_version!==v||m?.request_id!==f.requestId)throw f.pendingMutation?G(f.requestId,new Error("Operation response protocol or request ID did not match.")):d("invalid_operation_response","The collection authority returned a response for a different protocol request.");if(m.ok===!1){if(!Xe(m.problem))throw f.pendingMutation?G(f.requestId,new Error("Operation rejection did not contain a canonical problem.")):d("invalid_operation_response","The collection authority returned an invalid operation problem.");let _=new b(m.problem),A=await R(_);if(A.retried)return A.result;throw f.pendingMutation&&!_.outcomeUnknown&&this.clearPendingMutation(f.requestId),_}if(m.ok!==!0||!("result"in m))throw f.pendingMutation?G(f.requestId,new Error("Successful operation response did not contain a result.")):d("invalid_operation_response","The collection authority returned an incomplete operation response.");return f.pendingMutation&&this.clearPendingMutation(f.requestId),m.result}async performAuthoritySyncRequest(e,n,i,o,r,a={}){return K(a,this.timeouts.syncMs,async s=>{let c=this.grantKeyLeases();try{let l=await V(()=>this.currentToken(),c,s.signal);l&&await this.authorizedToken({signal:s.signal,timeoutMs:null}),l=await V(()=>this.currentToken(),c,s.signal),sr(l,e,n);let u=await Jn(this.keyStore,l,i,o,r,s.signal);u.status===401&&l.refreshToken&&(l=await this.refreshAuthorization({signal:s.signal,timeoutMs:null}),l=await V(()=>this.currentToken(),c,s.signal),sr(l,e,n),u=await Jn(this.keyStore,l,i,o,r,s.signal));let p=await E(u,"invalid_operation_response","The collection authority returned an invalid synchronization response.");if(!u.ok)throw z(p,"sync_failed","Collection synchronization failed.",u.status);return p}catch(l){let u=i==="POST"&&o==="mutations"&&r&&typeof r=="object"&&typeof r.mutation_id=="string"?r.mutation_id:void 0;throw qt(l,s.signal,u,"hosted_provider_unavailable")}finally{c.release()}})}async sendOperation(e,n,i,o,r,a={},s,c=!1){let l=i??{},u,p=!1,f=!1,h=s??crypto.randomUUID(),y=null,R;if(s!==void 0){if(y=this.storedPendingMutation(s),R=y?.inputFingerprint??await co(n,i),y){if(y.collectionId!==e.collectionId||y.operation!==n||y.inputFingerprint!==R)throw d("pending_mutation_unresolved","A previous write still has an unknown outcome. Retry that exact write before making another change.");h=y.requestId,f=!c}p=!0}let C=y?.mutation??de(n,i);if(y?.envelope&&(e.authority||!e.encryption))throw d("pending_mutation_unresolved","The pending write requires its encrypted relay authority. Reconnect that authority before recovery.");if(y?.request&&e.encryption&&!e.authority)throw d("pending_mutation_unresolved","The pending write belongs to a different authority transport. Reconnect that authority before recovery.");if(e.encryption&&!e.authority){if(!e.grantId||!e.keyHandle)throw d("missing_grant_key","Reconnect this application to restore encrypted access.");try{if(p)if(y){if(!y.envelope)throw d("pending_mutation_unresolved","The pending write belongs to a different transport. Reconnect before retrying it.");u=eo(y.envelope,a.deadlineUnixMs)}else u=await oe(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,h,a.deadlineUnixMs),this.pendingMutationStore.store({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},keyId:e.encryption.key_id,keyHandle:e.keyHandle,applicationId:e.clientId,encryption:e.encryption,operation:n,mutation:C,inputFingerprint:R,requestId:h,envelope:u,createdAt:Date.now()});else u=await oe(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,void 0,a.deadlineUnixMs)}catch(T){throw T instanceof x?U(T.code,T.message):T}h=u.request_id,l=u}else{let T=y?.request??{protocol_version:$,request_id:h,input:l};l=T,p&&!y&&this.pendingMutationStore.store({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},operation:n,mutation:C,inputFingerprint:R,requestId:h,request:T,createdAt:Date.now()})}if(o&&u&&!e.authority){let T=!1;try{let P=await fetch(`${this.loopbackUrl}/v1/operations`,me({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(u),signal:a.signal}));if(!Fe(P.status)||await $e(P))return P.ok&&(this.markDirectAvailable(),this.setRoute("direct")),{response:P,requestId:h,encryptedRequest:u,pendingMutation:p,...p?{pendingMutationRecord:y??this.storedPendingMutation(h)??void 0}:{},resumingMutation:f};T=P.status>=500,this.markDirectUnavailable()}catch(P){if(a.signal?.aborted)throw p?G(h,P):P;T=!0,await ct()==="denied"?this.setDirectStatus("denied"):this.markDirectUnavailable()}let O;try{e.expiresAt<=Date.now()+3e4&&await this.refreshAuthorization({signal:a.signal,timeoutMs:null});let P=await V(()=>this.currentToken(),r,a.signal);if(!P)throw d("not_authorized","Reconnect this application to continue.");O=P}catch(P){throw p&&(T||f)?G(h,P):P}let S;p||(u=await ir(this.keyStore,O,n,i,a.deadlineUnixMs),h=u.request_id);try{S=await fetch(`${this.serverUrl}/v1/authorities/${encodeURIComponent(O.collectionId)}/operations/${n}`,{method:"POST",headers:{authorization:`Bearer ${O.accessToken}`,"content-type":"application/json"},body:JSON.stringify(u),signal:a.signal})}catch(P){throw p?G(h,P):P}return S.ok&&this.setRoute("relay"),{response:S,requestId:h,encryptedRequest:u,directDeliveryUncertain:T,pendingMutation:p,...p?{pendingMutationRecord:y??this.storedPendingMutation(h)??void 0}:{},resumingMutation:f}}let m=e.authority?`${e.authority.operationsUrl}/${n}`:`${this.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/operations/${n}`,v=JSON.stringify(l),_=e.authority?await Pe(this.keyStore,e,"POST",m,v,e.authority.accessToken):{},A;try{A=await io(m,e.authority?.accessToken??e.accessToken,_,v,a.signal)}catch(T){throw p?G(h,T):T}return A.ok&&this.setRoute(e.authority?"remote":"relay"),{response:A,requestId:h,encryptedRequest:u,pendingMutation:p,...p?{pendingMutationRecord:y??this.storedPendingMutation(h)??void 0}:{},resumingMutation:f}}directCapable(e){return or(e,this.directAccessMode)}hasResumableMutationTransport(){return this.currentToken()!==null}directEligible(e){return e!==null&&this.directCapable(e)&&this.storage.getItem(this.internals.directPreferenceKey())!=="disabled"}async shouldAttemptDirect(e){if(!this.directEligible(e))return!1;if(this.directStatus==="available")return!0;if(this.directStatus==="unavailable"&&Date.now()<this.directRetryAt)return!1;let n=await ct();return n==="denied"?(this.setDirectStatus("denied"),!1):(n==="prompt"||n===null)&&this.storage.getItem(this.internals.directPreferenceKey())!=="enabled"?(this.setDirectStatus("permission_required"),!1):(this.setDirectStatus("checking"),!0)}async probeDirectAccess(e){return this.setDirectStatus("checking"),await rr(this.loopbackUrl,$,e)?(this.markDirectAvailable(),"available"):await ct()==="denied"?this.setDirectStatus("denied"):(this.markDirectUnavailable(),"unavailable")}markDirectAvailable(){this.directFailures=0,this.directRetryAt=0,this.setDirectStatus("available")}markDirectUnavailable(){this.directFailures+=1,this.directRetryAt=Date.now()+Math.min(6e4,1e3*2**(this.directFailures-1)),this.setDirectStatus("unavailable")}setDirectStatus(e){return this.directStatus!==e&&(this.directStatus=e,this.emitConnection()),e}setRoute(e){this.currentRoute!==e&&(this.currentRoute=e,this.emitConnection())}emitConnection(){this.onChange()}invalidateRejectedAuthorization(e){let n=M(this.storage.getItem(this.internals.tokenKey(this.collectionId)));!n||!to(n,e)||(this.internals.removeToken(this.collectionId,n.keyHandle),this.currentRoute="relay",this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection())}currentToken(){return nr({stored:this.storage.getItem(this.internals.tokenKey(this.collectionId)),collectionId:this.collectionId,relayEncryption:this.internals.relayEncryption,invalidate:(e,n="invalid_stored_grant")=>this.internals.removeToken(this.collectionId,e,n),directCapable:e=>this.directCapable(e)})}async authorizedToken(e={}){let n=this.currentToken();if(!n)return null;if(n.expiresAt>Date.now()+3e4)return n;if(!n.refreshToken||(n.refreshExpiresAt??0)<=Date.now()){if(this.directCapable(n))throw d("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");return this.internals.removeToken(this.collectionId,n.keyHandle),null}return this.refreshAuthorization(e)}refreshAuthorization(e={}){return this.refreshOperations.run("refresh",e,this.timeouts.requestMs,n=>this.performRefresh(n))}async performRefresh(e){let n=this.grantKeyLeases();try{let i=await V(()=>this.currentToken(),n,e);return await er({current:i,serverUrl:this.serverUrl,keyStore:this.keyStore,signal:e,currentToken:()=>this.currentToken(),directCapable:o=>this.directCapable(o),removeToken:o=>this.internals.removeToken(this.collectionId,o),storeTokenResponse:(o,r,a)=>this.storeTokenResponse(o,r,a)})}finally{n.release()}}storeTokenResponse(e,n,i){if(e.collection_id!==this.collectionId)throw d("collection_mismatch","The refreshed authorization belongs to a different collection.");let o=this.internals.storeTokenResponse(e,n,i);return this.currentRoute=o.authority?"remote":"relay",this.directStatus=o.authority||this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection(),o}storedPendingMutations(){return this.pendingMutationStore.list(this.currentToken()?.collectionId??null)}storedPendingMutation(e){return this.pendingMutationStore.find(this.currentToken()?.collectionId??null,e)}clearPendingMutation(e){let n=this.pendingMutationStore.take(e);n?.keyHandle&&this.internals.deleteGrantKeyWhenUnused(this.collectionId,n.keyHandle)}grantKeyLeases(){return new ge(this.collectionId,(e,n,i)=>this.internals.acquireGrantKeyLease(e,n,i))}};function sr(t,e,n){if(!(t?.authority&&t.collectionId===e&&t.authority.replicaId===n))throw d("authority_authorization_changed","Reconnect this collection authority before synchronizing.")}var tc=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),nc=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Oe=class{state=nc.slice();block=new Uint8Array(64);words=new Uint32Array(64);blockLength=0;byteLength=0;finished=!1;update(e){if(this.finished)throw new Error("SHA-256 digest is already finalized.");if(this.byteLength+=e.byteLength,!Number.isSafeInteger(this.byteLength))throw new Error("SHA-256 input exceeds the safe browser byte range.");let n=0;if(this.blockLength>0){let i=Math.min(64-this.blockLength,e.byteLength);this.block.set(e.subarray(0,i),this.blockLength),this.blockLength+=i,n+=i,this.blockLength===64&&(this.compress(this.block),this.blockLength=0)}for(;n+64<=e.byteLength;)this.compress(e.subarray(n,n+64)),n+=64;return n<e.byteLength&&(this.block.set(e.subarray(n),0),this.blockLength=e.byteLength-n),this}digestHex(){if(this.finished)throw new Error("SHA-256 digest is already finalized.");this.finished=!0,this.block[this.blockLength]=128,this.block.fill(0,this.blockLength+1),this.blockLength>=56&&(this.compress(this.block),this.block.fill(0));let e=this.byteLength*8,n=Math.floor(e/4294967296),i=e>>>0;return cr(this.block,56,n),cr(this.block,60,i),this.compress(this.block),[...this.state].map(o=>o.toString(16).padStart(8,"0")).join("")}compress(e){let n=this.words;for(let p=0;p<16;p+=1){let f=p*4;n[p]=(e[f]<<24|e[f+1]<<16|e[f+2]<<8|e[f+3])>>>0}for(let p=16;p<64;p+=1){let f=n[p-15],h=n[p-2],y=te(f,7)^te(f,18)^f>>>3,R=te(h,17)^te(h,19)^h>>>10;n[p]=n[p-16]+y+n[p-7]+R>>>0}let i=this.state[0],o=this.state[1],r=this.state[2],a=this.state[3],s=this.state[4],c=this.state[5],l=this.state[6],u=this.state[7];for(let p=0;p<64;p+=1){let f=te(s,6)^te(s,11)^te(s,25),h=s&c^~s&l,y=u+f+h+tc[p]+n[p]>>>0,R=te(i,2)^te(i,13)^te(i,22),C=i&o^i&r^o&r,m=R+C>>>0;u=l,l=c,c=s,s=a+y>>>0,a=r,r=o,o=i,i=y+m>>>0}this.state[0]=this.state[0]+i>>>0,this.state[1]=this.state[1]+o>>>0,this.state[2]=this.state[2]+r>>>0,this.state[3]=this.state[3]+a>>>0,this.state[4]=this.state[4]+s>>>0,this.state[5]=this.state[5]+c>>>0,this.state[6]=this.state[6]+l>>>0,this.state[7]=this.state[7]+u>>>0}};function te(t,e){return t>>>e|t<<32-e}function cr(t,e,n){t[e]=n>>>24,t[e+1]=n>>>16,t[e+2]=n>>>8,t[e+3]=n}var an=class{constructor(e,n){this.signal=n;this.iterator=ic(e)}signal;iterator;remainder=new Uint8Array;remainderOffset=0;maxSourceChunkBytes=null;iteratorClosing=!1;ended=!1;setMaxSourceChunkBytes(e){this.maxSourceChunkBytes=e}async read(e){let n=new Uint8Array(e),i=0;for(;i<e;){if(this.remainderOffset===this.remainder.byteLength){let r=await this.nextSourceChunk();if(r.done)throw this.ended=!0,d("invalid_request","Streamed file bytes ended before the declared size.");if(!(r.value instanceof Uint8Array))throw d("invalid_request","A streamed file chunk was not a Uint8Array.");if(this.maxSourceChunkBytes===null)throw new Error("Stream source was read before upload negotiation completed.");if(r.value.byteLength>this.maxSourceChunkBytes)throw d("invalid_request",`A streamed file chunk exceeded the negotiated ${this.maxSourceChunkBytes}-byte upload part size.`);if(this.remainder=r.value,this.remainderOffset=0,this.remainder.byteLength===0)continue}let o=Math.min(e-i,this.remainder.byteLength-this.remainderOffset);n.set(this.remainder.subarray(this.remainderOffset,this.remainderOffset+o),i),i+=o,this.remainderOffset+=o}return n}async expectEnd(){if(this.remainderOffset<this.remainder.byteLength)throw d("invalid_request","Streamed file bytes exceed the declared size.");for(;!this.ended;){let e=await this.nextSourceChunk();if(e.done){this.ended=!0;return}if(!(e.value instanceof Uint8Array))throw d("invalid_request","A streamed file chunk was not a Uint8Array.");if(e.value.byteLength>0)throw d("invalid_request","Streamed file bytes exceed the declared size.")}}async close(){this.ended=!0,this.closeIterator()}async nextSourceChunk(){lr(this.signal);let e=this.iterator.next(),n=this.signal;if(!n)return e;let i=()=>{},o=new Promise((r,a)=>{let s=()=>{this.closeIterator(),a(dr(n))};n.addEventListener("abort",s,{once:!0}),i=()=>n.removeEventListener("abort",s),n.aborted&&s()});try{let r=await Promise.race([e,o]);return lr(n),r}finally{i()}}closeIterator(){if(!this.iteratorClosing){this.iteratorClosing=!0;try{this.iterator.return?.()?.catch(()=>{})}catch{}}}};function ic(t){if(typeof t.getReader=="function"){let n=t.getReader(),i=!1,o=()=>{i||(i=!0,n.releaseLock())};return{async next(){if(i)return{done:!0,value:void 0};let r=await n.read();return r.done&&o(),r},async return(){if(!i)try{await n.cancel()}finally{o()}return{done:!0,value:void 0}}}}let e=t;if(typeof e[Symbol.asyncIterator]!="function")throw d("invalid_request","Streamed files require a readable byte stream.");return e[Symbol.asyncIterator]()}function lr(t){if(t?.aborted)throw dr(t)}function dr(t){return d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t?.reason})}var ur=1024*1024,oc=4,pr=8,_t=3,Qn=64*1024*1024,fr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,hr=/^sha256:[0-9a-f]{64}$/u;async function yr(t,e,n){let i=new Oe;for(let o=0;o<t.size;o+=ur){_e(e);let r=new Uint8Array(await t.slice(o,o+ur).arrayBuffer());i.update(r),n(Math.min(t.size,o+r.byteLength))}return t.size===0&&n(0),i.digestHex()}function mr(t,e){if(t instanceof Blob)return e&&e!==t.type?t.slice(0,t.size,e):t;if(t instanceof ArrayBuffer)return new Blob([t],{type:e});let n=new Uint8Array(t.byteLength);return n.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),new Blob([n.buffer],{type:e})}function gr(t){return t instanceof Blob?t.size:t.byteLength}async function _r(t){return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t}function Yn(t=oc){if(!Number.isInteger(t)||t<1||t>pr)throw d("invalid_request",`File concurrency must be between 1 and ${pr}.`);return t}function br(t){if(!Number.isInteger(t)||t<1||t>1e3)throw d("invalid_request","File page size must be between 1 and 1000.");return t}function Xn(t,e,n){if(t.protocol_version!==1||t.type!=="file_transfer"||t.transfer_id!==e||t.direction!==n||!Number.isSafeInteger(t.total_size)||t.total_size<0||!Array.isArray(t.received)||!rc(t))throw d("invalid_operation_response","The authority returned an invalid file transfer session.");let i=t.strategy.kind==="framed_chunks"?t.strategy.chunk_size:t.strategy.kind==="object_put"?Math.max(1,t.total_size):t.strategy.part_size,o=t.strategy.kind==="object_put"?1:Math.ceil(t.total_size/i);if(new Set(t.received).size!==t.received.length||t.received.some(a=>!Number.isSafeInteger(a)||a<0||a>=o))throw d("invalid_operation_response","The authority returned invalid transfer progress.");let r=t.uploaded_parts??[];if(!Array.isArray(r)||r.some((a,s)=>!Number.isSafeInteger(a?.part_number)||a.part_number<1||a.part_number>o||typeof a.etag!="string"||a.etag.length===0||a.etag.length>255||s>0&&r[s-1].part_number>=a.part_number)||(t.strategy.kind==="object_multipart"?r.length!==t.received.length||r.some((a,s)=>a.part_number-1!==t.received[s]):r.length!==0))throw d("invalid_operation_response","The authority returned invalid uploaded part receipts.")}function Cr(t,e){let n=e.strategy.kind==="framed_chunks"?e.strategy.chunk_size:e.strategy.kind==="object_put"?Math.max(1,e.total_size):e.strategy.part_size,i=e.strategy.kind==="object_put"?1:Math.ceil(e.total_size/n);if(t?.protocol_version!==1||t.type!=="file_transfer_status"||t.transfer_id!==e.transfer_id||!["open","committed","aborted","expired"].includes(t.state)||!Array.isArray(t.received)||new Set(t.received).size!==t.received.length||t.received.some(r=>!Number.isSafeInteger(r)||r<0||r>=i)||!Number.isSafeInteger(t.received_bytes)||t.received_bytes<0||t.received_bytes>e.total_size||t.received.reduce((r,a)=>r+Zn(e.total_size,n,a),0)!==t.received_bytes)throw d("invalid_operation_response","The authority returned invalid transfer status.");let o=t.uploaded_parts;if(!Array.isArray(o)||o.some((r,a)=>!Number.isSafeInteger(r?.part_number)||r.part_number<1||r.part_number>i||typeof r.etag!="string"||r.etag.length===0||r.etag.length>255||a>0&&o[a-1].part_number>=r.part_number)||(e.strategy.kind==="object_multipart"?o.length!==t.received.length||o.some((r,a)=>r.part_number-1!==t.received[a]):o.length!==0))throw d("invalid_operation_response","The authority returned invalid uploaded part status.")}function rc(t){return t.strategy.kind==="framed_chunks"?t.protection==="grant_aead_v1"&&Number.isSafeInteger(t.strategy.chunk_size)&&t.strategy.chunk_size>0:t.protection!=="transport_tls"?!1:t.strategy.kind==="object_put"?!0:Number.isSafeInteger(t.strategy.part_size)&&t.strategy.part_size>0}function Zn(t,e,n){return Math.min(e,Math.max(0,t-n*e))}async function sn(t,e){for(let n=1;n<=Gn;n+=1){_e(e);try{return await t()}catch(i){if(e?.aborted||n===Gn||i instanceof b&&!i.retryable)throw i;await $o(n,e)}}throw new Error("Unreachable file chunk retry state.")}function vr(t,e,n,i,o,r){let a;try{a=new URL(t.url)}catch{throw d("invalid_operation_response","The authority returned an invalid object URL.")}if(t.protocol_version!==1||t.type!=="file_part"||t.transfer_id!==e||t.part_index!==n||t.offset!==i||t.content_length!==o||t.method.toUpperCase()!==r||a.protocol!=="https:"&&!(a.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname))||a.username||a.password)throw d("invalid_operation_response","The authority returned an invalid prepared file part.")}function wr(t){let e=new Headers;for(let[n,i]of Object.entries(t))["host","content-length"].includes(n.toLowerCase())||e.set(n,i);return e}async function Sr(t,e,n){let i=new Array(t),o=0;return await Promise.all(Array.from({length:Math.min(t,e)},async()=>{for(;o<t;){let r=o;o+=1,i[r]=await n(r)}})),i}function _e(t){if(t?.aborted)throw d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t.reason})}function Te(t){return t instanceof b?t:typeof DOMException<"u"&&t instanceof DOMException&&t.name==="AbortError"?d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t}):d("temporarily_unavailable","The file transfer could not be completed.",{cause:t})}var Qe=class{constructor(e,n,i,o,r=xe()){this.capability=e;this.request=n;this.framed=i;this.hosted=o;this.timeouts=r}capability;request;framed;hosted;timeouts;async*list(e={}){let n=pe(e,this.timeouts.fileIndexMs),i=n.signal;try{this.requireAction("list");let o;do{_e(i);let r=new URLSearchParams({protocol_version:String(1),...e.folder?{folder:e.folder}:{},...o?{after:o}:{},...e.pageSize?{limit:String(br(e.pageSize))}:{}}),a;for(;;)try{a=await this.request("GET",`?${r.toString()}`,void 0,i);break}catch(s){let c=Te(s);if(c.code!=="file_index_warming")throw c;e.onIndexing?.(),await Z(500,i)}if(a.protocol_version!==1||a.type!=="files_page"||!Array.isArray(a.files))throw d("invalid_operation_response","The authority returned an invalid file page.");for(let s of a.files)_e(i),yield cn(s);o=a.next}while(o)}finally{n.dispose()}}async upload(e,n,i={}){return K(i,this.timeouts.uploadMs,o=>this.uploadWithinBudget(e,n,{...i,signal:o.signal,timeoutMs:null}))}async uploadWithinBudget(e,n,i){this.requireAction(i.ifRevision?"replace":"add");let o=mr(n,i.mediaType),r=Yn(i.concurrency),a=await yr(o,i.signal,s=>{i.onProgress?.({phase:"hashing",transferredBytes:s,totalBytes:o.size})});return this.uploadKnownSource(e,o.size,`sha256:${a}`,(i.mediaType??o.type)||void 0,i,r,async(s,c,l)=>o.slice(c,c+l))}async uploadStream(e,n,i={}){return K(i,this.timeouts.uploadMs,o=>this.uploadStreamWithinBudget(e,n,{...i,signal:o.signal,timeoutMs:null}))}async uploadStreamWithinBudget(e,n,i){if(this.requireAction(i.ifRevision?"replace":"add"),!Number.isSafeInteger(n.size)||n.size<0)throw d("invalid_request","Streamed file size must be a non-negative safe integer.");if(!hr.test(n.contentDigest))throw d("invalid_request","Streamed files require a lowercase SHA-256 content digest.");let o=new an(n.stream,i.signal),r=new Oe;return this.uploadKnownSource(e,n.size,n.contentDigest,i.mediaType??n.mediaType,i,1,async(a,s,c)=>{let l=await o.read(c);return r.update(l),l},async()=>{if(await o.expectEnd(),`sha256:${r.digestHex()}`!==n.contentDigest)throw d("invalid_request","Streamed file bytes do not match the declared SHA-256 digest.")},()=>o.close(),a=>o.setMaxSourceChunkBytes(a))}async uploadKnownSource(e,n,i,o,r,a,s,c,l,u){let p=r.transferId??crypto.randomUUID();if(!fr.test(p))throw d("invalid_request","File transfer ID must be a UUID.");let f=!1;try{let h=await this.request("POST","uploads",{protocol_version:1,type:"open_file_upload",transfer_id:p,path:e,size:n,content_digest:i,...o?{media_type:o}:{},...r.ifRevision?{if_revision:r.ifRevision}:{}},r.signal);if(Xn(h,p,"upload"),h.total_size!==n||h.strategy.kind==="object_ranges")throw d("invalid_operation_response","The authority returned an incompatible upload strategy.");let y=h.strategy.kind==="framed_chunks";if(y&&!this.framed)throw d("invalid_operation_response","Encrypted file chunk delivery is unavailable.");let R=h.strategy.kind==="object_put"?Math.max(1,n):h.strategy.kind==="framed_chunks"?h.strategy.chunk_size:h.strategy.part_size,C=h.strategy.kind==="object_put"?1:Math.ceil(n/R),m=await this.request("GET",`transfers/${encodeURIComponent(p)}`,void 0,r.signal);if(Cr(m,h),m.state!=="open"&&m.state!=="committed")throw d("invalid_operation_response",`The authority cannot resume a ${m.state} file transfer.`);if(u?.(R),!y&&m.received.length===C){let S=await this.tryReplayUploadCommit(p,h.strategy.kind==="object_multipart"?m.uploaded_parts:void 0,r.signal);if(S)return f=!0,cn(S.file)}let v=new Set(m.received),_=new Map(m.uploaded_parts.map(S=>[S.part_number-1,S])),A=[...v].reduce((S,P)=>S+Zn(n,R,P),0),T=await Sr(C,a,async S=>{let P=S*R,q=Math.min(R,Math.max(0,n-P)),H=await s(S,P,q);if(gr(H)!==q)throw d("invalid_request","Streamed file bytes ended before the declared size.");if(v.has(S))return _.get(S)??null;let ne=y?await sn(async()=>this.framed.uploadChunk(h,S,await _r(H),r.signal),r.signal).then(()=>null):await this.uploadPart(p,S,P,H,q,h.strategy.kind==="object_multipart",r.signal);return A+=q,r.onProgress?.({phase:"uploading",transferredBytes:A,totalBytes:n}),ne});await c?.();let O=await this.commitUpload(p,h.strategy.kind==="object_multipart"?T.filter(S=>S!==null):void 0,r.signal);if(O.protocol_version!==1||O.type!=="file_upload_committed"||O.transfer_id!==p||O.file.path!==e||O.file.size!==n||O.file.content_digest!==i)throw d("invalid_operation_response","The authority returned an invalid file receipt.");return f=!0,cn(O.file)}catch(h){throw Te(h)}finally{await l?.().catch(()=>{}),!f&&r.transferId===void 0&&await this.abort(p)}}async download(e,n={}){if(e.size>Qn)throw d("invalid_request",`download() buffers at most ${Qn} bytes; use downloadStream() for larger files.`);let i=await this.downloadStream(e,n),o=[],r=i.getReader();for(;;){let a=await r.read();if(a.done)break;o.push(a.value)}return new Blob(o.map(a=>{let s=new Uint8Array(a.byteLength);return s.set(a),s.buffer}),{type:e.mediaType??""})}async downloadStream(e,n={}){return K(n,this.timeouts.requestMs,i=>this.openDownloadStream(e,n,i.signal))}async openDownloadStream(e,n,i){this.requireAction("read");let o=Yn(n.concurrency),r=crypto.randomUUID(),a;try{if(a=await this.request("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:r,file_id:e.fileId,revision:e.revision},i),Xn(a,r,"download"),a.total_size!==e.size||a.strategy.kind!=="object_ranges"&&a.strategy.kind!=="framed_chunks")throw d("invalid_operation_response","The authority returned an incompatible download session.");if(a.strategy.kind==="framed_chunks"&&!this.framed)throw d("invalid_operation_response","Encrypted file chunk delivery is unavailable.");if(a.strategy.kind==="object_ranges"&&e.size>0&&!this.hosted)throw d("invalid_operation_response","Authenticated hosted file delivery is unavailable.")}catch(O){throw await this.abort(r),Te(O)}let s=a.strategy.kind==="framed_chunks"?a.strategy.chunk_size:a.strategy.part_size,c=Math.ceil(e.size/s),l=new Oe,u=0,p=0,f=null,h=0,y=!1,R=new AbortController,C=n.signal?AbortSignal.any([n.signal,R.signal]):R.signal,m=new Map,v=0,_=()=>{if(a.strategy.kind==="framed_chunks")for(;v<c&&m.size<o;){let O=v;v+=1;let S=sn(()=>this.framed.downloadChunk(a,O,C),C).then(P=>({ok:!0,chunk:P}),P=>({ok:!1,error:P}));m.set(O,S)}},A=async()=>{y||(y=!0,R.abort(),await f?.cancel().catch(()=>{}),f=null,await Promise.all(m.values()),m.clear(),await this.abort(r))},T=()=>{if(h!==e.size||`sha256:${l.digestHex()}`!==e.contentDigest)throw d("invalid_operation_response","Downloaded file bytes failed integrity verification.")};return new ReadableStream({pull:async O=>{try{if(_e(C),a.strategy.kind==="object_ranges")for(;;){if(!f){if(u>=c){T(),O.close(),A();return}let Kr=u*s;p=Math.min(s,e.size-Kr),f=(await sn(()=>this.hosted.downloadPart(a,u,p,C),C)).getReader()}let le=await f.read();if(le.done){if(f.releaseLock(),f=null,p!==0)throw d("invalid_operation_response","A hosted file range ended before its declared byte length.");u+=1;continue}if(!(le.value instanceof Uint8Array))throw d("invalid_operation_response","A hosted file range returned a non-byte chunk.");if(le.value.byteLength!==0){if(le.value.byteLength>p)throw d("invalid_operation_response","A hosted file range exceeded its declared byte length.");p-=le.value.byteLength,l.update(le.value),h+=le.value.byteLength,n.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),O.enqueue(le.value);return}}if(u>=c){T(),O.close(),A();return}let S=u*s,P=Math.min(s,e.size-S);_();let q=m.get(u);if(!q)throw d("invalid_operation_response","A file chunk was not scheduled.");let H=await q;if(m.delete(u),!H.ok)throw H.error;let ne=H.chunk;if(ne.byteLength!==P)throw d("invalid_operation_response","A file chunk had the wrong byte length.");l.update(ne),h+=ne.byteLength,u+=1,_(),n.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),u===c&&T(),O.enqueue(ne),u===c&&(O.close(),A())}catch(S){let P=n.signal?.aborted?d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:n.signal.reason}):S;await A(),O.error(Te(P))}},cancel:A})}async downloadBytes(e,n={}){return new Uint8Array(await(await this.download(e,n)).arrayBuffer())}async move(e,n,i={}){return K(i,this.timeouts.requestMs,o=>this.moveWithinBudget(e,n,{...i,signal:o.signal,timeoutMs:null}))}async moveWithinBudget(e,n,i){this.requireAction("move");let o=i.mutationId??crypto.randomUUID(),r;try{r=await this.request("POST",`${encodeURIComponent(e.fileId)}/move`,{protocol_version:1,type:"move_file",mutation_id:o,file_id:e.fileId,if_revision:i.ifRevision??e.revision,from_path:e.path,path:n,update_references:!1},i.signal)}catch(a){throw Te(a)}if(r.protocol_version!==1||r.type!=="file_moved"||r.mutation_id!==o||r.file.file_id!==e.fileId||r.file.path!==n)throw d("invalid_operation_response","The authority returned an invalid file move receipt.");return cn(r.file)}async delete(e,n={}){return K(n,this.timeouts.requestMs,i=>this.deleteWithinBudget(e,{...n,signal:i.signal,timeoutMs:null}))}async deleteWithinBudget(e,n){this.requireAction("delete");let i=n.mutationId??crypto.randomUUID(),o;try{o=await this.request("POST",`${encodeURIComponent(e.fileId)}/delete`,{protocol_version:1,type:"delete_file",mutation_id:i,file_id:e.fileId,if_revision:n.ifRevision??e.revision,path:e.path},n.signal)}catch(r){throw Te(r)}if(o.protocol_version!==1||o.type!=="file_deleted"||o.mutation_id!==i||o.file_id!==e.fileId||o.previous_path!==e.path)throw d("invalid_operation_response","The authority returned an invalid file delete receipt.");return{protocolVersion:o.protocol_version,type:o.type,mutationId:o.mutation_id,fileId:o.file_id,previousPath:o.previous_path,revision:o.revision}}async uploadPart(e,n,i,o,r,a,s){for(let c=1;c<=_t;c+=1){_e(s);try{let l=await this.request("POST",`uploads/${encodeURIComponent(e)}/parts`,{protocol_version:1,type:"prepare_file_upload_part",transfer_id:e,part_number:n+1,content_length:r},s);vr(l,e,n,i,r,"PUT");let u=await fetch(l.url,{method:l.method,headers:wr(l.headers),body:o,redirect:"error",signal:s});if(!u.ok)throw new Error(`Object upload failed with HTTP ${u.status}.`);let p=u.headers.get("etag");if(a&&!p)throw new Error("Multipart object upload did not return an ETag.");return{part_number:n+1,etag:p??""}}catch(l){if(s?.aborted||c===_t)throw l}}throw new Error("Unreachable upload retry state.")}async tryReplayUploadCommit(e,n,i){try{return await this.commitUpload(e,n,i)}catch(o){if(o instanceof b&&o.code==="file_upload_incomplete")return null;throw o}}async commitUpload(e,n,i){let o;for(let r=1;r<=_t;r+=1){_e(i);try{return await this.request("POST",`uploads/${encodeURIComponent(e)}/commit`,{protocol_version:1,type:"commit_file_upload",transfer_id:e,...n===void 0?{}:{parts:n}},i)}catch(a){if(o=a,i?.aborted||a instanceof b||r===_t)throw a}}throw o}requireAction(e){if(!this.capability()?.actions.includes(e))throw d("not_authorized",`This connection is not authorized to ${e} files.`)}async abort(e){await this.request("DELETE",`transfers/${encodeURIComponent(e)}`).catch(()=>{})}};function cn(t){return{fileId:t.file_id,path:t.path,revision:t.revision,contentDigest:t.content_digest,size:t.size,...t.media_type?{mediaType:t.media_type}:{},mediaClass:t.media_class,modifiedAt:t.modified_at}}var ac=4,Rr=32,ln=class{constructor(e,n,i={}){this.transport=e;this.requestTimeoutMs=n;this.foregroundCapacity=ei(i.foregroundCapacity,ac),this.foregroundQueueCapacity=ei(i.foregroundQueueCapacity,Rr),this.mutationQueueCapacity=ei(i.mutationQueueCapacity,Rr)}transport;requestTimeoutMs;foregroundCapacity;foregroundQueueCapacity;mutationQueueCapacity;foregroundQueue=[];mutationQueue=[];identicalReads=new Map;latestFamilies=new Map;activeForeground=0;mutationActive=!1;operation(e,n,i={}){let o=!ue(e,n),r=sc(i.coordination,o),a=o&&r.coalesce!==!1&&!r.latestWins&&i.signal===void 0?cc(e,n,i.timeoutMs):void 0;if(a){let c=this.identicalReads.get(a);if(c)return c}let s=K(i,this.requestTimeoutMs,c=>this.schedule(e,n,i,r,o,c));return a&&(this.identicalReads.set(a,s),s.finally(()=>{this.identicalReads.get(a)===s&&this.identicalReads.delete(a)}).catch(()=>{})),s}schedule(e,n,i,o,r,a){let s=o.latestWins?this.replaceLatest(o.family):void 0,c=lc(a.signal,s?.signal),{coordination:l,...u}=i,p=ot({...u,timeoutMs:null},a),f=()=>this.transport.operation(e,n,{...p,signal:c.signal}),h=r?this.foregroundQueue:this.mutationQueue,y=r?this.foregroundQueueCapacity:this.mutationQueueCapacity;return h.length>=y?(c.dispose(),this.releaseLatest(o.family,s),Promise.reject(d("connector_busy","The selected connection request queue is full.",{operationOutcome:"not_sent",status:503}))):new Promise((R,C)=>{let m={budget:a,run:f,resolve:A=>R(A),reject:C,started:!1,settled:!1},v=()=>{m.started||m.settled||(m.settled=!0,h.splice(h.indexOf(m),1),m.reject(J(c.signal)),c.dispose(),this.releaseLatest(o.family,s))};c.signal.addEventListener("abort",v,{once:!0});let _=m.run;m.run=async()=>{c.signal.removeEventListener("abort",v);try{if(c.signal.aborted)throw J(c.signal);return await _()}finally{c.dispose(),this.releaseLatest(o.family,s)}},h.push(m),this.pump()})}replaceLatest(e){let n=new AbortController;return this.latestFamilies.get(e)?.abort(d("operation_cancelled","A newer request replaced this read before it changed the collection.",{operationOutcome:"not_sent"})),this.latestFamilies.set(e,n),n}releaseLatest(e,n){e&&n&&this.latestFamilies.get(e)===n&&this.latestFamilies.delete(e)}pump(){for(;this.activeForeground<this.foregroundCapacity;){let e=Ar(this.foregroundQueue);if(!e)break;this.activeForeground+=1,this.start(e,()=>{this.activeForeground-=1,this.pump()})}if(!this.mutationActive){let e=Ar(this.mutationQueue);e&&(this.mutationActive=!0,this.start(e,()=>{this.mutationActive=!1,this.pump()}))}}start(e,n){e.started=!0,e.run().then(i=>{e.settled||(e.settled=!0,e.resolve(i))},i=>{e.settled||(e.settled=!0,e.reject(i))}).finally(n)}};function Ar(t){for(;t.length>0;){let e=t.shift();if(!e.settled)return e}}function sc(t,e){let n=t??{};if(n.latestWins&&!e)throw new TypeError("latestWins coordination is available only for read operations.");if(n.latestWins&&!n.family?.trim())throw new TypeError("latestWins coordination requires a non-empty family.");return n}function cc(t,e,n){return`${t}:${n===void 0?"default":String(n)}:${ti(e)}`}function ti(t){return t===null||typeof t!="object"?JSON.stringify(t)??String(t):Array.isArray(t)?`[${t.map(ti).join(",")}]`:`{${Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${ti(n)}`).join(",")}}`}function lc(t,e){if(!e)return{signal:t,dispose:()=>{}};let n=new AbortController,i=()=>n.abort(t.reason),o=()=>n.abort(e.reason);return t.aborted?i():t.addEventListener("abort",i,{once:!0}),e.aborted?o():e.addEventListener("abort",o,{once:!0}),{signal:n.signal,dispose:()=>{t.removeEventListener("abort",i),e.removeEventListener("abort",o)}}}function ei(t,e){let n=t??e;if(!Number.isSafeInteger(n)||n<=0)throw new TypeError("Request coordinator capacities must be positive safe integers.");return n}var Ye=class{constructor(e,n){this.internals=e;this.collectionId=n;this.transport=new rn({serverUrl:e.serverUrl,storage:e.storage,keyStore:e.keyStore,directAccessMode:e.directAccessMode,loopbackUrl:e.loopbackUrl,collectionId:n,internals:e,timeouts:e.timeouts,onChange:()=>this.emitConnection()}),this.files=new Qe(()=>this.fileCapability,(i,o,r,a)=>this.transport.files.control(i,o,r,a),{uploadChunk:(i,o,r,a)=>this.transport.files.uploadChunk(i,o,r,a),downloadChunk:(i,o,r)=>this.transport.files.downloadChunk(i,o,r)},{downloadPart:(i,o,r,a)=>this.transport.files.downloadHostedPart(i,o,r,a)},e.timeouts),this.collectionClient=new Ge(new ln({operation:(i,o,r)=>this.transport.performOperation(i,o,r)},e.timeouts.requestMs),e.timeouts.requestMs),this.notifications=new Vt({serverUrl:e.serverUrl,storage:e.storage,authorizedToken:i=>this.transport.authorizedToken({signal:i,timeoutMs:null}),register:i=>this.internals.register({signal:i,timeoutMs:null}),notificationKey:i=>e.notificationKey(n,i),requestTimeoutMs:e.timeouts.requestMs})}internals;collectionId;collectionClient;notifications;transport;files;connectionListeners=new Set;get displayName(){return this.transport.currentToken()?.collectionName??`Collection ${this.collectionId.slice(0,8)}`}get operations(){return[...this.transport.currentToken()?.operations??[]]}get scope(){return this.transport.currentToken()?.scope??null}get fileCapability(){return this.transport.currentToken()?.fileCapability??null}get directAccess(){return this.transport.directAccess}get route(){return this.transport.route}register(e){return D(()=>this.internals.register(e),Se)}info(){let e=this.transport.currentToken();return e?{collectionId:e.collectionId,displayName:e.collectionName,operations:[...e.operations],scope:e.scope,...e.fileCapability?{fileCapability:e.fileCapability}:{},authority:e.authority?{kind:"hosted",durability:"provider"}:{kind:"connector",durability:"computer"},route:this.transport.route,directAccess:this.transport.directAccess}:null}authorizationCapabilities(e=we){let n=this.operations,i=lt(e).filter(o=>!n.includes(o));return{authorized:this.info()!==null,sufficient:this.info()!==null&&i.length===0,collectionId:this.collectionId,grantedOperations:n,missingOperations:i}}hasOperations(e){return this.authorizationCapabilities(e).sufficient}authorize(e={}){return D(()=>this.internals.authorize({...e,target:{kind:"collection",collectionId:this.collectionId}}),fe)}async requestCapabilities(e,n={}){return D(async()=>{let i=await this.internals.register(n);if(Y(i.requirements,{...n,capabilities:e}),this.info()!==null&&e.every(a=>(W(B(i.requirements),a)??[]).every(s=>this.operations.includes(s))))return{kind:"unchanged",connection:this};if(B(i.requirements)===1){let{capabilities:a,...s}=n;return this.internals.authorize({...s,target:{kind:"collection",collectionId:this.collectionId},operations:[...new Set([...this.operations,...e.flatMap(c=>W(1,c)??[])])]})}let r=Tt(i.requirements,this.operations);return this.internals.authorize({...n,target:{kind:"collection",collectionId:this.collectionId},capabilities:[...new Set([...r,...e])]})},fe)}async requestOperations(e,n={}){return D(async()=>{let i=await this.internals.register(n);Y(i.requirements,{...n,operations:e});let o=this.authorizationCapabilities(e);return o.sufficient?{kind:"unchanged",connection:this}:this.internals.authorize({...n,target:{kind:"collection",collectionId:this.collectionId},operations:[...new Set([...o.grantedOperations,...e])]})},fe)}onConnectionChange(e){return this.connectionListeners.add(e),e(this.info()),()=>this.connectionListeners.delete(e)}notifyStorageChanged(){this.transport.notifyStorageChanged()}checkDirectAccess(e){return D(()=>this.transport.checkDirectAccess(e),Mn)}requestDirectAccess(e){return D(()=>this.transport.requestDirectAccess(e),Mn)}disableDirectAccess(){this.transport.disableDirectAccess()}sync(){let e=this.transport.currentToken();if(!e)return null;let n=e.collectionId;if(!e.authority){if(!e.grantId||!e.operations.includes("sync"))return null;let o=e.grantId;return{collectionId:n,replicaId:o,transport:{openSession:r=>this.transport.performOperation("sync",{action:"open_session"},dn(r,this.internals.timeouts.syncMs)),snapshot:(r,a,s)=>this.transport.performOperation("sync",{action:"snapshot",snapshot_id:r,...a?{page:a}:{}},dn(s,this.internals.timeouts.syncMs)),changes:(r,a=200,s)=>this.transport.performOperation("sync",{action:"changes",after:r,limit:a},dn(s,this.internals.timeouts.syncMs)),mutate:(r,a)=>this.transport.performOperation("sync",{action:"mutate",mutation:r},dn(a,this.internals.timeouts.syncMs))}}}let i=e.authority.replicaId;return{collectionId:n,replicaId:i,transport:{openSession:o=>this.transport.performAuthoritySyncRequest(n,i,"POST","sessions",void 0,o),snapshot:(o,r,a)=>{let s=new URLSearchParams({snapshot_id:o});return r&&s.set("page",r),this.transport.performAuthoritySyncRequest(n,i,"GET",`snapshot?${s}`,void 0,a)},changes:(o,r=200,a)=>this.transport.performAuthoritySyncRequest(n,i,"GET",`changes?${new URLSearchParams({after:String(o),limit:String(r)})}`,void 0,a),mutate:(o,r)=>this.transport.performAuthoritySyncRequest(n,i,"POST","mutations",o,r)}}}registerNotifications(e){return D(()=>this.notifications.registerNotifications(e),rt)}registerNativeNotifications(e){return D(()=>this.notifications.registerNativeNotifications(e),rt)}unregisterNativeNotifications(e){return D(()=>this.notifications.unregisterNativeNotifications(e),rt)}unregisterNotifications(e,n){return D(()=>this.notifications.unregisterNotifications(e,n),rt)}forget(){let e=this.transport.currentToken();this.internals.removeToken(this.collectionId,e?.keyHandle,"not_authorized",!0),this.transport.notifyStorageChanged()}describe(e){return this.collectionClient.describe(e)}changes(e={},n){return this.collectionClient.changes(e,n)}read(e,n){return this.collectionClient.read(e,n)}query(e={},n){return this.collectionClient.query(e,n)}queryPages(e={},n={}){return this.collectionClient.queryPages(e,n)}queryAll(e={},n={}){return this.collectionClient.queryAll(e,n)}listViews(e){return this.collectionClient.listViews(e)}executeView(e,n){return this.collectionClient.executeView(e,n)}executeViewPages(e,n={}){return this.collectionClient.executeViewPages(e,n)}readViewSource(e,n){return this.collectionClient.readViewSource(e,n)}createViewSource(e,n){return this.collectionClient.createViewSource(e,n)}updateViewSource(e,n){return this.collectionClient.updateViewSource(e,n)}deleteViewSource(e,n){return this.collectionClient.deleteViewSource(e,n)}create(e,n){return this.collectionClient.create(e,n)}update(e,n){return this.collectionClient.update(e,n)}delete(e,n){return this.collectionClient.delete(e,n)}preflightDelete(e,n){return this.collectionClient.preflightDelete(e,n)}rename(e,n){return this.collectionClient.rename(e,n)}preflightRename(e,n){return this.collectionClient.preflightRename(e,n)}async renameWithProgress(e,n={}){return K(n,this.internals.timeouts.requestMs,async i=>{let o=Date.now(),r=!1,a,s=(c,l,u=0)=>{n.onProgress?.({operation:"rename",state:c,elapsedMs:Date.now()-o,cancellable:l,resumed:r,completedUnits:u,...a?{estimate:a}:{}})};try{Re(i.signal),s("preflighting",!0);let c=n.preflight?I(n.preflight):await this.preflightRename(e,{signal:i.signal,timeoutMs:null});if(!c.ok)return c;let l=c.value;try{oo(e,l)}catch(f){if(f instanceof b)return g(f.problem);throw f}a=ao(e,l),s("ready",!0),Re(i.signal);let u=this.transport.hasResumableMutationTransport();s("applying",u);let p=await this.rename(e,u?{signal:i.signal,timeoutMs:null}:{timeoutMs:Pr(i.remainingMs())});return p.ok&&s("completed",!1,a.totalUnits),p}catch(c){if(Dn(c,i.signal)&&s("cancelled",!1),c instanceof b)return g(c.problem);throw c}})}async deleteWithProgress(e,n={}){return K(n,this.internals.timeouts.requestMs,async i=>{let o=Date.now(),r=!1,a,s=(c,l,u=0)=>{n.onProgress?.({operation:"delete",state:c,elapsedMs:Date.now()-o,cancellable:l,resumed:r,completedUnits:u,...a?{estimate:a}:{}})};try{Re(i.signal),s("preflighting",!0);let c=n.preflight?I(n.preflight):await this.preflightDelete(e,{signal:i.signal,timeoutMs:null});if(!c.ok)return c;let l=c.value;try{ro(e,l)}catch(f){if(f instanceof b)return g(f.problem);throw f}a=so(l),s("ready",!0),Re(i.signal);let u=this.transport.hasResumableMutationTransport();s("applying",u);let p=await this.delete(e,u?{signal:i.signal,timeoutMs:null}:{timeoutMs:Pr(i.remainingMs())});return p.ok&&s("completed",!1,a.totalUnits),p}catch(c){if(Dn(c,i.signal)&&s("cancelled",!1),c instanceof b)return g(c.problem);throw c}})}pendingMutations(){return this.transport.pendingMutations().map(e=>({...e,recover:n=>D(()=>this.recoverPendingMutation(e.requestId,n),j)}))}pendingMutation(e){let n=this.transport.pendingMutation(e);return n?{...n,recover:i=>D(()=>this.recoverPendingMutation(e,i),j)}:null}async recoverPendingMutation(e,n){let i=await this.transport.recoverPendingMutation(e,n);if(i&&typeof i=="object"&&"valid"in i){let o=i;if(!o.valid)throw new b(ke(o));return o.result}return i}validate(e={},n){return this.collectionClient.validate(e,n)}readType(e,n){return this.collectionClient.readType(e,n)}createType(e,n){return this.collectionClient.createType(e,n)}updateType(e,n){return this.collectionClient.updateType(e,n)}assessTypePack(e,n){return this.collectionClient.assessTypePack(e,n)}applyTypePack(e,n){return this.collectionClient.applyTypePack(e,n)}assessCollectionSetup(e,n){return this.collectionClient.assessCollectionSetup(e,n)}applyCollectionSetup(e,n){return this.collectionClient.applyCollectionSetup(e,n)}listTimers(e,n){return this.collectionClient.listTimers(e,n)}putTimer(e,n){return this.collectionClient.putTimer(e,n)}cancelTimer(e,n){return this.collectionClient.cancelTimer(e,n)}reconcileTimers(e,n){return this.collectionClient.reconcileTimers(e,n)}watch(e={},n={}){return D(()=>F(n,this.internals.timeouts.watchStartMs,async i=>{let o=await this.collectionClient.changes(e.cursor===void 0?{}:{after:e.cursor,limit:200},{signal:i.signal,timeoutMs:null});if(!o.ok)throw new b(o.problem);if(o.value.reset)throw new b(w("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again."));return new ni(this.collectionClient,o.value.cursor,e,e.cursor===void 0?[]:o.value.events,this.internals.timeouts.watchStartMs)}),xt)}emitConnection(){let e=this.info();for(let n of this.connectionListeners)n(e)}},ni=class{constructor(e,n,i,o,r){this.client=e;this.input=i;this.watchStartTimeoutMs=r;this.pendingChanges=[...o],this.currentStatus={state:"connected",cursor:n,recovered:!1};let a=i.lifetimeSignal;if(a?.aborted)this.close();else if(a){let s=()=>this.close();a.addEventListener("abort",s,{once:!0}),this.removeLifetimeAbort=()=>a.removeEventListener("abort",s)}this.controller.signal.aborted||this.run(n)}client;input;watchStartTimeoutMs;changes=new Set;statuses=new Set;problems=new Set;controller=new AbortController;removeLifetimeAbort;currentStatus;currentProblem=null;pendingChanges;get status(){return this.currentStatus}get problem(){return this.currentProblem}subscribe(e,n,i){this.changes.add(e),n&&(this.statuses.add(n),n(this.currentStatus)),i&&(this.problems.add(i),this.currentProblem&&i(this.currentProblem));for(let o of this.pendingChanges)e(o);return this.pendingChanges=[],()=>{this.changes.delete(e),n&&this.statuses.delete(n),i&&this.problems.delete(i)}}close(){if(this.controller.signal.aborted)return;this.controller.abort(),this.removeLifetimeAbort?.(),this.removeLifetimeAbort=void 0;let e="cursor"in this.currentStatus?this.currentStatus.cursor:void 0;this.publishStatus({state:"closed",...e===void 0?{}:{cursor:e}})}async run(e){let n=!0,i=this.client.watch({cursor:e,pollIntervalMs:this.input.pollIntervalMs,retry:this.input.retry,signal:this.controller.signal,timeoutMs:this.watchStartTimeoutMs,onStatus:o=>{if(n&&o.state==="connecting"){n=!1;return}n=!1,this.publishStatus(o)}});try{for await(let o of i){if(this.controller.signal.aborted)return;if(!o.ok){this.currentProblem=o.problem;for(let r of this.problems)r(o.problem);return}for(let r of this.changes)r(o.value)}}finally{this.controller.signal.aborted||this.close()}}publishStatus(e){this.currentStatus=e;for(let n of this.statuses)n(e)}};function dn(t,e){return{...t,timeoutMs:t?.timeoutMs===void 0?e:t.timeoutMs}}function Pr(t){return t===null?null:Math.max(1,Math.ceil(t))}function un(t,e){let n=M(t.getItem(`${e}:connections`));return n?.version===1&&Array.isArray(n.collectionIds)&&n.collectionIds.every(i=>typeof i=="string")?n.collectionIds:[]}function Or(t,e,n){kr(t,e,[...un(t,e),n])}function Tr(t,e,n){kr(t,e,un(t,e).filter(i=>i!==n))}function kr(t,e,n){t.setItem(`${e}:connections`,JSON.stringify({version:1,collectionIds:[...new Set(n)]}))}async function xr(t){if(typeof location>"u"&&!t.navigate&&!t.options.openVerification)throw d("browser_required","Authorization navigation requires a browser environment.");let n=(t.options.presentation==="popup"||t.portableDeclared)&&!t.options.openVerification&&!t.navigate&&typeof window<"u"?window.open("","mdbase-connect-authorization","popup,width=620,height=760"):null;try{return{application:await t.register(t.options.signal),popup:n}}catch(i){throw n?.close(),i}}async function Er(t){let e=zr(t.storagePrefix,t.state);try{for(;;){let n=M(t.storage.getItem(e));if(n?.version===1){if(t.storage.removeItem(e),n.status==="failed")throw U(n.code,n.message,{details:n.returnTo?{return_to:n.returnTo}:void 0});let i=t.connection(n.collectionId);if(!i)throw d("invalid_callback","Authorization completed without a usable saved connection.");return{kind:"connected",connection:i,...n.returnTo?{returnTo:n.returnTo}:{}}}await Z(200,t.signal)}}finally{t.popup.close(),t.storage.removeItem(e);let n=`${t.storagePrefix}:pending:${t.state}`;M(t.storage.getItem(n))?.state===t.state&&(t.storage.removeItem(n),t.pending.keyHandle&&await t.keyStore.delete(t.pending.keyHandle))}}function qr(t){return t.completion.then(e=>(t.popupAttempt&&Ir(t,{version:1,status:"connected",collectionId:e.connection.collectionId,...e.returnTo?{returnTo:e.returnTo}:{}}),t.popupAttempt&&Mr(),e)).catch(e=>{throw t.popupAttempt&&Ir(t,{version:1,status:"failed",code:e instanceof b?e.code:"invalid_callback",message:e instanceof Error?e.message:"Authorization could not be completed.",...t.pending?.returnTo?{returnTo:t.pending.returnTo}:{}}),t.popupAttempt&&Mr(),e})}function Ir(t,e){t.storage.setItem(zr(t.storagePrefix,t.state),JSON.stringify(e))}function zr(t,e){return`${t}:completion:${e}`}function Mr(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function ii(t,e,n,i){let o=`${e}:pending-mutation:`,r=new Set;for(let a=0;a<t.length;a+=1){let s=t.key(a);if(!s?.startsWith(o))continue;let c=M(t.getItem(s));if(!c||!n.includes(c.operation)||i&&c.collectionId!==i)continue;let l=c.envelope?.protocol_version??c.request?.protocol_version;l!==void 0&&l!==$&&Ze(l)&&r.add(l)}return[...r].sort((a,s)=>s-a)}function oi(t,e,n){return ri(t,e).has(n)}function ri(t,e){let n=new Set;for(let i=0;i<t.length;i+=1){let o=t.key(i);if(o!==e&&!o?.startsWith(`${e}:`))continue;let r=M(t.getItem(o));r?.keyHandle&&n.add(r.keyHandle)}return n}function Fr(t,e,n){let i=[e];for(let o=0;o<t.length;o+=1){let r=t.key(o);r?.startsWith(`${e}:`)&&i.push(r)}for(let o of i){let r=M(t.getItem(o));r?.keyHandle&&n(r.keyHandle),t.removeItem(o)}}function Dr({body:t,clientId:e,keyHandle:n,previous:i,retiredKeyHandles:o,defaultApplicationOrigin:r,pinConnectorIdentity:a}){let s=t.collection_id;if(typeof s!="string")throw d("invalid_token_response","Authorization returned no collection ID.");let c=Ft(t.scope);if(!c)throw d("invalid_token_response","Authorization returned no valid collection scope.");if(!Dt(c))throw d("legacy_scope_reauthorization_required","Authorization returned a legacy contract-scoped grant. Reauthorize for the entire collection.");if(t.authority&&!pt(t.authority,s))throw d("invalid_token_response","Authorization returned an invalid remote authority capability.");if(t.authority&&t.encryption)throw d("invalid_token_response","Authorization returned conflicting collection transports.");if(t.file_capability!==null&&t.file_capability!==void 0&&!zt(t.file_capability))throw d("invalid_token_response","Authorization returned an invalid file capability.");if(t.encryption){try{re(t.encryption)}catch{throw d("invalid_token_response","Authorization returned an invalid encrypted relay binding.")}if(a(t.encryption.connector_id,t.encryption.connector_agreement_public_key),t.encryption.collection_id!==s||typeof t.grant_id!="string"||t.grant_id.length===0)throw d("invalid_token_response","Authorization returned an encrypted relay binding for another grant.")}if(i?.encryption&&t.encryption&&i.keyHandle&&i.keyHandle===n&&(i.grantId!==t.grant_id||i.encryption.connector_id!==t.encryption.connector_id||i.encryption.connector_agreement_public_key!==t.encryption.connector_agreement_public_key||i.encryption.application_agreement_public_key!==t.encryption.application_agreement_public_key))throw d("connector_identity_changed","The connector identity changed during authorization renewal. Reauthorize before sending collection data.");return{version:1,accessToken:t.access_token,refreshToken:t.refresh_token,clientId:e,collectionId:s,collectionName:t.collection_name??`Collection ${s.slice(0,8)}`,operations:t.operations,scope:c,expiresAt:Date.now()+t.expires_in*1e3,refreshExpiresAt:t.refresh_expires_in?Date.now()+t.refresh_expires_in*1e3:void 0,grantId:t.grant_id,encryption:t.encryption??void 0,fileCapability:t.file_capability??void 0,applicationOrigin:t.application_origin??r,keyHandle:n,...o?.length?{retiredKeyHandles:o}:{},savedAt:Date.now(),authority:t.authority?{operationsUrl:t.authority.operations_url,syncUrl:t.authority.sync_url,filesUrl:t.authority.files_url,replicaId:t.authority.replica_id,accessToken:t.authority.access_token,proofPublicKey:t.authority.proof_public_key}:void 0}}function ai(t,e){let n=new Set;if(e&&n.add(e),t?.keyHandle&&n.add(t.keyHandle),Array.isArray(t?.retiredKeyHandles))for(let i of t.retiredKeyHandles)typeof i=="string"&&i.length>0&&n.add(i);return n}function Ur(t,e,n,i,o=[],r=!1){let a=[],s=[],c=ai(n);for(let u of ri(t,e))c.add(u);let l=new Set(o);for(let u of l)c.add(u);for(let u of c)u!==i&&(r||l.has(u)||oi(t,e,u)?a:s).push(u);return{retained:a,disposable:s}}function dc(t,e,n){let i=M(t.getItem(e));if(!i||!Array.isArray(i.retiredKeyHandles))return;let o=i.retiredKeyHandles.filter(r=>r!==n);o.length!==i.retiredKeyHandles.length&&(o.length>0?i.retiredKeyHandles=o:delete i.retiredKeyHandles,t.setItem(e,JSON.stringify(i)))}async function Lr(t,e,n,i,o){M(t.getItem(i))?.keyHandle===o||oi(t,n,o)||(await e.delete(o),dc(t,i,o))}var pn=class{serverUrl;manifest;manifestSource;redirectUri;storage;relayEncryption;keyStore;identityStore;directAccessMode;loopbackUrl;navigate;timeouts;credentialStorage;application=null;manifestPromise=null;completionPromises=new Je;grantKeyLeases;connectionCache=new Map;listeners=new Set;invalidatedConnections=new Map;constructor(e){this.serverUrl=go(String(e.serverUrl));let n=po(e.manifest,e.redirectUri);this.manifest=n.manifest,this.manifestSource=n.manifestSource;let i=vo(this.manifest);this.redirectUri=n.redirectUri,this.storage=e.storage??Co(i),this.relayEncryption=e.relayEncryption??"required",this.keyStore=e.keyStore??(i?new qe:new Ee),this.identityStore=e.identityStore??(i?new Ke:new je),this.credentialStorage=e.storage||e.keyStore||e.identityStore?"custom":this.storage instanceof De?"memory":"persistent",this.directAccessMode=e.directAccess??"auto",this.loopbackUrl=fo(String(e.loopbackUrl??`http://127.0.0.1:${xi}`)),this.navigate=e.navigate,this.timeouts=xe(e.timeouts),this.grantKeyLeases=new Ht(this.storagePrefix(),(o,r)=>this.deleteGrantKeyWhenUnused(o,r)),typeof window<"u"&&this.storage===window.localStorage&&window.addEventListener("storage",o=>{o.storageArea!==this.storage||!o.key?.startsWith(this.storagePrefix())||(this.connectionCache.get(bo(o.key))?.notifyStorageChanged(),this.emitConnections())})}environment(){let e=typeof this.manifest!="string"&&this.manifest.distribution==="portable"?"portable":this.application?.distribution??"web";return{distribution:e,applicationOrigin:e==="portable"?"null":this.defaultApplicationOrigin(),credentialStorage:this.credentialStorage}}register(e={}){return F(e,this.timeouts.requestMs,n=>this.registerWithinBudget(n.signal))}async registerWithinBudget(e){if(this.application)return this.application;let n=await ae(`${this.serverUrl}/v1/apps/register`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({manifest:await this.manifestDeclaration({signal:e,timeoutMs:null})}),signal:e},"temporarily_unavailable","Application registration is temporarily unavailable."),i=await E(n,"invalid_operation_response","Connect returned an invalid application registration response.");if(!n.ok)throw z(i,"discovery_failed","Application discovery failed.",n.status);return this.application=i.application,this.application}manifestDeclaration(e={}){if(this.manifestPromise)return this.manifestPromise;let i=F(e,this.timeouts.requestMs,o=>this.loadManifest(o.signal)).catch(o=>{throw this.manifestPromise===i&&(this.manifestPromise=null),o});return this.manifestPromise=i,this.manifestPromise}async loadManifest(e){if(typeof this.manifest!="string")return this.manifest;let n=this.manifest,i;try{i=await fetch(n,{headers:{accept:"application/json"},signal:e})}catch(o){throw d("manifest_load_failed","The bundled application declaration could not be loaded.",{cause:o})}if(!i.ok)throw d("manifest_load_failed",`The bundled application declaration returned HTTP ${i.status}.`,{status:i.status});try{return await E(i,"invalid_application_manifest","The bundled application declaration is not valid JSON.")}catch(o){throw d("invalid_application_manifest","The bundled application declaration is not valid JSON.",{cause:o,details:{issues:[{path:"/",keyword:"json",message:"must be valid JSON",params:{}}]}})}}async authorize(e={}){let n=e.presentation==="popup"?6e5:this.timeouts.requestMs;return F(e,n,i=>this.authorizeWithinBudget({...e,signal:i.signal,timeoutMs:null}))}async authorizeWithinBudget(e){let n=typeof this.manifest!="string"&&this.manifest.distribution==="portable",{application:i,popup:o}=await xr({options:e,portableDeclared:n,navigate:this.navigate,register:r=>this.registerWithinBudget(r)});try{Y(i.requirements,e)}catch(r){throw o?.close(),r}return i.distribution==="portable"?(e.openVerification&&o?.close(),this.authorizePortable(i,e,e.openVerification?null:o)):this.authorizeWeb(i,e,o)}async authorizeWeb(e,n,i){let{verifier:o,challenge:r}=await dt(),a=X(24),s=crypto.randomUUID(),c=n.target?.kind==="collection"?n.target.collectionId:void 0,l=`grant:${e.id}:${a}`,u=await this.keyStore.create(l),p;try{p=await this.loadApplicationIdentity(e)}catch(m){throw await this.keyStore.delete(l),m}let f=On(e,n),h=Tn(e.requirements),y=new Date,R=await gt({protocol_version:ee,authorization_id:s,application_id:e.id,application_declaration_id:ft(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await Ve(p),installation_signing_public_key:p.signingPublicKey,grant_agreement_public_key:u.agreementPublicKey,grant_signing_public_key:u.signingPublicKey,flow:"authorization_code",authorization_nonce:X(32),issued_at:y.toISOString(),expires_at:new Date(y.getTime()+600*1e3).toISOString(),redirect_uri:this.redirectUri,state:a,code_challenge:r,contracts:Rn(f,h,ii(this.storage,this.storagePrefix(),f,c),B(e.requirements)),requested_operations:f,...h?{requested_files:h}:{},...c?{collection_id:c}:{}},p),C={version:1,verifier:o,state:a,clientId:e.id,redirectUri:this.redirectUri,relayEncryption:this.relayEncryption,collectionId:c,returnTo:n.returnTo,keyHandle:l,authorizationId:s,applicationAgreementPublicKey:u.agreementPublicKey,applicationSigningPublicKey:u.signingPublicKey,...n.presentation==="popup"&&i?{presentation:"popup"}:{}};this.storage.setItem(this.pendingKey(a),JSON.stringify(C));try{let m=await fetch(`${this.serverUrl}/oauth/authorization_request`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.id,redirect_uri:this.redirectUri,code_challenge:r,code_challenge_method:"S256",state:a,operations:f.join(","),...c?{collection_id:c}:{},application_authorization:JSON.stringify(R)}),signal:n.signal}),v=await E(m,"invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(!m.ok)throw z(v,"device_authorization_failed","Application authorization could not be started.",m.status);if(typeof v.authorization_uri!="string"||v.authorization_id!==s||!Number.isInteger(v.expires_in)||v.expires_in<=0)throw d("invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(n.presentation==="popup"&&i)return i.location.href=v.authorization_uri,await Er({storage:this.storage,storagePrefix:this.storagePrefix(),state:a,pending:C,popup:i,signal:n.signal,keyStore:this.keyStore,connection:_=>this.connection(_)});if(i?.close(),this.navigate)await this.navigate(v.authorization_uri);else if(typeof location<"u")location.assign(v.authorization_uri);else throw d("browser_required","Authorization navigation requires a browser environment.");return{kind:"redirecting"}}catch(m){throw i?.close(),this.storage.removeItem(this.pendingKey(a)),await this.keyStore.delete(l),n.signal?.aborted?Ue(n.signal,"Application authorization was cancelled.",m):m}}async authorizePortable(e,n,i){if(this.relayEncryption!=="required")throw i?.close(),d("encryption_required","Downloaded applications require encrypted relay authorization.");let{verifier:o,challenge:r}=await dt(),a=`grant:${e.id}:${X(24)}`,s=await this.keyStore.create(a),c;try{c=await this.loadApplicationIdentity(e)}catch(v){throw i?.close(),await this.keyStore.delete(a),v}let l=On(e,n),u=Tn(e.requirements),p=crypto.randomUUID(),f=new Date,h=await gt({protocol_version:ee,authorization_id:p,application_id:e.id,application_declaration_id:ft(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await Ve(c),installation_signing_public_key:c.signingPublicKey,grant_agreement_public_key:s.agreementPublicKey,grant_signing_public_key:s.signingPublicKey,flow:"device_code",authorization_nonce:X(32),issued_at:f.toISOString(),expires_at:new Date(f.getTime()+600*1e3).toISOString(),code_challenge:r,contracts:Rn(l,u,ii(this.storage,this.storagePrefix(),l,n.target?.kind==="collection"?n.target.collectionId:void 0),B(e.requirements)),requested_operations:l,...u?{requested_files:u}:{},...n.target?.kind==="collection"?{collection_id:n.target.collectionId}:{}},c),y,R;try{y=await fetch(`${this.serverUrl}/oauth/device_authorization`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.id,operations:l.join(","),...n.target?.kind==="collection"?{collection_id:n.target.collectionId}:{},code_challenge:r,code_challenge_method:"S256",application_authorization:JSON.stringify(h)}),signal:n.signal}),R=await E(y,"invalid_device_authorization_response","The authorization service returned an invalid device authorization response.")}catch(v){throw i?.close(),await this.keyStore.delete(a),d("device_authorization_failed","Downloaded application authorization could not be started.",{cause:v})}if(!y.ok)throw i?.close(),await this.keyStore.delete(a),z(R,"device_authorization_failed","Downloaded application authorization could not be started.",y.status);let C;try{C=mo(R)}catch(v){throw i?.close(),await this.keyStore.delete(a),n.signal?.aborted?Ue(n.signal,"Downloaded application authorization was cancelled.",v):v}if(n.onDeviceCode?.(C),n.openVerification)await n.openVerification(C);else if(i)try{i.location.href=C.verificationUriComplete}catch{}else throw await this.keyStore.delete(a),d("approval_window_blocked","The approval window was blocked. Show the provided verification link and code, then try again.",{details:{user_code:C.userCode,verification_uri:C.verificationUri,verification_uri_complete:C.verificationUriComplete,expires_at:C.expiresAt,interval_seconds:C.intervalSeconds}});let m=C.intervalSeconds;try{for(;Date.now()<C.expiresAt;){if(await Z(m*1e3,n.signal),n.signal?.aborted)throw Ue(n.signal,"Downloaded application authorization was cancelled.");let v;try{v=await fetch(`${this.serverUrl}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:R.device_code,client_id:e.id,code_verifier:o}),signal:n.signal})}catch(S){if(n.signal?.aborted)throw Ue(n.signal,"Downloaded application authorization was cancelled.",S);continue}let _=await E(v,"invalid_token_response","The authorization service returned an invalid token response.");if(!v.ok){let S=ut(_);if(S==="authorization_pending")continue;if(S==="slow_down"){m+=5;continue}throw z(_,"token_exchange_failed","Downloaded application authorization could not be completed.",v.status)}let A=pt(_.authority,_.collection_id),T=_.encryption&&_.encryption.protocol_version===Ot&&_.encryption.suite===tt&&_.encryption.application_agreement_public_key===s.agreementPublicKey;if(_.application_origin!=="null")throw d("invalid_token_response","Authorization did not bind the portable grant to its opaque application origin.");if(_.authority&&(!A||_.encryption!=null||_.authority.proof_public_key!==s.signingPublicKey))throw d("invalid_token_response","Authorization returned a remote authority capability that is not bound to this portable grant key.");if(!_.authority&&!T)throw d("encryption_required","Authorization did not establish the expected key-bound local portable grant.");let O=this.storeTokenResponse(_,e.id,a);if(n.target?.kind==="collection"&&n.target.collectionId!==O.collectionId)throw this.removeToken(O.collectionId,O.keyHandle),d("collection_mismatch","The approved collection does not match the collection requested by this link.");return i?.close(),{kind:"connected",connection:this.connection(O.collectionId),...n.returnTo?{returnTo:n.returnTo}:{}}}throw d("expired_token","The downloaded application authorization code expired.")}catch(v){throw i?.close(),await this.keyStore.delete(a),n.signal?.aborted?Ue(n.signal,"Downloaded application authorization was cancelled.",v):v}}completeAuthorization(e,n={}){let i=Nt(e);if(!i)return Promise.reject(d("invalid_callback","Authorization callback is missing its state."));let o=M(this.storage.getItem(this.pendingKey(i))),r=o?.presentation==="popup";return this.completionPromises.run(i,n,this.timeouts.requestMs,a=>qr({storage:this.storage,storagePrefix:this.storagePrefix(),state:i,pending:o,popupAttempt:r,completion:this.performAuthorizationCompletion(e,i,a)}))}async performAuthorizationCompletion(e,n,i){let o=new URL(e),r=o.searchParams.get("code"),a=this.pendingKey(n),s=M(this.storage.getItem(a));if(!s||s.version!==1||n!==s.state)throw d("invalid_callback","Authorization callback is missing or does not match this browser session.");if(o.searchParams.has("error"))throw s.keyHandle&&await this.keyStore.delete(s.keyHandle),this.storage.removeItem(a),U(o.searchParams.get("error")??"access_denied",o.searchParams.get("error_description")??"Collection access was not approved.",{details:s.returnTo?{return_to:s.returnTo}:void 0});if(!r)throw d("invalid_callback","Authorization callback is missing its code.");let c=await ae(`${this.serverUrl}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:r,client_id:s.clientId,redirect_uri:s.redirectUri,code_verifier:s.verifier}),signal:i},"temporarily_unavailable","Authorization completion is temporarily unavailable."),l=await E(c,"invalid_token_response","The authorization service returned an invalid token response.");if(!c.ok)throw z(l,"token_exchange_failed","Authorization could not be completed.",c.status);if(s.relayEncryption==="required"&&!l.authority&&(!l.encryption||!s.keyHandle||l.encryption.application_agreement_public_key!==s.applicationAgreementPublicKey))throw s.keyHandle&&await this.keyStore.delete(s.keyHandle),this.storage.removeItem(a),d("encryption_required","Authorization did not establish the required encrypted relay grant.");if(l.authority?.proof_public_key){if(!s.keyHandle||!s.applicationSigningPublicKey||l.authority.proof_public_key!==s.applicationSigningPublicKey)throw s.keyHandle&&await this.keyStore.delete(s.keyHandle),this.storage.removeItem(a),d("invalid_token_response","Authorization returned a remote authority capability bound to another application key.")}else l.authority&&s.keyHandle&&await this.keyStore.delete(s.keyHandle);let u=this.storeTokenResponse(l,s.clientId,l.authority?.proof_public_key?s.keyHandle:l.authority?void 0:s.keyHandle);if(s.collectionId&&s.collectionId!==u.collectionId)throw this.removeToken(u.collectionId,u.keyHandle),this.storage.removeItem(a),d("collection_mismatch","The approved collection does not match the collection requested by this link.");return this.storage.removeItem(a),{connection:this.connection(u.collectionId),...s.returnTo?{returnTo:s.returnTo}:{}}}connections(){let e=[];for(let n of un(this.storage,this.storagePrefix())){let i=this.connection(n)?.info();i&&e.push(i)}return e.sort((n,i)=>n.displayName.localeCompare(i.displayName)||n.collectionId.localeCompare(i.collectionId))}connection(e){if(!this.storage.getItem(this.tokenKey(e)))return null;let n=this.connectionCache.get(e);return n||(n=new Ye(this,e),this.connectionCache.set(e,n)),n.info()?n:null}unavailableReason(e){return this.invalidatedConnections.get(e)??null}connectionApplicationId(e){if(!this.connection(e))return null;let n=M(this.storage.getItem(this.tokenKey(e)));return typeof n?.clientId=="string"&&n.clientId.length>0?n.clientId:null}onConnectionsChange(e){return this.listeners.add(e),e(this.connections()),()=>this.listeners.delete(e)}storeTokenResponse(e,n,i){let o=e.collection_id;if(typeof o!="string")throw d("invalid_token_response","Authorization returned no collection ID.");let r=M(this.storage.getItem(this.tokenKey(o))),a=Ur(this.storage,this.pendingMutationKey(o),r,i,this.grantKeyLeases.handles(o),this.grantKeyLeases.retainAutomaticallyRetiredKeys),s;try{s=Dr({body:e,clientId:n,keyHandle:i,previous:r,retiredKeyHandles:a.retained,defaultApplicationOrigin:this.defaultApplicationOrigin(),pinConnectorIdentity:(c,l)=>this.pinConnectorIdentity(c,l)})}catch(c){throw c instanceof b&&c.code==="legacy_scope_reauthorization_required"&&this.removeToken(o,i,c.code),c}this.storage.setItem(this.tokenKey(o),JSON.stringify(s));for(let c of a.disposable)this.deleteGrantKeyWhenUnused(o,c);return Or(this.storage,this.storagePrefix(),o),this.invalidatedConnections.delete(o),this.connectionCache.delete(o),this.emitConnections(),s}forgetConnectorIdentity(e){this.storage.removeItem(this.connectorPinKey(e))}pinConnectorIdentity(e,n){let i=this.connectorPinKey(e),o=M(this.storage.getItem(i));if(o&&(o.version!==1||o.publicKey!==n))throw d("connector_identity_changed","The connector identity changed since this application first connected. Forget the saved connector identity only after verifying the computer, then authorize again.");o||this.storage.setItem(i,JSON.stringify({version:1,publicKey:n}))}connectorPinKey(e){return`mdbase-connect:${this.serverUrl}:connector-pin:${e}`}async loadApplicationIdentity(e){try{return await Bt(this.identityStore,this.serverUrl,e)}catch(n){throw d("application_identity_unavailable",n instanceof Ae?n.message:"The application installation identity is unavailable.",{cause:n})}}removeToken(e,n,i="authorization_lost",o=!1){this.invalidatedConnections.set(e,i);let r=M(this.storage.getItem(this.tokenKey(e))),a=ai(r,n);this.storage.removeItem(this.tokenKey(e)),o&&Fr(this.storage,this.pendingMutationKey(e),s=>a.add(s));for(let s of a)this.deleteGrantKeyWhenUnused(e,s);for(let s of["web_push","fcm"])this.storage.removeItem(this.notificationKey(e,s));Tr(this.storage,this.storagePrefix(),e),this.connectionCache.delete(e),this.emitConnections()}acquireGrantKeyLease(e,n,i){return this.grantKeyLeases.acquire(e,n,i)}deleteGrantKeyWhenUnused(e,n){this.grantKeyLeases.deleteExclusive(e,n,()=>Lr(this.storage,this.keyStore,this.pendingMutationKey(e),this.tokenKey(e),n))}tokenKey(e){return`${this.storagePrefix()}:token:${e}`}pendingMutationKey(e){return`${this.storagePrefix()}:pending-mutation:${e}`}notificationKey(e,n="web_push"){return`${this.storagePrefix()}:notifications:${e}:${n}`}directPreferenceKey(){return`mdbase-connect:direct:${this.defaultApplicationOrigin()}`}defaultApplicationOrigin(){return _o(this.manifest,this.manifestSource,this.redirectUri,this.application?.distribution==="portable")}pendingKey(e){return`${this.storagePrefix()}:pending:${e}`}storagePrefix(){return`mdbase-connect:${this.serverUrl}:${this.manifestSource}`}emitConnections(){let e=this.connections();for(let n of this.listeners)n(e)}};var fn=class{internals;constructor(e){this.internals=new pn(e)}register(e){return D(()=>this.internals.register(e),Se)}authorize(e={}){return D(()=>this.internals.authorize(e),fe)}application(e){return new Ne(this,e,this.internals.timeouts)}manifest(e){return D(()=>this.internals.manifestDeclaration(e),Se)}environment(){return this.internals.environment()}completeAuthorization(e,n){return D(()=>this.internals.completeAuthorization(e===void 0?Ut():String(e),n),fe)}connections(){return this.internals.connections()}connection(e){return this.internals.connection(e)}unavailableReason(e){return this.internals.unavailableReason(e)}connectionApplicationId(e){return this.internals.connectionApplicationId(e)}onConnectionsChange(e){return this.internals.onConnectionsChange(e)}forgetAll(){for(let e of this.connections())this.connection(e.collectionId)?.forget()}forgetConnectorIdentity(e){this.internals.forgetConnectorIdentity(e)}};function si(t){if(!t||typeof t!="object")throw d("invalid_push_payload","The push payload is not an object.");let e=t;if(e.type!=="mdbase.notification"||e.version!==1||typeof e.signal_id!="string"||typeof e.criterion_id!="string"||typeof e.cursor!="string"||!e.presentation||typeof e.presentation.title!="string")throw d("invalid_push_payload","The push payload is not an mdbase notification.");return e}function Nr(t){if(!t||typeof t!="object")throw d("invalid_push_payload","The native notification data is not an object.");let e=t;if(e.type!=="mdbase.notification"||e.version!==1&&e.version!=="1"||typeof e.signal_id!="string"||typeof e.criterion_id!="string"||typeof e.cursor!="string")throw d("invalid_push_payload","The native notification data is not an mdbase notification.");return{type:"mdbase.notification",version:1,signal_id:e.signal_id,criterion_id:e.criterion_id,cursor:e.cursor}}function Br(t,e){let n=si(e);return t.showNotification(n.presentation.title,{...n.presentation.body?{body:n.presentation.body}:{},...n.presentation.tag?{tag:n.presentation.tag}:{},data:{type:n.type,signal_id:n.signal_id,criterion_id:n.criterion_id,cursor:n.cursor}})}function jr(t){return{subscribe:e=>t.subscribe(e),getSnapshot:()=>t.getSnapshot()}}var hn=class{collectionParameter;fallbackPath;listeners=new Set;handlePopState=()=>this.emit();constructor(e={}){this.collectionParameter=e.collectionParameter??"collection",this.fallbackPath=e.fallbackPath??"/"}selectedCollectionId(){return this.currentUrl().searchParams.get(this.collectionParameter)}select(e,n={}){let i=ht(this.currentUrl());e?i.searchParams.set(this.collectionParameter,e):i.searchParams.delete(this.collectionParameter);let o=this.browserHistory();o[n.history==="push"?"pushState":"replaceState"](o.state,"",i),this.emit()}authorizationReturnTo(){let e=ht(this.currentUrl());return`${e.pathname}${e.search}${e.hash}`}authorizationCallback(){let e=this.currentUrl().href;return Lt(e)?e:null}finishAuthorization(e,n){let i=this.safeAppUrl(e??this.fallbackPath);ht(i),i.searchParams.set(this.collectionParameter,n),this.browserHistory().replaceState(null,"",i),this.emit()}clearAuthorizationCallback(e){let n=e?this.safeAppUrl(e):this.currentUrl(),i=this.browserHistory();i.replaceState(i.state,"",ht(n)),this.emit()}subscribe(e){let n=this.listeners.size===0;return this.listeners.add(e),n&&typeof window<"u"&&window.addEventListener("popstate",this.handlePopState),()=>{this.listeners.delete(e),this.listeners.size===0&&typeof window<"u"&&window.removeEventListener("popstate",this.handlePopState)}}emit(){for(let e of this.listeners)e()}safeAppUrl(e){let n=this.currentUrl(),i=new URL(e,n.origin);return i.origin===n.origin?i:new URL(this.fallbackPath,n.origin)}currentUrl(){if(typeof location>"u")throw d("browser_required","Browser selection requires a browser environment.");return new URL(location.href)}browserHistory(){if(typeof history>"u")throw d("browser_required","Browser selection requires a browser environment.");return history}},yn=class{collectionId=null;listeners=new Set;selectedCollectionId(){return this.collectionId}select(e){if(e!==this.collectionId){this.collectionId=e;for(let n of this.listeners)n()}}authorizationReturnTo(){}authorizationCallback(){return null}finishAuthorization(e,n){this.select(n)}clearAuthorizationCallback(){}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};return Jr(uc);})();
1
+ "use strict";var MdbaseConnect=(()=>{var mn=Object.defineProperty;var $r=Object.getOwnPropertyDescriptor;var Wr=Object.getOwnPropertyNames;var Jr=Object.prototype.hasOwnProperty;var Yr=(t,e)=>{for(var n in e)mn(t,n,{get:e[n],enumerable:!0})},Qr=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Wr(e))!Jr.call(t,o)&&o!==n&&mn(t,o,{get:()=>e[o],enumerable:!(i=$r(e,o))||i.enumerable});return t};var Xr=t=>Qr(mn({},"__esModule",{value:!0}),t);var hc={};Yr(hc,{ApplicationIdentityStoreError:()=>Re,FileTransferCryptoError:()=>se,GrantFileTransferCipher:()=>He,IndexedDbApplicationIdentityStore:()=>je,IndexedDbGrantKeyStore:()=>Ee,MDBASE_RECORD_CREATED_CONTRACT:()=>xi,MDBASE_TIMER_FIRED_CONTRACT:()=>Ei,MdbaseApplicationSession:()=>Ne,MdbaseBrowserSelection:()=>hn,MdbaseCollectionClient:()=>Ge,MdbaseConnect:()=>fn,MdbaseConnectError:()=>b,MdbaseConnection:()=>Qe,MdbaseFileClient:()=>Ye,MdbaseMemorySelection:()=>yn,MdbaseMemoryVerificationStore:()=>mt,MdbaseSession:()=>Le,MemoryApplicationIdentityStore:()=>Ke,MemoryGrantKeyStore:()=>qe,RelayCryptoError:()=>x,applicationIdentity:()=>Bt,applicationInstallationId:()=>Ve,authorityProofMessage:()=>Fn,connectError:()=>d,connectFailure:()=>g,connectProblem:()=>w,connectSuccess:()=>I,createPkce:()=>dt,decryptRelayResponse:()=>ze,deriveFileTransferKey:()=>Gn,deriveP256SharedSecret:()=>st,effectiveCapabilities:()=>kt,encryptRelayRequest:()=>oe,externalStore:()=>Gr,isRetryableConnectError:()=>Di,operationProblem:()=>ke,operationsForApplicationCapabilities:()=>li,parseMdbaseNativeNotificationData:()=>Kr,parseMdbasePushPayload:()=>ci,showMdbasePushNotification:()=>Vr,signApplicationAuthorization:()=>gt,signAuthorityRequest:()=>Et,validateGrantEncryption:()=>re});var bt={"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"]},Ct=["assess_collection_setup","apply_collection_setup"];function li(t,e={}){let n=e.includeOptional===!1?t.required:[...t.required,...t.optional??[]];return[...new Set(n.flatMap(i=>bt[i]))]}var Zr=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([])});function W(t,e){let n=t===1?Zr:t===2?bt:void 0;if(!(!n||!Object.hasOwn(n,e)))return[...n[e]]}var gc=Object.freeze([1,2]),di="application-authorization-v2-issuance",gn=Object.freeze(["application-authorization-v2-issuance"]);var be={access_denied:{category:"authorization",recovery:"reauthorize"},access_paused:{category:"availability",recovery:"resume_connector_access"},application_declaration_mismatch:{category:"authorization",recovery:"reauthorize"},application_identity_unavailable:{category:"compatibility",recovery:"upgrade_application"},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_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_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_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_request:{category:"validation",recovery:"fix_request"},invalid_token_response:{category:"integrity",recovery:"contact_support"},legacy_scope_reauthorization_required:{category:"authorization",recovery:"reauthorize"},managed_fcm_not_declared:{category:"compatibility",recovery:"fix_request"},manifest_load_failed:{category:"availability",recovery:"retry"},manifest_required:{category:"validation",recovery:"fix_request"},missing_grant_key:{category:"authorization",recovery:"reauthorize"},mutation_recovery_expired:{category:"compatibility",recovery:"none"},mutation_request_conflict:{category:"conflict",recovery:"resolve_conflict"},no_pending_mutation:{category:"conflict",recovery:"refresh"},not_authorized:{category:"authorization",recovery:"reauthorize"},not_remote_authority:{category:"compatibility",recovery:"choose_collection"},notification_criterion_not_declared:{category:"validation",recovery:"fix_request"},notification_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"},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"},sandbox_unsupported:{category:"compatibility",recovery:"fix_request"},scope_denied:{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"},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"}},ea={access_denied:{type:"object",required:[],properties:{return_to:{type:"string"}}},approval_window_blocked:{type:"object",required:["user_code","verification_uri","verification_uri_complete","expires_at","interval_seconds"],properties:{user_code:{type:"string"},verification_uri:{type:"string"},verification_uri_complete:{type:"string"},expires_at:{type:"integer"},interval_seconds:{type:"integer"}}},authorization_binding_incompatible:{type:"object",required:["contract","required","supported","peer"],properties:{contract:{type:"string"},required:{type:"array",items:{type:"integer"}},supported:{type:"array",items:{type:"integer"}},peer:{type:"string"},operation:{type:"string"}}},capability_contract_incompatible:{type:"object",required:["contract","required","supported","peer"],properties:{contract:{type:"string"},required:{type:"array",items:{type:"integer"}},supported:{type:"array",items:{type:"integer"}},peer:{type:"string"},operation:{type:"string"}}},collection_configuration_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_contracts_missing:{type:"object",required:["contracts"],properties:{contracts:{type:"array",items:{type:"object",required:["id","version"],properties:{id:{type:"string"},version:{type:"string"}}}}}},collection_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_type_registry_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}}}},collection_version_unsupported:{type:"object",required:["current_version","required_version"],properties:{current_version:{type:"string"},required_version:{type:"string"}}},connector_offline:{type:"object",required:[],properties:{connector_name:{type:"string"}}},durable_mutation_unsupported:{type:"object",required:["contract","required","supported","peer"],properties:{contract:{type:"string"},required:{type:"array",items:{type:"integer"}},supported:{type:"array",items:{type:"integer"}},peer:{type:"string"},operation:{type:"string"}}},insufficient_access:{type:"object",required:["required_operations","granted_operations","missing_operations"],properties:{required_operations:{type:"array",items:{type:"string"}},granted_operations:{type:"array",items:{type:"string"}},missing_operations:{type:"array",items:{type:"string"}}}},invalid_application_manifest:{type:"object",required:["issues"],properties:{issues:{type:"array",items:{type:"object",required:["path","keyword","message","params"],properties:{path:{type:"string"},keyword:{type:"string"},message:{type:"string"},params:{type:"object"}}}}}},mutation_request_conflict:{type:"object",required:["request_id"],properties:{request_id:{type:"string"}}},operation_invalid:{type:"object",required:["diagnostics"],properties:{diagnostics:{type:"array",items:{type:"object"}},partial_result:{}}},operation_outcome_unknown:{type:"object",required:["request_id"],properties:{request_id:{type:"string"}}},rate_limited:{type:"object",required:[],properties:{retry_after_ms:{type:"integer"}}},transport_protocol_incompatible:{type:"object",required:["contract","required","supported","peer"],properties:{contract:{type:"string"},required:{type:"array",items:{type:"integer"}},supported:{type:"array",items:{type:"integer"}},peer:{type:"string"},operation:{type:"string"}}}};function ui(t){return Object.hasOwn(be,t)}function Xe(t){if(!pi(t))return!1;let e=t;if(e.problem_version!==1||typeof e.message!="string"||e.message.length===0||e.operation_outcome!==void 0&&e.operation_outcome!=="not_sent"&&e.operation_outcome!=="rejected"&&e.operation_outcome!=="unknown"||e.trace_id!==void 0&&(typeof e.trace_id!="string"||e.trace_id.length===0))return!1;if(e.code==="unknown")return typeof e.server_code=="string"&&e.server_code.length>0&&e.category==="unknown"&&e.recovery==="none";if(typeof e.code!="string"||!ui(e.code)||e.server_code!==void 0)return!1;let n=be[e.code],i=ea[e.code],o=i===void 0?e.details===void 0:e.details===void 0?(i.required?.length??0)===0:_n(e.details,i);return e.category===n.category&&e.recovery===n.recovery&&o}function _n(t,e){if(e.type===void 0)return!0;if(e.type==="string")return typeof t=="string";if(e.type==="integer")return typeof t=="number"&&Number.isInteger(t);if(e.type==="number")return typeof t=="number"&&Number.isFinite(t);if(e.type==="boolean")return typeof t=="boolean";if(e.type==="array")return Array.isArray(t)&&t.every(i=>_n(i,e.items??{}));if(!pi(t))return!1;if(!e.properties)return!0;let n=t;return!Object.keys(n).every(i=>Object.hasOwn(e.properties,i))||!(e.required??[]).every(i=>Object.hasOwn(n,i))?!1:Object.entries(n).every(([i,o])=>_n(o,e.properties[i]))}function pi(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function bn(t,e,n={}){if(ui(t)){let i=be[t],o={problem_version:1,code:t,category:i.category,recovery:i.recovery,message:e,...n.details===void 0?{}:{details:n.details},...n.operation_outcome===void 0?{}:{operation_outcome:n.operation_outcome},...n.trace_id===void 0?{}:{trace_id:n.trace_id}};if(Xe(o))return o}return{problem_version:1,code:"unknown",server_code:t,category:"unknown",recovery:"none",message:e,...n.details===void 0?{}:{details:n.details},...n.operation_outcome===void 0?{}:{operation_outcome:n.operation_outcome},...n.trace_id===void 0?{}:{trace_id:n.trace_id}}}var fi=new Uint8Array([77,68,66,70]),hi=1,yi=0,Cc=new Uint8Array([77,68,66,82]);var mi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function gi(t,e={}){return{actions:[...new Set([...t.required,...e.includeOptional===!1?[]:t.optional??[]])],scope:structuredClone(t.scope)}}var k=class extends Error{code;constructor(e,n){super(n),this.code=e,this.name="FileFrameError"}};function ta(t){return t==="upload_chunk"?1:2}function na(t){if(t===1)return"upload_chunk";if(t===2)return"download_chunk";throw new k("invalid_kind",`Unknown file frame kind ${t}`)}function ia(t){if(!t||typeof t!="object"||Array.isArray(t))throw new k("invalid_header","File frame header must be a JSON object");return t}function wt(t,e){let n=t[e];if(typeof n!="string"||n.length===0)throw new k("invalid_header",`File frame header ${e} must be a non-empty string`);return n}function vt(t,e){let n=wt(t,e);if(!mi.test(n))throw new k("invalid_header",`File frame header ${e} must be a UUID`);return n}function Ce(t,e,n=Number.MAX_SAFE_INTEGER){let i=t[e];if(!Number.isSafeInteger(i)||i<0||i>n)throw new k("invalid_header",`File frame header ${e} is outside its allowed range`);return i}function Cn(t){if(t.protocol_version!==1)throw new k("unsupported_version",`Unsupported file transfer protocol ${t.protocol_version}`);if(t.protection!=="grant_aead_v1"&&t.protection!=="transport_tls")throw new k("invalid_header","Unknown file transfer protection");if(t.direction!=="upload"&&t.direction!=="download")throw new k("invalid_header","Unknown file transfer direction");for(let[e,n]of[["grant_id",t.grant_id],["authority_id",t.authority_id],["collection_id",t.collection_id],["transfer_id",t.transfer_id]])if(!mi.test(n))throw new k("invalid_header",`File frame header ${e} must be a UUID`);for(let[e,n,i]of[["chunk_size",t.chunk_size,4194304],["chunk_index",t.chunk_index,Number.MAX_SAFE_INTEGER],["offset",t.offset,Number.MAX_SAFE_INTEGER],["plaintext_length",t.plaintext_length,4194304],["total_size",t.total_size,Number.MAX_SAFE_INTEGER]])if(!Number.isSafeInteger(n)||n<0||n>i)throw new k("invalid_header",`File frame header ${e} is outside its allowed range`);if(t.chunk_size<64*1024)throw new k("invalid_header","File frame chunk_size is below the protocol minimum");if(!Number.isSafeInteger(t.scope_epoch)||t.scope_epoch<1)throw new k("invalid_header","File frame header scope_epoch must be a positive integer");if(t.protection==="grant_aead_v1"&&!t.key_id)throw new k("invalid_header","AEAD-protected file frames require key_id");return{protocol_version:1,protection:t.protection,grant_id:t.grant_id,authority_id:t.authority_id,collection_id:t.collection_id,transfer_id:t.transfer_id,direction:t.direction,chunk_size:t.chunk_size,chunk_index:t.chunk_index,offset:t.offset,plaintext_length:t.plaintext_length,total_size:t.total_size,scope_epoch:t.scope_epoch,...t.key_id===void 0?{}:{key_id:t.key_id}}}function oa(t){let e;try{e=new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{throw new k("invalid_header","File frame header is not valid UTF-8")}let n;try{n=ia(JSON.parse(e))}catch(l){throw l instanceof k?l:new k("invalid_header","File frame header is not valid JSON")}let i=new Set(["protocol_version","protection","grant_id","authority_id","collection_id","transfer_id","direction","chunk_size","chunk_index","offset","plaintext_length","total_size","scope_epoch","key_id"]);if(Object.keys(n).some(l=>!i.has(l)))throw new k("invalid_header","File frame header contains an unknown field");let o=Ce(n,"protocol_version");if(o!==1)throw new k("unsupported_version",`Unsupported file transfer protocol ${o}`);let r=wt(n,"protection"),a=wt(n,"direction"),s=n.key_id===void 0?void 0:wt(n,"key_id"),c=Cn({protocol_version:1,protection:r,grant_id:vt(n,"grant_id"),authority_id:vt(n,"authority_id"),collection_id:vt(n,"collection_id"),transfer_id:vt(n,"transfer_id"),direction:a,chunk_size:Ce(n,"chunk_size",4194304),chunk_index:Ce(n,"chunk_index"),offset:Ce(n,"offset"),plaintext_length:Ce(n,"plaintext_length",4194304),total_size:Ce(n,"total_size"),scope_epoch:Ce(n,"scope_epoch"),...s===void 0?{}:{key_id:s}});if(JSON.stringify(c)!==e)throw new k("invalid_header","File frame header must use the canonical field order without duplicate fields or whitespace");return c}function vn(t,e,n){let i=t==="upload_chunk"?"upload":"download";if(e.direction!==i)throw new k("invalid_header",`Frame kind ${t} requires direction ${i}`);let o=e.chunk_index*e.chunk_size;if(!Number.isSafeInteger(o)||e.offset!==o)throw new k("invalid_header","Chunk offset does not match its index and protocol chunk size");if(e.offset+e.plaintext_length>e.total_size)throw new k("invalid_header","Chunk extends past the declared transfer size");let r=e.protection==="grant_aead_v1"?e.plaintext_length+16:e.plaintext_length;if(n!==r)throw new k("invalid_length","Payload length does not match the protected plaintext length")}function ra(t){return t.plaintext_length+(t.protection==="grant_aead_v1"?16:0)}function St(t,e){let n=Cn(e),i=ra(n);vn(t,n,i);let o=new TextEncoder().encode(JSON.stringify(n));if(o.byteLength>16384)throw new k("limit_exceeded","File frame header exceeds the protocol limit");let r=new Uint8Array(16+o.byteLength);r.set(fi,0);let a=new DataView(r.buffer,r.byteOffset,r.byteLength);return a.setUint8(4,hi),a.setUint8(5,ta(t)),a.setUint16(6,yi,!1),a.setUint32(8,o.byteLength,!1),a.setUint32(12,i,!1),r.set(o,16),r}function _i(t){let e=Cn(t.header);if(vn(t.kind,e,t.payload.byteLength),t.payload.byteLength>4194320)throw new k("limit_exceeded","File frame payload exceeds the protocol limit");let n=St(t.kind,e),i=new Uint8Array(n.byteLength+t.payload.byteLength);return i.set(n,0),i.set(t.payload,n.byteLength),i}function At(t,e={}){if(t.byteLength<16)throw new k("invalid_length","File frame is shorter than its fixed prefix");if(!fi.every((f,h)=>t[h]===f))throw new k("invalid_magic","File frame magic is not MDBF");let n=new DataView(t.buffer,t.byteOffset,t.byteLength),i=n.getUint8(4);if(i!==hi)throw new k("unsupported_version",`Unsupported file frame version ${i}`);let o=na(n.getUint8(5));if(n.getUint16(6,!1)!==yi)throw new k("unsupported_flags","File frame uses unsupported flags");let r=n.getUint32(8,!1),a=n.getUint32(12,!1),s=e.maxHeaderBytes??16384,c=e.maxPayloadBytes??4194320;if(r===0)throw new k("invalid_length","File frame header must not be empty");if(r>s||a>c)throw new k("limit_exceeded","File frame exceeds the configured decode limits");let l=16+r+a;if(!Number.isSafeInteger(l)||l!==t.byteLength)throw new k("invalid_length","File frame lengths do not match the supplied bytes");let u=16+r,p=oa(t.subarray(16,u));return vn(o,p,a),{kind:o,header:p,payload:t.slice(u)}}var aa=["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"],sa=["list_files","open_file_upload","open_file_download","move_file","delete_file","get_file_transfer_status","commit_file_upload","abort_file_transfer"],ca={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"},la={describe:1,changes:1,read:1,query:1,list_views:1,execute_view:1,read_view_source:1,create_view_source:1,update_view_source:1,delete_view_source:1,validate:1,create:1,update:1,delete:1,rename:1,read_type:1,create_type:1,update_type:1,assess_type_pack:1,apply_type_pack:1,assess_collection_setup:1,apply_collection_setup:1,list_timers:1,put_timer:1,cancel_timer:1,reconcile_timers:1,sync:1},da={list_files:1,open_file_upload:1,open_file_download:1,move_file:1,delete_file:1,get_file_transfer_status:1,commit_file_upload:1,abort_file_transfer:1},ua=new Set(["open_file_upload","move_file","delete_file","commit_file_upload","abort_file_transfer"]),pa=new Set(["delete","rename"]);var fa=new Set(aa),ha=new Set(sa);function bi(t){return fa.has(t)}function ya(t){return ha.has(t)}function Ci(t,e){if(t==="file_control"){let n=vi(e)&&typeof e.type=="string"?e.type:"";if(!ya(n))throw new Error(`Unknown file-control message: ${n}`);return da[n]}return la[t]}function de(t,e){let n=vi(e)?e:{};if(n.dry_run===!0&&pa.has(t))return null;if(t==="file_control"){let o=typeof n.type=="string"?n.type:"";return ua.has(o)?`file_control:${o}`:null}let i=ca[t];return i==="always"?t:i==="sync_action"&&n.action==="mutate"?"sync:mutate":null}function ue(t,e){return de(t,e)!==null}function vi(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var ma=1,ga="mdbase-connect mutation fingerprint v1\0",wn=new TextEncoder;function _a(t){return Sn(t,new Set)}function ba(t,e){let n=de(t,e);if(n===null)throw new TypeError("The operation is not a canonical mutation.");let i=wn.encode(n),o=wn.encode(_a(e)),r=wn.encode(ga),a=new Uint8Array(r.length+4+8+i.length+4+8+o.length),s=new DataView(a.buffer),c=0;return a.set(r,c),c+=r.length,s.setUint32(c,ma,!1),c+=4,c=Si(a,s,c,i),s.setUint32(c,Ci(t,e),!1),c+=4,Si(a,s,c,o),a}async function Ai(t,e){let n=new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",ba(t,e).buffer));return Ca(n)}function Sn(t,e){if(t===null)return"null";if(t===!0)return"true";if(t===!1)return"false";if(typeof t=="string")return wi(t),JSON.stringify(t);if(typeof t=="number"){if(!Number.isFinite(t))throw new TypeError("Mutation input numbers must be finite.");return JSON.stringify(t)}if(typeof t!="object")throw new TypeError(`Mutation input contains unsupported ${typeof t}.`);if(e.has(t))throw new TypeError("Mutation input must not contain cycles.");e.add(t);try{if(Array.isArray(t)){if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("Mutation input must not contain symbol properties.");let o=[];for(let r=0;r<t.length;r+=1){if(!Object.hasOwn(t,r))throw new TypeError("Mutation input arrays must not be sparse.");o.push(Sn(t[r],e))}return`[${o.join(",")}]`}let n=Object.getPrototypeOf(t);if(n!==Object.prototype&&n!==null)throw new TypeError("Mutation input objects must be plain JSON objects.");if(Object.getOwnPropertySymbols(t).length>0)throw new TypeError("Mutation input must not contain symbol properties.");let i=Object.entries(t);for(let[o]of i)wi(o);return i.sort(([o],[r])=>o<r?-1:o>r?1:0),`{${i.map(([o,r])=>{let a=Object.getOwnPropertyDescriptor(t,o);if(!a||a.get||a.set)throw new TypeError("Mutation input must not contain accessor properties.");return`${JSON.stringify(o)}:${Sn(r,e)}`}).join(",")}}`}finally{e.delete(t)}}function wi(t){for(let e=0;e<t.length;e+=1){let n=t.charCodeAt(e);if(n>=55296&&n<=56319){let i=t.charCodeAt(e+1);if(!(i>=56320&&i<=57343))throw new TypeError("Mutation input strings must not contain lone surrogates.");e+=1}else if(n>=56320&&n<=57343)throw new TypeError("Mutation input strings must not contain lone surrogates.")}}function Si(t,e,n,i){return e.setBigUint64(n,BigInt(i.length),!1),n+=8,t.set(i,n),n+i.length}function Ca(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}var $=3,wa=2,Ri=[$,wa],ee=5,An=4,Pi=[ee,An],Sa=2,Aa=1,Pc={operation_transport:[...Ri],authorization_binding:[...Pi],semantic_capabilities:[Sa,1],durable_mutation:[Aa]};function Rn(t,e,n=[],i=2){let o={operation_transport:$,authorization_binding:ee,semantic_capabilities:i},r=[...new Set(n)].filter(a=>a!==$).sort((a,s)=>s-a);return r.length>0&&(o.operation_transport_recovery=r),(t.some(a=>ue(a,{action:"mutate"}))||e?.actions.some(a=>a!=="list"&&a!=="read")===!0)&&(o.durable_mutation=1),o}function Ze(t){return Ri.includes(t)}function Oi(t){return Pi.includes(t)}var Ra=new TextEncoder().encode("mdbase-connect application installation id v2\0"),Pa=new TextEncoder().encode("mdbase-connect application authorization proof v4\0"),Oa=new TextEncoder().encode("mdbase-connect application authorization proof v5\0");async function ki(t){let e=Rt(t),i=new Uint8Array(await crypto.subtle.digest("SHA-256",ve([Ra,N(e)]))).slice(0,16);return i[6]=i[6]&15|128,i[8]=i[8]&63|128,[et(i.slice(0,4)),et(i.slice(4,6)),et(i.slice(6,8)),et(i.slice(8,10)),et(i.slice(10,16))].join("-")}function Ii(t){let e=[Rt(t.installation_signing_public_key),Rt(t.grant_agreement_public_key),Rt(t.grant_signing_public_key)];if(e.some((c,l)=>e.slice(l+1).some(u=>Ea(c,u))))throw new Error("Application authorization keys must be distinct.");let n=Pn(t.authorization_nonce),i=Pn(t.code_challenge),o=t.contracts,r=o.operation_transport_recovery??[],a=t.requested_operations.some(c=>ue(c,{action:"mutate"}))||t.requested_files?.actions.some(c=>!["list","read"].includes(c))===!0;if(!Oi(t.protocol_version)||n.byteLength!==32||!/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)+$/u.test(t.application_declaration_id)||!/^[0-9a-f]{64}$/u.test(t.application_manifest_digest)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(t.issued_at)||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?Z$/u.test(t.expires_at)||i.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!==t.protocol_version||!Ze(o.operation_transport)||t.protocol_version===ee&&o.operation_transport!==$||r.some(c=>!Ze(c)||c===o.operation_transport)||new Set(r).size!==r.length||t.protocol_version===An&&r.length>0||r.length>0&&!a||(a?o.durable_mutation!==1:o.durable_mutation!==void 0)||t.requested_operations.length===0&&t.requested_files===void 0||new Set(t.requested_operations).size!==t.requested_operations.length||t.requested_operations.some(c=>!c||c.includes("\0"))||(t.flow==="authorization_code"?t.redirect_uri===void 0||t.state===void 0:t.flow!=="device_code"||t.redirect_uri!==void 0||t.state!==void 0))throw new Error("Application authorization binding is invalid.");ka(t.requested_files);let s=t.requested_operations.map(c=>N(new TextEncoder().encode(c)));return ve([t.protocol_version===ee?Oa:Pa,Y(t.protocol_version),N(Pt(t.application_id)),N(Pt(t.authorization_id)),N(new TextEncoder().encode(t.application_declaration_id)),N(Mi(t.application_manifest_digest)),N(Pt(t.application_installation_id)),...e.map(N),N(new TextEncoder().encode(t.flow)),N(n),N(new TextEncoder().encode(t.issued_at)),N(new TextEncoder().encode(t.expires_at)),Ti(t.redirect_uri),Ti(t.state),N(new TextEncoder().encode(t.code_challenge)),Y(o.operation_transport),...t.protocol_version===ee?[Y(r.length),...r.map(Y)]:[],Y(o.authorization_binding),Y(o.semantic_capabilities),Ta(o.durable_mutation),Y(s.length),...s,Ia(t.requested_files),Ma(t.collection_id)])}function Ta(t){return t===void 0?new Uint8Array(1):ve([new Uint8Array([1]),Y(t)])}function ka(t){if(t!==void 0&&(t.actions.length===0||new Set(t.actions).size!==t.actions.length||t.scope.kind==="selected_folders"&&(t.scope.folders.length===0||new Set(t.scope.folders).size!==t.scope.folders.length||t.scope.folders.some(e=>!e||e.includes("\0")))))throw new Error("Application authorization file request is invalid.")}function Ia(t){if(t===void 0)return new Uint8Array(1);let e=t.actions.map(n=>N(new TextEncoder().encode(n)));return ve([new Uint8Array([1]),Y(e.length),...e,N(new TextEncoder().encode(t.scope.kind)),...t.scope.kind==="selected_folders"?[Y(t.scope.folders.length),...t.scope.folders.map(n=>N(new TextEncoder().encode(n)))]:[]])}function Ti(t){return t===void 0?new Uint8Array(1):ve([new Uint8Array([1]),N(new TextEncoder().encode(t))])}function Ma(t){return t===void 0?new Uint8Array(1):ve([new Uint8Array([1]),N(Pt(t))])}function Rt(t){let e=Pn(t);if(e.byteLength!==65||e[0]!==4)throw new Error("Application authorization public key is invalid.");return e}function Pn(t){if(!/^[A-Za-z0-9_-]+$/u.test(t))throw new Error("Invalid base64url value.");let e=t.replaceAll("-","+").replaceAll("_","/"),n=e.padEnd(Math.ceil(e.length/4)*4,"="),i=Uint8Array.from(atob(n),o=>o.charCodeAt(0));if(xa(i)!==t)throw new Error("Non-canonical base64url value.");return i}function Pt(t){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(t))throw new Error("Invalid UUID value.");let e=t.replaceAll("-","");return Mi(e)}function Mi(t){if(!/^[0-9a-f]+$/u.test(t)||t.length%2!==0)throw new Error("Invalid hexadecimal value.");return Uint8Array.from({length:t.length/2},(e,n)=>Number.parseInt(t.slice(n*2,n*2+2),16))}function N(t){return ve([Y(t.byteLength),t])}function Y(t){let e=new Uint8Array(4);return new DataView(e.buffer).setUint32(0,t,!1),e}function ve(t){let e=new Uint8Array(t.reduce((i,o)=>i+o.byteLength,0)),n=0;for(let i of t)e.set(i,n),n+=i.byteLength;return e}function xa(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function Ea(t,e){return t.byteLength===e.byteLength&&t.every((n,i)=>n===e[i])}function et(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}var xi={id:"mdbase.record.created",version:"1.0.0",digest:"sha256:7f3bed6baa356ee9389e977ae7b77a102e2bee871a7c1d9f2026fc21cacdbfc9"};var Ei={id:"mdbase.runtime.timer.fired",version:"1.0.0",digest:"sha256:41105be7a7abf33b31ced47e1e1965242236e40ccaea286b959b0a8c591f5642"};var qi=28485,tt="P256-HKDF-SHA256-AES256GCM",Ot=1;var qa="contract-setup-v1",za="file-relay-v1",Fa="protocol-usage-report-v1",Da="policy-freshness-lease-v1",Ua=["application-authorization-v4","authorization-activation","encrypted-relay","policy-ack"];var La=["durable-mutation-journal-v1","durable-file-lifecycle-v1"],Na="candidate-b-activation-v1",Ec=[...gn,...La,"mutation-replay-after-credential-retirement-v1",Na],Ba="application-declaration-evidence-v1",qc=[...gn,Ba,...Ua,Da,"application-authorization-v5",qa,za,Fa],On=1;var zi="mdbase-authority-request-proof-v1",nt={version:"x-mdbase-proof-version",timestamp:"x-mdbase-proof-timestamp",nonce:"x-mdbase-proof-nonce",signature:"x-mdbase-proof-signature"};var b=class extends Error{constructor(n,i={}){super(n.message,i.cause===void 0?void 0:{cause:i.cause});this.problem=n;this.name="MdbaseConnectError",this.code=n.code,this.status=i.status}problem;code;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 w(t,e,...[n={}]){let i=be[t];return{problem_version:1,code:t,category:i.category,recovery:i.recovery,message:e,...n.details===void 0?{}:{details:n.details},...n.operationOutcome===void 0?{}:{operation_outcome:n.operationOutcome},...n.traceId===void 0?{}:{trace_id:n.traceId}}}function Fi(t,e,n={}){return bn(t,e,{details:n.details,operation_outcome:n.operationOutcome,trace_id:n.traceId})}function d(t,e,...n){let i=n[0];return new b(w(t,e,...n),{status:i?.status,cause:i?.cause})}function U(t,e,n={}){let{status:i,cause:o,...r}=n;return new b(bn(t,e,{details:r.details,operation_outcome:r.operationOutcome,trace_id:r.traceId}),{status:i,cause:o})}function ke(t){let e=Ka(t.diagnostics),n=Ha(t.diagnostics);if(e==="collection_version_unsupported"){let i=Va(t.diagnostics);return w(e,n,{operationOutcome:"rejected",details:i})}return e!=="operation_invalid"?w(e,n,{operationOutcome:"rejected",details:{diagnostics:t.diagnostics}}):w(e,n,{operationOutcome:"rejected",details:{diagnostics:t.diagnostics,partial_result:t.result}})}function Ka(t){let e=new Set(t.filter(n=>n.severity==="error").map(n=>n.code));return["migration_required","migration_lossy","unsupported_version"].some(n=>e.has(n))?"collection_version_unsupported":["invalid_config","invalid_configuration","missing_config","missing_spec_version"].some(n=>e.has(n))?"collection_configuration_invalid":["duplicate_type","invalid_contract_definition","invalid_data_contract","invalid_type_definition","invalid_type_path"].some(n=>e.has(n))?"collection_type_registry_invalid":["collection_invalid","collection_open_failed"].some(n=>e.has(n))?"collection_invalid":"operation_invalid"}function Va(t){let e=t.map(n=>n.details).find(n=>Ga(n));return{current_version:typeof e?.current_version=="string"?e.current_version:"0.2.x",required_version:typeof e?.required_version=="string"?e.required_version:"0.3.0"}}function Ga(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Di(t){return t instanceof b&&t.retryable}function Ha(t){return t.filter(e=>e.severity==="error").map(e=>e.message).join(" ")||t.map(e=>e.message).join(" ")||"The collection rejected this operation."}var we=["describe","changes","read","query"];function B(t){let e=t.capabilities===void 0?1:t.capabilities?.contract_version;return e!==1&&e!==2&&Ie("Unsupported declared capability contract version."),e}function Ie(t){throw d("invalid_application_manifest",t,{details:{issues:[{path:"/requirements/capabilities",keyword:"authorizationSelection",message:t,params:{}}]}})}function Q(t,e){if(e.operations!==void 0&&e.capabilities!==void 0&&Ie("Specify operations or capabilities, not both."),e.operations!==void 0&&B(t)!==1&&Ie("Exact operations authorization is only supported for legacy v1 declarations."),e.capabilities!==void 0){let n=new Set([...t.capabilities?.required??[],...t.capabilities?.optional??[]]);e.capabilities.some(i=>!n.has(i)||W(B(t),i)===void 0)&&Ie("Authorization can only include capabilities declared by the application.")}}function Ui(t){let e=t.capabilities;return e?[...new Set([...e.required,...e.optional??[]].flatMap(n=>W(e.contract_version,n)??[]))]:[...we]}function Tn(t,e){let{requirements:n}=t;if(Q(n,e),B(n)===1){if(e.operations!==void 0)return[...new Set(e.operations)];if(e.capabilities===void 0)return[...we]}let i=n.capabilities,r=[...i?.required??[],...e.capabilities??i?.optional??[]].flatMap(s=>W(B(n),s)??[]),a=(t.provisions?.type_packs.length??0)>0||(t.provisions?.configuration?.length??0)>0;return[...new Set([...r,...B(n)===2&&a?Ct:[]])]}function Tt(t,e){return[...t.capabilities?.required??[],...t.capabilities?.optional??[]].filter(n=>(W(B(t),n)??[]).every(i=>e.includes(i)))}function kn(t){let e=t.files;if(e)return B(t)===1?((!("actions"in e)||"required"in e||"optional"in e)&&Ie("Legacy file declarations must use exact files.actions."),{actions:[...e.actions],scope:structuredClone(e.scope)}):("actions"in e&&Ie("V2 file declarations must use required/optional file actions."),gi(e))}function kt(t,e,n){let i=new Set(t.required),o=[...new Set([...t.required,...t.optional??[]])],r={};for(let a of o)r[a]=$a(a,i.has(a),n,t.contract_version,e);return{contractVersion:t.contract_version,values:r,requiredAvailable:t.required.every(a=>r[a]?.state==="available")}}function $a(t,e,n,i,o){let r=W(i,t)??[],a=r.filter(c=>!n.operations.includes(c)),s={id:t,requirement:e?"required":"optional",operations:r,missingOperations:a,evidence:[{source:"application",fact:`${e?"Required":"Optional"} in capability contract v${i}.`}]};if(a.length>0)return{...s,state:"requires_authorization",evidence:[...s.evidence,{source:"authorization",fact:`Missing ${a.join(", ")}.`}],reason:"The current grant does not include every operation for this capability."};if(n.scope.access!=="full_collection")return{...s,state:"requires_authorization",reason:"The current grant uses legacy contract scope and must be reauthorized for the entire collection.",evidence:[...s.evidence,{source:"authorization",fact:"Legacy contract scope is compatibility evidence, not active data authority."}]};if(i===1&&t.startsWith("files.")){let c=t.slice(6);if(!n.fileCapability?.actions.includes(c))return{...s,state:n.fileCapability?"requires_authorization":"unsupported",reason:n.fileCapability?`The current file grant does not include ${c}.`:"This connection has no file capability."}}return i===1&&t==="notifications.background-delivery"&&(o.notifications?.criteria.length??0)===0?{...s,state:"requires_setup",reason:"The application manifest declares no notification criteria."}:{...s,state:"available",evidence:[...s.evidence,{source:"authorization",fact:r.length>0?`Granted operations: ${r.join(", ")}.`:"No record operation is required."},{source:"authority",fact:n.authority.kind==="hosted"?"Backed by a durable hosted mdbase authority.":"Backed by a user-operated mdbase connector."}],...t==="offline.replica"||i===1&&t==="sync.offline-replica"?{details:{durability:"device",writes:"queued",authority:n.authority.kind}}:{},...i===1&&t==="notifications.background-delivery"?{details:{delivery:"authority",payload:"opaque"}}:{}}}var Me=3e4,In=1e4,Wa=10*6e4,Ja=12e4,Ya=6e4;function xe(t={}){return{requestMs:it(t.requestMs,Me,"requestMs"),watchStartMs:it(t.watchStartMs,In,"watchStartMs"),fileIndexMs:it(t.fileIndexMs,Wa,"fileIndexMs"),uploadMs:it(t.uploadMs,Ja,"uploadMs"),syncMs:it(t.syncMs,Ya,"syncMs")}}function ot(t,e){return{...t,signal:e.signal,...e.deadline===null?{}:{deadlineUnixMs:e.deadline}}}function pe(t={},e=Me,n=Date.now){let i=t.timeoutMs===void 0?e:t.timeoutMs,o=i===null?null:Qa(i),r=new AbortController,a=o===null?null:n()+o,s=()=>r.abort(t.signal?.reason);t.signal?.aborted?s():t.signal?.addEventListener("abort",s,{once:!0});let c=o===null?void 0:setTimeout(()=>r.abort(d("timeout","The operation exceeded its request deadline.",{operationOutcome:"not_sent"})),o),l=!1;return{signal:r.signal,deadline:a,remainingMs:()=>a===null?null:Math.max(0,a-n()),dispose:()=>{l||(l=!0,c!==void 0&&clearTimeout(c),t.signal?.removeEventListener("abort",s))}}}async function F(t,e,n){let i=pe(t,e),o,r=new Promise((s,c)=>{o=c}),a=()=>o?.(J(i.signal));i.signal.addEventListener("abort",a,{once:!0});try{if(i.signal.aborted)throw J(i.signal);return await Promise.race([n(i),r])}finally{i.signal.removeEventListener("abort",a),i.dispose()}}async function K(t,e,n){let i=pe(t,e);try{if(i.signal.aborted)throw J(i.signal);return await n(i)}finally{i.dispose()}}function J(t){return t.reason instanceof b?t.reason:d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t.reason})}function Qa(t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError("timeoutMs must be a positive safe integer or null.");return t}function it(t,e,n){if(t===void 0)return e;if(t===null)return null;if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${n} must be a positive safe integer or null.`);return t}async function Li(t){let{collectionId:e,readiness:n,contracts:i,connection:o,controller:r,options:a,requestMs:s,isCurrent:c,publish:l}=t,u=()=>r.abort(a?.signal?.reason);a?.signal?.aborted?u():a?.signal?.addEventListener("abort",u,{once:!0});try{let p=await F({...a,signal:r.signal},s,h=>o.describe(h));if(!c())return!1;if(!p.ok){let h=["access_denied","collection_access_denied","insufficient_access","not_authorized","authorization_expired","application_declaration_mismatch"].includes(p.problem.code);return n.contracts={state:h?"requires_authorization":"temporarily_unavailable",missing:[],evidence:[{source:"runtime",fact:p.problem.message}]},l(h?{status:"authorization_required"}:{status:"blocked",problem:p.problem}),!1}if(p.value.collectionId!==e)return n.contracts={state:"temporarily_unavailable",missing:[],evidence:[]},l({status:"blocked",problem:{code:"collection_not_ready",message:"Description belongs to a different collection."}}),!1;let f=i.filter(h=>!p.value.contracts.some(y=>y.id===h.id&&y.version===h.version&&y.digest===h.digest));if(n.contracts={state:f.length?"requires_setup":"verified",missing:f,evidence:[{source:"authority",fact:"Exact contract ID, version and digest checked by live describe for this collection."}]},f.length)return l({status:"blocked",problem:{code:"collection_not_ready",message:"The collection is missing required exact contracts."}}),!1}catch(p){if(!c())return!1;if(!(p instanceof b))throw p;return n.contracts={state:"temporarily_unavailable",missing:[],evidence:[{source:"runtime",fact:p.problem.message}]},l({status:"blocked",problem:p.problem}),!1}finally{a?.signal?.removeEventListener("abort",u)}return!0}function Ni(t,e,n){let i=structuredClone(t);return i.setup.state!=="not_required"&&i.setup.state!=="current"&&(i.setup.state=e==="ready"?n==="cached"?"cached":"current":e==="setup_review_required"?"review_required":e==="authorization_required"?"requires_authorization":e==="blocked"?"blocked":"checking",i.setup.evidence=[{source:e==="ready"&&n==="cached"?"runtime":"authority",fact:`Collection setup verification: ${i.setup.state}.`}]),i}function Bi(t,e,n,i){return{collectionId:e,info:n,capabilities:kt(t.requirements.capabilities,t,n),...t.requirements?.capabilities?.contract_version===2?{readiness:Za(t,n)}:{},connections:i}}function It(t,e){return`mdbase-application-session:v1:${t.id}:${e}`}function Mn(t){return JSON.stringify({capabilities:t.requirements?.capabilities,requirements:t.requirements?.configuration??[],provisions:t.provisions??{}})}function ji(t,e,n,i){return{applicationId:e,declarationDigest:n,requirements:{configuration:t.requirements?.configuration??[]},provisions:{configuration:t.provisions?.configuration??[],typePacks:t.provisions?.type_packs??[]},...i?{typePackAdoptions:i}:{}}}function Xa(t,e){if(!e||t.kind!==e.kind)return!1;if(t.kind==="collection"||e.kind==="collection")return!0;let n=[...new Set(t.folders)].sort(),i=[...new Set(e.folders)].sort();return JSON.stringify(n)===JSON.stringify(i)}function Za(t,e){let n=t.requirements?.files,i=n&&"required"in n?n:void 0,o=!i||Xa(i.scope,e.fileCapability?.scope),r=u=>u.filter(p=>!o||!e.fileCapability?.actions.includes(p)),a=r(i?.required??[]),s=r(i?.optional??[]),c=t.requirements?.contracts??[],l=(t.provisions?.type_packs.length??0)>0||(t.provisions?.configuration?.length??0)>0;return{files:{state:i?a.length?"requires_authorization":"available":"not_required",missingRequiredActions:a,missingOptionalActions:s,scopeMatches:o,evidence:[{source:"authorization",fact:"Compared exact file actions and folder scope with connection.info().fileCapability."}]},contracts:{state:c.length?"checking":"not_required",missing:[],evidence:[]},setup:{state:l?"checking":"not_required",evidence:[]},notifications:{state:t.notifications?.criteria.length?"requires_registration":"not_required",registration:"unverified",evidence:[{source:"runtime",fact:"The connection API exposes registration commands but no current delivery-registration query. Manifest criteria do not prove approval or delivery registration."}]}}}var es=["access_denied","access_paused","application_declaration_mismatch","authorization_binding_incompatible","authorization_expired","capability_contract_incompatible","collection_access_denied","connector_identity_changed","connector_offline","connector_upgrade_required","direct_operation_rejected","durable_mutation_unsupported","operation_outcome_unknown","encryption_required","encrypted_relay_rejected","hosted_provider_unavailable","insufficient_access","invalid_encrypted_response","invalid_operation_response","invalid_request","missing_grant_key","mutation_recovery_expired","mutation_request_conflict","not_authorized","operation_cancelled","operation_failed","rate_limited","relay_authorization_expired","relay_unavailable","temporarily_unavailable","timeout","transport_protocol_incompatible","unsupported_operation"],Ki=Object.keys(be),Se=["discovery_failed","invalid_operation_response","invalid_application_manifest","invalid_request","manifest_load_failed","rate_limited","temporarily_unavailable","timeout"],fe=[...Se,"access_denied","application_declaration_mismatch","application_identity_unavailable","approval_window_blocked","authorization_binding_incompatible","authorization_cancelled","authorization_replayed","browser_required","capability_contract_incompatible","collection_access_denied","collection_configuration_invalid","collection_contracts_missing","collection_incompatible","collection_invalid","collection_kind_unsupported","collection_mismatch","collection_not_found","collection_type_registry_invalid","collection_version_unsupported","connector_identity_changed","connector_offline","connector_upgrade_required","device_authorization_failed","durable_mutation_unsupported","encryption_required","expired_token","invalid_application_authorization","invalid_callback","invalid_device_authorization_response","invalid_token_response","legacy_scope_reauthorization_required","scope_denied","reconnect_required","token_exchange_failed","transport_protocol_incompatible"],rt=[...Se,"authorization_expired","invalid_operation_response","invalid_push_subscription","managed_fcm_not_declared","not_authorized","notification_criterion_not_declared","notification_reauthorization_required","notification_registration_failed","notification_unregistration_failed","notifications_not_declared","notifications_unavailable"],xn=["connector_offline","connector_upgrade_required","invalid_operation_response","not_authorized","operation_failed","temporarily_unavailable","timeout"],sl=[...fe,"collection_not_ready","collection_not_selected","operation_cancelled","session_destroyed","session_not_started","session_starting","unknown_collection"],ts=["collection_configuration_invalid","collection_invalid","collection_type_registry_invalid","collection_version_unsupported"],Mt=[...es,...ts],ie=[...Mt,"invalid_path","operation_invalid"],En=[...ie,"cursor_capacity_exhausted","generation_expired","invalid_read_cursor","query_snapshot_changed","sandbox_unsupported"],j=[...ie,"concurrent_modification","invalid_preflight","pending_mutation_unresolved"],xt=[...Mt,"change_cursor_reset"],he=[...j,"type_pack_provision_failed"];function I(t,e=[]){return{ok:!0,value:t,diagnostics:e}}function g(t){return{ok:!1,problem:t}}async function D(t,e){try{return I(await t())}catch(n){if(!(n instanceof b))throw n;let i=n.problem;return i.code==="unknown"||e.includes(i.code)?g(i):g(Fi(i.code,i.message,{details:i.details,operationOutcome:i.operation_outcome,traceId:i.trace_id}))}}var ns="mdbase-connect-keys",ye="grant-keys",zn=18446744073709551615n,is="mdbase-connect relay request key v1",os="mdbase-connect relay response key v1",Vi=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Ee=class{database=null;async create(e){let n=await $i(e),i=await this.open();return await Hi(i,o=>o.add({...n,counter:"0"})),n}async get(e){let n=await this.open(),i=await cs(n.transaction(ye).objectStore(ye).get(e));return i?{handle:i.handle,agreementPrivateKey:i.agreementPrivateKey,agreementPublicKey:i.agreementPublicKey,signingPrivateKey:i.signingPrivateKey,signingPublicKey:i.signingPublicKey}:null}async nextCounter(e){let n=await this.open();return new Promise((i,o)=>{let r=n.transaction(ye,"readwrite"),a=r.objectStore(ye),s=a.get(e),c=null;s.onerror=()=>o(s.error),s.onsuccess=()=>{let l=s.result;if(!l){r.abort(),o(new x("missing_grant_key","The encrypted grant key is unavailable."));return}let u=BigInt(l.counter)+1n;if(u>zn){r.abort(),o(new x("counter_exhausted","The encrypted grant must be authorized again."));return}c=u.toString(),a.put({...l,counter:c})},r.onerror=()=>o(r.error),r.onabort=()=>o(r.error??new Error("Key counter transaction aborted.")),r.oncomplete=()=>{c&&i(c)}})}async delete(e){let n=await this.open();await Hi(n,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new x("key_storage_unavailable","Encrypted relay authorization requires browser IndexedDB or an injected grant key store.");return this.database||(this.database=new Promise((e,n)=>{let i=indexedDB.open(ns,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(ye)||i.result.createObjectStore(ye,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},qe=class{records=new Map;sequence=Promise.resolve();async create(e){if(this.records.has(e))throw new Error(`Grant key already exists: ${e}`);let n=await $i(e);return this.records.set(e,{...n,counter:"0"}),n}async get(e){let n=this.records.get(e);return n?{handle:n.handle,agreementPrivateKey:n.agreementPrivateKey,agreementPublicKey:n.agreementPublicKey,signingPrivateKey:n.signingPrivateKey,signingPublicKey:n.signingPublicKey}:null}nextCounter(e){let n,i,o=new Promise((r,a)=>{n=r,i=a});return this.sequence=this.sequence.then(()=>{let r=this.records.get(e);if(!r)throw new x("missing_grant_key","The encrypted grant key is unavailable.");let a=BigInt(r.counter)+1n;if(a>zn)throw new x("counter_exhausted","The encrypted grant must be authorized again.");r.counter=a.toString(),n(r.counter)}).catch(r=>{i(r)}),o}async delete(e){this.records.delete(e)}};async function Et(t,e,n,i){let o=await rs(t,e,n),r=i.timestamp??Math.floor(Date.now()/1e3),a=i.nonce??crypto.randomUUID(),s=await Fn({...i,timestamp:r,nonce:a}),c=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},o.signingPrivateKey,new TextEncoder().encode(s));return{[nt.version]:String(On),[nt.timestamp]:String(r),[nt.nonce]:a,[nt.signature]:at(new Uint8Array(c))}}async function Fn(t){let e=t.method.toUpperCase(),n=await Gi(t.body??""),i=await Gi(t.credential);for(let o of[e,t.target,String(t.timestamp),t.nonce])if(!o||o.includes(`
2
+ `)||o.includes("\r"))throw new x("invalid_proof_input","Authority request proof metadata is invalid.");return[zi,On,e,t.target,n,i,t.timestamp,t.nonce].join(`
3
+ `)}async function oe(t,e,n,i,o,r=crypto.randomUUID(),a){if(re(n.encryption),a!==void 0&&(!Number.isSafeInteger(a)||a<=0))throw new x("invalid_deadline","The operation deadline is invalid.");let s=await Wi(t,e,n.encryption.application_agreement_public_key),c=await t.nextCounter(e),l={binding:n,protocolVersion:$,requestId:r,operation:i,counter:c},u=await Ji(s.agreementPrivateKey,n,l.protocolVersion,"request"),p=new TextEncoder().encode(JSON.stringify(o??{})),f=await crypto.subtle.encrypt({name:"AES-GCM",iv:Xi(c),additionalData:new TextEncoder().encode(Qi(l,"request")),tagLength:128},u,p);return{type:"encrypted_operation_request",...as(l),...a===void 0?{}:{deadline_unix_ms:a},ciphertext:at(new Uint8Array(f))}}async function ze(t,e,n,i,o){if(!ss(i,o))throw new x("invalid_encrypted_response","Encrypted response metadata does not match its request.");let r=await Wi(t,e,n.encryption.application_agreement_public_key),a={binding:n,protocolVersion:i.protocol_version,requestId:i.request_id,operation:i.operation,counter:i.counter},s=await Ji(r.agreementPrivateKey,n,i.protocol_version,"response");try{let c=await crypto.subtle.decrypt({name:"AES-GCM",iv:Xi(i.counter),additionalData:new TextEncoder().encode(Qi(a,"response")),tagLength:128},s,eo(Zi(o.ciphertext))),l=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(c));if(l?.ok===!0&&"result"in l||l?.ok===!1&&Xe(l.problem))return l;throw new Error("invalid response body")}catch(c){throw c instanceof x?c:new x("encrypted_response_rejected","The encrypted connector response could not be authenticated.")}}var x=class extends Error{constructor(n,i){super(i);this.code=n}code};async function $i(t){let e=await crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),n=at(new Uint8Array(await crypto.subtle.exportKey("raw",e.publicKey))),i=await crypto.subtle.exportKey("pkcs8",e.privateKey),o=await crypto.subtle.importKey("pkcs8",i,{name:"ECDH",namedCurve:"P-256"},!1,["deriveBits"]),r=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),a=at(new Uint8Array(await crypto.subtle.exportKey("raw",r.publicKey))),s=await crypto.subtle.exportKey("pkcs8",r.privateKey),c=await crypto.subtle.importKey("pkcs8",s,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]);return{handle:t,agreementPrivateKey:o,agreementPublicKey:n,signingPrivateKey:c,signingPublicKey:a}}async function Wi(t,e,n){let i=await t.get(e);if(!i||i.agreementPublicKey!==n)throw new x("missing_grant_key","The encrypted grant key is unavailable or does not match the grant.");return i}async function rs(t,e,n){let i=await t.get(e);if(!i||i.signingPublicKey!==n)throw new x("missing_grant_key","The remote authority signing key is unavailable or does not match the grant.");return i}async function Ji(t,e,n,i){let o=await st(t,e.encryption.connector_agreement_public_key),r=await crypto.subtle.importKey("raw",o,"HKDF",!1,["deriveKey"]),a=new TextEncoder().encode(Yi(e,n)),s=await crypto.subtle.digest("SHA-256",a);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:s,info:new TextEncoder().encode(i==="request"?is:os)},r,{name:"AES-GCM",length:256},!1,i==="request"?["encrypt"]:["decrypt"])}async function st(t,e){try{let n=await crypto.subtle.importKey("raw",eo(qn(e)),{name:"ECDH",namedCurve:"P-256"},!1,[]);return await crypto.subtle.deriveBits({name:"ECDH",public:n},t,256)}catch{throw new x("invalid_public_key","The connector relay public key is invalid.")}}function Yi(t,e){let n=t.encryption;return["mdbase-connect",e,n.suite,t.grantId,t.applicationId,n.connector_id,n.collection_id,n.scope_epoch,n.key_id].join("|")}function Qi(t,e){return[Yi(t.binding,t.protocolVersion),t.requestId,e,t.operation,t.counter].join("|")}function as(t){let e=t.binding.encryption;return{protocol_version:t.protocolVersion,suite:tt,request_id:t.requestId,grant_id:t.binding.grantId,application_id:t.binding.applicationId,connector_id:e.connector_id,collection_id:e.collection_id,operation:t.operation,scope_epoch:e.scope_epoch,key_id:e.key_id,counter:t.counter}}function ss(t,e){return e.type==="encrypted_operation_response"&&typeof e.ciphertext=="string"&&t.protocol_version===e.protocol_version&&t.suite===e.suite&&t.request_id===e.request_id&&t.grant_id===e.grant_id&&t.application_id===e.application_id&&t.connector_id===e.connector_id&&t.collection_id===e.collection_id&&t.operation===e.operation&&t.scope_epoch===e.scope_epoch&&t.key_id===e.key_id&&t.counter===e.counter}function re(t){if(t.protocol_version!==Ot||t.suite!==tt||!Number.isSafeInteger(t.scope_epoch)||t.scope_epoch<=0||typeof t.key_id!="string"||t.key_id.length===0||t.key_id.length>200||t.key_id.includes("|"))throw new x("unsupported_encryption","The grant uses an unsupported relay encryption profile.");if(typeof t.connector_id!="string"||!Vi.test(t.connector_id)||typeof t.collection_id!="string"||!Vi.test(t.collection_id))throw new x("unsupported_encryption","The grant uses invalid encrypted relay identities.");qn(t.application_agreement_public_key),qn(t.connector_agreement_public_key)}function Xi(t){let e=BigInt(t);if(e<=0n||e>zn||e.toString()!==t)throw new x("invalid_counter","The encrypted relay counter is invalid.");let n=new Uint8Array(new ArrayBuffer(12));return new DataView(n.buffer).setBigUint64(4,e,!1),n}function at(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}async function Gi(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return at(new Uint8Array(e))}function Zi(t){if(!/^[A-Za-z0-9_-]+$/.test(t))throw new x("invalid_base64","Encrypted relay data is malformed.");let e="=".repeat((4-t.length%4)%4),n=atob(t.replaceAll("-","+").replaceAll("_","/")+e);return Uint8Array.from(n,i=>i.charCodeAt(0))}function qn(t){let e=Zi(t);if(e.length!==65||e[0]!==4)throw new x("invalid_public_key","Encrypted relay public keys must be uncompressed P-256 points.");return e}function eo(t){return Uint8Array.from(t).buffer}function cs(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function Hi(t,e){return new Promise((n,i)=>{let o=t.transaction(ye,"readwrite"),r=e(o.objectStore(ye));r.onerror=()=>i(r.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Grant key transaction aborted.")),o.oncomplete=()=>n()})}function me(t){return{...t,credentials:"omit",targetAddressSpace:"loopback"}}async function ct(){if(typeof navigator>"u"||!navigator.permissions?.query)return null;try{return(await navigator.permissions.query({name:"local-network-access"})).state}catch{return null}}function Fe(t){return t===404||t===405||t===426||t>=500}function to(t,e){return ue(t,e)}function no(t,e){if(t.deadline_unix_ms===e)return t;let{deadline_unix_ms:n,...i}=t;return{...i,...e===void 0?{}:{deadline_unix_ms:e}}}function lt(t){return[...new Set(t)]}function io(t,e){return t.grantId||e.grantId?t.grantId===e.grantId&&t.keyHandle===e.keyHandle&&t.encryption?.key_id===e.encryption?.key_id:t.accessToken===e.accessToken}function Ae(t){if(t?.aborted)throw d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t.reason})}function qt(t,e,n,i){return t instanceof b?t:e?.aborted?n?G(n,t):e.reason instanceof b?e.reason:d("operation_cancelled","The operation was cancelled before it changed the collection.",{operationOutcome:"not_sent",cause:t}):n?G(n,t):t instanceof TypeError?d(i,i==="hosted_provider_unavailable"?"The hosted collection provider is unavailable.":"The Connect relay is unavailable.",{cause:t}):t instanceof Error?t:new Error(String(t))}function oo(t){return U(t.code==="unknown"?t.server_code:t.code,t.message,{details:t.details,operationOutcome:t.operation_outcome??"rejected",traceId:t.trace_id})}function ro(t,e,n,i,o){return fetch(t,{method:"POST",headers:{authorization:`Bearer ${e}`,"content-type":"application/json",...n},body:i,signal:o})}function Un(t,e){return e?.aborted===!0||t instanceof b&&t.code==="operation_cancelled"}function ao(t,e){if(e.dryRun!==!0||e.wouldRename!==!0||e.from!==t.from||e.to!==t.to)throw d("invalid_preflight","The rename preview does not match this mutation. Run the preview again.")}function so(t,e){if(e.dryRun!==!0||e.wouldDelete!==!0||e.path!==t.path)throw d("invalid_preflight","The delete preview does not match this mutation. Run the preview again.")}function co(t,e){if(t.updateRefs===!1)return{affectedRecords:0,totalUnits:1,warnings:0};let n=e.referencesAffected??[];return{affectedRecords:new Set(n.map(i=>i.path)).size,totalUnits:1+n.length,warnings:e.warnings?.length??0}}function lo(t){return{affectedRecords:new Set((t.brokenLinks??[]).map(e=>e.path)).size,totalUnits:1,warnings:0}}async function uo(t,e){return Ai(t,e??{})}function po(t){return JSON.stringify(Dn(t))}function Dn(t){return Array.isArray(t)?t.map(e=>Dn(e)):t&&typeof t=="object"?Object.fromEntries(Object.entries(t).filter(([,e])=>e!==void 0).sort(([e],[n])=>e<n?-1:e>n?1:0).map(([e,n])=>[e,Dn(n)])):t}function G(t,e){return d("operation_outcome_unknown","The write may have completed, but mdbase could not recover its authoritative result. Retry the exact same write to recover safely.",{operationOutcome:"unknown",details:{request_id:t},cause:e})}function X(t){let e=new Uint8Array(t);return crypto.getRandomValues(e),Ln(e)}function Ln(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function fo(t){let e=t.replaceAll("-","+").replaceAll("_","/").padEnd(Math.ceil(t.length/4)*4,"="),n=atob(e),i=new Uint8Array(new ArrayBuffer(n.length));for(let o=0;o<n.length;o+=1)i[o]=n.charCodeAt(o);return i}function ho(t,e){let n=t instanceof URL?t.href:t??ds(),i=typeof n=="string"?n:n.distribution==="portable"?`bundle:${n.id}:${ps(n)}`:`bundle:${n.id}`,o=e===void 0?typeof n!="string"&&n.distribution==="portable"?"":us():String(e);return{manifest:n,manifestSource:i,redirectUri:o}}async function ae(t,e,n,i){try{return await fetch(t,e)}catch(o){throw d(n,i,{cause:o})}}async function E(t,e,n){let i;try{i=await t.text()}catch(o){throw U(e,n,{status:t.status,cause:o})}if(i.trim()==="")throw U(e,n,{status:t.status});try{return JSON.parse(i)}catch(o){throw U(e,n,{status:t.status,cause:o})}}function yo(t){let e=new URL(t);if(e.protocol!=="http:"||!["127.0.0.1","[::1]"].includes(e.hostname)||e.username||e.password||e.pathname!=="/"||e.search||e.hash)throw d("invalid_loopback_url","loopbackUrl must be an HTTP origin on 127.0.0.1 or ::1.");return e.origin}async function dt(){let t=X(32),e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t));return{verifier:t,challenge:Ln(new Uint8Array(e))}}function z(t,e,n,i){return U(ut(t)??t?.error?.code??e,t?.error_description??t?.error?.message??n,{status:i,details:t?.error?.details,operationOutcome:t?.error?.operation_outcome,traceId:t?.error?.trace_id})}function ut(t){return typeof t?.error=="string"?t.error:void 0}function pt(t,e){if(!t||typeof t!="object"||Array.isArray(t)||typeof e!="string")return!1;let n=t;if(typeof n.operations_url!="string"||typeof n.sync_url!="string"||typeof n.files_url!="string"||typeof n.replica_id!="string"||n.replica_id.length===0||typeof n.access_token!="string"||n.access_token.length===0||n.proof_public_key!==void 0&&(typeof n.proof_public_key!="string"||n.proof_public_key.length===0))return!1;try{let i=new URL(n.operations_url),o=new URL(n.sync_url),r=new URL(n.files_url);return[i,o,r].every(a=>(a.protocol==="https:"||a.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname))&&!a.username&&!a.password&&!a.search&&!a.hash)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/operations$/i.test(i.pathname)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/sync$/i.test(o.pathname)&&/^\/v1\/authorities\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\/files$/i.test(r.pathname)&&i.origin===o.origin&&i.origin===r.origin&&i.pathname.split("/")[3]===e&&o.pathname.split("/")[3]===e&&r.pathname.split("/")[3]===e}catch{return!1}}function mo(t,e){return pt({operations_url:t?.operationsUrl,sync_url:t?.syncUrl,files_url:t?.filesUrl,replica_id:t?.replicaId,access_token:t?.accessToken,proof_public_key:t?.proofPublicKey},e)}function zt(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t,n=e.actions;if(e.kind!=="files"||e.protocol_version!==1||!Array.isArray(n)||n.length===0||n.length>6||new Set(n).size!==n.length||n.some(o=>!["list","read","add","replace","move","delete"].includes(o)))return!1;let i=e.scope;return!i||typeof i!="object"||Array.isArray(i)?!1:i.kind==="collection"?Object.keys(i).length===1:i.kind==="selected_folders"&&Object.keys(i).length===2&&Array.isArray(i.folders)&&i.folders.length>0&&i.folders.length<=100&&new Set(i.folders).size===i.folders.length&&i.folders.every(o=>typeof o=="string"&&o.length>0&&o.length<=1024&&ls(o))}function ls(t){let e=new Set([".mdbase",".git","node_modules","_contracts","_schemas","_types","_views"]);return!t.startsWith("/")&&!t.endsWith("/")&&!t.includes("\\")&&t.split("/").every(n=>{let i=n.split(".")[0]?.toUpperCase()??"";return n!==""&&n!=="."&&n!==".."&&!n.startsWith(".")&&!n.endsWith(" ")&&!n.endsWith(".")&&!/[<>:"|?*]/.test(n)&&!e.has(n.toLowerCase())&&!["CON","PRN","AUX","NUL"].includes(i)&&!/^(COM|LPT)[1-9]$/.test(i)})}function go(t,e){if(!t||typeof t!="object"||Array.isArray(t)||t.collection_id!==e)return!1;try{return re(t),!0}catch{return!1}}function _o(t){if(typeof t?.device_code!="string"||typeof t?.user_code!="string"||typeof t?.verification_uri!="string"||typeof t?.verification_uri_complete!="string"||!Number.isFinite(t?.expires_in)||!Number.isFinite(t?.interval))throw d("invalid_device_authorization_response","Connect returned an invalid downloaded application authorization response.");return{userCode:t.user_code,verificationUri:t.verification_uri,verificationUriComplete:t.verification_uri_complete,expiresAt:Date.now()+Math.max(1,t.expires_in)*1e3,intervalSeconds:Math.max(1,t.interval)}}function M(t){if(!t)return null;try{return JSON.parse(t)}catch{return null}}function Ft(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return e.access!=="contract"&&e.access!=="full_collection"||!Array.isArray(e.contracts)||e.contracts.some(n=>!n||typeof n!="object"||n.contract_type!=="record"||typeof n.id!="string"||typeof n.version!="string"||!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(n.version)||!/^sha256:[0-9a-f]{64}$/.test(n.digest)||!n.schema||typeof n.schema!="object"||Array.isArray(n.schema)||!Array.isArray(n.implementations)||n.implementations.some(i=>!i||typeof i!="object"||typeof i.type_name!="string"||!Number.isInteger(i.type_version)||!/^sha256:[0-9a-f]{64}$/.test(i.digest)||!i.fields||typeof i.fields!="object"||Array.isArray(i.fields)||Object.values(i.fields).some(o=>typeof o!="string")))?null:e}function Dt(t){return t.access==="full_collection"&&t.contracts.length===0}function bo(t){return t.endsWith("/")?t.slice(0,-1):t}function ds(){if(typeof location>"u")throw d("manifest_required","manifest is required outside a browser environment.");if(location.origin==="null")throw d("manifest_required","Downloaded applications must provide their v1 portable manifest inline.");return new URL("/.well-known/mdbase-app.json",location.origin).href}function us(){if(typeof location>"u")throw d("redirect_uri_required","redirectUri is required outside a browser environment.");return location.href.split(/[?#]/)[0]}function Co(t,e,n,i){if(typeof t!="string"&&t.distribution==="portable"||i)return"null";let o=new URL(n);if(["http:","https:"].includes(o.protocol))return o.origin;if(typeof location<"u")return location.origin;if(typeof t!="string")return new URL(t.homepage).origin;try{return new URL(e).origin}catch{return""}}function vo(t){let e=":token:",n=t.lastIndexOf(e);return n<0?"":t.slice(n+e.length)}function Ut(){if(typeof location>"u")throw d("callback_url_required","callbackUrl is required outside a browser environment.");return location.href}function wo(t){if(t)return new De;if(typeof localStorage>"u")throw d("storage_required","storage is required outside a browser environment.");try{let e=`mdbase-connect:probe:${X(8)}`;return localStorage.setItem(e,"1"),localStorage.removeItem(e),localStorage}catch{return new De}}var De=class{values=new Map;get length(){return this.values.size}clear(){this.values.clear()}getItem(e){return this.values.get(e)??null}key(e){return[...this.values.keys()][e]??null}removeItem(e){this.values.delete(e)}setItem(e,n){this.values.set(String(e),String(n))}};function So(t){return typeof t=="string"||t.distribution!=="portable"?!1:typeof location>"u"||location.origin==="null"||!["http:","https:"].includes(location.protocol)}function ps(t){let e=po(t),n=2166136261,i=2654435769;for(let o=0;o<e.length;o+=1){let r=e.charCodeAt(o);n=Math.imul(n^r,16777619),i=Math.imul(i^r,2246822507)}return`${(n>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}async function Ao(t,e){let n=await fetch(`${t}/health`,{signal:e,cache:"no-store"}),i=await n.json().catch(()=>null);if(!n.ok||!Array.isArray(i?.capabilities)||!i.capabilities.every(o=>typeof o=="string")||!i.capabilities.includes(di))throw d("capability_contract_incompatible","This server does not support new version-2 application authorizations.",{details:{contract:"fresh_application_authorization",required:[2],supported:[],peer:"server"}})}function ft(t){let e="bundle:";if(!t.startsWith(e)||t.length===e.length)throw new Error("The registered application has no valid declaration identity.");return t.slice(e.length)}function Ue(t,e,n){return t.reason instanceof b?t.reason:d("authorization_cancelled",e,{cause:n})}function ht(t){for(let e of["code","state","error","error_description"])t.searchParams.delete(e);return t}function Lt(t){let e;try{e=new URL(t)}catch{return!1}return e.searchParams.has("state")&&(e.searchParams.has("code")||e.searchParams.has("error"))}function Nt(t){try{let e=new URL(t).searchParams.get("state");return e&&e.length>0?e:null}catch{return null}}function Ro(t){if(!t.details||typeof t.details!="object"||Array.isArray(t.details))return;let e=t.details.return_to;return typeof e=="string"?e:void 0}var Le=class{constructor(e,n){this.connect=e;this.operations=lt(n.operations??we),this.selection=n.selection,this.autoSelect=n.autoSelect??"only",this.snapshot={status:"not_started",connections:[]}}connect;operations;selection;autoSelect;listeners=new Set;snapshot;snapshotKey="";stopConnections;stopSelection;stopActiveConnection;activeCollectionId=null;unavailableReason="not_authorized";started=!1;destroyed=!1;refreshing=!1;refreshQueued=!1;transactionDepth=0;lifecycleGeneration=0;operationControllers=new Set;startOperation=null;callbackCompletions=new Map;start(e){if(this.destroyed)return Promise.resolve(g(w("session_destroyed","This session has been destroyed.")));if(this.started&&!this.startOperation)return Promise.resolve(I(this.snapshot));let n=this.startOperation??this.beginStart();return this.waitForStart(n,e)}beginStart(){let e=new AbortController,n=++this.lifecycleGeneration;this.publish({status:"starting",connections:this.connect.connections()});let i={promise:this.performStart({signal:e.signal,timeoutMs:null},n),controller:e,waiters:0,generation:n};this.startOperation=i;let o=()=>{this.startOperation===i&&(this.startOperation=null)};return i.promise.then(o,o),i}async waitForStart(e,n){e.waiters+=1;try{return await F(n,In,()=>e.promise)}catch(i){if(i instanceof b)return g(i.problem);throw i}finally{e.waiters-=1,e.waiters===0&&this.startOperation===e&&(e.controller.abort(),this.startOperation=null,this.lifecycleGeneration+=1,this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"not_started",connections:this.connect.connections()}))}}async performStart(e,n){try{this.started=!0,this.stopConnections=this.connect.onConnectionsChange(()=>this.refresh()),this.stopSelection=this.selection.subscribe(()=>{this.unavailableReason="not_authorized",this.refresh()});let i=this.selection.authorizationCallback();if(i){let o=await this.completeAuthorizationCallback(i,e);if(!o.ok)return n===this.lifecycleGeneration&&!this.destroyed&&(this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"start_failed",problem:o.problem,connections:this.connect.connections()})),o}else this.autoSelectOnlyConnection();return n!==this.lifecycleGeneration||this.destroyed?g(w("session_destroyed","This session has been destroyed.")):(this.publishCurrent(),I(this.snapshot))}catch(i){if(i instanceof b){let o=i.problem;return n===this.lifecycleGeneration&&!this.destroyed&&(this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"start_failed",problem:o,connections:this.connect.connections()})),g(o)}throw n===this.lifecycleGeneration&&!this.destroyed&&(this.stopLifecycleSubscriptions(),this.started=!1,this.publish({status:"not_started",connections:this.connect.connections()})),i}}destroy(){if(!this.destroyed){this.lifecycleGeneration+=1,this.startOperation?.controller.abort(),this.startOperation=null;for(let e of this.operationControllers)e.abort();this.operationControllers.clear(),this.stopLifecycleSubscriptions(),this.started=!1,this.destroyed=!0,this.callbackCompletions.clear(),this.publish({status:"destroyed",connections:[]}),this.listeners.clear()}}stopLifecycleSubscriptions(){this.stopConnections?.(),this.stopSelection?.(),this.stopActiveConnection?.(),this.stopConnections=void 0,this.stopSelection=void 0,this.stopActiveConnection=void 0,this.activeCollectionId=null}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}select(e,n={}){let i=this.lifecycleProblem();if(i)return g(i);let o=this.connect.connection(e);return o?(this.unavailableReason="not_authorized",this.selection.select(e,n),this.refresh(),I(o)):g(w("unknown_collection","This collection is not authorized for this application."))}clearSelection(e={}){let n=this.lifecycleProblem();return n?g(n):(this.unavailableReason="not_authorized",this.selection.select(null,e),this.refresh(),I(void 0))}forget(e){let n=this.lifecycleProblem();if(n)return g(n);this.transactionDepth+=1;try{let i=this.selection.selectedCollectionId()===e;this.connect.connection(e)?.forget(),i&&this.selection.select(null,{history:"replace"})}finally{this.transactionDepth-=1,this.refresh()}return I(void 0)}async authorize(e,n={}){let i=this.lifecycleProblem();if(i)return g(i);let o=this.selection.selectedCollectionId();if(e==="selected"&&!o)return g(w("collection_not_selected","Choose a collection before updating its access."));let r=typeof e=="object"?e.collectionId:e==="selected"?o:null,a=this.beginLifecycleOperation(n);this.transactionDepth+=1;try{let s=await this.connect.manifest?.(a.options);if(s&&!s.ok)return s;if(!this.lifecycleCurrent(a.generation))return this.destroyedOutcome(I(void 0));let c=s?B(s.value.requirements):1,l=await this.connect.authorize({...a.options,...c===1&&n.operations===void 0&&n.capabilities===void 0?{operations:this.operations}:{},target:r===null?{kind:"choose"}:{kind:"collection",collectionId:r},returnTo:this.selection.authorizationReturnTo()});return this.lifecycleCurrent(a.generation)?(l.ok&&l.value.kind==="connected"&&this.selection.finishAuthorization(l.value.returnTo,l.value.connection.collectionId),l):this.destroyedOutcome(l)}finally{a.dispose(),this.transactionDepth-=1,this.refresh()}}ensureOperations(e,n){return this.ensureAuthorization({operations:e},n)}ensureCapabilities(e,n){return this.ensureAuthorization({capabilities:e},n)}async ensureAuthorization(e,n){let i=this.lifecycleProblem();if(i)return g(i);let o=this.snapshot;if(o.status!=="ready")return g(w("collection_not_ready","Choose an authorized collection first."));let r=this.beginLifecycleOperation(n);this.transactionDepth+=1;try{let a=await this.connect.manifest?.(r.options);if(a&&!a.ok)return a;if(!this.lifecycleCurrent(r.generation))return this.destroyedOutcome(I(void 0));let s=a?.value.requirements??("operations"in e?{access:"full_collection",contracts:[]}:{access:"full_collection",contracts:[],capabilities:{contract_version:2,required:[],optional:Object.keys(bt)}});Q(s,{...n,...e});let c="operations"in e?e.operations:e.capabilities.flatMap(f=>W(B(s),f)??[]),l=o.connection.authorizationCapabilities(c);if(l.sufficient)return I({kind:"unchanged",connection:o.connection});let u="operations"in e||B(s)===1?{operations:lt([...l.grantedOperations,...c])}:{capabilities:[...new Set([...Tt(s,l.grantedOperations),...e.capabilities])]},p=await this.connect.authorize({...r.options,...u,target:{kind:"collection",collectionId:o.collectionId},returnTo:this.selection.authorizationReturnTo()});return this.lifecycleCurrent(r.generation)?(p.ok&&p.value.kind==="connected"&&this.selection.finishAuthorization(p.value.returnTo,p.value.connection.collectionId),p):this.destroyedOutcome(p)}catch(a){if(a instanceof b)return g(a.problem);throw a}finally{r.dispose(),this.transactionDepth-=1,this.refresh()}}handleAuthorizationCallback(e,n){let i=this.lifecycleProblem();return i?Promise.resolve(g(i)):Lt(e)?this.completeAuthorizationCallback(e,n):Promise.resolve(g(w("invalid_callback","This URL is not an authorization callback.")))}completeAuthorizationCallback(e,n){if(n?.signal?.aborted){let r=J(n.signal);return Promise.resolve(g(r.problem))}let i=Nt(e);if(!i)return Promise.resolve(g(w("invalid_callback","Authorization callback is missing its state.")));let o=this.callbackCompletions.get(i)??this.beginCallbackCompletion(e,i);return this.waitForCallbackCompletion(o,n)}beginCallbackCompletion(e,n){let i=new AbortController,o=this.lifecycleGeneration;this.transactionDepth+=1,this.operationControllers.add(i);let r={state:n,controller:i,waiters:0,settled:!1,abandoned:!1,promise:void 0},a=this.connect.completeAuthorization(e,{signal:i.signal,timeoutMs:null}).catch(s=>{if(s instanceof b)return g(s.problem);throw s});return r.promise=a.then(s=>{if(o!==this.lifecycleGeneration||this.destroyed)return this.destroyedOutcome(s);if(!s.ok){if(!r.abandoned&&s.problem.recovery!=="retry"){let l=Ro(s.problem);this.selection.clearAuthorizationCallback(l)}return this.refresh(),s}let c=s.value;return this.unavailableReason="not_authorized",this.selection.finishAuthorization(c.returnTo,c.connection.collectionId),this.refresh(),I(c.connection,s.diagnostics)}).catch(s=>{if(o!==this.lifecycleGeneration||this.destroyed)return g(w("session_destroyed","This session was destroyed before authorization completion finished."));throw r.abandoned||(this.selection.clearAuthorizationCallback(),this.refresh()),s}).finally(()=>{r.settled=!0,this.operationControllers.delete(i),this.transactionDepth-=1,this.refresh(),this.callbackCompletions.get(n)===r&&this.callbackCompletions.delete(n)}),this.callbackCompletions.set(n,r),r}async waitForCallbackCompletion(e,n){e.waiters+=1;try{return await F(n,Me,()=>e.promise)}catch(i){if(i instanceof b)return g(i.problem);throw i}finally{e.waiters-=1,e.waiters===0&&!e.settled&&this.callbackCompletions.get(e.state)===e&&(e.abandoned=!0,this.callbackCompletions.delete(e.state),e.controller.abort())}}lifecycleProblem(){return this.destroyed?w("session_destroyed","This session has been destroyed."):this.snapshot.status==="starting"?w("session_starting","The session is still starting."):this.snapshot.status==="start_failed"?this.snapshot.problem:this.started?null:w("session_not_started","Start the session before using it.")}beginLifecycleOperation(e={}){let n=new AbortController,i=()=>n.abort(e.signal?.reason);return e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0}),this.operationControllers.add(n),{generation:this.lifecycleGeneration,options:{...e,signal:n.signal},dispose:()=>{e.signal?.removeEventListener("abort",i),this.operationControllers.delete(n)}}}lifecycleCurrent(e){return!this.destroyed&&e===this.lifecycleGeneration}destroyedOutcome(e){return!e.ok&&e.problem.code==="operation_outcome_unknown"?e:g(w("session_destroyed","This session was destroyed before the operation finished."))}autoSelectOnlyConnection(){if(this.autoSelect!=="only"||this.selection.selectedCollectionId())return;let e=this.connect.connections();e.length===1&&this.selection.select(e[0].collectionId,{history:"replace"})}refresh(){if(!(!this.started||this.destroyed||this.snapshot.status==="starting"||this.snapshot.status==="start_failed")){if(this.transactionDepth>0){this.refreshQueued=!0;return}if(this.refreshing){this.refreshQueued=!0;return}this.refreshing=!0;try{do this.refreshQueued=!1,this.publishCurrent();while(this.refreshQueued)}finally{this.refreshing=!1}}}publishCurrent(){let e=this.selection.selectedCollectionId(),n=this.connect.connections(),i=e?this.connect.connection(e):null;i?.collectionId!==this.activeCollectionId&&(this.stopActiveConnection?.(),this.activeCollectionId=i?.collectionId??null,this.stopActiveConnection=i?.onConnectionChange(r=>{!r&&this.selection.selectedCollectionId()===i.collectionId&&(this.unavailableReason="authorization_lost"),this.refresh()}));let o;if(!e)o={status:"unselected",connections:n};else if(!i||!i.info())o={status:"unavailable",collectionId:e,reason:this.connect.unavailableReason(e)??this.unavailableReason,connections:n};else{let r=i.info();o={status:"ready",collectionId:e,connection:i,info:r,access:i.authorizationCapabilities(this.operations),connections:n}}this.publish(o)}publish(e){if(this.snapshot.status==="destroyed"&&e.status!=="destroyed")return;let n=fs(e);if(n!==this.snapshotKey){this.snapshot=e,this.snapshotKey=n;for(let i of this.listeners)i()}}};function fs(t){return t.status==="not_started"||t.status==="starting"||t.status==="destroyed"?JSON.stringify(t):t.status==="start_failed"?JSON.stringify({status:t.status,problem:t.problem,connections:t.connections}):t.status==="unselected"?JSON.stringify({status:t.status,connections:t.connections}):t.status==="unavailable"?JSON.stringify({status:t.status,collectionId:t.collectionId,reason:t.reason,connections:t.connections}):JSON.stringify({status:t.status,collectionId:t.collectionId,info:t.info,access:t.access,connections:t.connections})}var mt=class{values=new Map;read(e){return this.values.get(e)??null}write(e,n){this.values.set(e,n)}remove(e){this.values.delete(e)}},Ne=class{constructor(e,n,i=xe()){this.connect=e;this.options=n;this.timeouts=i;this.verificationStore=n.verificationStore??bs()}connect;options;timeouts;listeners=new Set;verificationStore;snapshot={status:"not_started",connections:[]};manifest=null;application=null;base=null;stopBase;setupAssessment=null;setupTypePackAdoptions=null;verificationGeneration=0;readinessController;lifecycleGeneration=0;operationControllers=new Set;startOperation=null;start(e){if(this.snapshot.status==="destroyed")return Promise.resolve(g(w("session_destroyed","This application session has been destroyed.")));if(this.base&&!this.startOperation)return Promise.resolve(I(this.snapshot));let n=this.startOperation??this.beginStart();return this.waitForStart(n,e,this.timeouts.watchStartMs)}async waitForStart(e,n,i){e.waiters+=1;try{return await F(n,i,()=>e.promise)}catch(o){if(o instanceof b)return g(o.problem);throw o}finally{e.waiters-=1,e.waiters===0&&this.startOperation===e&&this.abandonStart(e)}}abandonStart(e){e.controller.abort(),this.readinessController?.abort(),this.startOperation=null,this.lifecycleGeneration+=1,this.verificationGeneration+=1,this.base&&this.cleanupBase(this.base),this.application=null,this.manifest=null,this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"not_started",connections:this.connect.connections()})}beginStart(){this.publish({status:"starting",connections:this.connect.connections()});let e=new AbortController,n=++this.lifecycleGeneration,i={promise:this.startWithinBudget({signal:e.signal,timeoutMs:null},n),controller:e,waiters:0,generation:n};this.startOperation=i;let o=()=>{this.startOperation===i&&(this.startOperation=null)};return i.promise.then(o,o),i}async startWithinBudget(e,n){try{return await this.performStartWithinBudget(e,n)}catch(i){if(i instanceof b)return this.startFailure(i.problem,n);throw n===this.lifecycleGeneration&&(this.verificationGeneration+=1,this.base&&this.cleanupBase(this.base),this.application=null,this.manifest=null,this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"not_started",connections:this.connect.connections()})),i}}async performStartWithinBudget(e,n){let i=await this.connect.register(e);if(!i.ok)return this.startFailure(i.problem,n);let o=await this.connect.manifest(e);if(!o.ok)return this.startFailure(o.problem,n);if(o.value.requirements?.access!=="full_collection")return this.startFailure(w("invalid_application_manifest","Application sessions require explicit full_collection access.",{details:{issues:[{path:"/requirements/access",keyword:"const",message:"must be full_collection",params:{allowedValue:"full_collection"}}]}}),n);let r=o.value.requirements.capabilities;if(!r)return this.startFailure(w("invalid_application_manifest","Application sessions require a versioned semantic capability contract.",{details:{issues:[{path:"/requirements/capabilities",keyword:"required",message:"is required for application sessions",params:{}}]}}),n);if(n!==this.lifecycleGeneration||e.signal?.aborted)return g(w("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}));this.application=i.value,this.manifest=o.value;let a=new Le(this.connect,{selection:this.options.selection,autoSelect:this.options.autoSelect,operations:hs(r,o.value)});this.base=a;try{let s=await a.start(e);return s.ok?n!==this.lifecycleGeneration||e.signal?.aborted?(this.cleanupBase(a),g(w("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}))):(this.stopBase=a.subscribe(()=>{this.base===a&&this.refresh()}),await this.refresh(!0,e),n!==this.lifecycleGeneration||e.signal?.aborted?(this.cleanupBase(a),g(w("operation_cancelled","Application session startup was cancelled.",{operationOutcome:"not_sent"}))):I(this.snapshot)):(this.cleanupBase(a),this.startFailure(s.problem,n))}catch(s){throw this.cleanupBase(a),s}}startFailure(e,n){return n===this.lifecycleGeneration&&this.publish({status:"start_failed",problem:e,connections:this.connect.connections()}),g(e)}destroy(){if(this.snapshot.status!=="destroyed"){this.lifecycleGeneration+=1,this.verificationGeneration+=1,this.readinessController?.abort(),this.startOperation?.controller.abort(),this.startOperation=null;for(let e of this.operationControllers)e.abort();this.operationControllers.clear(),this.base&&this.cleanupBase(this.base),this.application=null,this.manifest=null,this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"destroyed",connections:[]}),this.listeners.clear()}}cleanupBase(e){this.base===e&&(this.stopBase?.(),this.stopBase=void 0,e.destroy(),this.base=null)}getSnapshot(){return this.snapshot}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}connection(){let e=this.base?.getSnapshot();return e?.status==="ready"?e.connection:null}select(e,n={}){let i=this.lifecycleBase();return i.ok?i.value.select(e,n):i}clearSelection(e={}){let n=this.lifecycleBase();return n.ok?(n.value.clearSelection(e),I(void 0)):n}forget(e){let n=this.lifecycleBase();return n.ok?(n.value.forget(e),I(void 0)):n}authorize(e,n={}){return this.withLifecycleBase(n,async(i,o,r)=>{let a=await i.authorize(e,{...n,...o});return a.ok&&a.value.kind==="connected"&&this.lifecycleCurrent(r)&&await this.refresh(!0,o),a})}handleAuthorizationCallback(e,n){let i=String(e),o=this.startOperation!==null&&this.options.selection.authorizationCallback()===i;return this.withLifecycleBase(n,async(r,a,s)=>{if(o){let l=r.getSnapshot();return l.status==="ready"?I(l.connection):g(w("collection_not_ready","Authorization did not produce a ready collection."))}let c=await r.handleAuthorizationCallback(i,a);return c.ok&&this.lifecycleCurrent(s)&&await this.refresh(!0,a),c})}completeAuthorization(e,n){let i=e===void 0?Ut():String(e),o=this.startOperation!==null&&this.options.selection.authorizationCallback()===i;return this.withLifecycleBase(n,async(r,a,s)=>{if(o){let l=r.getSnapshot();return l.status==="ready"?I(l.connection):g(w("collection_not_ready","Authorization did not produce a ready collection."))}let c=await r.handleAuthorizationCallback(i,a);return c.ok&&this.lifecycleCurrent(s)&&await this.refresh(!0,a),c})}ensureCapabilities(e,n){return this.withLifecycleBase(n,(i,o,r)=>{Q(this.manifest.requirements,{...n,capabilities:e});let a=this.manifest.requirements?.capabilities,s=new Set([...a?.required??[],...a?.optional??[]]);return e.some(c=>!s.has(c))?Promise.resolve(g(w("invalid_application_manifest","Applications may only request capabilities declared in their manifest.",{details:{issues:[{path:"/requirements/capabilities",keyword:"undeclaredCapability",message:"must declare every capability requested by the application",params:{requested:e,declared:[...s]}}]}}))):i.ensureCapabilities(e,o).then(async c=>(c.ok&&c.value.kind==="connected"&&this.lifecycleCurrent(r)&&await this.refresh(!0,o),c))})}ensureOperations(e,n){return this.withLifecycleBase(n,async(i,o,r)=>{Q(this.manifest.requirements,{...n,operations:e});let a=await i.ensureOperations(e,o);return a.ok&&a.value.kind==="connected"&&this.lifecycleCurrent(r)&&await this.refresh(!0,o),a})}applyCollectionSetup(e){return this.withLifecycleBase(e,(n,i,o)=>this.applyCollectionSetupStarted(i,o))}async applyCollectionSetupStarted(e,n){if(this.snapshot.status!=="setup_review_required"||!this.setupAssessment)return g(w("collection_not_ready","There is no reviewed collection setup to apply."));if(!this.setupAssessment.applicable)return g(w("collection_not_ready","Resolve the collection setup conflicts before applying this update."));let i=this.connection();if(!i)return g(w("collection_not_ready","The collection is not ready."));let o=this.verificationGeneration,r=this.setupAssessment,a={...this.collectionSetupInput(this.setupTypePackAdoptions??void 0),expectedAssessmentDigest:r.assessmentDigest,expectedCollectionRevision:r.collectionRevision,expectedProvisionDigest:r.provisionDigest,allowTypePackDowngrades:r.typePacks.filter(c=>c.status==="downgrade").map(c=>c.desired.id)},s=await i.applyCollectionSetup(a,e);return this.lifecycleCurrent(n)?o!==this.verificationGeneration||this.connection()!==i?g(w("collection_not_ready","The selected collection changed during setup.")):s.ok?(this.setupAssessment=null,this.setupTypePackAdoptions=null,await this.verifySetup(this.context(i),++this.verificationGeneration,e),I(this.snapshot)):(s.problem.code==="application_declaration_mismatch"&&(this.setupAssessment=null,this.setupTypePackAdoptions=null,this.publish({status:"authorization_required",...this.context(i)})),s):!s.ok&&s.problem.code==="operation_outcome_unknown"?g(s.problem):g(w("session_destroyed",yt("session_destroyed")))}async refresh(e=!1,n){if(!this.base||!this.manifest)return;let i=this.base.getSnapshot();this.readinessController?.abort(),this.verificationGeneration+=1;let o=this.verificationGeneration;if(this.setupAssessment=null,this.setupTypePackAdoptions=null,i.status==="unselected"){this.publish({status:"unselected",connections:i.connections});return}if(i.status==="unavailable"){this.publish(i);return}if(i.status!=="ready")return;let r=this.context(i.connection);if(this.connect.connectionApplicationId(i.collectionId)!==this.application?.id){this.publish({status:"authorization_required",...r});return}if(!r.capabilities.requiredAvailable||r.readiness?.files.state==="requires_authorization"||!_s(this.manifest,r.info)){this.publish({status:"authorization_required",...r});return}if(!((this.manifest.provisions?.type_packs.length??0)>0||(this.manifest.provisions?.configuration?.length??0)>0)){let l=this.publishReady(r,o,n);e&&await l;return}let s=It(this.manifest,i.collectionId);r.readiness?.contracts.state!=="checking"&&this.verificationStore.read(s)===Mn(this.manifest)?this.publish({status:"ready",verification:"cached",...r}):this.publish({status:"checking_setup",...r});let c=this.verifySetup(r,o,n);e&&await c}async verifySetup(e,n,i){let o=this.connection(),r=this.requireManifest();if(!o||o.collectionId!==e.collectionId)return;let a=this.collectionSetupInput(),s=i?await o.assessCollectionSetup(a,i):await o.assessCollectionSetup(a);if(n===this.verificationGeneration){if(!s.ok){this.publish(s.problem.code==="application_declaration_mismatch"?{status:"authorization_required",...e}:{status:"blocked",problem:s.problem,...e});return}if(!s.value.applicable){let c=gs(s.value);if(Object.keys(c).length>0){if(s=i?await o.assessCollectionSetup(this.collectionSetupInput(c),i):await o.assessCollectionSetup(this.collectionSetupInput(c)),n!==this.verificationGeneration)return;if(!s.ok){this.publish(s.problem.code==="application_declaration_mismatch"?{status:"authorization_required",...e}:{status:"blocked",problem:s.problem,...e});return}this.setupTypePackAdoptions=c}}if(n===this.verificationGeneration){if(s.value.status!=="current"){this.setupAssessment=s.value,this.verificationStore.remove(It(r,e.collectionId)),this.publish({status:"setup_review_required",update:ms(s.value,r.provisions?.type_packs??[]),...e});return}this.verificationStore.write(It(r,e.collectionId),Mn(r)),e.readiness&&(e.readiness.setup={state:"current",evidence:[{source:"authority",fact:"Collection setup assessment is current."}]}),await this.publishReady(e,n,i)}}}async publishReady(e,n,i){let o=this.requireManifest().requirements?.contracts??[];if(e.readiness&&o.length){let r=this.connection();if(!r||r.collectionId!==e.collectionId)return;this.publish({status:"checking_setup",...e});let a=new AbortController;this.readinessController?.abort(),this.readinessController=a;try{if(!await Li({...e,readiness:e.readiness,contracts:o,connection:r,controller:a,options:i,requestMs:this.timeouts.requestMs,isCurrent:()=>n===this.verificationGeneration&&this.connection()===r,publish:s=>this.publish({...s,...e})}))return}finally{this.readinessController===a&&(this.readinessController=void 0)}}n===this.verificationGeneration&&this.publish({status:"ready",verification:"verified",...e})}collectionSetupInput(e){let n=this.requireManifest(),i=this.requireApplication();return ji(n,ft(i.family_identity),`sha256:${i.manifest_digest}`,e)}context(e){return Bi(this.requireManifest(),e.collectionId,e.info(),this.connect.connections())}publish(e){if(!(this.snapshot.status==="destroyed"&&e.status!=="destroyed")&&("readiness"in e&&e.readiness&&(e={...e,readiness:Ni(e.readiness,e.status,e.status==="ready"?e.verification:void 0)}),JSON.stringify(this.snapshot)!==JSON.stringify(e))){this.snapshot=e;for(let n of this.listeners)n()}}lifecycleBase(){let e=this.snapshot.status;if(this.startOperation||e==="starting")return g(w("session_starting","The application session is still starting."));if(this.snapshot.status==="start_failed")return g(this.snapshot.problem);if(this.base)return I(this.base);let n=e==="destroyed"?"session_destroyed":"session_not_started";return g(w(n,yt(n)))}async withLifecycleBase(e,n){let i=this.beginLifecycleOperation(e),o=pe(i.options,this.timeouts.requestMs),r={signal:o.signal,timeoutMs:null};try{let a=this.startOperation;if(a){let l=await this.waitForStart(a,r,null);if(!l.ok)return l}if(!this.lifecycleCurrent(i.generation))return g(w("session_destroyed",yt("session_destroyed")));let s=this.lifecycleBase();if(!s.ok)return s;let c=await n(s.value,r,i.generation);return this.lifecycleCurrent(i.generation)?c:this.destroyedOutcome(c)}catch(a){if(a instanceof b)return this.lifecycleCurrent(i.generation)?g(a.problem):a.problem.code==="operation_outcome_unknown"?g(a.problem):g(w("session_destroyed",yt("session_destroyed")));throw a}finally{o.dispose(),i.dispose()}}beginLifecycleOperation(e={}){let n=new AbortController,i=()=>n.abort(e.signal?.reason);return e.signal?.aborted?i():e.signal?.addEventListener("abort",i,{once:!0}),this.operationControllers.add(n),{generation:this.lifecycleGeneration,options:{...e,signal:n.signal},dispose:()=>{e.signal?.removeEventListener("abort",i),this.operationControllers.delete(n)}}}lifecycleCurrent(e){return this.snapshot.status!=="destroyed"&&e===this.lifecycleGeneration}destroyedOutcome(e){return!e.ok&&e.problem.code==="operation_outcome_unknown"?e:g(w("session_destroyed",yt("session_destroyed")))}requireManifest(){if(!this.manifest)throw new Error("Start the application session before using it.");return this.manifest}requireApplication(){if(!this.application)throw new Error("Start the application session before using it.");return this.application}};function hs(t,e){let n=(e.provisions?.type_packs.length??0)>0||(e.provisions?.configuration?.length??0)>0;return[...Ui(e.requirements),...t.contract_version===2&&n?Ct:[]]}function ys(t,e){let n=e.status==="conflict"?"Existing user-owned resources conflict with this application definition pack.":e.status==="install"?"This collection needs the application definitions installed.":`This collection has a ${e.status} definition change to review.`;return{id:e.desired.id,name:t.manifest.name??e.desired.id,status:e.status,applicable:e.applicable,assessmentDigest:e.assessmentDigest,...e.current?{currentVersion:e.current.version}:{},desiredVersion:e.desired.version,resources:e.resources,contractSetups:e.contractSetups,canApply:e.applicable,reason:n}}function ms(t,e){let n=t.typePacks.map(r=>{let a=e.find(s=>s.manifest.id===r.desired.id);if(!a)throw new Error(`Collection setup returned undeclared type pack '${r.desired.id}'.`);return ys(a,r)}),i=t.configuration.filter(r=>r.action!=="current").length,o=t.status==="conflict"?"Existing collection policy conflicts with this application's required setup.":`This application requires ${i} configuration change${i===1?"":"s"} and ${n.length} definition update${n.length===1?"":"s"}.`;return{status:t.status,applicable:t.applicable,assessmentDigest:t.assessmentDigest,collectionRevision:t.collectionRevision,provisionDigest:t.provisionDigest,configuration:t.configuration,typePacks:n,canApply:t.applicable,reason:o}}function gs(t){let e={};for(let n of t.typePacks){let i=Object.fromEntries(n.resources.filter(o=>o.action==="conflict"&&o.mode==="managed"&&o.currentDigest!==void 0&&o.installedDigest===void 0).map(o=>[o.target,o.currentDigest]));Object.keys(i).length>0&&(e[n.desired.id]=i)}return e}function _s(t,e){return t.requirements?.access==="full_collection"&&e.scope.access==="full_collection"&&e.scope.contracts.length===0}function yt(t){return t==="session_destroyed"?"This application session has been destroyed.":t==="session_starting"?"The application session is still starting.":"Start the application session before using it."}function bs(){return typeof localStorage<"u"?{read:t=>localStorage.getItem(t),write:(t,e)=>localStorage.setItem(t,e),remove:t=>localStorage.removeItem(t)}:new mt}function Z(t,e){return new Promise((n,i)=>{if(e?.aborted){i(e?.reason??new DOMException("Aborted","AbortError"));return}let o=()=>e?.removeEventListener("abort",a),r=setTimeout(()=>{o(),n()},t),a=()=>{clearTimeout(r),o(),i(e?.reason??new DOMException("Aborted","AbortError"))};e?.addEventListener("abort",a,{once:!0})})}var Cs="mdbase-connect-identities",Be="application-identities",Nn=BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),vs=Nn/2n,je=class{database=null;async create(e){let n=await Oo(e),i=await this.open();return await Po(i,o=>o.add(n)),n}async get(e){let n=await this.open();return await ws(n.transaction(Be).objectStore(Be).get(e))??null}async delete(e){let n=await this.open();await Po(n,i=>i.delete(e))}open(){if(typeof indexedDB>"u")throw new Re("Persistent application identity requires browser IndexedDB or an injected identity store.");return this.database||(this.database=new Promise((e,n)=>{let i=indexedDB.open(Cs,1);i.onupgradeneeded=()=>{i.result.objectStoreNames.contains(Be)||i.result.createObjectStore(Be,{keyPath:"handle"})},i.onerror=()=>n(i.error),i.onsuccess=()=>e(i.result)})),this.database}},Ke=class{records=new Map;async create(e){if(this.records.has(e))throw new Error(`Application identity already exists: ${e}`);let n=await Oo(e);return this.records.set(e,n),n}async get(e){return this.records.get(e)??null}async delete(e){this.records.delete(e)}},Re=class extends Error{constructor(e){super(e),this.name="ApplicationIdentityStoreError"}};async function Ve(t){return ki(t.signingPublicKey)}async function gt(t,e){if(t.installation_signing_public_key!==e.signingPublicKey||t.application_installation_id!==await Ve(e))throw new Error("Application authorization identity does not match its binding.");let n=As(new Uint8Array(await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e.signingPrivateKey,Ii(t))));return{binding:t,signature:To(n)}}async function Bt(t,e,n){let i=`application-installation:v2:${e}:${n.id}`,o=await t.get(i);if(o)return o;try{return await t.create(i)}catch(r){let a=await t.get(i);if(a)return a;throw r}}async function Oo(t){let e=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,["sign","verify"]),n=To(new Uint8Array(await crypto.subtle.exportKey("raw",e.publicKey))),i=await crypto.subtle.exportKey("pkcs8",e.privateKey),o=await crypto.subtle.importKey("pkcs8",i,{name:"ECDSA",namedCurve:"P-256"},!1,["sign"]);return{handle:t,signingPrivateKey:o,signingPublicKey:n}}function ws(t){return new Promise((e,n)=>{t.onerror=()=>n(t.error),t.onsuccess=()=>e(t.result)})}function Po(t,e){return new Promise((n,i)=>{let o=t.transaction(Be,"readwrite");e(o.objectStore(Be)).onerror=()=>i(o.error),o.onerror=()=>i(o.error),o.onabort=()=>i(o.error??new Error("Identity transaction aborted.")),o.oncomplete=()=>n()})}function Ss(t){let e=new Uint8Array(t.reduce((i,o)=>i+o.byteLength,0)),n=0;for(let i of t)e.set(i,n),n+=i.byteLength;return e}function To(t){return btoa(String.fromCharCode(...t)).replaceAll("+","-").replaceAll("/","_").replace(/=+$/u,"")}function As(t){if(t.byteLength!==64)throw new Error("Application authorization signature is invalid.");let e=Rs(t.slice(32));if(e===0n||e>=Nn)throw new Error("Application authorization signature is invalid.");return e<=vs?t:Ss([t.slice(0,32),Ps(Nn-e,32)])}function Rs(t){return BigInt(`0x${Os(t)}`)}function Ps(t,e){let n=t.toString(16).padStart(e*2,"0");return Uint8Array.from({length:e},(i,o)=>Number.parseInt(n.slice(o*2,o*2+2),16))}function Os(t){return[...t].map(e=>e.toString(16).padStart(2,"0")).join("")}async function*Io(t,e,n={},i={}){let{offset:o,limit:r,cursor:a,pagination:s,snapshot:c,...l}=n,u=Ts(o,0),p=ko(i.firstPageSize??i.pageSize??r,200),f=ko(i.pageSize??r,1e3),h=a,y=a!==void 0,A=a,C=c,m=0,v=0;try{for(;!i.signal?.aborted;){let _=h,R={signal:i.signal,timeoutMs:i.pageTimeoutMs,coordination:{...i.coordination,coalesce:!1}},T=v===0&&a===void 0&&s===void 0&&c===void 0,O=await t({...l,...y?{}:{limit:v===0?p:f},...y?_?{cursor:_}:{pagination:"cursor"}:{offset:u,...C?{snapshot:C}:{},...!C&&s==="cursor"?{pagination:"cursor"}:{}},...!y&&!C&&T?{pagination:"cursor"}:{}},R);if(T&&!O.ok&&O.problem.code==="operation_invalid"&&(O=await t({...l,limit:p,offset:u},R)),!O.ok){yield O;return}let S=O.value,P=S.meta?.cursor;if(P?(y=!0,h=P,A=P):y&&(h=void 0,A=_),y&&S.meta?.hasMore&&!P){yield g(w("invalid_operation_response","The collection authority omitted the cursor required for the next query page."));return}let q=S.meta?.snapshot;if(!y&&C&&q&&C!==q){yield g(w("query_snapshot_changed","The collection query snapshot changed while paging. Refresh the query before continuing."));return}!y&&!C&&q&&(C=q),m+=S.results.length;let H=!S.meta?.hasMore||S.results.length===0,ne={results:S.results,...S.meta?{meta:S.meta}:{},page:v,offset:u,loaded:m,complete:H,...P?{cursor:P}:{},...!y&&C?{snapshot:C}:{}};if(i.onProgress?.(ne),yield I(ne,O.diagnostics),H)return;u+=S.results.length,v+=1}}finally{y&&A&&e(A).catch(()=>{})}}function Ts(t,e){return typeof t=="number"&&Number.isFinite(t)?Math.max(0,Math.floor(t)):e}function ko(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):e}async function*xo(t,e,n,i={}){let{offset:o,limit:r,cursor:a,...s}=n,c=ks(o,0),l=Mo(i.firstPageSize??r,200),u=Mo(i.pageSize??r,1e3),p=a,f=a!==void 0,h=a,y=0,A=0;try{for(;!i.signal?.aborted;){let C=p,m=await t({...s,limit:A===0?l:u,...f&&C?{cursor:C}:{offset:c}},{signal:i.signal,timeoutMs:i.pageTimeoutMs,coordination:{...i.coordination,coalesce:!1}});if(!m.ok){yield m;return}let v=m.value,_=v.meta.cursor;if(_?(f=!0,p=_,h=_):f&&(p=void 0,h=C),f&&v.meta.hasMore&&!_){yield g(w("invalid_operation_response","The collection authority omitted the cursor required for the next saved-view page."));return}y+=v.results.length;let R=!v.meta.hasMore||v.results.length===0,T={...v,page:A,offset:c,loaded:y,complete:R,..._?{cursor:_}:{}};if(i.onProgress?.(T),yield I(T,m.diagnostics),R)return;c+=v.results.length,A+=1}}finally{f&&h&&await e(h)}}function ks(t,e){return typeof t=="number"&&Number.isFinite(t)?Math.max(0,Math.floor(t)):e}function Mo(t,e){return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):e}function Eo(t){if(t!==!1)return{initialDelayMs:Math.max(0,t?.initialDelayMs??500),maxDelayMs:Math.max(0,t?.maxDelayMs??15e3),multiplier:Math.max(1,t?.multiplier??2),...t?.maxAttempts===void 0?{}:{maxAttempts:Math.max(0,t.maxAttempts)}}}var Ge=class{constructor(e,n=Me){this.transport=e;this.requestTimeoutMs=n}transport;requestTimeoutMs;operation(e,n,i){return D(()=>this.transport.operation(e,n,i),Ki)}async describe(e){let n=await this.rawOperation("describe",{},Mt,e);return L(n,Gs)}async changes(e={},n){let i=await this.rawOperation("changes",e,xt,n);return L(i,Vs)}async read(e,n){let i=await this.envelopeOperation("read",Is(e),ie,n);return L(i,jt)}async query(e={},n){let i=await this.envelopeOperation("query",Ms(e),En,n);return L(i,({results:o,meta:r})=>({results:o.map(Vo),...r?{meta:{...typeof r.total_count=="number"?{totalCount:r.total_count}:{},...r.total_count_outcome===void 0?{}:{totalCountOutcome:r.total_count_outcome},hasMore:r.has_more,...r.cursor?{cursor:r.cursor}:{},...r.snapshot?{snapshot:r.snapshot}:{}}}:{}}))}async*queryPages(e={},n={}){yield*Io((i,o)=>this.query(i,o),i=>this.releaseQueryCursor(i),e,n)}async queryAll(e={},n={}){let i=pe(n,this.requestTimeoutMs),o=[],r,a=[];try{for await(let s of this.queryPages(e,{firstPageSize:n.firstPageSize,pageSize:n.pageSize,signal:i.signal,pageTimeoutMs:null,coordination:n.coordination,onProgress:n.onProgress})){if(!s.ok)return s;let c=s.value;o.push(...c.results),r=c,a.push(...s.diagnostics)}if(i.signal.aborted)throw J(i.signal);return I({results:o,meta:{totalCount:r?.meta?.totalCount??o.length,hasMore:r?!r.complete:!1,...r?.snapshot?{snapshot:r.snapshot}:{}}},a)}catch(s){if(s instanceof b)return g(s.problem);throw s}finally{i.dispose()}}async listViews(e){let n=await this.envelopeOperation("list_views",{},ie,e);return L(n,i=>({views:i.views,meta:{totalCount:i.meta.total_count}}))}async executeView(e,n){let i=await this.envelopeOperation("execute_view",e,ie,n);return L(i,Ls)}async*executeViewPages(e,n={}){yield*xo((i,o)=>this.executeView(i,o),i=>this.releaseQueryCursor(i),e,n)}readViewSource(e,n){return this.envelopeOperation("read_view_source",e,ie,n)}createViewSource(e,n){return this.envelopeOperation("create_view_source",e,j,n)}updateViewSource(e,n){return this.envelopeOperation("update_view_source",Bn(e),j,n)}deleteViewSource(e,n){return this.envelopeOperation("delete_view_source",Bn(e),j,n)}async create(e,n){let i=await this.envelopeOperation("create",xs(e),j,n);return L(i,jt)}async update(e,n){let i=await this.envelopeOperation("update",Es(e),j,n);return L(i,jt)}async delete(e,n){let i=await this.envelopeOperation("delete",qo(e),j,n);return L(i,Bo)}async preflightDelete(e,n){let i=await this.envelopeOperation("delete",{...qo(e),check_backlinks:!0,dry_run:!0},j,n);return L(i,Fs)}async rename(e,n){let i=await this.envelopeOperation("rename",zo(e),j,n);return L(i,Ds)}async preflightRename(e,n){let i=await this.envelopeOperation("rename",{...zo(e),dry_run:!0},j,n);return L(i,Us)}validate(e={},n){return this.envelopeOperation("validate",e,ie,n)}readType(e,n){return this.envelopeOperation("read_type",e,he,n)}createType(e,n){return this.envelopeOperation("create_type",e,he,n)}updateType(e,n){return this.envelopeOperation("update_type",Bn(e),he,n)}async assessTypePack(e,n){let i=await this.envelopeOperation("assess_type_pack",Lo(e),he,n);return L(i,Kn)}async applyTypePack(e,n){let i=await this.envelopeOperation("apply_type_pack",qs(e),he,n);return L(i,Bs)}async assessCollectionSetup(e,n){let i=await this.envelopeOperation("assess_collection_setup",No(e),he,n);return L(i,Uo)}async applyCollectionSetup(e,n){let i=await this.envelopeOperation("apply_collection_setup",zs(e),he,n);return L(i,o=>({assessment:Uo(o.assessment),receipt:js(o.receipt)}))}async listTimers(e,n){let i=await this.rawOperation("list_timers",{namespace:e},ie,n);return L(i,o=>({namespace:o.namespace,timers:o.timers.map(jn)}))}async putTimer(e,n){let i=await this.rawOperation("put_timer",{namespace:e.namespace,criterion_id:e.criterionId,timer:Fo(e.timer)},j,n);return L(i,jn)}cancelTimer(e,n){return this.rawOperation("cancel_timer",e,j,n)}async reconcileTimers(e,n){let i=await this.rawOperation("reconcile_timers",{namespace:e.namespace,criterion_id:e.criterionId,timers:e.timers.map(Fo)},j,n);return L(i,o=>({namespace:o.namespace,timers:o.timers.map(jn),cancelledIds:o.cancelled_ids}))}async*watch(e={}){let n=e.cursor,i=Math.max(100,e.pollIntervalMs??1e3),o=Eo(e.retry),r=0,a=!1;for(e.onStatus?.({state:"connecting",...n===void 0?{}:{cursor:n}});!e.signal?.aborted;){let s=await this.changes(n===void 0?{}:{after:n,limit:200},{signal:e.signal,timeoutMs:e.timeoutMs});if(!s.ok){let u=s.problem;if(e.signal?.aborted)return;if(!o||u.recovery!=="retry"){yield s;return}if(a=!1,r+=1,o.maxAttempts!==void 0&&r>o.maxAttempts){yield s;return}let p=Math.min(o.maxDelayMs,Math.round(o.initialDelayMs*o.multiplier**(r-1)));e.onStatus?.({state:"reconnecting",...n===void 0?{}:{cursor:n},attempt:r,retryInMs:p,problem:u});try{await Z(p,e.signal)}catch{if(!e.signal?.aborted)throw d("operation_failed","Watch retry delay failed unexpectedly.")}continue}let c=s.value;if(n===void 0){n=c.cursor;continue}if(c.reset){let u=w("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again.");e.onStatus?.({state:"reset_required",cursor:n,problem:u}),yield g(u);return}let l=r>0;r=0,(!a||l)&&e.onStatus?.({state:"connected",cursor:n,recovered:l}),a=!0;for(let u of c.events)yield I(u);if(n=c.cursor,!c.hasMore)try{await Z(i,e.signal)}catch{if(!e.signal?.aborted)throw d("operation_failed","Watch polling delay failed unexpectedly.")}}}rawOperation(e,n,i,o){return D(()=>this.transport.operation(e,n,o),i)}async releaseQueryCursor(e){try{await this.envelopeOperation("query",{release_cursor:e},En,{timeoutMs:2e3,coordination:{coalesce:!1}})}catch{}}async envelopeOperation(e,n,i,o){let r=await D(()=>this.transport.operation(e,n,o),i);if(!r.ok)return r;let a=r.value;return a.valid?I(a.result,a.diagnostics):g(ke(a))}};function L(t,e){return t.ok?I(e(t.value),t.diagnostics):t}function Is(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function Ms(t){return{...t.types?{types:t.types}:{},...t.timezone?{timezone:t.timezone}:{},...t.context?{context:t.context}:{},...t.projections?{projections:Object.fromEntries(Object.entries(t.projections).map(([e,n])=>[e,{expr:n.expression,...n.description?{description:n.description}:{}}]))}:{},...t.where?{where:t.where}:{},...t.select?{select:t.select.map(e=>typeof e=="string"?e:{name:e.name,expr:e.expression,...e.label?{label:e.label}:{},...e.description?{description:e.description}:{}})}:{},...t.orderBy?{order_by:t.orderBy}:{},...t.groupBy?{group_by:t.groupBy}:{},...t.summaryFunctions?{summary_functions:Object.fromEntries(Object.entries(t.summaryFunctions).map(([e,n])=>[e,{expr:n.expression,...n.description?{description:n.description}:{}}]))}:{},...t.summaries?{summaries:t.summaries}:{},...t.limit===void 0?{}:{limit:t.limit},...t.offset===void 0?{}:{offset:t.offset},...t.pagination?{pagination:t.pagination}:{},...t.cursor?{cursor:t.cursor}:{},...t.snapshot?{snapshot:t.snapshot}:{},...t.includeBody===void 0?{}:{include_body:t.includeBody},...t.frontmatterMode?{frontmatter_mode:t.frontmatterMode}:{},...t.contract?{contract:t.contract}:{}}}function xs(t){return{...t.path?{path:t.path}:{},...t.type?{type:t.type}:{},...t.contract?{contract:t.contract}:{},...t.frontmatter?{frontmatter:t.frontmatter}:{},...t.body===void 0?{}:{body:t.body},...t.ifRevision?{if_revision:t.ifRevision}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function Es(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.ifRevision?{if_revision:t.ifRevision}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument},...t.document===void 0?{patch:t.patch,...t.body===void 0?{}:{body:t.body}}:{document:t.document}}}function qo(t){return{path:t.path,...t.contract?{contract:t.contract}:{},...t.checkBacklinks===void 0?{}:{check_backlinks:t.checkBacklinks},...t.ifRevision?{if_revision:t.ifRevision}:{}}}function zo(t){return{from:t.from,to:t.to,...t.contract?{contract:t.contract}:{},...t.updateRefs===void 0?{}:{update_refs:t.updateRefs},...t.ifRevision?{if_revision:t.ifRevision}:{},...t.includeDocument===void 0?{}:{include_document:t.includeDocument}}}function Bn(t){let{ifRevision:e,...n}=t;return{...n,...e?{if_revision:e}:{}}}function Lo(t){return{provision:t.provision,installed_by:t.installedBy,...t.adoptResources?{adopt_resources:t.adoptResources}:{},...t.preserveSeedTargets?{preserve_seed_targets:t.preserveSeedTargets}:{},...t.targetOverrides?{target_overrides:t.targetOverrides}:{},...t.contractSetups?{contract_setups:t.contractSetups.map(jo)}:{}}}function qs(t){return{...Lo(t),expected_assessment_digest:t.expectedAssessmentDigest,...t.allowDowngrade===void 0?{}:{allow_downgrade:t.allowDowngrade}}}function No(t){return{application_id:t.applicationId,declaration_digest:t.declarationDigest,requirements:t.requirements,provisions:{configuration:t.provisions.configuration,type_packs:t.provisions.typePacks},...t.contractSetups?{contract_setups:t.contractSetups.map(jo)}:{},...t.typePackAdoptions?{type_pack_adoptions:t.typePackAdoptions}:{}}}function zs(t){return{...No(t),expected_assessment_digest:t.expectedAssessmentDigest,expected_collection_revision:t.expectedCollectionRevision,expected_provision_digest:t.expectedProvisionDigest,...t.allowTypePackDowngrades?{allow_type_pack_downgrades:t.allowTypePackDowngrades}:{}}}function Bo(t){return{path:t.path,deleted:t.deleted,...t.broken_links?{brokenLinks:t.broken_links}:{}}}function Fs(t){return{...Bo(t),deleted:!1,dryRun:!0,wouldDelete:!0}}function Ds(t){let{references_updated:e,...n}=t;return{...jt(n),from:t.from,to:t.to,...e?{referencesUpdated:e}:{}}}function Us(t){return{from:t.from,to:t.to,dryRun:!0,wouldRename:!0,...t.references_affected?{referencesAffected:t.references_affected}:{},...t.warnings?{warnings:t.warnings}:{}}}function Fo(t){return{id:t.id,fire_at:t.fireAt,...t.data===void 0?{}:{data:t.data}}}function jn(t){return{id:t.id,fireAt:t.fire_at,...t.data===void 0?{}:{data:t.data},criterionId:t.criterion_id,generation:t.generation,status:t.status,createdAt:t.created_at,updatedAt:t.updated_at,firedAt:t.fired_at}}function jo(t){return t.mode==="starter"?t:{contract:t.contract,mode:"existing",type_name:t.typeName,type_revision:t.typeRevision,fields:t.fields,...t.binding?{binding:t.binding}:{}}}function Ko(t){return{id:t.id,version:t.version,digest:t.digest,type:t.type,implementationDigest:t.implementation_digest}}function Vo(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,...e===void 0?{}:{effectiveFrontmatter:e},...n?{contract:Ko(n)}:{}}}function jt(t){let{effective_frontmatter:e,contract:n,...i}=t;return{...i,effectiveFrontmatter:e,...n?{contract:Ko(n)}:{}}}function Ls(t){return{results:t.results.map(e=>{let n=Vo(e);if(!n.effectiveFrontmatter)throw new Error("Saved view result omitted canonical effective frontmatter.");return{...n,effectiveFrontmatter:n.effectiveFrontmatter}}),meta:{totalCount:t.meta.total_count,hasMore:t.meta.has_more,...t.meta.cursor?{cursor:t.meta.cursor}:{},view:t.meta.view,...t.meta.context?{context:t.meta.context}:{},...t.meta.groups?{groups:t.meta.groups}:{}}}}function Do(t){return{source:t.source,target:t.target,kind:t.kind,mode:t.mode,action:t.action,digest:t.digest,...t.current_digest?{currentDigest:t.current_digest}:{},...t.installed_digest?{installedDigest:t.installed_digest}:{},...t.adopted_from_digest?{adoptedFromDigest:t.adopted_from_digest}:{},...t.reason?{reason:t.reason}:{}}}function Kt(t){return{id:t.id,version:t.version,digest:t.digest,installedBy:t.installed_by,resources:t.resources.map(e=>({source:e.source,target:e.target,kind:e.kind,mode:e.mode,digest:e.digest,...e.adopted_from_digest?{adoptedFromDigest:e.adopted_from_digest}:{}}))}}function Ns(t){return t.mode==="starter"?t:{contract:t.contract,mode:"existing",typeName:t.type_name,typeRevision:t.type_revision,fields:t.fields,...t.binding?{binding:t.binding}:{}}}function Kn(t){return{status:t.status,applicable:t.applicable,assessmentDigest:t.assessment_digest,...t.current?{current:Kt(t.current)}:{},desired:Kt(t.desired),resources:t.resources.map(Do),lock:t.lock,contractSetups:{choices:t.contract_setups.choices.map(Ns),resources:t.contract_setups.resources.map(Do)}}}function Bs(t){return{...Kn(t),receipt:Kt(t.receipt),cleanupDeferred:t.cleanup_deferred}}function Uo(t){return{status:t.status,applicable:t.applicable,applicationId:t.application_id,declarationDigest:t.declaration_digest,provisionDigest:t.provision_digest,collectionRevision:t.collection_revision,finalCollectionRevision:t.final_collection_revision,baselineDiagnosticCount:t.baseline_diagnostic_count,finalDiagnosticCount:t.final_diagnostic_count,resolvedDiagnosticCount:t.resolved_diagnostic_count,introducedDiagnosticCount:t.introduced_diagnostic_count,baselineDiagnosticDigest:t.baseline_diagnostic_digest,configuration:t.configuration,typePacks:t.type_packs.map(Kn),finalResourceRevisions:t.final_resource_revisions,assessmentDigest:t.assessment_digest}}function js(t){return{applicationId:t.application_id,declarationDigest:t.declaration_digest,provisionDigest:t.provision_digest,assessmentDigest:t.assessment_digest,collectionRevision:t.collection_revision,configuration:t.configuration,typePacks:t.type_packs.map(Kt),cleanupDeferred:t.cleanup_deferred}}function Ks(t){return{cursor:t.cursor,type:t.type,occurredAt:t.occurred_at,payload:t.payload}}function Vs(t){return{events:t.events.map(Ks),cursor:t.cursor,hasMore:t.has_more,reset:t.reset}}function Gs(t){return{protocolVersion:t.protocol_version,collectionId:t.collection_id,displayName:t.display_name,specVersion:t.spec_version,operations:t.operations,changeCursor:t.change_cursor,types:t.types,contracts:t.contracts.map(e=>({contractType:e.contract_type,id:e.id,version:e.version,digest:e.digest,schema:e.schema,...e.binding_schema?{bindingSchema:e.binding_schema}:{},implementations:e.implementations.map(n=>({typeName:n.type_name,typeVersion:n.type_version,...n.type_path?{typePath:n.type_path}:{},digest:n.digest,fields:n.fields,...n.binding?{binding:n.binding}:{}}))})),...t.configuration?{configuration:t.configuration}:{}}}var Vt=class{constructor(e){this.context=e}context;async registerNotifications(e){return F(e,this.context.requestTimeoutMs,n=>this.registerNotificationsWithinBudget(e,n.signal))}async registerNotificationsWithinBudget(e,n){let i=await this.context.authorizedToken(n);if(!i)throw d("not_authorized","Connect this application before enabling notifications.");let r=(await this.context.register(n)).notifications?.criteria.map(m=>m.id)??[],a=[...new Set(e.criteria??r)],s=a.find(m=>!r.includes(m));if(s)throw d("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${s}.`);if(a.length===0)throw d("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=await ae(`${this.context.serverUrl}/v1/notifications/vapid-public-key`,{signal:n},"notifications_unavailable","Push notifications are unavailable."),l=await E(c,"invalid_operation_response","Connect returned an invalid notification key response.");if(!c.ok)throw z(l,"notifications_unavailable","Push notifications are unavailable.",c.status);let u=await e.serviceWorker.pushManager.getSubscription();u||(u=await e.serviceWorker.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:fo(l.public_key)}));let p=u.toJSON();if(!p.endpoint||!p.keys?.p256dh||!p.keys.auth)throw d("invalid_push_subscription","The browser returned an incomplete push subscription.");let f=M(this.context.storage.getItem(this.context.notificationKey())),h=e.installationId??f?.installationId??X(24),y=await ae(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${i.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:h,criteria:a,subscription:{endpoint:p.endpoint,expirationTime:p.expirationTime??null,keys:p.keys}}),signal:n},"notification_registration_failed","Could not register push notifications."),A=await E(y,"invalid_operation_response","Connect returned an invalid notification registration response.");if(!y.ok)throw z(A,"notification_registration_failed","Could not register push notifications.",y.status);f?.channelId&&f.channelId!==A.channel_id&&fetch(`${this.context.serverUrl}/v1/notifications/channels/${f.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${i.accessToken}`},signal:n}).catch(()=>{});let C={channelId:A.channel_id,installationId:h,criteria:a};return this.context.storage.setItem(this.context.notificationKey(),JSON.stringify(C)),C}async registerNativeNotifications(e){return F(e,this.context.requestTimeoutMs,n=>this.registerNativeNotificationsWithinBudget(e,n.signal))}async registerNativeNotificationsWithinBudget(e,n){let i=await this.context.authorizedToken(n);if(!i)throw d("not_authorized","Connect this application before enabling notifications.");let o=await this.context.register(n);if(o.notifications?.native_delivery?.mode!=="managed_fcm")throw d("managed_fcm_not_declared","This application does not declare Connect-managed native notifications.");let r=o.notifications.criteria.map(y=>y.id),a=[...new Set(e.criteria??r)],s=a.find(y=>!r.includes(y));if(s)throw d("notification_criterion_not_declared",`The application manifest does not declare notification criterion ${s}.`);if(a.length===0)throw d("notifications_not_declared","This application manifest does not declare any notification criteria.");let c=this.context.notificationKey("fcm"),l=M(this.context.storage.getItem(c)),u=e.installationId??l?.installationId??X(24),p=await ae(`${this.context.serverUrl}/v1/notifications/channels`,{method:"POST",headers:{authorization:`Bearer ${i.accessToken}`,"content-type":"application/json"},body:JSON.stringify({installation_id:u,criteria:a,transport:"fcm",token:e.token}),signal:n},"notification_registration_failed","Could not register native notifications."),f=await E(p,"invalid_operation_response","Connect returned an invalid native notification response.");if(!p.ok)throw z(f,"notification_registration_failed","Could not register native notifications.",p.status);l?.channelId&&l.channelId!==f.channel_id&&this.deleteNotificationChannel(l.channelId,i.accessToken,n).catch(()=>{});let h={channelId:f.channel_id,installationId:u,transport:"fcm",criteria:a};return this.context.storage.setItem(c,JSON.stringify(h)),h}async unregisterNativeNotifications(e={}){return F(e,this.context.requestTimeoutMs,n=>this.unregisterNativeNotificationsWithinBudget(n.signal))}async unregisterNativeNotificationsWithinBudget(e){let n=this.context.notificationKey("fcm"),i=M(this.context.storage.getItem(n)),o=await this.context.authorizedToken(e);if(i?.channelId&&!o)throw d("not_authorized","Reconnect this application before disabling native notifications.");i?.channelId&&o&&await this.deleteNotificationChannel(i.channelId,o.accessToken,e),this.context.storage.removeItem(n)}async unregisterNotifications(e,n={}){return F(n,this.context.requestTimeoutMs,i=>this.unregisterNotificationsWithinBudget(e,i.signal))}async unregisterNotificationsWithinBudget(e,n){let i=M(this.context.storage.getItem(this.context.notificationKey())),o=await this.context.authorizedToken(n);if(i?.channelId&&!o)throw d("not_authorized","Reconnect this application before disabling push notifications.");if(i?.channelId&&o){let a=await ae(`${this.context.serverUrl}/v1/notifications/channels/${i.channelId}`,{method:"DELETE",headers:{authorization:`Bearer ${o.accessToken}`},signal:n},"notification_unregistration_failed","Could not unregister push notifications.");if(!a.ok&&a.status!==404){let s=await E(a,"invalid_operation_response","Connect returned an invalid notification response.");throw z(s,"notification_unregistration_failed","Could not unregister push notifications.",a.status)}}this.context.storage.removeItem(this.context.notificationKey()),await(await e?.pushManager.getSubscription())?.unsubscribe()}async deleteNotificationChannel(e,n,i){let o=await ae(`${this.context.serverUrl}/v1/notifications/channels/${e}`,{method:"DELETE",headers:{authorization:`Bearer ${n}`},signal:i},"notification_unregistration_failed","Could not unregister push notifications.");if(!o.ok&&o.status!==404){let r=await E(o,"invalid_operation_response","Connect returned an invalid notification response.");throw z(r,"notification_unregistration_failed","Could not unregister push notifications.",o.status)}}};async function Gt(t,e,n,i,o,r){if(!t.authority)throw d("not_remote_authority","This authorization has no remote authority endpoint.");let a=n===""||n.startsWith("?")?n:`/${n}`,s=`${t.authority.filesUrl}${a}`,c=i===void 0?void 0:JSON.stringify(i),l=await r(t,e,s,c,t.authority.accessToken);return fetch(s,{method:e,redirect:"error",headers:{authorization:`Bearer ${t.authority.accessToken}`,...c===void 0?{}:{"content-type":"application/json"},...l},...c===void 0?{}:{body:c},...o?{signal:o}:{}})}async function Go(t,e,n,i,o,r,a,s=async c=>c){let c=t,l=await Gt(c,e,n,i,o,a);if(l.status===401&&c.refreshToken){if(c=await s(await r(o)),!c.authority||!c.fileCapability)throw d("authority_authorization_changed","Reconnect this collection before accessing its files.");l=await Gt(c,e,n,i,o,a)}let u=await E(l,"invalid_operation_response","The hosted authority returned an invalid file response.");if(!l.ok)throw z(u,"operation_failed","Collection file request failed.",l.status);return u}async function Ho(t,e,n,i,o,r,a=async s=>s){let s=t,c=await Gt(s,"GET",e,void 0,i,r);if(c.status===401&&s.refreshToken){if(s=await a(await o(i)),!s.authority||!s.fileCapability)throw d("authority_authorization_changed","Reconnect this collection before accessing its files.");c=await Gt(s,"GET",e,void 0,i,r)}if(!c.ok){let u=await E(c,"invalid_operation_response","The hosted authority returned an invalid file range error response.");throw z(u,"operation_failed","Collection file range request failed.",c.status)}let l=c.headers.get("content-length");if(l===null||!/^(0|[1-9][0-9]*)$/u.test(l)||Number(l)!==n)throw await c.body?.cancel().catch(()=>{}),d("invalid_operation_response","The hosted file response declared an unexpected byte length.");if(!c.body)throw d("invalid_operation_response","The hosted file response did not contain a byte stream.");return c.body}var Ht=class{constructor(e,n){this.namespace=e;this.onFinalRelease=n}namespace;onFinalRelease;leases=new Map;locks=Hs();retainAutomaticallyRetiredKeys=this.locks===null;async acquire(e,n,i){let o=this.acquireLocal(e,n);if(!this.locks)return o;try{let r=await $s(this.locks,this.lockName(e,n),i);return Vn(()=>{r(),o()})}catch(r){throw o(),r}}deleteExclusive(e,n,i){this.retainAutomaticallyRetiredKeys||(this.locks?this.locks.request(this.lockName(e,n),{mode:"exclusive"},i).catch(()=>{}):this.has(e,n)||Promise.resolve().then(i).catch(()=>{}))}has(e,n){return this.leases.get(e)?.has(n)??!1}handles(e){return this.leases.get(e)?.keys()??[]}acquireLocal(e,n){let i=this.leases.get(e)??new Map;return i.set(n,(i.get(n)??0)+1),this.leases.set(e,i),Vn(()=>{let o=(i.get(n)??1)-1;o>0?i.set(n,o):(i.delete(n),i.size===0&&this.leases.delete(e),this.onFinalRelease(e,n))})}lockName(e,n){return`mdbase-connect:grant-key:${this.namespace}:${e}:${n}`}},ge=class{constructor(e,n){this.collectionId=e;this.acquire=n}collectionId;acquire;releases=new Map;async retain(e,n){let i=typeof e=="string"?e:e?.keyHandle;if(!i)return;let o=this.releases.get(i);o||(o=this.acquire(this.collectionId,i,n),this.releases.set(i,o));try{await o}catch(r){throw this.releases.get(i)===o&&this.releases.delete(i),this.release(),r}}release(){for(let e of this.releases.values())e.then(n=>n());this.releases.clear()}};async function V(t,e,n){for(;;){let i=t();if(!i)return null;await e.retain(i,n);let o=t();if(!o)return null;if(o.keyHandle===i.keyHandle)return o}}function Hs(){let t=typeof navigator>"u"?void 0:navigator.locks;return t||(typeof window<"u"||typeof globalThis.importScripts=="function"?null:void 0)}async function $s(t,e,n){let i,o,r,a=new Promise((l,u)=>{i=l,o=u}),s=new Promise(l=>{r=l});return t.request(e,{mode:"shared",...n?{signal:n}:{}},async()=>{i(),await s}).catch(o),await a,Vn(r)}function Vn(t){let e=!1;return()=>{e||(e=!0,t())}}var Ws="mdbase-connect file chunk key v1",$t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,se=class extends Error{constructor(n,i){super(i);this.code=n;this.name="FileTransferCryptoError"}code},He=class t{constructor(e,n){this.binding=e;this.key=n}binding;key;static async open(e,n,i){$o(i);let o=await e.get(n);if(!o||o.agreementPublicKey!==i.encryption.application_agreement_public_key)throw new x("missing_grant_key","The encrypted grant key is unavailable or does not match the file transfer grant.");let r=await st(o.agreementPrivateKey,i.encryption.connector_agreement_public_key);return t.fromSharedSecret(r,i)}static async fromSharedSecret(e,n){$o(n);let i=await Gn(e,n);return new t(n,i)}async encryptChunk(e,n,i){if(this.validateHeader(n),i.byteLength!==n.plaintext_length)throw new se("plaintext_length_mismatch","File chunk plaintext length does not match its authenticated header.");let o=St(e,n),r=await crypto.subtle.encrypt({name:"AES-GCM",iv:Wo(n.chunk_index),additionalData:Wt(o),tagLength:128},this.key,Wt(i));return _i({kind:e,header:n,payload:new Uint8Array(r)})}async decryptChunk(e){let n=At(e);this.validateHeader(n.header);let i=St(n.kind,n.header);try{let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:Wo(n.header.chunk_index),additionalData:Wt(i),tagLength:128},this.key,Wt(n.payload));return new Uint8Array(o)}catch{throw new se("authentication_failed","The encrypted file chunk could not be authenticated.")}}validateHeader(e){let n=this.binding.encryption;if(e.protocol_version!==1||e.protection!=="grant_aead_v1"||e.grant_id!==this.binding.grantId||e.authority_id!==this.binding.authorityId||e.collection_id!==n.collection_id||e.transfer_id!==this.binding.transferId||e.direction!==this.binding.direction||e.scope_epoch!==n.scope_epoch||e.key_id!==n.key_id)throw new se("header_binding_mismatch","The file frame does not match its transfer encryption binding.")}};async function Gn(t,e){let n=new TextEncoder().encode(Js(e)),i=await crypto.subtle.digest("SHA-256",n),o=await crypto.subtle.importKey("raw",t,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:i,info:new TextEncoder().encode(Ws)},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}function $o(t){if(re(t.encryption),!$t.test(t.grantId)||!$t.test(t.applicationId)||!$t.test(t.authorityId)||!$t.test(t.transferId)||t.direction!=="upload"&&t.direction!=="download")throw new se("invalid_binding","The file transfer encryption binding is invalid.")}function Js(t){let e=t.encryption;return["mdbase-connect","file-transfer",1,e.suite,t.grantId,t.applicationId,e.connector_id,t.authorityId,e.collection_id,e.scope_epoch,e.key_id,t.transferId,t.direction].join("|")}function Wo(t){if(!Number.isSafeInteger(t)||t<0)throw new se("invalid_chunk_index","The file chunk index is invalid.");let e=new Uint8Array(new ArrayBuffer(12));return new DataView(e.buffer).setBigUint64(4,BigInt(t),!1),e}function Wt(t){return Uint8Array.from(t).buffer}var Yt=8,Hn=10;function Qt(t){return t instanceof b&&t.code==="connector_busy"}async function Jo(t){if(!Qt(t.error)||t.completedRetries>=Yt)return{retried:!1};try{await Xt(t.completedRetries,t.signal)}catch(e){throw t.attempt.pendingMutation&&(t.knownRejectedMutationRetry||!t.attempt.resumingMutation)&&t.clearPending(t.attempt.requestId),e}return{retried:!0,result:await t.retry(t.attempt.pendingMutationRecord,t.knownRejectedMutationRetry||t.attempt.pendingMutation===!0&&!t.attempt.resumingMutation)}}async function $e(t){if(t.status!==502&&t.status!==503)return!1;let e=await t.clone().json().catch(()=>null);return e?.error==="connector_busy"||typeof e?.error=="object"&&e.error?.code==="connector_busy"}function Xt(t,e){return Qo(Xo(50,800,t),e)}function Yo(t,e){return Qo(Xo(100,1e3,t-1),e)}async function Qo(t,e){try{await Z(t,e)}catch(n){throw e?.aborted?e.reason instanceof b?e.reason:d("operation_cancelled","The operation was cancelled while waiting for connector capacity.",{operationOutcome:"not_sent",cause:n}):n}}function Xo(t,e,n){let i=Math.min(e,t*2**Math.max(0,n));return Math.max(1,Math.round(i*(.75+Math.random()*.5)))}var en=class{constructor(e){this.options=e}options;async control(e,n,i,o,r){let a=this.grantKeyLeases(e.collectionId);try{return e=await this.retainEntryToken(e,a,r),await this.controlAttempt(e,n,i,o,r,!1,0,a)}finally{a.release()}}async controlAttempt(e,n,i,o,r,a,s,c){We(e);let l=tc(n,i,o),u=await this.encryptControl(e,l),p,f=await this.options.shouldAttemptDirect(e);if(f){try{p=await fetch(`${this.options.loopbackUrl}/v1/files/control`,me({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(u),signal:r}))}catch(h){if(r?.aborted)throw h;this.options.onDirectUnavailable()}if(p&&(!Fe(p.status)||await $e(p)))return p.ok&&this.options.onDirectAvailable(),this.decryptControlResponse(e,n,i,o,r,u,p,a,s,c);p&&this.options.onDirectUnavailable()}return f&&n==="GET"&&(e=e.expiresAt>Date.now()+3e4?e:await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,c,r),Zt(e),u=await this.encryptControl(e,l)),p=await this.sendRelayControl(e,u,r),await Qs(p,e)&&(e=await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,c,r),Zt(e),u=await this.encryptControl(e,l),p=await this.sendRelayControl(e,u,r)),p.ok&&this.options.onRelayAvailable(),this.decryptControlResponse(e,n,i,o,r,u,p,a,s,c)}async decryptControlResponse(e,n,i,o,r,a,s,c,l,u){let p=await E(s,"invalid_operation_response","The collection authority returned an invalid file control response.");if(!s.ok){let y=z(p,"operation_failed","Collection file request failed.",s.status);if(Qt(y)&&l<Yt)return await Xt(l,r),this.controlAttempt(e,n,i,o,r,c,l+1,u);if(y.code==="fresh_request_required"&&n==="GET"&&!c)return this.controlAttempt(e,n,i,o,r,!0,l,u);throw y}let f=p?.envelope;if(!f)throw d("invalid_encrypted_response","The connector omitted its encrypted file response.");let h=await ze(this.options.keyStore,e.keyHandle,Wn(e),a,f);if(!h.ok&&h.problem.code==="fresh_request_required"&&n==="GET"&&!c)return this.controlAttempt(e,n,i,o,r,!0,l,u);if(!h.ok){let y=ec(h.problem);if(Qt(y)&&l<Yt)return await Xt(l,r),this.controlAttempt(e,n,i,o,r,c,l+1,u);throw y}return h.result}async uploadChunk(e,n,i,o,r){let a=r??await this.localFileToken(e,"upload",o),s=this.grantKeyLeases(a.collectionId);try{let c=await this.retainEntryToken(a,s,o);return $n(c,e,"upload"),await this.uploadChunkWithLease(c,s,e,n,i,o)}finally{s.release()}}async uploadChunkWithLease(e,n,i,o,r,a){let s=e,c=await Zo(this.options.keyStore,s,i,o,r),l;if(await this.options.shouldAttemptDirect(s)){try{l=await fetch(`${this.options.loopbackUrl}/v1/files/upload`,me(er(c,a)))}catch(u){if(a?.aborted)throw u;this.options.onDirectUnavailable()}if(l&&(!Fe(l.status)||await $e(l)))return l.ok&&this.options.onDirectAvailable(),Ys(l,"Encrypted file chunk upload failed.");l&&this.options.onDirectUnavailable()}if(l=await this.sendRelayUpload(s,c,a),l.status===401&&s.refreshToken&&(s=await this.options.refreshAuthorization(a),s=await this.retainEntryToken(s,n,a),Zt(s),c=await Zo(this.options.keyStore,s,i,o,r),l=await this.sendRelayUpload(s,c,a)),!l.ok){let u=await E(l,"invalid_operation_response","The collection authority returned an invalid file upload response.");throw z(u,"operation_failed","Encrypted file chunk upload failed.",l.status)}this.options.onRelayAvailable()}async downloadChunk(e,n,i,o){let r=o??await this.localFileToken(e,"download",i),a=this.grantKeyLeases(r.collectionId);try{return r=await this.retainEntryToken(r,a,i),$n(r,e,"download"),await this.downloadChunkWithLease(r,a,e,n,i)}finally{a.release()}}async downloadChunkWithLease(e,n,i,o,r){let a;if(await this.options.shouldAttemptDirect(e)){try{a=await fetch(`${this.options.loopbackUrl}/v1/files/download/${encodeURIComponent(e.grantId)}/${encodeURIComponent(i.transfer_id)}/${o}`,me({method:"GET",signal:r}))}catch(s){if(r?.aborted)throw s;this.options.onDirectUnavailable()}if(a&&(!Fe(a.status)||await $e(a)))return a.ok&&this.options.onDirectAvailable(),this.decryptDownloadResponse(e,i,o,a);a&&this.options.onDirectUnavailable()}return a=await this.sendRelayDownload(e,i,o,r),a.status===401&&e.refreshToken&&(e=await this.options.refreshAuthorization(r),e=await this.retainEntryToken(e,n,r),Zt(e),a=await this.sendRelayDownload(e,i,o,r)),a.ok&&this.options.onRelayAvailable(),this.decryptDownloadResponse(e,i,o,a)}async decryptDownloadResponse(e,n,i,o){if(!o.ok){let s=await E(o,"invalid_operation_response","The collection authority returned an invalid file download response.");throw z(s,"operation_failed","Encrypted file chunk download failed.",o.status)}if(o.headers.get("content-type")?.split(";",1)[0]!=="application/mdbase-connect-file")throw d("invalid_operation_response","The connector returned an invalid file response media type.");let r=new Uint8Array(await o.arrayBuffer()),a;try{Zs(n,i,r),a=await(await nr(this.options.keyStore,e,n)).decryptChunk(r)}catch(s){throw s instanceof b?s:d("invalid_operation_response","The connector returned an invalid encrypted file frame.",{cause:s})}if(a.byteLength!==Jn(n,i))throw d("invalid_operation_response","The connector returned a truncated file chunk.");return a}encryptControl(e,n){return We(e),oe(this.options.keyStore,e.keyHandle,Wn(e),"file_control",n)}sendRelayControl(e,n,i){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/control`,{method:"POST",headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/json"},body:JSON.stringify(n),signal:i})}sendRelayUpload(e,n,i){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/upload`,{...er(n,i),headers:{authorization:`Bearer ${e.accessToken}`,"content-type":"application/mdbase-connect-file"}})}sendRelayDownload(e,n,i,o){return fetch(`${this.options.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/files/download/${encodeURIComponent(n.transfer_id)}/${i}`,{method:"GET",headers:{authorization:`Bearer ${e.accessToken}`},signal:o})}async localFileToken(e,n,i){let o=await this.options.authorizedToken(i);return $n(o,e,n),o}grantKeyLeases(e){return new ge(e,this.options.acquireGrantKeyLease??(()=>Promise.resolve(()=>{})))}async retainEntryToken(e,n,i){if(!this.options.currentToken)return await n.retain(e,i),e;let o=await V(this.options.currentToken,n,i);if(o)return o;throw d("not_authorized","Reconnect this application to continue.")}};function $n(t,e,n){if(!t||t.authority||!t.fileCapability||!t.encryption||!t.grantId||!t.keyHandle||e.direction!==n||e.protection!=="grant_aead_v1")throw d("not_authorized","This connection cannot use encrypted local file delivery.");tn(e)}function Zt(t){if(t.authority||!t.fileCapability)throw d("not_authorized","This connection cannot use encrypted local file delivery.");We(t)}async function Zo(t,e,n,i,o){let r=Xs(e,n,i,o.byteLength);return(await nr(t,e,n)).encryptChunk("upload_chunk",r,o)}function er(t,e){return{method:"POST",headers:{"content-type":"application/mdbase-connect-file"},body:Uint8Array.from(t).buffer,signal:e}}async function Ys(t,e){if(t.ok)return;let n=await E(t,"invalid_operation_response","The collection authority returned an invalid file transfer response.");throw z(n,"operation_failed",e,t.status)}async function Qs(t,e){return e.refreshToken?t.status===401?!0:t.status!==409?!1:(await E(t.clone(),"invalid_operation_response","The collection authority returned an invalid file response.").catch(()=>null))?.error?.code==="encryption_binding_stale":!1}function We(t){if(!t.encryption||!t.grantId||!t.keyHandle)throw d("missing_grant_key","Reconnect this application to restore encrypted file access.")}function Wn(t){return We(t),{grantId:t.grantId,applicationId:t.clientId,encryption:t.encryption}}function nr(t,e,n){return We(e),He.open(t,e.keyHandle,{...Wn(e),authorityId:e.encryption.connector_id,transferId:n.transfer_id,direction:n.direction})}function Xs(t,e,n,i){We(t);let o=tn(e),r=Jn(e,n);if(i!==r)throw d("invalid_request","The file chunk has the wrong byte length.");return{protocol_version:1,protection:"grant_aead_v1",grant_id:t.grantId,authority_id:t.encryption.connector_id,collection_id:t.collectionId,transfer_id:e.transfer_id,direction:e.direction,chunk_size:o,chunk_index:n,offset:n*o,plaintext_length:i,total_size:e.total_size,scope_epoch:t.encryption.scope_epoch,key_id:t.encryption.key_id}}function Zs(t,e,n){let i=At(n),o=Jn(t,e),r=tn(t);if(i.kind!=="download_chunk"||i.header.chunk_index!==e||i.header.chunk_size!==r||i.header.offset!==e*r||i.header.plaintext_length!==o||i.header.total_size!==t.total_size)throw d("invalid_operation_response","The connector returned a file frame for a different chunk.")}function ec(t){return U(t.code==="unknown"?t.server_code:t.code,t.message,{details:t.details,operationOutcome:t.operation_outcome??"rejected",traceId:t.trace_id})}function tc(t,e,n){if(t==="GET"&&(e===""||e.startsWith("?"))){let o=new URLSearchParams(e.startsWith("?")?e.slice(1):e),r=o.get("limit");return{protocol_version:1,type:"list_files",...o.get("folder")?{folder:o.get("folder")}:{},...o.get("after")?{after:o.get("after")}:{},...r?{limit:Number(r)}:{}}}let i=e.split("/");if(t==="GET"&&i.length===2&&i[0]==="transfers")return tr("get_file_transfer_status",i[1]);if(t==="DELETE"&&i.length===2&&i[0]==="transfers")return tr("abort_file_transfer",i[1]);if(t==="POST"&&nc(n)){let o=e==="uploads"?"open_file_upload":e==="downloads"?"open_file_download":i.length===3&&i[0]==="uploads"&&i[2]==="commit"?"commit_file_upload":i.length===2&&i[1]==="move"&&n.file_id===decodeURIComponent(i[0])?"move_file":i.length===2&&i[1]==="delete"&&n.file_id===decodeURIComponent(i[0])?"delete_file":null;if(o&&n.type===o)return{...n}}throw d("invalid_request","The file control request path is invalid.")}function tr(t,e){return{protocol_version:1,type:t,transfer_id:decodeURIComponent(e)}}function tn(t){if(t.strategy.kind!=="framed_chunks"||!Number.isSafeInteger(t.strategy.chunk_size)||t.strategy.chunk_size<=0)throw d("invalid_operation_response","The connector returned an invalid framed transfer strategy.");return t.strategy.chunk_size}function Jn(t,e){let n=tn(t);if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t.total_size)||t.total_size<0)throw d("invalid_request","The file chunk index is invalid.");let i=e*n;if(!Number.isSafeInteger(i)||i>=t.total_size)throw d("invalid_request","The file chunk index is outside the transfer.");return Math.min(n,t.total_size-i)}function nc(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}var nn=class{constructor(e){this.options=e;this.local=new en(e)}options;local;async control(e,n="",i,o){let r=await this.requireFileToken(o),a=r.token;try{return a.authority?await Go(a,e,n,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders,r.retain):await this.local.control(a,e,n,i,o)}finally{r.release()}}async uploadChunk(e,n,i,o){let r=await this.requireFileToken(o);try{return await this.local.uploadChunk(e,n,i,o,r.token)}finally{r.release()}}async downloadChunk(e,n,i){let o=await this.requireFileToken(i);try{return await this.local.downloadChunk(e,n,i,o.token)}finally{o.release()}}async downloadHostedPart(e,n,i,o){let r=await this.requireFileToken(o),a=r.token;try{if(!a.authority)throw d("not_remote_authority","Hosted file delivery requires a remote authority endpoint.");return await Ho(a,`downloads/${encodeURIComponent(e.transfer_id)}/parts/${n}`,i,o,this.options.refreshAuthorization,this.options.authorityProofHeaders,r.retain)}finally{r.release()}}async requireFileToken(e){let n=new ge(this.options.collectionId,this.options.acquireGrantKeyLease);try{await V(this.options.currentToken,n,e),await this.options.authorizedToken(e);let i=await V(this.options.currentToken,n,e);if(!i?.fileCapability)throw d("not_authorized","This connection has no file capability.");return{token:i,retain:async o=>{let r=await V(this.options.currentToken,n,e);if(r)return r;throw d("not_authorized","Reconnect this application to continue.")},release:()=>n.release()}}catch(i){throw n.release(),i}}};async function Pe(t,e,n,i,o,r){if(!e.authority?.proofPublicKey)return{};if(!e.keyHandle)throw d("missing_grant_key","Reconnect this application to restore remote authority request signing.");try{let a=new URL(i);return await Et(t,e.keyHandle,e.authority.proofPublicKey,{method:n,target:`${a.pathname}${a.search}`,body:o,credential:r})}catch(a){throw a instanceof x?U(a.code,a.message):a}}async function ir(t){let e=t.current;if(!e?.refreshToken)throw d("not_authorized","Reconnect this application to continue.");if((e.refreshExpiresAt??0)<=Date.now())throw d("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");let n=e.refreshToken,i=`${t.serverUrl}/oauth/token`,o=new URLSearchParams({grant_type:"refresh_token",refresh_token:e.refreshToken,client_id:e.clientId}).toString(),r=e.authority?await Pe(t.keyStore,e,"POST",i,o,e.refreshToken):{},a=await fetch(i,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded",...r},body:o,signal:t.signal}),s=await E(a,"invalid_token_response","The authorization service returned an invalid token response.");if(!a.ok){let c=t.currentToken();if(c?.refreshToken&&c.refreshToken!==n)return c;throw t.directCapable(e)||t.removeToken(e.keyHandle),(ut(s)??s?.error?.code)==="invalid_grant"?d("authorization_expired",s?.error_description??s?.error?.message??"Reconnect this application to continue.",{status:a.status}):z(s,"authorization_expired","Reconnect this application to continue.",a.status)}return t.storeTokenResponse(s,e.clientId,e.keyHandle)}var on=class{constructor(e,n){this.storage=e;this.baseKey=n}storage;baseKey;list(e){if(!e)return[];let n=M(this.storage.getItem(this.baseKey));if(or(n)&&n.collectionId===e){let o=this.key(n.requestId);this.storage.getItem(o)||this.storage.setItem(o,JSON.stringify(n)),this.storage.removeItem(this.baseKey)}let i=[];for(let o=0;o<this.storage.length;o+=1){let r=this.storage.key(o);r?.startsWith(`${this.baseKey}:`)&&i.push(r)}return i.map(o=>M(this.storage.getItem(o))).filter(o=>or(o)&&o.collectionId===e).sort((o,r)=>o.createdAt-r.createdAt||o.requestId.localeCompare(r.requestId))}find(e,n){return this.list(e).find(i=>i.requestId===n)??null}identifier(e){return e.mutation??de(e.operation,e.request?.input??(e.operation==="sync"?{action:"mutate"}:{}))??(e.operation==="sync"?"sync:mutate":e.operation)}store(e){this.storage.setItem(this.key(e.requestId),JSON.stringify(e))}take(e){let n=this.key(e),i=M(this.storage.getItem(n));return this.storage.removeItem(n),i}key(e){return`${this.baseKey}:${encodeURIComponent(e)}`}};function or(t){return!!(t&&typeof t.collectionId=="string"&&typeof t.requestId=="string"&&t.requestId.length>0&&bi(t.operation)&&typeof t.inputFingerprint=="string"&&Number.isFinite(t.createdAt)&&t.createdAt>0&&(t.envelope||t.request)&&(t.operation==="sync"||de(t.operation,t.request?.input??{})!==null))}function rr({stored:t,collectionId:e,relayEncryption:n,invalidate:i,directCapable:o}){let r=M(t),a=(c,l="invalid_stored_grant")=>(i(typeof c=="string"?c:void 0,l),null);if(!r)return t&&a(),null;if(r.version!==1||typeof r.accessToken!="string"||r.accessToken.length===0||typeof r.clientId!="string"||r.clientId.length===0||r.collectionId!==e||typeof r.collectionName!="string"||r.collectionName.length===0||!Array.isArray(r.operations)||r.operations.some(c=>typeof c!="string")||typeof r.expiresAt!="number"||!Number.isFinite(r.expiresAt)||r.refreshToken!==void 0&&(typeof r.refreshToken!="string"||r.refreshToken.length===0)||r.refreshExpiresAt!==void 0&&(typeof r.refreshExpiresAt!="number"||!Number.isFinite(r.refreshExpiresAt)))return a(r.keyHandle);let s=Ft(r.scope);if(!s)return a(r.keyHandle);if(!Dt(s))return a(r.keyHandle,"legacy_scope_reauthorization_required");if(r.fileCapability&&!zt(r.fileCapability)||r.authority&&!mo(r.authority,r.collectionId))return a(r.keyHandle);if(n==="required"){if(r.authority){if(!r.keyHandle||!r.authority.proofPublicKey)return a(r.keyHandle)}else if(!r.grantId||!r.keyHandle||!go(r.encryption,r.collectionId))return a(r.keyHandle)}return r.expiresAt<=Date.now()&&(!r.refreshToken||(r.refreshExpiresAt??0)<=Date.now())?o(r)?r:(i(r.keyHandle),null):r}async function Yn(t,e,n,i,o,r){if(!e.authority)throw d("not_remote_authority","This authorization has no remote authority endpoint.");let a=`${e.authority.syncUrl}/${i}`,s=o===void 0?void 0:JSON.stringify(o),c=await Pe(t,e,n,a,s,e.authority.accessToken);return fetch(a,{method:n,headers:{authorization:`Bearer ${e.authority.accessToken}`,...o===void 0?{}:{"content-type":"application/json"},...c},...s===void 0?{}:{body:s},signal:r})}async function ar(t,e,n,i,o){if(!e.encryption||!e.grantId||!e.keyHandle)throw d("authorization_binding_incompatible","The refreshed authorization no longer supports encrypted connector operations.",{details:{contract:"grant_encryption",required:[1],supported:e.encryption?[e.encryption.protocol_version]:[],peer:"connector",operation:n}});try{return await oe(t,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,void 0,o)}catch(r){throw r instanceof x?U(r.code,r.message):r}}var Je=class{operations=new Map;run(e,n,i,o){if(n?.signal?.aborted)return Promise.reject(J(n.signal));let r=this.operations.get(e)??this.begin(e,o);return this.wait(e,r,n,i)}begin(e,n){let i=new AbortController,o={controller:i,waiters:0,settled:!1,promise:void 0};return o.promise=Promise.resolve().then(()=>n(i.signal)).finally(()=>{o.settled=!0,this.operations.get(e)===o&&this.operations.delete(e)}),this.operations.set(e,o),o}async wait(e,n,i,o){n.waiters+=1;try{return await F(i,o,()=>n.promise)}finally{n.waiters-=1,n.waiters===0&&!n.settled&&this.operations.get(e)===n&&(this.operations.delete(e),n.controller.abort())}}};function sr(t,e){return!t||t.authority||!t.encryption||!t.grantId||!t.keyHandle||e==="disabled"?!1:typeof location>"u"||!t.applicationOrigin||t.applicationOrigin===location.origin}async function cr(t,e,n){try{let i=await fetch(`${t}/v1/ready`,me({method:"GET",cache:"no-store",signal:n})),o=await E(i,"invalid_operation_response","The connector returned an invalid readiness response.").catch(()=>null);return i.ok&&o?.service==="mdbase-connect"&&o?.loopback_protocol_version===1&&o?.operation_transport_protocol_version===e}catch{return!1}}async function lr(t,e){try{return{body:await E(t,"invalid_operation_response","The collection authority returned a response that is not valid JSON.")}}catch(n){if(!t.ok&&e&&ic(t.status))return{body:void 0,httpError:U("operation_failed","Collection operation failed.",{status:t.status,operationOutcome:"rejected"})};throw d("invalid_operation_response","The collection authority returned a response that is not valid JSON.",{cause:n})}}function ic(t){return t>=400&&t<500&&![408,425,429].includes(t)}var rn=class{serverUrl;storage;keyStore;directAccessMode;loopbackUrl;collectionId;internals;onChange;timeouts;pendingMutationStore;files;refreshOperations=new Je;directStatus;currentRoute="relay";directFailures=0;directRetryAt=0;constructor(e){this.serverUrl=e.serverUrl,this.storage=e.storage,this.keyStore=e.keyStore,this.directAccessMode=e.directAccessMode,this.loopbackUrl=e.loopbackUrl,this.collectionId=e.collectionId,this.internals=e.internals,this.onChange=e.onChange,this.timeouts=e.timeouts,this.pendingMutationStore=new on(this.storage,this.internals.pendingMutationKey(this.collectionId)),this.files=new nn({keyStore:this.keyStore,serverUrl:this.serverUrl,loopbackUrl:this.loopbackUrl,collectionId:this.collectionId,currentToken:()=>this.currentToken(),authorizedToken:n=>this.authorizedToken({signal:n,timeoutMs:null}),refreshAuthorization:n=>this.refreshAuthorization({signal:n,timeoutMs:null}),shouldAttemptDirect:n=>this.shouldAttemptDirect(n),onDirectAvailable:()=>{this.markDirectAvailable(),this.setRoute("direct")},onDirectUnavailable:()=>this.markDirectUnavailable(),onRelayAvailable:()=>this.setRoute("relay"),acquireGrantKeyLease:(n,i,o)=>this.internals.acquireGrantKeyLease(n,i,o),authorityProofHeaders:(n,i,o,r,a)=>Pe(this.keyStore,n,i,o,r,a)}),this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable"}get directAccess(){return this.currentToken()?.authority?"disabled":this.directStatus}get route(){return this.currentToken()?.authority?"remote":this.currentRoute}notifyStorageChanged(){this.emitConnection()}async checkDirectAccess(e={}){return F(e,this.timeouts.watchStartMs,n=>this.checkDirectAccessWithinBudget(n.signal))}async checkDirectAccessWithinBudget(e){let n=this.currentToken();if(!this.directEligible(n))return this.setDirectStatus("disabled");let i=await ct();return i==="denied"?this.setDirectStatus("denied"):(i==="prompt"||i===null)&&this.storage.getItem(this.internals.directPreferenceKey())!=="enabled"?this.setDirectStatus("permission_required"):this.probeDirectAccess(e)}async requestDirectAccess(e={}){return F(e,this.timeouts.watchStartMs,n=>this.requestDirectAccessWithinBudget(n.signal))}async requestDirectAccessWithinBudget(e){let n=this.currentToken();return this.directCapable(n)?(this.storage.setItem(this.internals.directPreferenceKey(),"enabled"),this.directRetryAt=0,this.probeDirectAccess(e)):this.setDirectStatus("disabled")}disableDirectAccess(){this.storage.setItem(this.internals.directPreferenceKey(),"disabled"),this.setDirectStatus("disabled"),this.setRoute("relay")}pendingMutations(){return this.storedPendingMutations().map(e=>({requestId:e.requestId,operation:this.pendingMutationStore.identifier(e),fingerprint:e.inputFingerprint,status:"outcome_unknown",createdAt:new Date(e.createdAt).toISOString()}))}pendingMutation(e){let n=this.storedPendingMutation(e);return n?{requestId:n.requestId,operation:this.pendingMutationStore.identifier(n),fingerprint:n.inputFingerprint,status:"outcome_unknown",createdAt:new Date(n.createdAt).toISOString()}:null}async recoverPendingMutation(e,n){let i=this.storedPendingMutation(e);if(!i)throw d("no_pending_mutation","There is no interrupted mutation to resume.");return K(n,this.timeouts.requestMs,o=>this.performOperationWithinBudget(i.operation,i.request?.input??{},ot(n??{},o),i))}async performOperation(e,n,i={}){return K(i,this.timeouts.requestMs,o=>this.performOperationWithinBudget(e,n,ot(i,o)))}async performOperationWithinBudget(e,n,i,o,r=!1,a=0,s=!1){Ae(i.signal);let c=this.grantKeyLeases();try{let l=await V(()=>this.currentToken(),c,i.signal);if(!l)throw d("not_authorized","Connect this application before accessing a collection.");return await c.retain(o?.keyHandle,i.signal),await this.performLeasedOperation(l,e,n,i,c,o,r,a,s)}finally{c.release()}}async performLeasedOperation(e,n,i,o,r,a,s=!1,c=0,l=!1){if(!e.operations.includes(n))throw d("insufficient_access",`This connection does not allow ${n}.`,{details:{required_operations:[n],granted_operations:[...e.operations],missing_operations:[n]}});let u=await this.shouldAttemptDirect(e);if(!u){if(!await this.authorizedToken({signal:o.signal,timeoutMs:null}))throw d("not_authorized","Reconnect this application to continue.");let R=await V(()=>this.currentToken(),r,o.signal);if(!R)throw d("not_authorized","Reconnect this application to continue.");e=R}let p=a?.requestId??(to(n,i)?crypto.randomUUID():void 0),f;try{f=await this.sendOperation(e,n,i,u,r,o,p,l)}catch(_){throw qt(_,o.signal,p!==void 0&&this.storedPendingMutation(p)!==null?p:void 0,e.authority?"hosted_provider_unavailable":"relay_unavailable")}let h=f.response,y=h.status===409&&(await E(h.clone(),"invalid_operation_response","The collection authority returned an invalid operation response.").catch(()=>null))?.error?.code==="encryption_binding_stale";if((h.status===401||y)&&e.refreshToken){if(f.pendingMutation&&(f.directDeliveryUncertain||f.encryptedRequest&&f.resumingMutation))throw d("operation_outcome_unknown","The direct operation may have completed, but its encrypted grant changed before the response could be recovered. Refresh before making another change.",{operationOutcome:"unknown",details:{request_id:f.requestId}});f.pendingMutation&&this.clearPendingMutation(f.requestId),e=await this.refreshAuthorization({signal:o.signal,timeoutMs:null});let _=await V(()=>this.currentToken(),r,o.signal);if(!_)throw d("not_authorized","Reconnect this application to continue.");e=_,u=await this.shouldAttemptDirect(e);try{f=await this.sendOperation(e,n,i,u,r,o,p,l)}catch(R){throw qt(R,o.signal,p!==void 0&&this.storedPendingMutation(p)!==null?p:void 0,e.authority?"hosted_provider_unavailable":"relay_unavailable")}h=f.response}let A=_=>Jo({error:_,attempt:f,completedRetries:c,signal:o.signal,knownRejectedMutationRetry:l,clearPending:R=>this.clearPendingMutation(R),retry:(R,T)=>this.performOperationWithinBudget(n,i,o,R,s,c+1,T)}),C;try{C=await lr(h,e.authority!==void 0)}catch(_){throw f.pendingMutation?G(f.requestId,_):_}let m=C.body;if(!h.ok){let _=C.httpError??z(m,"operation_failed","Collection operation failed.",h.status),R=await A(_);if(R.retried)return R.result;if(_.code==="fresh_request_required"&&!f.pendingMutation&&!s)return this.performOperationWithinBudget(n,i,o,void 0,!0);throw f.pendingMutation&&_.outcomeUnknown?_:f.pendingMutation&&(f.directDeliveryUncertain||f.encryptedRequest&&f.resumingMutation)?G(f.requestId,_):(f.pendingMutation&&!f.directDeliveryUncertain&&this.clearPendingMutation(f.requestId),_.code==="direct_operation_rejected"&&_.status===403&&this.invalidateRejectedAuthorization(e),_)}if(f.encryptedRequest){let _=m?.envelope,R=f.pendingMutationRecord,T=R?.encryption??e.encryption,O=R?.grantId??e.grantId,S=R?.applicationId??e.clientId,P=R?.keyHandle??e.keyHandle;if(!_||!T||!O||!P)throw f.pendingMutation?G(f.requestId,new Error("Encrypted operation response was missing its envelope.")):d("invalid_encrypted_response","The relay did not return an encrypted connector response.");try{let q=await ze(this.keyStore,P,{grantId:O,applicationId:S,encryption:T},f.encryptedRequest,_);if(!q.ok&&q.problem.code==="fresh_request_required"&&!f.pendingMutation&&!s)return this.performOperationWithinBudget(n,i,o,void 0,!0);if(!q.ok){let H=oo(q.problem);throw f.pendingMutation&&!H.outcomeUnknown&&this.clearPendingMutation(f.requestId),H}return f.pendingMutation&&this.clearPendingMutation(f.requestId),q.result}catch(q){throw q instanceof b?q:q instanceof x?f.pendingMutation?G(f.requestId,q):U(q.code,q.message):q}}let v=f.pendingMutationRecord?.request?.protocol_version??$;if(m?.protocol_version!==v||m?.request_id!==f.requestId)throw f.pendingMutation?G(f.requestId,new Error("Operation response protocol or request ID did not match.")):d("invalid_operation_response","The collection authority returned a response for a different protocol request.");if(m.ok===!1){if(!Xe(m.problem))throw f.pendingMutation?G(f.requestId,new Error("Operation rejection did not contain a canonical problem.")):d("invalid_operation_response","The collection authority returned an invalid operation problem.");let _=new b(m.problem),R=await A(_);if(R.retried)return R.result;throw f.pendingMutation&&!_.outcomeUnknown&&this.clearPendingMutation(f.requestId),_}if(m.ok!==!0||!("result"in m))throw f.pendingMutation?G(f.requestId,new Error("Successful operation response did not contain a result.")):d("invalid_operation_response","The collection authority returned an incomplete operation response.");return f.pendingMutation&&this.clearPendingMutation(f.requestId),m.result}async performAuthoritySyncRequest(e,n,i,o,r,a={}){return K(a,this.timeouts.syncMs,async s=>{let c=this.grantKeyLeases();try{let l=await V(()=>this.currentToken(),c,s.signal);l&&await this.authorizedToken({signal:s.signal,timeoutMs:null}),l=await V(()=>this.currentToken(),c,s.signal),dr(l,e,n);let u=await Yn(this.keyStore,l,i,o,r,s.signal);u.status===401&&l.refreshToken&&(l=await this.refreshAuthorization({signal:s.signal,timeoutMs:null}),l=await V(()=>this.currentToken(),c,s.signal),dr(l,e,n),u=await Yn(this.keyStore,l,i,o,r,s.signal));let p=await E(u,"invalid_operation_response","The collection authority returned an invalid synchronization response.");if(!u.ok)throw z(p,"sync_failed","Collection synchronization failed.",u.status);return p}catch(l){let u=i==="POST"&&o==="mutations"&&r&&typeof r=="object"&&typeof r.mutation_id=="string"?r.mutation_id:void 0;throw qt(l,s.signal,u,"hosted_provider_unavailable")}finally{c.release()}})}async sendOperation(e,n,i,o,r,a={},s,c=!1){let l=i??{},u,p=!1,f=!1,h=s??crypto.randomUUID(),y=null,A;if(s!==void 0){if(y=this.storedPendingMutation(s),A=y?.inputFingerprint??await uo(n,i),y){if(y.collectionId!==e.collectionId||y.operation!==n||y.inputFingerprint!==A)throw d("pending_mutation_unresolved","A previous write still has an unknown outcome. Retry that exact write before making another change.");h=y.requestId,f=!c}p=!0}let C=y?.mutation??de(n,i);if(y?.envelope&&(e.authority||!e.encryption))throw d("pending_mutation_unresolved","The pending write requires its encrypted relay authority. Reconnect that authority before recovery.");if(y?.request&&e.encryption&&!e.authority)throw d("pending_mutation_unresolved","The pending write belongs to a different authority transport. Reconnect that authority before recovery.");if(e.encryption&&!e.authority){if(!e.grantId||!e.keyHandle)throw d("missing_grant_key","Reconnect this application to restore encrypted access.");try{if(p)if(y){if(!y.envelope)throw d("pending_mutation_unresolved","The pending write belongs to a different transport. Reconnect before retrying it.");u=no(y.envelope,a.deadlineUnixMs)}else u=await oe(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,h,a.deadlineUnixMs),this.pendingMutationStore.store({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},keyId:e.encryption.key_id,keyHandle:e.keyHandle,applicationId:e.clientId,encryption:e.encryption,operation:n,mutation:C,inputFingerprint:A,requestId:h,envelope:u,createdAt:Date.now()});else u=await oe(this.keyStore,e.keyHandle,{grantId:e.grantId,applicationId:e.clientId,encryption:e.encryption},n,i,void 0,a.deadlineUnixMs)}catch(T){throw T instanceof x?U(T.code,T.message):T}h=u.request_id,l=u}else{let T=y?.request??{protocol_version:$,request_id:h,input:l};l=T,p&&!y&&this.pendingMutationStore.store({collectionId:e.collectionId,...e.grantId?{grantId:e.grantId}:{},operation:n,mutation:C,inputFingerprint:A,requestId:h,request:T,createdAt:Date.now()})}if(o&&u&&!e.authority){let T=!1;try{let P=await fetch(`${this.loopbackUrl}/v1/operations`,me({method:"POST",headers:{"content-type":"application/mdbase-connect+json"},body:JSON.stringify(u),signal:a.signal}));if(!Fe(P.status)||await $e(P))return P.ok&&(this.markDirectAvailable(),this.setRoute("direct")),{response:P,requestId:h,encryptedRequest:u,pendingMutation:p,...p?{pendingMutationRecord:y??this.storedPendingMutation(h)??void 0}:{},resumingMutation:f};T=P.status>=500,this.markDirectUnavailable()}catch(P){if(a.signal?.aborted)throw p?G(h,P):P;T=!0,await ct()==="denied"?this.setDirectStatus("denied"):this.markDirectUnavailable()}let O;try{e.expiresAt<=Date.now()+3e4&&await this.refreshAuthorization({signal:a.signal,timeoutMs:null});let P=await V(()=>this.currentToken(),r,a.signal);if(!P)throw d("not_authorized","Reconnect this application to continue.");O=P}catch(P){throw p&&(T||f)?G(h,P):P}let S;p||(u=await ar(this.keyStore,O,n,i,a.deadlineUnixMs),h=u.request_id);try{S=await fetch(`${this.serverUrl}/v1/authorities/${encodeURIComponent(O.collectionId)}/operations/${n}`,{method:"POST",headers:{authorization:`Bearer ${O.accessToken}`,"content-type":"application/json"},body:JSON.stringify(u),signal:a.signal})}catch(P){throw p?G(h,P):P}return S.ok&&this.setRoute("relay"),{response:S,requestId:h,encryptedRequest:u,directDeliveryUncertain:T,pendingMutation:p,...p?{pendingMutationRecord:y??this.storedPendingMutation(h)??void 0}:{},resumingMutation:f}}let m=e.authority?`${e.authority.operationsUrl}/${n}`:`${this.serverUrl}/v1/authorities/${encodeURIComponent(e.collectionId)}/operations/${n}`,v=JSON.stringify(l),_=e.authority?await Pe(this.keyStore,e,"POST",m,v,e.authority.accessToken):{},R;try{R=await ro(m,e.authority?.accessToken??e.accessToken,_,v,a.signal)}catch(T){throw p?G(h,T):T}return R.ok&&this.setRoute(e.authority?"remote":"relay"),{response:R,requestId:h,encryptedRequest:u,pendingMutation:p,...p?{pendingMutationRecord:y??this.storedPendingMutation(h)??void 0}:{},resumingMutation:f}}directCapable(e){return sr(e,this.directAccessMode)}hasResumableMutationTransport(){return this.currentToken()!==null}directEligible(e){return e!==null&&this.directCapable(e)&&this.storage.getItem(this.internals.directPreferenceKey())!=="disabled"}async shouldAttemptDirect(e){if(!this.directEligible(e))return!1;if(this.directStatus==="available")return!0;if(this.directStatus==="unavailable"&&Date.now()<this.directRetryAt)return!1;let n=await ct();return n==="denied"?(this.setDirectStatus("denied"),!1):(n==="prompt"||n===null)&&this.storage.getItem(this.internals.directPreferenceKey())!=="enabled"?(this.setDirectStatus("permission_required"),!1):(this.setDirectStatus("checking"),!0)}async probeDirectAccess(e){return this.setDirectStatus("checking"),await cr(this.loopbackUrl,$,e)?(this.markDirectAvailable(),"available"):await ct()==="denied"?this.setDirectStatus("denied"):(this.markDirectUnavailable(),"unavailable")}markDirectAvailable(){this.directFailures=0,this.directRetryAt=0,this.setDirectStatus("available")}markDirectUnavailable(){this.directFailures+=1,this.directRetryAt=Date.now()+Math.min(6e4,1e3*2**(this.directFailures-1)),this.setDirectStatus("unavailable")}setDirectStatus(e){return this.directStatus!==e&&(this.directStatus=e,this.emitConnection()),e}setRoute(e){this.currentRoute!==e&&(this.currentRoute=e,this.emitConnection())}emitConnection(){this.onChange()}invalidateRejectedAuthorization(e){let n=M(this.storage.getItem(this.internals.tokenKey(this.collectionId)));!n||!io(n,e)||(this.internals.removeToken(this.collectionId,n.keyHandle),this.currentRoute="relay",this.directStatus=this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection())}currentToken(){return rr({stored:this.storage.getItem(this.internals.tokenKey(this.collectionId)),collectionId:this.collectionId,relayEncryption:this.internals.relayEncryption,invalidate:(e,n="invalid_stored_grant")=>this.internals.removeToken(this.collectionId,e,n),directCapable:e=>this.directCapable(e)})}async authorizedToken(e={}){let n=this.currentToken();if(!n)return null;if(n.expiresAt>Date.now()+3e4)return n;if(!n.refreshToken||(n.refreshExpiresAt??0)<=Date.now()){if(this.directCapable(n))throw d("relay_authorization_expired","Direct access is still available on this computer, but using the relay requires reconnecting this application.");return this.internals.removeToken(this.collectionId,n.keyHandle),null}return this.refreshAuthorization(e)}refreshAuthorization(e={}){return this.refreshOperations.run("refresh",e,this.timeouts.requestMs,n=>this.performRefresh(n))}async performRefresh(e){let n=this.grantKeyLeases();try{let i=await V(()=>this.currentToken(),n,e);return await ir({current:i,serverUrl:this.serverUrl,keyStore:this.keyStore,signal:e,currentToken:()=>this.currentToken(),directCapable:o=>this.directCapable(o),removeToken:o=>this.internals.removeToken(this.collectionId,o),storeTokenResponse:(o,r,a)=>this.storeTokenResponse(o,r,a)})}finally{n.release()}}storeTokenResponse(e,n,i){if(e.collection_id!==this.collectionId)throw d("collection_mismatch","The refreshed authorization belongs to a different collection.");let o=this.internals.storeTokenResponse(e,n,i);return this.currentRoute=o.authority?"remote":"relay",this.directStatus=o.authority||this.directAccessMode==="disabled"?"disabled":"unavailable",this.emitConnection(),o}storedPendingMutations(){return this.pendingMutationStore.list(this.currentToken()?.collectionId??null)}storedPendingMutation(e){return this.pendingMutationStore.find(this.currentToken()?.collectionId??null,e)}clearPendingMutation(e){let n=this.pendingMutationStore.take(e);n?.keyHandle&&this.internals.deleteGrantKeyWhenUnused(this.collectionId,n.keyHandle)}grantKeyLeases(){return new ge(this.collectionId,(e,n,i)=>this.internals.acquireGrantKeyLease(e,n,i))}};function dr(t,e,n){if(!(t?.authority&&t.collectionId===e&&t.authority.replicaId===n))throw d("authority_authorization_changed","Reconnect this collection authority before synchronizing.")}var oc=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),rc=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Oe=class{state=rc.slice();block=new Uint8Array(64);words=new Uint32Array(64);blockLength=0;byteLength=0;finished=!1;update(e){if(this.finished)throw new Error("SHA-256 digest is already finalized.");if(this.byteLength+=e.byteLength,!Number.isSafeInteger(this.byteLength))throw new Error("SHA-256 input exceeds the safe browser byte range.");let n=0;if(this.blockLength>0){let i=Math.min(64-this.blockLength,e.byteLength);this.block.set(e.subarray(0,i),this.blockLength),this.blockLength+=i,n+=i,this.blockLength===64&&(this.compress(this.block),this.blockLength=0)}for(;n+64<=e.byteLength;)this.compress(e.subarray(n,n+64)),n+=64;return n<e.byteLength&&(this.block.set(e.subarray(n),0),this.blockLength=e.byteLength-n),this}digestHex(){if(this.finished)throw new Error("SHA-256 digest is already finalized.");this.finished=!0,this.block[this.blockLength]=128,this.block.fill(0,this.blockLength+1),this.blockLength>=56&&(this.compress(this.block),this.block.fill(0));let e=this.byteLength*8,n=Math.floor(e/4294967296),i=e>>>0;return ur(this.block,56,n),ur(this.block,60,i),this.compress(this.block),[...this.state].map(o=>o.toString(16).padStart(8,"0")).join("")}compress(e){let n=this.words;for(let p=0;p<16;p+=1){let f=p*4;n[p]=(e[f]<<24|e[f+1]<<16|e[f+2]<<8|e[f+3])>>>0}for(let p=16;p<64;p+=1){let f=n[p-15],h=n[p-2],y=te(f,7)^te(f,18)^f>>>3,A=te(h,17)^te(h,19)^h>>>10;n[p]=n[p-16]+y+n[p-7]+A>>>0}let i=this.state[0],o=this.state[1],r=this.state[2],a=this.state[3],s=this.state[4],c=this.state[5],l=this.state[6],u=this.state[7];for(let p=0;p<64;p+=1){let f=te(s,6)^te(s,11)^te(s,25),h=s&c^~s&l,y=u+f+h+oc[p]+n[p]>>>0,A=te(i,2)^te(i,13)^te(i,22),C=i&o^i&r^o&r,m=A+C>>>0;u=l,l=c,c=s,s=a+y>>>0,a=r,r=o,o=i,i=y+m>>>0}this.state[0]=this.state[0]+i>>>0,this.state[1]=this.state[1]+o>>>0,this.state[2]=this.state[2]+r>>>0,this.state[3]=this.state[3]+a>>>0,this.state[4]=this.state[4]+s>>>0,this.state[5]=this.state[5]+c>>>0,this.state[6]=this.state[6]+l>>>0,this.state[7]=this.state[7]+u>>>0}};function te(t,e){return t>>>e|t<<32-e}function ur(t,e,n){t[e]=n>>>24,t[e+1]=n>>>16,t[e+2]=n>>>8,t[e+3]=n}var an=class{constructor(e,n){this.signal=n;this.iterator=ac(e)}signal;iterator;remainder=new Uint8Array;remainderOffset=0;maxSourceChunkBytes=null;iteratorClosing=!1;ended=!1;setMaxSourceChunkBytes(e){this.maxSourceChunkBytes=e}async read(e){let n=new Uint8Array(e),i=0;for(;i<e;){if(this.remainderOffset===this.remainder.byteLength){let r=await this.nextSourceChunk();if(r.done)throw this.ended=!0,d("invalid_request","Streamed file bytes ended before the declared size.");if(!(r.value instanceof Uint8Array))throw d("invalid_request","A streamed file chunk was not a Uint8Array.");if(this.maxSourceChunkBytes===null)throw new Error("Stream source was read before upload negotiation completed.");if(r.value.byteLength>this.maxSourceChunkBytes)throw d("invalid_request",`A streamed file chunk exceeded the negotiated ${this.maxSourceChunkBytes}-byte upload part size.`);if(this.remainder=r.value,this.remainderOffset=0,this.remainder.byteLength===0)continue}let o=Math.min(e-i,this.remainder.byteLength-this.remainderOffset);n.set(this.remainder.subarray(this.remainderOffset,this.remainderOffset+o),i),i+=o,this.remainderOffset+=o}return n}async expectEnd(){if(this.remainderOffset<this.remainder.byteLength)throw d("invalid_request","Streamed file bytes exceed the declared size.");for(;!this.ended;){let e=await this.nextSourceChunk();if(e.done){this.ended=!0;return}if(!(e.value instanceof Uint8Array))throw d("invalid_request","A streamed file chunk was not a Uint8Array.");if(e.value.byteLength>0)throw d("invalid_request","Streamed file bytes exceed the declared size.")}}async close(){this.ended=!0,this.closeIterator()}async nextSourceChunk(){pr(this.signal);let e=this.iterator.next(),n=this.signal;if(!n)return e;let i=()=>{},o=new Promise((r,a)=>{let s=()=>{this.closeIterator(),a(fr(n))};n.addEventListener("abort",s,{once:!0}),i=()=>n.removeEventListener("abort",s),n.aborted&&s()});try{let r=await Promise.race([e,o]);return pr(n),r}finally{i()}}closeIterator(){if(!this.iteratorClosing){this.iteratorClosing=!0;try{this.iterator.return?.()?.catch(()=>{})}catch{}}}};function ac(t){if(typeof t.getReader=="function"){let n=t.getReader(),i=!1,o=()=>{i||(i=!0,n.releaseLock())};return{async next(){if(i)return{done:!0,value:void 0};let r=await n.read();return r.done&&o(),r},async return(){if(!i)try{await n.cancel()}finally{o()}return{done:!0,value:void 0}}}}let e=t;if(typeof e[Symbol.asyncIterator]!="function")throw d("invalid_request","Streamed files require a readable byte stream.");return e[Symbol.asyncIterator]()}function pr(t){if(t?.aborted)throw fr(t)}function fr(t){return d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t?.reason})}var hr=1024*1024,sc=4,yr=8,_t=3,Qn=64*1024*1024,mr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu,gr=/^sha256:[0-9a-f]{64}$/u;async function _r(t,e,n){let i=new Oe;for(let o=0;o<t.size;o+=hr){_e(e);let r=new Uint8Array(await t.slice(o,o+hr).arrayBuffer());i.update(r),n(Math.min(t.size,o+r.byteLength))}return t.size===0&&n(0),i.digestHex()}function br(t,e){if(t instanceof Blob)return e&&e!==t.type?t.slice(0,t.size,e):t;if(t instanceof ArrayBuffer)return new Blob([t],{type:e});let n=new Uint8Array(t.byteLength);return n.set(new Uint8Array(t.buffer,t.byteOffset,t.byteLength)),new Blob([n.buffer],{type:e})}function Cr(t){return t instanceof Blob?t.size:t.byteLength}async function vr(t){return t instanceof Blob?new Uint8Array(await t.arrayBuffer()):t}function Xn(t=sc){if(!Number.isInteger(t)||t<1||t>yr)throw d("invalid_request",`File concurrency must be between 1 and ${yr}.`);return t}function wr(t){if(!Number.isInteger(t)||t<1||t>1e3)throw d("invalid_request","File page size must be between 1 and 1000.");return t}function Zn(t,e,n){if(t.protocol_version!==1||t.type!=="file_transfer"||t.transfer_id!==e||t.direction!==n||!Number.isSafeInteger(t.total_size)||t.total_size<0||!Array.isArray(t.received)||!cc(t))throw d("invalid_operation_response","The authority returned an invalid file transfer session.");let i=t.strategy.kind==="framed_chunks"?t.strategy.chunk_size:t.strategy.kind==="object_put"?Math.max(1,t.total_size):t.strategy.part_size,o=t.strategy.kind==="object_put"?1:Math.ceil(t.total_size/i);if(new Set(t.received).size!==t.received.length||t.received.some(a=>!Number.isSafeInteger(a)||a<0||a>=o))throw d("invalid_operation_response","The authority returned invalid transfer progress.");let r=t.uploaded_parts??[];if(!Array.isArray(r)||r.some((a,s)=>!Number.isSafeInteger(a?.part_number)||a.part_number<1||a.part_number>o||typeof a.etag!="string"||a.etag.length===0||a.etag.length>255||s>0&&r[s-1].part_number>=a.part_number)||(t.strategy.kind==="object_multipart"?r.length!==t.received.length||r.some((a,s)=>a.part_number-1!==t.received[s]):r.length!==0))throw d("invalid_operation_response","The authority returned invalid uploaded part receipts.")}function Sr(t,e){let n=e.strategy.kind==="framed_chunks"?e.strategy.chunk_size:e.strategy.kind==="object_put"?Math.max(1,e.total_size):e.strategy.part_size,i=e.strategy.kind==="object_put"?1:Math.ceil(e.total_size/n);if(t?.protocol_version!==1||t.type!=="file_transfer_status"||t.transfer_id!==e.transfer_id||!["open","committed","aborted","expired"].includes(t.state)||!Array.isArray(t.received)||new Set(t.received).size!==t.received.length||t.received.some(r=>!Number.isSafeInteger(r)||r<0||r>=i)||!Number.isSafeInteger(t.received_bytes)||t.received_bytes<0||t.received_bytes>e.total_size||t.received.reduce((r,a)=>r+ei(e.total_size,n,a),0)!==t.received_bytes)throw d("invalid_operation_response","The authority returned invalid transfer status.");let o=t.uploaded_parts;if(!Array.isArray(o)||o.some((r,a)=>!Number.isSafeInteger(r?.part_number)||r.part_number<1||r.part_number>i||typeof r.etag!="string"||r.etag.length===0||r.etag.length>255||a>0&&o[a-1].part_number>=r.part_number)||(e.strategy.kind==="object_multipart"?o.length!==t.received.length||o.some((r,a)=>r.part_number-1!==t.received[a]):o.length!==0))throw d("invalid_operation_response","The authority returned invalid uploaded part status.")}function cc(t){return t.strategy.kind==="framed_chunks"?t.protection==="grant_aead_v1"&&Number.isSafeInteger(t.strategy.chunk_size)&&t.strategy.chunk_size>0:t.protection!=="transport_tls"?!1:t.strategy.kind==="object_put"?!0:Number.isSafeInteger(t.strategy.part_size)&&t.strategy.part_size>0}function ei(t,e,n){return Math.min(e,Math.max(0,t-n*e))}async function sn(t,e){for(let n=1;n<=Hn;n+=1){_e(e);try{return await t()}catch(i){if(e?.aborted||n===Hn||i instanceof b&&!i.retryable)throw i;await Yo(n,e)}}throw new Error("Unreachable file chunk retry state.")}function Ar(t,e,n,i,o,r){let a;try{a=new URL(t.url)}catch{throw d("invalid_operation_response","The authority returned an invalid object URL.")}if(t.protocol_version!==1||t.type!=="file_part"||t.transfer_id!==e||t.part_index!==n||t.offset!==i||t.content_length!==o||t.method.toUpperCase()!==r||a.protocol!=="https:"&&!(a.protocol==="http:"&&["localhost","127.0.0.1","[::1]","::1"].includes(a.hostname))||a.username||a.password)throw d("invalid_operation_response","The authority returned an invalid prepared file part.")}function Rr(t){let e=new Headers;for(let[n,i]of Object.entries(t))["host","content-length"].includes(n.toLowerCase())||e.set(n,i);return e}async function Pr(t,e,n){let i=new Array(t),o=0;return await Promise.all(Array.from({length:Math.min(t,e)},async()=>{for(;o<t;){let r=o;o+=1,i[r]=await n(r)}})),i}function _e(t){if(t?.aborted)throw d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t.reason})}function Te(t){return t instanceof b?t:typeof DOMException<"u"&&t instanceof DOMException&&t.name==="AbortError"?d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:t}):d("temporarily_unavailable","The file transfer could not be completed.",{cause:t})}var Ye=class{constructor(e,n,i,o,r=xe()){this.capability=e;this.request=n;this.framed=i;this.hosted=o;this.timeouts=r}capability;request;framed;hosted;timeouts;async*list(e={}){let n=pe(e,this.timeouts.fileIndexMs),i=n.signal;try{this.requireAction("list");let o;do{_e(i);let r=new URLSearchParams({protocol_version:String(1),...e.folder?{folder:e.folder}:{},...o?{after:o}:{},...e.pageSize?{limit:String(wr(e.pageSize))}:{}}),a;for(;;)try{a=await this.request("GET",`?${r.toString()}`,void 0,i);break}catch(s){let c=Te(s);if(c.code!=="file_index_warming")throw c;e.onIndexing?.(),await Z(500,i)}if(a.protocol_version!==1||a.type!=="files_page"||!Array.isArray(a.files))throw d("invalid_operation_response","The authority returned an invalid file page.");for(let s of a.files)_e(i),yield cn(s);o=a.next}while(o)}finally{n.dispose()}}async upload(e,n,i={}){return K(i,this.timeouts.uploadMs,o=>this.uploadWithinBudget(e,n,{...i,signal:o.signal,timeoutMs:null}))}async uploadWithinBudget(e,n,i){this.requireAction(i.ifRevision?"replace":"add");let o=br(n,i.mediaType),r=Xn(i.concurrency),a=await _r(o,i.signal,s=>{i.onProgress?.({phase:"hashing",transferredBytes:s,totalBytes:o.size})});return this.uploadKnownSource(e,o.size,`sha256:${a}`,(i.mediaType??o.type)||void 0,i,r,async(s,c,l)=>o.slice(c,c+l))}async uploadStream(e,n,i={}){return K(i,this.timeouts.uploadMs,o=>this.uploadStreamWithinBudget(e,n,{...i,signal:o.signal,timeoutMs:null}))}async uploadStreamWithinBudget(e,n,i){if(this.requireAction(i.ifRevision?"replace":"add"),!Number.isSafeInteger(n.size)||n.size<0)throw d("invalid_request","Streamed file size must be a non-negative safe integer.");if(!gr.test(n.contentDigest))throw d("invalid_request","Streamed files require a lowercase SHA-256 content digest.");let o=new an(n.stream,i.signal),r=new Oe;return this.uploadKnownSource(e,n.size,n.contentDigest,i.mediaType??n.mediaType,i,1,async(a,s,c)=>{let l=await o.read(c);return r.update(l),l},async()=>{if(await o.expectEnd(),`sha256:${r.digestHex()}`!==n.contentDigest)throw d("invalid_request","Streamed file bytes do not match the declared SHA-256 digest.")},()=>o.close(),a=>o.setMaxSourceChunkBytes(a))}async uploadKnownSource(e,n,i,o,r,a,s,c,l,u){let p=r.transferId??crypto.randomUUID();if(!mr.test(p))throw d("invalid_request","File transfer ID must be a UUID.");let f=!1;try{let h=await this.request("POST","uploads",{protocol_version:1,type:"open_file_upload",transfer_id:p,path:e,size:n,content_digest:i,...o?{media_type:o}:{},...r.ifRevision?{if_revision:r.ifRevision}:{}},r.signal);if(Zn(h,p,"upload"),h.total_size!==n||h.strategy.kind==="object_ranges")throw d("invalid_operation_response","The authority returned an incompatible upload strategy.");let y=h.strategy.kind==="framed_chunks";if(y&&!this.framed)throw d("invalid_operation_response","Encrypted file chunk delivery is unavailable.");let A=h.strategy.kind==="object_put"?Math.max(1,n):h.strategy.kind==="framed_chunks"?h.strategy.chunk_size:h.strategy.part_size,C=h.strategy.kind==="object_put"?1:Math.ceil(n/A),m=await this.request("GET",`transfers/${encodeURIComponent(p)}`,void 0,r.signal);if(Sr(m,h),m.state!=="open"&&m.state!=="committed")throw d("invalid_operation_response",`The authority cannot resume a ${m.state} file transfer.`);if(u?.(A),!y&&m.received.length===C){let S=await this.tryReplayUploadCommit(p,h.strategy.kind==="object_multipart"?m.uploaded_parts:void 0,r.signal);if(S)return f=!0,cn(S.file)}let v=new Set(m.received),_=new Map(m.uploaded_parts.map(S=>[S.part_number-1,S])),R=[...v].reduce((S,P)=>S+ei(n,A,P),0),T=await Pr(C,a,async S=>{let P=S*A,q=Math.min(A,Math.max(0,n-P)),H=await s(S,P,q);if(Cr(H)!==q)throw d("invalid_request","Streamed file bytes ended before the declared size.");if(v.has(S))return _.get(S)??null;let ne=y?await sn(async()=>this.framed.uploadChunk(h,S,await vr(H),r.signal),r.signal).then(()=>null):await this.uploadPart(p,S,P,H,q,h.strategy.kind==="object_multipart",r.signal);return R+=q,r.onProgress?.({phase:"uploading",transferredBytes:R,totalBytes:n}),ne});await c?.();let O=await this.commitUpload(p,h.strategy.kind==="object_multipart"?T.filter(S=>S!==null):void 0,r.signal);if(O.protocol_version!==1||O.type!=="file_upload_committed"||O.transfer_id!==p||O.file.path!==e||O.file.size!==n||O.file.content_digest!==i)throw d("invalid_operation_response","The authority returned an invalid file receipt.");return f=!0,cn(O.file)}catch(h){throw Te(h)}finally{await l?.().catch(()=>{}),!f&&r.transferId===void 0&&await this.abort(p)}}async download(e,n={}){if(e.size>Qn)throw d("invalid_request",`download() buffers at most ${Qn} bytes; use downloadStream() for larger files.`);let i=await this.downloadStream(e,n),o=[],r=i.getReader();for(;;){let a=await r.read();if(a.done)break;o.push(a.value)}return new Blob(o.map(a=>{let s=new Uint8Array(a.byteLength);return s.set(a),s.buffer}),{type:e.mediaType??""})}async downloadStream(e,n={}){return K(n,this.timeouts.requestMs,i=>this.openDownloadStream(e,n,i.signal))}async openDownloadStream(e,n,i){this.requireAction("read");let o=Xn(n.concurrency),r=crypto.randomUUID(),a;try{if(a=await this.request("POST","downloads",{protocol_version:1,type:"open_file_download",transfer_id:r,file_id:e.fileId,revision:e.revision},i),Zn(a,r,"download"),a.total_size!==e.size||a.strategy.kind!=="object_ranges"&&a.strategy.kind!=="framed_chunks")throw d("invalid_operation_response","The authority returned an incompatible download session.");if(a.strategy.kind==="framed_chunks"&&!this.framed)throw d("invalid_operation_response","Encrypted file chunk delivery is unavailable.");if(a.strategy.kind==="object_ranges"&&e.size>0&&!this.hosted)throw d("invalid_operation_response","Authenticated hosted file delivery is unavailable.")}catch(O){throw await this.abort(r),Te(O)}let s=a.strategy.kind==="framed_chunks"?a.strategy.chunk_size:a.strategy.part_size,c=Math.ceil(e.size/s),l=new Oe,u=0,p=0,f=null,h=0,y=!1,A=new AbortController,C=n.signal?AbortSignal.any([n.signal,A.signal]):A.signal,m=new Map,v=0,_=()=>{if(a.strategy.kind==="framed_chunks")for(;v<c&&m.size<o;){let O=v;v+=1;let S=sn(()=>this.framed.downloadChunk(a,O,C),C).then(P=>({ok:!0,chunk:P}),P=>({ok:!1,error:P}));m.set(O,S)}},R=async()=>{y||(y=!0,A.abort(),await f?.cancel().catch(()=>{}),f=null,await Promise.all(m.values()),m.clear(),await this.abort(r))},T=()=>{if(h!==e.size||`sha256:${l.digestHex()}`!==e.contentDigest)throw d("invalid_operation_response","Downloaded file bytes failed integrity verification.")};return new ReadableStream({pull:async O=>{try{if(_e(C),a.strategy.kind==="object_ranges")for(;;){if(!f){if(u>=c){T(),O.close(),R();return}let Hr=u*s;p=Math.min(s,e.size-Hr),f=(await sn(()=>this.hosted.downloadPart(a,u,p,C),C)).getReader()}let le=await f.read();if(le.done){if(f.releaseLock(),f=null,p!==0)throw d("invalid_operation_response","A hosted file range ended before its declared byte length.");u+=1;continue}if(!(le.value instanceof Uint8Array))throw d("invalid_operation_response","A hosted file range returned a non-byte chunk.");if(le.value.byteLength!==0){if(le.value.byteLength>p)throw d("invalid_operation_response","A hosted file range exceeded its declared byte length.");p-=le.value.byteLength,l.update(le.value),h+=le.value.byteLength,n.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),O.enqueue(le.value);return}}if(u>=c){T(),O.close(),R();return}let S=u*s,P=Math.min(s,e.size-S);_();let q=m.get(u);if(!q)throw d("invalid_operation_response","A file chunk was not scheduled.");let H=await q;if(m.delete(u),!H.ok)throw H.error;let ne=H.chunk;if(ne.byteLength!==P)throw d("invalid_operation_response","A file chunk had the wrong byte length.");l.update(ne),h+=ne.byteLength,u+=1,_(),n.onProgress?.({phase:"downloading",transferredBytes:h,totalBytes:e.size}),u===c&&T(),O.enqueue(ne),u===c&&(O.close(),R())}catch(S){let P=n.signal?.aborted?d("operation_cancelled","The file transfer was cancelled.",{operationOutcome:"not_sent",cause:n.signal.reason}):S;await R(),O.error(Te(P))}},cancel:R})}async downloadBytes(e,n={}){return new Uint8Array(await(await this.download(e,n)).arrayBuffer())}async move(e,n,i={}){return K(i,this.timeouts.requestMs,o=>this.moveWithinBudget(e,n,{...i,signal:o.signal,timeoutMs:null}))}async moveWithinBudget(e,n,i){this.requireAction("move");let o=i.mutationId??crypto.randomUUID(),r;try{r=await this.request("POST",`${encodeURIComponent(e.fileId)}/move`,{protocol_version:1,type:"move_file",mutation_id:o,file_id:e.fileId,if_revision:i.ifRevision??e.revision,from_path:e.path,path:n,update_references:!1},i.signal)}catch(a){throw Te(a)}if(r.protocol_version!==1||r.type!=="file_moved"||r.mutation_id!==o||r.file.file_id!==e.fileId||r.file.path!==n)throw d("invalid_operation_response","The authority returned an invalid file move receipt.");return cn(r.file)}async delete(e,n={}){return K(n,this.timeouts.requestMs,i=>this.deleteWithinBudget(e,{...n,signal:i.signal,timeoutMs:null}))}async deleteWithinBudget(e,n){this.requireAction("delete");let i=n.mutationId??crypto.randomUUID(),o;try{o=await this.request("POST",`${encodeURIComponent(e.fileId)}/delete`,{protocol_version:1,type:"delete_file",mutation_id:i,file_id:e.fileId,if_revision:n.ifRevision??e.revision,path:e.path},n.signal)}catch(r){throw Te(r)}if(o.protocol_version!==1||o.type!=="file_deleted"||o.mutation_id!==i||o.file_id!==e.fileId||o.previous_path!==e.path)throw d("invalid_operation_response","The authority returned an invalid file delete receipt.");return{protocolVersion:o.protocol_version,type:o.type,mutationId:o.mutation_id,fileId:o.file_id,previousPath:o.previous_path,revision:o.revision}}async uploadPart(e,n,i,o,r,a,s){for(let c=1;c<=_t;c+=1){_e(s);try{let l=await this.request("POST",`uploads/${encodeURIComponent(e)}/parts`,{protocol_version:1,type:"prepare_file_upload_part",transfer_id:e,part_number:n+1,content_length:r},s);Ar(l,e,n,i,r,"PUT");let u=await fetch(l.url,{method:l.method,headers:Rr(l.headers),body:o,redirect:"error",signal:s});if(!u.ok)throw new Error(`Object upload failed with HTTP ${u.status}.`);let p=u.headers.get("etag");if(a&&!p)throw new Error("Multipart object upload did not return an ETag.");return{part_number:n+1,etag:p??""}}catch(l){if(s?.aborted||c===_t)throw l}}throw new Error("Unreachable upload retry state.")}async tryReplayUploadCommit(e,n,i){try{return await this.commitUpload(e,n,i)}catch(o){if(o instanceof b&&o.code==="file_upload_incomplete")return null;throw o}}async commitUpload(e,n,i){let o;for(let r=1;r<=_t;r+=1){_e(i);try{return await this.request("POST",`uploads/${encodeURIComponent(e)}/commit`,{protocol_version:1,type:"commit_file_upload",transfer_id:e,...n===void 0?{}:{parts:n}},i)}catch(a){if(o=a,i?.aborted||a instanceof b||r===_t)throw a}}throw o}requireAction(e){if(!this.capability()?.actions.includes(e))throw d("not_authorized",`This connection is not authorized to ${e} files.`)}async abort(e){await this.request("DELETE",`transfers/${encodeURIComponent(e)}`).catch(()=>{})}};function cn(t){return{fileId:t.file_id,path:t.path,revision:t.revision,contentDigest:t.content_digest,size:t.size,...t.media_type?{mediaType:t.media_type}:{},mediaClass:t.media_class,modifiedAt:t.modified_at}}var lc=4,Or=32,ln=class{constructor(e,n,i={}){this.transport=e;this.requestTimeoutMs=n;this.foregroundCapacity=ti(i.foregroundCapacity,lc),this.foregroundQueueCapacity=ti(i.foregroundQueueCapacity,Or),this.mutationQueueCapacity=ti(i.mutationQueueCapacity,Or)}transport;requestTimeoutMs;foregroundCapacity;foregroundQueueCapacity;mutationQueueCapacity;foregroundQueue=[];mutationQueue=[];identicalReads=new Map;latestFamilies=new Map;activeForeground=0;mutationActive=!1;operation(e,n,i={}){let o=!ue(e,n),r=dc(i.coordination,o),a=o&&r.coalesce!==!1&&!r.latestWins&&i.signal===void 0?uc(e,n,i.timeoutMs):void 0;if(a){let c=this.identicalReads.get(a);if(c)return c}let s=K(i,this.requestTimeoutMs,c=>this.schedule(e,n,i,r,o,c));return a&&(this.identicalReads.set(a,s),s.finally(()=>{this.identicalReads.get(a)===s&&this.identicalReads.delete(a)}).catch(()=>{})),s}schedule(e,n,i,o,r,a){let s=o.latestWins?this.replaceLatest(o.family):void 0,c=pc(a.signal,s?.signal),{coordination:l,...u}=i,p=ot({...u,timeoutMs:null},a),f=()=>this.transport.operation(e,n,{...p,signal:c.signal}),h=r?this.foregroundQueue:this.mutationQueue,y=r?this.foregroundQueueCapacity:this.mutationQueueCapacity;return h.length>=y?(c.dispose(),this.releaseLatest(o.family,s),Promise.reject(d("connector_busy","The selected connection request queue is full.",{operationOutcome:"not_sent",status:503}))):new Promise((A,C)=>{let m={budget:a,run:f,resolve:R=>A(R),reject:C,started:!1,settled:!1},v=()=>{m.started||m.settled||(m.settled=!0,h.splice(h.indexOf(m),1),m.reject(J(c.signal)),c.dispose(),this.releaseLatest(o.family,s))};c.signal.addEventListener("abort",v,{once:!0});let _=m.run;m.run=async()=>{c.signal.removeEventListener("abort",v);try{if(c.signal.aborted)throw J(c.signal);return await _()}finally{c.dispose(),this.releaseLatest(o.family,s)}},h.push(m),this.pump()})}replaceLatest(e){let n=new AbortController;return this.latestFamilies.get(e)?.abort(d("operation_cancelled","A newer request replaced this read before it changed the collection.",{operationOutcome:"not_sent"})),this.latestFamilies.set(e,n),n}releaseLatest(e,n){e&&n&&this.latestFamilies.get(e)===n&&this.latestFamilies.delete(e)}pump(){for(;this.activeForeground<this.foregroundCapacity;){let e=Tr(this.foregroundQueue);if(!e)break;this.activeForeground+=1,this.start(e,()=>{this.activeForeground-=1,this.pump()})}if(!this.mutationActive){let e=Tr(this.mutationQueue);e&&(this.mutationActive=!0,this.start(e,()=>{this.mutationActive=!1,this.pump()}))}}start(e,n){e.started=!0,e.run().then(i=>{e.settled||(e.settled=!0,e.resolve(i))},i=>{e.settled||(e.settled=!0,e.reject(i))}).finally(n)}};function Tr(t){for(;t.length>0;){let e=t.shift();if(!e.settled)return e}}function dc(t,e){let n=t??{};if(n.latestWins&&!e)throw new TypeError("latestWins coordination is available only for read operations.");if(n.latestWins&&!n.family?.trim())throw new TypeError("latestWins coordination requires a non-empty family.");return n}function uc(t,e,n){return`${t}:${n===void 0?"default":String(n)}:${ni(e)}`}function ni(t){return t===null||typeof t!="object"?JSON.stringify(t)??String(t):Array.isArray(t)?`[${t.map(ni).join(",")}]`:`{${Object.entries(t).sort(([e],[n])=>e.localeCompare(n)).map(([e,n])=>`${JSON.stringify(e)}:${ni(n)}`).join(",")}}`}function pc(t,e){if(!e)return{signal:t,dispose:()=>{}};let n=new AbortController,i=()=>n.abort(t.reason),o=()=>n.abort(e.reason);return t.aborted?i():t.addEventListener("abort",i,{once:!0}),e.aborted?o():e.addEventListener("abort",o,{once:!0}),{signal:n.signal,dispose:()=>{t.removeEventListener("abort",i),e.removeEventListener("abort",o)}}}function ti(t,e){let n=t??e;if(!Number.isSafeInteger(n)||n<=0)throw new TypeError("Request coordinator capacities must be positive safe integers.");return n}var Qe=class{constructor(e,n){this.internals=e;this.collectionId=n;this.transport=new rn({serverUrl:e.serverUrl,storage:e.storage,keyStore:e.keyStore,directAccessMode:e.directAccessMode,loopbackUrl:e.loopbackUrl,collectionId:n,internals:e,timeouts:e.timeouts,onChange:()=>this.emitConnection()}),this.files=new Ye(()=>this.fileCapability,(i,o,r,a)=>this.transport.files.control(i,o,r,a),{uploadChunk:(i,o,r,a)=>this.transport.files.uploadChunk(i,o,r,a),downloadChunk:(i,o,r)=>this.transport.files.downloadChunk(i,o,r)},{downloadPart:(i,o,r,a)=>this.transport.files.downloadHostedPart(i,o,r,a)},e.timeouts),this.collectionClient=new Ge(new ln({operation:(i,o,r)=>this.transport.performOperation(i,o,r)},e.timeouts.requestMs),e.timeouts.requestMs),this.notifications=new Vt({serverUrl:e.serverUrl,storage:e.storage,authorizedToken:i=>this.transport.authorizedToken({signal:i,timeoutMs:null}),register:i=>this.internals.register({signal:i,timeoutMs:null}),notificationKey:i=>e.notificationKey(n,i),requestTimeoutMs:e.timeouts.requestMs})}internals;collectionId;collectionClient;notifications;transport;files;connectionListeners=new Set;get displayName(){return this.transport.currentToken()?.collectionName??`Collection ${this.collectionId.slice(0,8)}`}get operations(){return[...this.transport.currentToken()?.operations??[]]}get scope(){return this.transport.currentToken()?.scope??null}get fileCapability(){return this.transport.currentToken()?.fileCapability??null}get directAccess(){return this.transport.directAccess}get route(){return this.transport.route}register(e){return D(()=>this.internals.register(e),Se)}info(){let e=this.transport.currentToken();return e?{collectionId:e.collectionId,displayName:e.collectionName,operations:[...e.operations],scope:e.scope,...e.fileCapability?{fileCapability:e.fileCapability}:{},authority:e.authority?{kind:"hosted",durability:"provider"}:{kind:"connector",durability:"computer"},route:this.transport.route,directAccess:this.transport.directAccess}:null}authorizationCapabilities(e=we){let n=this.operations,i=lt(e).filter(o=>!n.includes(o));return{authorized:this.info()!==null,sufficient:this.info()!==null&&i.length===0,collectionId:this.collectionId,grantedOperations:n,missingOperations:i}}hasOperations(e){return this.authorizationCapabilities(e).sufficient}authorize(e={}){return D(()=>this.internals.authorize({...e,target:{kind:"collection",collectionId:this.collectionId}}),fe)}async requestCapabilities(e,n={}){return D(async()=>{let i=await this.internals.register(n);if(Q(i.requirements,{...n,capabilities:e}),this.info()!==null&&e.every(a=>(W(B(i.requirements),a)??[]).every(s=>this.operations.includes(s))))return{kind:"unchanged",connection:this};if(B(i.requirements)===1){let{capabilities:a,...s}=n;return this.internals.authorize({...s,target:{kind:"collection",collectionId:this.collectionId},operations:[...new Set([...this.operations,...e.flatMap(c=>W(1,c)??[])])]})}let r=Tt(i.requirements,this.operations);return this.internals.authorize({...n,target:{kind:"collection",collectionId:this.collectionId},capabilities:[...new Set([...r,...e])]})},fe)}async requestOperations(e,n={}){return D(async()=>{let i=await this.internals.register(n);Q(i.requirements,{...n,operations:e});let o=this.authorizationCapabilities(e);return o.sufficient?{kind:"unchanged",connection:this}:this.internals.authorize({...n,target:{kind:"collection",collectionId:this.collectionId},operations:[...new Set([...o.grantedOperations,...e])]})},fe)}onConnectionChange(e){return this.connectionListeners.add(e),e(this.info()),()=>this.connectionListeners.delete(e)}notifyStorageChanged(){this.transport.notifyStorageChanged()}checkDirectAccess(e){return D(()=>this.transport.checkDirectAccess(e),xn)}requestDirectAccess(e){return D(()=>this.transport.requestDirectAccess(e),xn)}disableDirectAccess(){this.transport.disableDirectAccess()}sync(){let e=this.transport.currentToken();if(!e)return null;let n=e.collectionId;if(!e.authority){if(!e.grantId||!e.operations.includes("sync"))return null;let o=e.grantId;return{collectionId:n,replicaId:o,transport:{openSession:r=>this.transport.performOperation("sync",{action:"open_session"},dn(r,this.internals.timeouts.syncMs)),snapshot:(r,a,s)=>this.transport.performOperation("sync",{action:"snapshot",snapshot_id:r,...a?{page:a}:{}},dn(s,this.internals.timeouts.syncMs)),changes:(r,a=200,s)=>this.transport.performOperation("sync",{action:"changes",after:r,limit:a},dn(s,this.internals.timeouts.syncMs)),mutate:(r,a)=>this.transport.performOperation("sync",{action:"mutate",mutation:r},dn(a,this.internals.timeouts.syncMs))}}}let i=e.authority.replicaId;return{collectionId:n,replicaId:i,transport:{openSession:o=>this.transport.performAuthoritySyncRequest(n,i,"POST","sessions",void 0,o),snapshot:(o,r,a)=>{let s=new URLSearchParams({snapshot_id:o});return r&&s.set("page",r),this.transport.performAuthoritySyncRequest(n,i,"GET",`snapshot?${s}`,void 0,a)},changes:(o,r=200,a)=>this.transport.performAuthoritySyncRequest(n,i,"GET",`changes?${new URLSearchParams({after:String(o),limit:String(r)})}`,void 0,a),mutate:(o,r)=>this.transport.performAuthoritySyncRequest(n,i,"POST","mutations",o,r)}}}registerNotifications(e){return D(()=>this.notifications.registerNotifications(e),rt)}registerNativeNotifications(e){return D(()=>this.notifications.registerNativeNotifications(e),rt)}unregisterNativeNotifications(e){return D(()=>this.notifications.unregisterNativeNotifications(e),rt)}unregisterNotifications(e,n){return D(()=>this.notifications.unregisterNotifications(e,n),rt)}forget(){let e=this.transport.currentToken();this.internals.removeToken(this.collectionId,e?.keyHandle,"not_authorized",!0),this.transport.notifyStorageChanged()}describe(e){return this.collectionClient.describe(e)}changes(e={},n){return this.collectionClient.changes(e,n)}read(e,n){return this.collectionClient.read(e,n)}query(e={},n){return this.collectionClient.query(e,n)}queryPages(e={},n={}){return this.collectionClient.queryPages(e,n)}queryAll(e={},n={}){return this.collectionClient.queryAll(e,n)}listViews(e){return this.collectionClient.listViews(e)}executeView(e,n){return this.collectionClient.executeView(e,n)}executeViewPages(e,n={}){return this.collectionClient.executeViewPages(e,n)}readViewSource(e,n){return this.collectionClient.readViewSource(e,n)}createViewSource(e,n){return this.collectionClient.createViewSource(e,n)}updateViewSource(e,n){return this.collectionClient.updateViewSource(e,n)}deleteViewSource(e,n){return this.collectionClient.deleteViewSource(e,n)}create(e,n){return this.collectionClient.create(e,n)}update(e,n){return this.collectionClient.update(e,n)}delete(e,n){return this.collectionClient.delete(e,n)}preflightDelete(e,n){return this.collectionClient.preflightDelete(e,n)}rename(e,n){return this.collectionClient.rename(e,n)}preflightRename(e,n){return this.collectionClient.preflightRename(e,n)}async renameWithProgress(e,n={}){return K(n,this.internals.timeouts.requestMs,async i=>{let o=Date.now(),r=!1,a,s=(c,l,u=0)=>{n.onProgress?.({operation:"rename",state:c,elapsedMs:Date.now()-o,cancellable:l,resumed:r,completedUnits:u,...a?{estimate:a}:{}})};try{Ae(i.signal),s("preflighting",!0);let c=n.preflight?I(n.preflight):await this.preflightRename(e,{signal:i.signal,timeoutMs:null});if(!c.ok)return c;let l=c.value;try{ao(e,l)}catch(f){if(f instanceof b)return g(f.problem);throw f}a=co(e,l),s("ready",!0),Ae(i.signal);let u=this.transport.hasResumableMutationTransport();s("applying",u);let p=await this.rename(e,u?{signal:i.signal,timeoutMs:null}:{timeoutMs:kr(i.remainingMs())});return p.ok&&s("completed",!1,a.totalUnits),p}catch(c){if(Un(c,i.signal)&&s("cancelled",!1),c instanceof b)return g(c.problem);throw c}})}async deleteWithProgress(e,n={}){return K(n,this.internals.timeouts.requestMs,async i=>{let o=Date.now(),r=!1,a,s=(c,l,u=0)=>{n.onProgress?.({operation:"delete",state:c,elapsedMs:Date.now()-o,cancellable:l,resumed:r,completedUnits:u,...a?{estimate:a}:{}})};try{Ae(i.signal),s("preflighting",!0);let c=n.preflight?I(n.preflight):await this.preflightDelete(e,{signal:i.signal,timeoutMs:null});if(!c.ok)return c;let l=c.value;try{so(e,l)}catch(f){if(f instanceof b)return g(f.problem);throw f}a=lo(l),s("ready",!0),Ae(i.signal);let u=this.transport.hasResumableMutationTransport();s("applying",u);let p=await this.delete(e,u?{signal:i.signal,timeoutMs:null}:{timeoutMs:kr(i.remainingMs())});return p.ok&&s("completed",!1,a.totalUnits),p}catch(c){if(Un(c,i.signal)&&s("cancelled",!1),c instanceof b)return g(c.problem);throw c}})}pendingMutations(){return this.transport.pendingMutations().map(e=>({...e,recover:n=>D(()=>this.recoverPendingMutation(e.requestId,n),j)}))}pendingMutation(e){let n=this.transport.pendingMutation(e);return n?{...n,recover:i=>D(()=>this.recoverPendingMutation(e,i),j)}:null}async recoverPendingMutation(e,n){let i=await this.transport.recoverPendingMutation(e,n);if(i&&typeof i=="object"&&"valid"in i){let o=i;if(!o.valid)throw new b(ke(o));return o.result}return i}validate(e={},n){return this.collectionClient.validate(e,n)}readType(e,n){return this.collectionClient.readType(e,n)}createType(e,n){return this.collectionClient.createType(e,n)}updateType(e,n){return this.collectionClient.updateType(e,n)}assessTypePack(e,n){return this.collectionClient.assessTypePack(e,n)}applyTypePack(e,n){return this.collectionClient.applyTypePack(e,n)}assessCollectionSetup(e,n){return this.collectionClient.assessCollectionSetup(e,n)}applyCollectionSetup(e,n){return this.collectionClient.applyCollectionSetup(e,n)}listTimers(e,n){return this.collectionClient.listTimers(e,n)}putTimer(e,n){return this.collectionClient.putTimer(e,n)}cancelTimer(e,n){return this.collectionClient.cancelTimer(e,n)}reconcileTimers(e,n){return this.collectionClient.reconcileTimers(e,n)}watch(e={},n={}){return D(()=>F(n,this.internals.timeouts.watchStartMs,async i=>{let o=await this.collectionClient.changes(e.cursor===void 0?{}:{after:e.cursor,limit:200},{signal:i.signal,timeoutMs:null});if(!o.ok)throw new b(o.problem);if(o.value.reset)throw new b(w("change_cursor_reset","The collection change cursor expired. Refresh collection state before subscribing again."));return new ii(this.collectionClient,o.value.cursor,e,e.cursor===void 0?[]:o.value.events,this.internals.timeouts.watchStartMs)}),xt)}emitConnection(){let e=this.info();for(let n of this.connectionListeners)n(e)}},ii=class{constructor(e,n,i,o,r){this.client=e;this.input=i;this.watchStartTimeoutMs=r;this.pendingChanges=[...o],this.currentStatus={state:"connected",cursor:n,recovered:!1};let a=i.lifetimeSignal;if(a?.aborted)this.close();else if(a){let s=()=>this.close();a.addEventListener("abort",s,{once:!0}),this.removeLifetimeAbort=()=>a.removeEventListener("abort",s)}this.controller.signal.aborted||this.run(n)}client;input;watchStartTimeoutMs;changes=new Set;statuses=new Set;problems=new Set;controller=new AbortController;removeLifetimeAbort;currentStatus;currentProblem=null;pendingChanges;get status(){return this.currentStatus}get problem(){return this.currentProblem}subscribe(e,n,i){this.changes.add(e),n&&(this.statuses.add(n),n(this.currentStatus)),i&&(this.problems.add(i),this.currentProblem&&i(this.currentProblem));for(let o of this.pendingChanges)e(o);return this.pendingChanges=[],()=>{this.changes.delete(e),n&&this.statuses.delete(n),i&&this.problems.delete(i)}}close(){if(this.controller.signal.aborted)return;this.controller.abort(),this.removeLifetimeAbort?.(),this.removeLifetimeAbort=void 0;let e="cursor"in this.currentStatus?this.currentStatus.cursor:void 0;this.publishStatus({state:"closed",...e===void 0?{}:{cursor:e}})}async run(e){let n=!0,i=this.client.watch({cursor:e,pollIntervalMs:this.input.pollIntervalMs,retry:this.input.retry,signal:this.controller.signal,timeoutMs:this.watchStartTimeoutMs,onStatus:o=>{if(n&&o.state==="connecting"){n=!1;return}n=!1,this.publishStatus(o)}});try{for await(let o of i){if(this.controller.signal.aborted)return;if(!o.ok){this.currentProblem=o.problem;for(let r of this.problems)r(o.problem);return}for(let r of this.changes)r(o.value)}}finally{this.controller.signal.aborted||this.close()}}publishStatus(e){this.currentStatus=e;for(let n of this.statuses)n(e)}};function dn(t,e){return{...t,timeoutMs:t?.timeoutMs===void 0?e:t.timeoutMs}}function kr(t){return t===null?null:Math.max(1,Math.ceil(t))}function un(t,e){let n=M(t.getItem(`${e}:connections`));return n?.version===1&&Array.isArray(n.collectionIds)&&n.collectionIds.every(i=>typeof i=="string")?n.collectionIds:[]}function Ir(t,e,n){xr(t,e,[...un(t,e),n])}function Mr(t,e,n){xr(t,e,un(t,e).filter(i=>i!==n))}function xr(t,e,n){t.setItem(`${e}:connections`,JSON.stringify({version:1,collectionIds:[...new Set(n)]}))}async function zr(t){if(typeof location>"u"&&!t.navigate&&!t.options.openVerification)throw d("browser_required","Authorization navigation requires a browser environment.");let n=(t.options.presentation==="popup"||t.portableDeclared)&&!t.options.openVerification&&!t.navigate&&typeof window<"u"?window.open("","mdbase-connect-authorization","popup,width=620,height=760"):null;try{return{application:await t.register(t.options.signal),popup:n}}catch(i){throw n?.close(),i}}async function Fr(t){let e=Ur(t.storagePrefix,t.state);try{for(;;){let n=M(t.storage.getItem(e));if(n?.version===1){if(t.storage.removeItem(e),n.status==="failed")throw U(n.code,n.message,{details:n.returnTo?{return_to:n.returnTo}:void 0});let i=t.connection(n.collectionId);if(!i)throw d("invalid_callback","Authorization completed without a usable saved connection.");return{kind:"connected",connection:i,...n.returnTo?{returnTo:n.returnTo}:{}}}await Z(200,t.signal)}}finally{t.popup.close(),t.storage.removeItem(e);let n=`${t.storagePrefix}:pending:${t.state}`;M(t.storage.getItem(n))?.state===t.state&&(t.storage.removeItem(n),t.pending.keyHandle&&await t.keyStore.delete(t.pending.keyHandle))}}function Dr(t){return t.completion.then(e=>(t.popupAttempt&&Er(t,{version:1,status:"connected",collectionId:e.connection.collectionId,...e.returnTo?{returnTo:e.returnTo}:{}}),t.popupAttempt&&qr(),e)).catch(e=>{throw t.popupAttempt&&Er(t,{version:1,status:"failed",code:e instanceof b?e.code:"invalid_callback",message:e instanceof Error?e.message:"Authorization could not be completed.",...t.pending?.returnTo?{returnTo:t.pending.returnTo}:{}}),t.popupAttempt&&qr(),e})}function Er(t,e){t.storage.setItem(Ur(t.storagePrefix,t.state),JSON.stringify(e))}function Ur(t,e){return`${t}:completion:${e}`}function qr(){typeof window<"u"&&typeof window.close=="function"&&window.close()}function oi(t,e,n,i){let o=`${e}:pending-mutation:`,r=new Set;for(let a=0;a<t.length;a+=1){let s=t.key(a);if(!s?.startsWith(o))continue;let c=M(t.getItem(s));if(!c||!n.includes(c.operation)||i&&c.collectionId!==i)continue;let l=c.envelope?.protocol_version??c.request?.protocol_version;l!==void 0&&l!==$&&Ze(l)&&r.add(l)}return[...r].sort((a,s)=>s-a)}function ri(t,e,n){return ai(t,e).has(n)}function ai(t,e){let n=new Set;for(let i=0;i<t.length;i+=1){let o=t.key(i);if(o!==e&&!o?.startsWith(`${e}:`))continue;let r=M(t.getItem(o));r?.keyHandle&&n.add(r.keyHandle)}return n}function Lr(t,e,n){let i=[e];for(let o=0;o<t.length;o+=1){let r=t.key(o);r?.startsWith(`${e}:`)&&i.push(r)}for(let o of i){let r=M(t.getItem(o));r?.keyHandle&&n(r.keyHandle),t.removeItem(o)}}function Nr({body:t,clientId:e,keyHandle:n,previous:i,retiredKeyHandles:o,defaultApplicationOrigin:r,pinConnectorIdentity:a}){let s=t.collection_id;if(typeof s!="string")throw d("invalid_token_response","Authorization returned no collection ID.");let c=Ft(t.scope);if(!c)throw d("invalid_token_response","Authorization returned no valid collection scope.");if(!Dt(c))throw d("legacy_scope_reauthorization_required","Authorization returned a legacy contract-scoped grant. Reauthorize for the entire collection.");if(t.authority&&!pt(t.authority,s))throw d("invalid_token_response","Authorization returned an invalid remote authority capability.");if(t.authority&&t.encryption)throw d("invalid_token_response","Authorization returned conflicting collection transports.");if(t.file_capability!==null&&t.file_capability!==void 0&&!zt(t.file_capability))throw d("invalid_token_response","Authorization returned an invalid file capability.");if(t.encryption){try{re(t.encryption)}catch{throw d("invalid_token_response","Authorization returned an invalid encrypted relay binding.")}if(a(t.encryption.connector_id,t.encryption.connector_agreement_public_key),t.encryption.collection_id!==s||typeof t.grant_id!="string"||t.grant_id.length===0)throw d("invalid_token_response","Authorization returned an encrypted relay binding for another grant.")}if(i?.encryption&&t.encryption&&i.keyHandle&&i.keyHandle===n&&(i.grantId!==t.grant_id||i.encryption.connector_id!==t.encryption.connector_id||i.encryption.connector_agreement_public_key!==t.encryption.connector_agreement_public_key||i.encryption.application_agreement_public_key!==t.encryption.application_agreement_public_key))throw d("connector_identity_changed","The connector identity changed during authorization renewal. Reauthorize before sending collection data.");return{version:1,accessToken:t.access_token,refreshToken:t.refresh_token,clientId:e,collectionId:s,collectionName:t.collection_name??`Collection ${s.slice(0,8)}`,operations:t.operations,scope:c,expiresAt:Date.now()+t.expires_in*1e3,refreshExpiresAt:t.refresh_expires_in?Date.now()+t.refresh_expires_in*1e3:void 0,grantId:t.grant_id,encryption:t.encryption??void 0,fileCapability:t.file_capability??void 0,applicationOrigin:t.application_origin??r,keyHandle:n,...o?.length?{retiredKeyHandles:o}:{},savedAt:Date.now(),authority:t.authority?{operationsUrl:t.authority.operations_url,syncUrl:t.authority.sync_url,filesUrl:t.authority.files_url,replicaId:t.authority.replica_id,accessToken:t.authority.access_token,proofPublicKey:t.authority.proof_public_key}:void 0}}function si(t,e){let n=new Set;if(e&&n.add(e),t?.keyHandle&&n.add(t.keyHandle),Array.isArray(t?.retiredKeyHandles))for(let i of t.retiredKeyHandles)typeof i=="string"&&i.length>0&&n.add(i);return n}function Br(t,e,n,i,o=[],r=!1){let a=[],s=[],c=si(n);for(let u of ai(t,e))c.add(u);let l=new Set(o);for(let u of l)c.add(u);for(let u of c)u!==i&&(r||l.has(u)||ri(t,e,u)?a:s).push(u);return{retained:a,disposable:s}}function fc(t,e,n){let i=M(t.getItem(e));if(!i||!Array.isArray(i.retiredKeyHandles))return;let o=i.retiredKeyHandles.filter(r=>r!==n);o.length!==i.retiredKeyHandles.length&&(o.length>0?i.retiredKeyHandles=o:delete i.retiredKeyHandles,t.setItem(e,JSON.stringify(i)))}async function jr(t,e,n,i,o){M(t.getItem(i))?.keyHandle===o||ri(t,n,o)||(await e.delete(o),fc(t,i,o))}var pn=class{serverUrl;manifest;manifestSource;redirectUri;storage;relayEncryption;keyStore;identityStore;directAccessMode;loopbackUrl;navigate;timeouts;credentialStorage;application=null;manifestPromise=null;completionPromises=new Je;grantKeyLeases;connectionCache=new Map;listeners=new Set;invalidatedConnections=new Map;constructor(e){this.serverUrl=bo(String(e.serverUrl));let n=ho(e.manifest,e.redirectUri);this.manifest=n.manifest,this.manifestSource=n.manifestSource;let i=So(this.manifest);this.redirectUri=n.redirectUri,this.storage=e.storage??wo(i),this.relayEncryption=e.relayEncryption??"required",this.keyStore=e.keyStore??(i?new qe:new Ee),this.identityStore=e.identityStore??(i?new Ke:new je),this.credentialStorage=e.storage||e.keyStore||e.identityStore?"custom":this.storage instanceof De?"memory":"persistent",this.directAccessMode=e.directAccess??"auto",this.loopbackUrl=yo(String(e.loopbackUrl??`http://127.0.0.1:${qi}`)),this.navigate=e.navigate,this.timeouts=xe(e.timeouts),this.grantKeyLeases=new Ht(this.storagePrefix(),(o,r)=>this.deleteGrantKeyWhenUnused(o,r)),typeof window<"u"&&this.storage===window.localStorage&&window.addEventListener("storage",o=>{o.storageArea!==this.storage||!o.key?.startsWith(this.storagePrefix())||(this.connectionCache.get(vo(o.key))?.notifyStorageChanged(),this.emitConnections())})}environment(){let e=typeof this.manifest!="string"&&this.manifest.distribution==="portable"?"portable":this.application?.distribution??"web";return{distribution:e,applicationOrigin:e==="portable"?"null":this.defaultApplicationOrigin(),credentialStorage:this.credentialStorage}}register(e={}){return F(e,this.timeouts.requestMs,n=>this.registerWithinBudget(n.signal))}async registerWithinBudget(e){if(this.application)return this.application;let n=await ae(`${this.serverUrl}/v1/apps/register`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({manifest:await this.manifestDeclaration({signal:e,timeoutMs:null})}),signal:e},"temporarily_unavailable","Application registration is temporarily unavailable."),i=await E(n,"invalid_operation_response","Connect returned an invalid application registration response.");if(!n.ok)throw z(i,"discovery_failed","Application discovery failed.",n.status);return this.application=i.application,this.application}manifestDeclaration(e={}){if(this.manifestPromise)return this.manifestPromise;let i=F(e,this.timeouts.requestMs,o=>this.loadManifest(o.signal)).catch(o=>{throw this.manifestPromise===i&&(this.manifestPromise=null),o});return this.manifestPromise=i,this.manifestPromise}async loadManifest(e){if(typeof this.manifest!="string")return this.manifest;let n=this.manifest,i;try{i=await fetch(n,{headers:{accept:"application/json"},signal:e})}catch(o){throw d("manifest_load_failed","The bundled application declaration could not be loaded.",{cause:o})}if(!i.ok)throw d("manifest_load_failed",`The bundled application declaration returned HTTP ${i.status}.`,{status:i.status});try{return await E(i,"invalid_application_manifest","The bundled application declaration is not valid JSON.")}catch(o){throw d("invalid_application_manifest","The bundled application declaration is not valid JSON.",{cause:o,details:{issues:[{path:"/",keyword:"json",message:"must be valid JSON",params:{}}]}})}}async authorize(e={}){let n=e.presentation==="popup"?6e5:this.timeouts.requestMs;return F(e,n,i=>this.authorizeWithinBudget({...e,signal:i.signal,timeoutMs:null}))}async authorizeWithinBudget(e){let n=typeof this.manifest!="string"&&this.manifest.distribution==="portable",{application:i,popup:o}=await zr({options:e,portableDeclared:n,navigate:this.navigate,register:r=>this.registerWithinBudget(r)});try{Q(i.requirements,e),i.requirements.capabilities?.contract_version===2&&await Ao(this.serverUrl,e.signal)}catch(r){throw o?.close(),r}return i.distribution==="portable"?(e.openVerification&&o?.close(),this.authorizePortable(i,e,e.openVerification?null:o)):this.authorizeWeb(i,e,o)}async authorizeWeb(e,n,i){let{verifier:o,challenge:r}=await dt(),a=X(24),s=crypto.randomUUID(),c=n.target?.kind==="collection"?n.target.collectionId:void 0,l=`grant:${e.id}:${a}`,u=await this.keyStore.create(l),p;try{p=await this.loadApplicationIdentity(e)}catch(m){throw await this.keyStore.delete(l),m}let f=Tn(e,n),h=kn(e.requirements),y=new Date,A=await gt({protocol_version:ee,authorization_id:s,application_id:e.id,application_declaration_id:ft(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await Ve(p),installation_signing_public_key:p.signingPublicKey,grant_agreement_public_key:u.agreementPublicKey,grant_signing_public_key:u.signingPublicKey,flow:"authorization_code",authorization_nonce:X(32),issued_at:y.toISOString(),expires_at:new Date(y.getTime()+600*1e3).toISOString(),redirect_uri:this.redirectUri,state:a,code_challenge:r,contracts:Rn(f,h,oi(this.storage,this.storagePrefix(),f,c),B(e.requirements)),requested_operations:f,...h?{requested_files:h}:{},...c?{collection_id:c}:{}},p),C={version:1,verifier:o,state:a,clientId:e.id,redirectUri:this.redirectUri,relayEncryption:this.relayEncryption,collectionId:c,returnTo:n.returnTo,keyHandle:l,authorizationId:s,applicationAgreementPublicKey:u.agreementPublicKey,applicationSigningPublicKey:u.signingPublicKey,...n.presentation==="popup"&&i?{presentation:"popup"}:{}};this.storage.setItem(this.pendingKey(a),JSON.stringify(C));try{let m=await fetch(`${this.serverUrl}/oauth/authorization_request`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.id,redirect_uri:this.redirectUri,code_challenge:r,code_challenge_method:"S256",state:a,operations:f.join(","),...c?{collection_id:c}:{},application_authorization:JSON.stringify(A)}),signal:n.signal}),v=await E(m,"invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(!m.ok)throw z(v,"device_authorization_failed","Application authorization could not be started.",m.status);if(typeof v.authorization_uri!="string"||v.authorization_id!==s||!Number.isInteger(v.expires_in)||v.expires_in<=0)throw d("invalid_device_authorization_response","The authorization service returned an invalid authorization response.");if(n.presentation==="popup"&&i)return i.location.href=v.authorization_uri,await Fr({storage:this.storage,storagePrefix:this.storagePrefix(),state:a,pending:C,popup:i,signal:n.signal,keyStore:this.keyStore,connection:_=>this.connection(_)});if(i?.close(),this.navigate)await this.navigate(v.authorization_uri);else if(typeof location<"u")location.assign(v.authorization_uri);else throw d("browser_required","Authorization navigation requires a browser environment.");return{kind:"redirecting"}}catch(m){throw i?.close(),this.storage.removeItem(this.pendingKey(a)),await this.keyStore.delete(l),n.signal?.aborted?Ue(n.signal,"Application authorization was cancelled.",m):m}}async authorizePortable(e,n,i){if(this.relayEncryption!=="required")throw i?.close(),d("encryption_required","Downloaded applications require encrypted relay authorization.");let{verifier:o,challenge:r}=await dt(),a=`grant:${e.id}:${X(24)}`,s=await this.keyStore.create(a),c;try{c=await this.loadApplicationIdentity(e)}catch(v){throw i?.close(),await this.keyStore.delete(a),v}let l=Tn(e,n),u=kn(e.requirements),p=crypto.randomUUID(),f=new Date,h=await gt({protocol_version:ee,authorization_id:p,application_id:e.id,application_declaration_id:ft(e.family_identity),application_manifest_digest:e.manifest_digest,application_installation_id:await Ve(c),installation_signing_public_key:c.signingPublicKey,grant_agreement_public_key:s.agreementPublicKey,grant_signing_public_key:s.signingPublicKey,flow:"device_code",authorization_nonce:X(32),issued_at:f.toISOString(),expires_at:new Date(f.getTime()+600*1e3).toISOString(),code_challenge:r,contracts:Rn(l,u,oi(this.storage,this.storagePrefix(),l,n.target?.kind==="collection"?n.target.collectionId:void 0),B(e.requirements)),requested_operations:l,...u?{requested_files:u}:{},...n.target?.kind==="collection"?{collection_id:n.target.collectionId}:{}},c),y,A;try{y=await fetch(`${this.serverUrl}/oauth/device_authorization`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:e.id,operations:l.join(","),...n.target?.kind==="collection"?{collection_id:n.target.collectionId}:{},code_challenge:r,code_challenge_method:"S256",application_authorization:JSON.stringify(h)}),signal:n.signal}),A=await E(y,"invalid_device_authorization_response","The authorization service returned an invalid device authorization response.")}catch(v){throw i?.close(),await this.keyStore.delete(a),d("device_authorization_failed","Downloaded application authorization could not be started.",{cause:v})}if(!y.ok)throw i?.close(),await this.keyStore.delete(a),z(A,"device_authorization_failed","Downloaded application authorization could not be started.",y.status);let C;try{C=_o(A)}catch(v){throw i?.close(),await this.keyStore.delete(a),n.signal?.aborted?Ue(n.signal,"Downloaded application authorization was cancelled.",v):v}if(n.onDeviceCode?.(C),n.openVerification)await n.openVerification(C);else if(i)try{i.location.href=C.verificationUriComplete}catch{}else throw await this.keyStore.delete(a),d("approval_window_blocked","The approval window was blocked. Show the provided verification link and code, then try again.",{details:{user_code:C.userCode,verification_uri:C.verificationUri,verification_uri_complete:C.verificationUriComplete,expires_at:C.expiresAt,interval_seconds:C.intervalSeconds}});let m=C.intervalSeconds;try{for(;Date.now()<C.expiresAt;){if(await Z(m*1e3,n.signal),n.signal?.aborted)throw Ue(n.signal,"Downloaded application authorization was cancelled.");let v;try{v=await fetch(`${this.serverUrl}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:A.device_code,client_id:e.id,code_verifier:o}),signal:n.signal})}catch(S){if(n.signal?.aborted)throw Ue(n.signal,"Downloaded application authorization was cancelled.",S);continue}let _=await E(v,"invalid_token_response","The authorization service returned an invalid token response.");if(!v.ok){let S=ut(_);if(S==="authorization_pending")continue;if(S==="slow_down"){m+=5;continue}throw z(_,"token_exchange_failed","Downloaded application authorization could not be completed.",v.status)}let R=pt(_.authority,_.collection_id),T=_.encryption&&_.encryption.protocol_version===Ot&&_.encryption.suite===tt&&_.encryption.application_agreement_public_key===s.agreementPublicKey;if(_.application_origin!=="null")throw d("invalid_token_response","Authorization did not bind the portable grant to its opaque application origin.");if(_.authority&&(!R||_.encryption!=null||_.authority.proof_public_key!==s.signingPublicKey))throw d("invalid_token_response","Authorization returned a remote authority capability that is not bound to this portable grant key.");if(!_.authority&&!T)throw d("encryption_required","Authorization did not establish the expected key-bound local portable grant.");let O=this.storeTokenResponse(_,e.id,a);if(n.target?.kind==="collection"&&n.target.collectionId!==O.collectionId)throw this.removeToken(O.collectionId,O.keyHandle),d("collection_mismatch","The approved collection does not match the collection requested by this link.");return i?.close(),{kind:"connected",connection:this.connection(O.collectionId),...n.returnTo?{returnTo:n.returnTo}:{}}}throw d("expired_token","The downloaded application authorization code expired.")}catch(v){throw i?.close(),await this.keyStore.delete(a),n.signal?.aborted?Ue(n.signal,"Downloaded application authorization was cancelled.",v):v}}completeAuthorization(e,n={}){let i=Nt(e);if(!i)return Promise.reject(d("invalid_callback","Authorization callback is missing its state."));let o=M(this.storage.getItem(this.pendingKey(i))),r=o?.presentation==="popup";return this.completionPromises.run(i,n,this.timeouts.requestMs,a=>Dr({storage:this.storage,storagePrefix:this.storagePrefix(),state:i,pending:o,popupAttempt:r,completion:this.performAuthorizationCompletion(e,i,a)}))}async performAuthorizationCompletion(e,n,i){let o=new URL(e),r=o.searchParams.get("code"),a=this.pendingKey(n),s=M(this.storage.getItem(a));if(!s||s.version!==1||n!==s.state)throw d("invalid_callback","Authorization callback is missing or does not match this browser session.");if(o.searchParams.has("error"))throw s.keyHandle&&await this.keyStore.delete(s.keyHandle),this.storage.removeItem(a),U(o.searchParams.get("error")??"access_denied",o.searchParams.get("error_description")??"Collection access was not approved.",{details:s.returnTo?{return_to:s.returnTo}:void 0});if(!r)throw d("invalid_callback","Authorization callback is missing its code.");let c=await ae(`${this.serverUrl}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:r,client_id:s.clientId,redirect_uri:s.redirectUri,code_verifier:s.verifier}),signal:i},"temporarily_unavailable","Authorization completion is temporarily unavailable."),l=await E(c,"invalid_token_response","The authorization service returned an invalid token response.");if(!c.ok)throw z(l,"token_exchange_failed","Authorization could not be completed.",c.status);if(s.relayEncryption==="required"&&!l.authority&&(!l.encryption||!s.keyHandle||l.encryption.application_agreement_public_key!==s.applicationAgreementPublicKey))throw s.keyHandle&&await this.keyStore.delete(s.keyHandle),this.storage.removeItem(a),d("encryption_required","Authorization did not establish the required encrypted relay grant.");if(l.authority?.proof_public_key){if(!s.keyHandle||!s.applicationSigningPublicKey||l.authority.proof_public_key!==s.applicationSigningPublicKey)throw s.keyHandle&&await this.keyStore.delete(s.keyHandle),this.storage.removeItem(a),d("invalid_token_response","Authorization returned a remote authority capability bound to another application key.")}else l.authority&&s.keyHandle&&await this.keyStore.delete(s.keyHandle);let u=this.storeTokenResponse(l,s.clientId,l.authority?.proof_public_key?s.keyHandle:l.authority?void 0:s.keyHandle);if(s.collectionId&&s.collectionId!==u.collectionId)throw this.removeToken(u.collectionId,u.keyHandle),this.storage.removeItem(a),d("collection_mismatch","The approved collection does not match the collection requested by this link.");return this.storage.removeItem(a),{connection:this.connection(u.collectionId),...s.returnTo?{returnTo:s.returnTo}:{}}}connections(){let e=[];for(let n of un(this.storage,this.storagePrefix())){let i=this.connection(n)?.info();i&&e.push(i)}return e.sort((n,i)=>n.displayName.localeCompare(i.displayName)||n.collectionId.localeCompare(i.collectionId))}connection(e){if(!this.storage.getItem(this.tokenKey(e)))return null;let n=this.connectionCache.get(e);return n||(n=new Qe(this,e),this.connectionCache.set(e,n)),n.info()?n:null}unavailableReason(e){return this.invalidatedConnections.get(e)??null}connectionApplicationId(e){if(!this.connection(e))return null;let n=M(this.storage.getItem(this.tokenKey(e)));return typeof n?.clientId=="string"&&n.clientId.length>0?n.clientId:null}onConnectionsChange(e){return this.listeners.add(e),e(this.connections()),()=>this.listeners.delete(e)}storeTokenResponse(e,n,i){let o=e.collection_id;if(typeof o!="string")throw d("invalid_token_response","Authorization returned no collection ID.");let r=M(this.storage.getItem(this.tokenKey(o))),a=Br(this.storage,this.pendingMutationKey(o),r,i,this.grantKeyLeases.handles(o),this.grantKeyLeases.retainAutomaticallyRetiredKeys),s;try{s=Nr({body:e,clientId:n,keyHandle:i,previous:r,retiredKeyHandles:a.retained,defaultApplicationOrigin:this.defaultApplicationOrigin(),pinConnectorIdentity:(c,l)=>this.pinConnectorIdentity(c,l)})}catch(c){throw c instanceof b&&c.code==="legacy_scope_reauthorization_required"&&this.removeToken(o,i,c.code),c}this.storage.setItem(this.tokenKey(o),JSON.stringify(s));for(let c of a.disposable)this.deleteGrantKeyWhenUnused(o,c);return Ir(this.storage,this.storagePrefix(),o),this.invalidatedConnections.delete(o),this.connectionCache.delete(o),this.emitConnections(),s}forgetConnectorIdentity(e){this.storage.removeItem(this.connectorPinKey(e))}pinConnectorIdentity(e,n){let i=this.connectorPinKey(e),o=M(this.storage.getItem(i));if(o&&(o.version!==1||o.publicKey!==n))throw d("connector_identity_changed","The connector identity changed since this application first connected. Forget the saved connector identity only after verifying the computer, then authorize again.");o||this.storage.setItem(i,JSON.stringify({version:1,publicKey:n}))}connectorPinKey(e){return`mdbase-connect:${this.serverUrl}:connector-pin:${e}`}async loadApplicationIdentity(e){try{return await Bt(this.identityStore,this.serverUrl,e)}catch(n){throw d("application_identity_unavailable",n instanceof Re?n.message:"The application installation identity is unavailable.",{cause:n})}}removeToken(e,n,i="authorization_lost",o=!1){this.invalidatedConnections.set(e,i);let r=M(this.storage.getItem(this.tokenKey(e))),a=si(r,n);this.storage.removeItem(this.tokenKey(e)),o&&Lr(this.storage,this.pendingMutationKey(e),s=>a.add(s));for(let s of a)this.deleteGrantKeyWhenUnused(e,s);for(let s of["web_push","fcm"])this.storage.removeItem(this.notificationKey(e,s));Mr(this.storage,this.storagePrefix(),e),this.connectionCache.delete(e),this.emitConnections()}acquireGrantKeyLease(e,n,i){return this.grantKeyLeases.acquire(e,n,i)}deleteGrantKeyWhenUnused(e,n){this.grantKeyLeases.deleteExclusive(e,n,()=>jr(this.storage,this.keyStore,this.pendingMutationKey(e),this.tokenKey(e),n))}tokenKey(e){return`${this.storagePrefix()}:token:${e}`}pendingMutationKey(e){return`${this.storagePrefix()}:pending-mutation:${e}`}notificationKey(e,n="web_push"){return`${this.storagePrefix()}:notifications:${e}:${n}`}directPreferenceKey(){return`mdbase-connect:direct:${this.defaultApplicationOrigin()}`}defaultApplicationOrigin(){return Co(this.manifest,this.manifestSource,this.redirectUri,this.application?.distribution==="portable")}pendingKey(e){return`${this.storagePrefix()}:pending:${e}`}storagePrefix(){return`mdbase-connect:${this.serverUrl}:${this.manifestSource}`}emitConnections(){let e=this.connections();for(let n of this.listeners)n(e)}};var fn=class{internals;constructor(e){this.internals=new pn(e)}register(e){return D(()=>this.internals.register(e),Se)}authorize(e={}){return D(()=>this.internals.authorize(e),fe)}application(e){return new Ne(this,e,this.internals.timeouts)}manifest(e){return D(()=>this.internals.manifestDeclaration(e),Se)}environment(){return this.internals.environment()}completeAuthorization(e,n){return D(()=>this.internals.completeAuthorization(e===void 0?Ut():String(e),n),fe)}connections(){return this.internals.connections()}connection(e){return this.internals.connection(e)}unavailableReason(e){return this.internals.unavailableReason(e)}connectionApplicationId(e){return this.internals.connectionApplicationId(e)}onConnectionsChange(e){return this.internals.onConnectionsChange(e)}forgetAll(){for(let e of this.connections())this.connection(e.collectionId)?.forget()}forgetConnectorIdentity(e){this.internals.forgetConnectorIdentity(e)}};function ci(t){if(!t||typeof t!="object")throw d("invalid_push_payload","The push payload is not an object.");let e=t;if(e.type!=="mdbase.notification"||e.version!==1||typeof e.signal_id!="string"||typeof e.criterion_id!="string"||typeof e.cursor!="string"||!e.presentation||typeof e.presentation.title!="string")throw d("invalid_push_payload","The push payload is not an mdbase notification.");return e}function Kr(t){if(!t||typeof t!="object")throw d("invalid_push_payload","The native notification data is not an object.");let e=t;if(e.type!=="mdbase.notification"||e.version!==1&&e.version!=="1"||typeof e.signal_id!="string"||typeof e.criterion_id!="string"||typeof e.cursor!="string")throw d("invalid_push_payload","The native notification data is not an mdbase notification.");return{type:"mdbase.notification",version:1,signal_id:e.signal_id,criterion_id:e.criterion_id,cursor:e.cursor}}function Vr(t,e){let n=ci(e);return t.showNotification(n.presentation.title,{...n.presentation.body?{body:n.presentation.body}:{},...n.presentation.tag?{tag:n.presentation.tag}:{},data:{type:n.type,signal_id:n.signal_id,criterion_id:n.criterion_id,cursor:n.cursor}})}function Gr(t){return{subscribe:e=>t.subscribe(e),getSnapshot:()=>t.getSnapshot()}}var hn=class{collectionParameter;fallbackPath;listeners=new Set;handlePopState=()=>this.emit();constructor(e={}){this.collectionParameter=e.collectionParameter??"collection",this.fallbackPath=e.fallbackPath??"/"}selectedCollectionId(){return this.currentUrl().searchParams.get(this.collectionParameter)}select(e,n={}){let i=ht(this.currentUrl());e?i.searchParams.set(this.collectionParameter,e):i.searchParams.delete(this.collectionParameter);let o=this.browserHistory();o[n.history==="push"?"pushState":"replaceState"](o.state,"",i),this.emit()}authorizationReturnTo(){let e=ht(this.currentUrl());return`${e.pathname}${e.search}${e.hash}`}authorizationCallback(){let e=this.currentUrl().href;return Lt(e)?e:null}finishAuthorization(e,n){let i=this.safeAppUrl(e??this.fallbackPath);ht(i),i.searchParams.set(this.collectionParameter,n),this.browserHistory().replaceState(null,"",i),this.emit()}clearAuthorizationCallback(e){let n=e?this.safeAppUrl(e):this.currentUrl(),i=this.browserHistory();i.replaceState(i.state,"",ht(n)),this.emit()}subscribe(e){let n=this.listeners.size===0;return this.listeners.add(e),n&&typeof window<"u"&&window.addEventListener("popstate",this.handlePopState),()=>{this.listeners.delete(e),this.listeners.size===0&&typeof window<"u"&&window.removeEventListener("popstate",this.handlePopState)}}emit(){for(let e of this.listeners)e()}safeAppUrl(e){let n=this.currentUrl(),i=new URL(e,n.origin);return i.origin===n.origin?i:new URL(this.fallbackPath,n.origin)}currentUrl(){if(typeof location>"u")throw d("browser_required","Browser selection requires a browser environment.");return new URL(location.href)}browserHistory(){if(typeof history>"u")throw d("browser_required","Browser selection requires a browser environment.");return history}},yn=class{collectionId=null;listeners=new Set;selectedCollectionId(){return this.collectionId}select(e){if(e!==this.collectionId){this.collectionId=e;for(let n of this.listeners)n()}}authorizationReturnTo(){}authorizationCallback(){return null}finishAuthorization(e,n){this.select(n)}clearAuthorizationCallback(){}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}};return Xr(hc);})();