@enbox/api 0.6.22 → 0.6.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.mjs CHANGED
@@ -2055,7 +2055,7 @@ zebra
2055
2055
  zero
2056
2056
  zone
2057
2057
  zoo`.split(`
2058
- `);Ho();jt();y();y();nn();y();jt();nn();y();jt();nn();y();nn();nn();Nn();y();jt();nn();y();Ho();y();jt();y();y();var k7=wn(xx(),1);Nn();import{Level as Rhe}from"level";y();var She=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})};function khe(t){let e=[],r=[];for(let n of t)n.message?n.message.descriptor.interface==="Records"&&n.message.descriptor.method==="Write"&&n.message.descriptor.dataCid&&!n.encodedData?r.push(n.messageCid):e.push(n):r.push(n.messageCid);return{prefetched:e,needsFetchCids:r}}var Ex=class{constructor(e){this._deps=e}reconcile(e,r){return She(this,void 0,void 0,function*(){var n;let{did:i,dwnUrl:a,delegateDid:s,protocol:o}=e,c=r?.direction,l=(n=r?.verifyConvergence)!==null&&n!==void 0?n:!1,d=this._deps.shouldContinue,u=yield this._deps.getLocalRoot(i,s,o);if(d&&!d())return{aborted:!0,changed:!1,didPull:!1,didPush:!1};let f=yield this._deps.getRemoteRoot(i,a,s,o);if(d&&!d())return{aborted:!0,changed:!1,didPull:!1,didPush:!1};let p=!1,h=!1,m;if(u!==f){let w=yield this._deps.diffWithRemote(e);if(d&&!d())return{aborted:!0,changed:!0,didPull:!1,didPush:!1,localRoot:u,remoteRoot:f};if((!c||c==="pull")&&w.onlyRemote.length>0){let{prefetched:E,needsFetchCids:k}=khe(w.onlyRemote);if(yield this._deps.pullMessages({did:i,dwnUrl:a,delegateDid:s,protocol:o,messageCids:k,prefetched:E}),d&&!d())return{aborted:!0,changed:!0,didPull:!0,didPush:!1,localRoot:u,remoteRoot:f};p=!0}if((!c||c==="push")&&w.onlyLocal.length>0){if(m=yield this._deps.pushMessages({did:i,dwnUrl:a,delegateDid:s,protocol:o,messageCids:w.onlyLocal}),d&&!d())return{aborted:!0,changed:!0,didPull:p,didPush:!0,localRoot:u,remoteRoot:f,pushResult:m};h=!0}}if(!l)return{changed:u!==f,didPull:p,didPush:h,localRoot:u,remoteRoot:f,pushResult:m};let g=yield this._deps.getLocalRoot(i,s,o);if(d&&!d())return{aborted:!0,changed:u!==f,didPull:p,didPush:h,localRoot:u,remoteRoot:f,pushResult:m};let _=yield this._deps.getRemoteRoot(i,a,s,o);return d&&!d()?{aborted:!0,changed:u!==f,didPull:p,didPush:h,localRoot:u,remoteRoot:f,pushResult:m}:{changed:u!==f,didPull:p,didPush:h,localRoot:u,remoteRoot:f,postLocalRoot:g,postRemoteRoot:_,converged:g===_,pushResult:m}})}};y();Nn();function b7(t){let e=t.descriptor;return e.interface!==Le.Records||e.method!==Ue.Write?!1:e.dateCreated===e.messageTimestamp}function Am(t){var e;if(t.length<=1)return t;let r=new Map,n=new Map,i=new Map,a=new Map;for(let u=0;u<t.length;u++){let f=t[u];r.set(u,f);let p=f.message.descriptor;if(p.interface===Le.Protocols&&p.method===Ue.Configure){let h=(e=p.definition)===null||e===void 0?void 0:e.protocol;h&&n.set(h,u)}if(p.interface===Le.Records&&p.method===Ue.Write){let h=f.message.recordId;b7(f.message)&&h&&i.set(h,u),p.protocol===Et.uri&&p.protocolPath===Et.grantPath&&h&&a.set(h,u)}}let s=new Map,o=new Array(t.length).fill(0),c=(u,f)=>{if(u===f)return;s.has(u)||s.set(u,new Set);let p=s.get(u);p.has(f)||(p.add(f),o[f]++)};for(let u=0;u<t.length;u++){let f=t[u].message.descriptor;if(f.interface===Le.Records){let h=f.protocol;h&&n.has(h)&&c(n.get(h),u)}if(f.interface===Le.Records&&f.parentId){let h=f.parentId;i.has(h)&&c(i.get(h),u)}if(f.interface===Le.Records&&f.method===Ue.Write){let h=t[u].message.recordId;h&&!b7(t[u].message)&&i.has(h)&&c(i.get(h),u)}if(f.interface===Le.Records&&f.method===Ue.Delete){let h=f.recordId;h&&i.has(h)&&c(i.get(h),u)}let p=f.permissionGrantId;p&&a.has(p)&&c(a.get(p),u)}let l=[];for(let u=0;u<t.length;u++)o[u]===0&&l.push(u);let d=[];for(;l.length>0;){let u=l.shift();d.push(r.get(u));let f=s.get(u);if(f)for(let p of f)o[p]--,o[p]===0&&l.push(p)}if(d.length<t.length){let u=new Set(d);for(let f=0;f<t.length;f++){let p=r.get(f);u.has(p)||d.push(p)}}return d}y();var Sx="^";function P7(t,e,r){return`${t}${Sx}${e}${Sx}${r}`}function xv(t,e,r){let n=`${t}${Sx}${e}`;return r?`${n}${Sx}${r}`:n}y();Nn();var ah=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},The=1048576;function x7(t,e){var r,n;return t.status.code===202||t.status.code===204||t.status.code===409||t.status.code===404&&(e?.descriptor.interface===Le.Records&&e?.descriptor.method===Ue.Delete||((r=t.entry)===null||r===void 0?void 0:r.message.descriptor.interface)===Le.Records&&((n=t.entry)===null||n===void 0?void 0:n.message.descriptor.method)===Ue.Delete)}function Dhe(t){return t.status.code===400||t.status.code===401||t.status.code===403}function mR(t){return ah(this,void 0,void 0,function*(){try{return yield be.getCid(t)}catch{return"unknown"}})}function _7(t){return ah(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s,agent:o,permissionsApi:c}){let l=[];if(s)for(let g of s){if(!g.message)continue;let _={message:g.message};if(g.encodedData){let w=ke.base64UrlToBytes(g.encodedData);_.bufferedData=w,_.dataStream=new ReadableStream({start(E){E.enqueue(w),E.close()}})}l.push(_)}let d=a.length>0?yield kx({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:o,permissionsApi:c}):[],u=[...l,...d],f=Am(u);yield Ihe(f);let p=3,h=f;for(let g=0;g<=p&&h.length>0;g++){let _=[];for(let w of h){let E=w.bufferedData?new ReadableStream({start(D){D.enqueue(w.bufferedData),D.close()}}):w.dataStream,k=yield o.dwn.processRawMessage(e,w.message,{dataStream:E});x7(k)||_.push(w)}if(_.length>0){let w=[],E=[];for(let k of _)if(k.bufferedData||!k.dataStream)E.push(k);else{let D=yield mR(k.message);w.push(D)}if(w.length>0){let k=yield kx({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:w,agent:o,permissionsApi:c});E.push(...k)}h=Am(E)}else h=[]}let m=[];for(let g of h){let _=yield mR(g.message);m.push(_)}return m})}function Ihe(t){return ah(this,void 0,void 0,function*(){for(let e of t){if(!e.dataStream)continue;let r=[],n=0,i=!1,a=e.dataStream.getReader();try{for(;;){let{done:c,value:l}=yield a.read();if(c)break;if(n+=l.byteLength,n>The){i=!0;break}r.push(l)}}finally{a.releaseLock()}if(i){e.dataStream=void 0;continue}let s=new Uint8Array(n),o=0;for(let c of r)s.set(c,o),o+=c.byteLength;e.bufferedData=s,e.dataStream=new ReadableStream({start(c){c.enqueue(s),c.close()}})}})}function kx(t){return ah(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:s,permissionsApi:o}){let c=[],l;n&&(l=(yield o.getPermissionForRequest({connectedDid:e,messageType:Se.MessagesRead,delegateDid:n,protocol:i,cached:!0})).grant.id);let d=4,u=0;for(;u<a.length;){let f=a.slice(u,u+d);u+=d;let p=yield Promise.all(f.map(h=>ah(this,void 0,void 0,function*(){var m,g;let _=yield s.processDwnRequest({store:!1,author:e,target:e,messageType:Se.MessagesRead,granteeDid:n,messageParams:{messageCid:h,permissionGrantId:l}}),w;try{w=yield s.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:_.message})}catch(D){console.error(`SyncEngineLevel: pull - failed to read ${h} from ${r}:`,(m=D.message)!==null&&m!==void 0?m:D);return}if(w.status.code!==200||!(!((g=w.entry)===null||g===void 0)&&g.message))return;let E=w.entry,k;return oh(E)&&E.data&&(k=E.data),{message:E.message,dataStream:k}})));for(let h of p)h&&c.push(h)}return c})}function yR(t){return ah(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:s,permissionsApi:o}){var c,l,d;let u=[],f=[],p=[],h=[];for(let g of a){let _=yield Ahe({author:e,messageCid:g,delegateDid:n,protocol:i,agent:s,permissionsApi:o});_?h.push(_):f.push(g)}let m=Am(h);for(let g of m){let _=yield mR(g.message);try{let w=yield s.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,data:g.dataStream,message:g.message});x7(w,g.message)?u.push(_):Dhe(w)?(w.status.code===400&&(!((c=w.status.detail)===null||c===void 0)&&c.includes("record limit"))?console.debug(`SyncEngineLevel: singleton already exists on remote, skipping push for ${_}`):console.warn(`SyncEngineLevel: push permanently failed for ${_}: ${w.status.code} ${w.status.detail}`),p.push({cid:_,statusCode:w.status.code,detail:(l=w.status.detail)!==null&&l!==void 0?l:""})):(console.error(`SyncEngineLevel: push failed for ${_}: ${w.status.code} ${w.status.detail}`),f.push(_))}catch(w){console.error(`SyncEngineLevel: push error for ${_}: ${(d=w.message)!==null&&d!==void 0?d:w}`),f.push(_)}}return{succeeded:u,failed:f,permanentlyFailed:p}})}function Ahe(t){return ah(this,arguments,void 0,function*({author:e,delegateDid:r,protocol:n,messageCid:i,agent:a,permissionsApi:s}){let o;r&&(o=(yield s.getPermissionForRequest({connectedDid:e,messageType:Se.MessagesRead,delegateDid:r,protocol:n,cached:!0})).grant.id);let{reply:c}=yield a.dwn.processRequest({author:e,target:e,messageType:Se.MessagesRead,granteeDid:r,messageParams:{messageCid:i,permissionGrantId:o}});if(c.status.code!==200||!c.entry)return;let l=c.entry,d={message:l.message};return oh(l)&&l.data&&(d.dataStream=l.data),d})}var He=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Rm=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(a){r[a]=t[a]&&function(s){return new Promise(function(o,c){s=t[a](s),i(o,c,s.done,s.value)})}}function i(a,s,o,c){Promise.resolve(c).then(function(l){a({value:l,done:o})},s)}},Che=16,E7=8,$he=100;function S7(t,e){if(e.kind==="full"||!e.protocolPathPrefixes&&!e.contextIdPrefixes)return!0;let r=t.descriptor;if(e.protocolPathPrefixes&&e.protocolPathPrefixes.length>0){let n=r.protocolPath;if(!n||!e.protocolPathPrefixes.some(a=>n===a||n.startsWith(a+"/")))return!1}if(e.contextIdPrefixes&&e.contextIdPrefixes.length>0){let n=t.contextId;if(!n||!e.contextIdPrefixes.some(a=>n===a||n.startsWith(a+"/")))return!1}return!0}var oa=class t{static validateSyncIdentityOptions(e){if(!e||!("protocols"in e))throw new Error("SyncEngineLevel: options.protocols is required \u2014 pass 'all' for a full replica or a non-empty protocol list.");if(e.protocols!=="all"&&!Array.isArray(e.protocols))throw new Error("SyncEngineLevel: protocols must be 'all' or a non-empty string array.");if(Array.isArray(e.protocols)&&e.protocols.length===0)throw new Error("SyncEngineLevel: protocols must be 'all' or a non-empty array of protocol URIs. An empty array is ambiguous.")}constructor({agent:e,dataPath:r,db:n}){this._syncLock=!1,this._activeLinks=new Map,this._linkRuntimes=new Map,this._syncMode="poll",this._engineGeneration=0,this._liveSubscriptions=[],this._localSubscriptions=[],this._connectivityState="unknown",this._eventListeners=new Set,this._pushRuntimes=new Map,this._recentlyPulledCids=new Map,this._closureContexts=new Map,this._syncTargetsCacheGeneration=0,this._consecutiveFailures=0,this._degradedPollTimers=new Map,this._repairAttempts=new Map,this._activeRepairs=new Map,this._repairRetryTimers=new Map,this._repairContext=new Map,this._reconcileTimers=new Map,this._reconcileInFlight=new Map,this._agent=e,this._permissionsApi=new Xn({agent:e}),this._db=n||new Rhe(r??"DATA/AGENT/SYNC_STORE")}get ledger(){return this._ledger||(this._ledger=new zi(this._db)),this._ledger}get _deadLetters(){return this._db.sublevel("deadLetters")}get agent(){if(this._agent===void 0)throw new Error("SyncEngineLevel: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,this._permissionsApi=new Xn({agent:e}),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++}get hasActiveSubscriptions(){return this._liveSubscriptions.length>0||this._localSubscriptions.length>0}get connectivityState(){if(this._activeLinks.size===0)return this._connectivityState;let e=!1,r=!1;for(let n of this._activeLinks.values())n.connectivity==="online"&&(e=!0),n.connectivity==="offline"&&(r=!0);return e?"online":r?"offline":"unknown"}on(e){return this._eventListeners.add(e),()=>{this._eventListeners.delete(e)}}emitEvent(e){for(let r of this._eventListeners)try{r(e)}catch{}}clear(){return He(this,void 0,void 0,function*(){this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,yield this.teardownLiveSync(),this._syncMode=void 0,yield this._permissionsApi.clear(),yield this._db.clear()})}close(){return He(this,void 0,void 0,function*(){this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,yield this.teardownLiveSync(),yield this._db.close()})}registerIdentity(e){return He(this,arguments,void 0,function*({did:r,options:n}){t.validateSyncIdentityOptions(n);let i=this._db.sublevel("registeredIdentities");if(yield this.getIdentityOptions(r))throw new Error(`SyncEngineLevel: Identity with DID ${r} is already registered.`);yield i.put(r,JSON.stringify(n)),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,this._syncMode==="live"&&(yield this.addIdentityToLiveSync(r,n))})}unregisterIdentity(e){return He(this,void 0,void 0,function*(){let r=this._db.sublevel("registeredIdentities");if(!(yield this.getIdentityOptions(e)))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);this._syncMode==="live"&&(yield this.removeIdentityFromLiveSync(e)),yield r.del(e),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++})}getIdentityOptions(e){return He(this,void 0,void 0,function*(){let r=this._db.sublevel("registeredIdentities");try{let n=yield r.get(e);if(n)return JSON.parse(n)}catch(n){let i=n;if(i.code==="LEVEL_NOT_FOUND")return;throw new Error(`SyncEngineLevel: Error reading level: ${i.code}.`)}})}updateIdentityOptions(e){return He(this,arguments,void 0,function*({did:r,options:n}){t.validateSyncIdentityOptions(n);let i=this._db.sublevel("registeredIdentities");if(!(yield this.getIdentityOptions(r)))throw new Error(`SyncEngineLevel: Identity with DID ${r} is not registered.`);yield i.put(r,JSON.stringify(n)),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,yield this.ledger.updateDelegateDid(r,n.delegateDid),this._syncMode==="live"&&this.hasActiveLinksForDid(r)&&(yield this.removeIdentityFromLiveSync(r),yield this.addIdentityToLiveSync(r,n))})}sync(e){return He(this,void 0,void 0,function*(){if(this._syncLock)throw new Error("SyncEngineLevel: Sync operation is already in progress.");this._syncLock=!0;try{let r=yield this.getSyncTargets(),n=new Map;for(let o of r){let c=n.get(o.dwnUrl);c||(c=[],n.set(o.dwnUrl,c)),c.push(o)}let i=0,a=0,s=yield Promise.allSettled([...n.entries()].map(o=>He(this,[o],void 0,function*([c,l]){for(let d of l){let{did:u,delegateDid:f,protocol:p}=d;try{yield this.createLinkReconciler().reconcile({did:u,dwnUrl:c,delegateDid:f,protocol:p},{direction:e})}catch(h){a++,console.error(`SyncEngineLevel: Error syncing ${u} with ${c}`,h);return}}i++})));for(let o of s)o.status==="rejected"&&a++;i>0?(this._consecutiveFailures=0,this._connectivityState="online"):a>0?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):r.length>0&&(this._consecutiveFailures=0,this._connectivityState="online")}finally{this._syncLock=!1}})}startSync(e){return He(this,void 0,void 0,function*(){var r,n;let i=(r=e.mode)!==null&&r!==void 0?r:"poll",a=(n=e.interval)!==null&&n!==void 0?n:i==="live"?"5m":"2m",s=(0,k7.default)(a);(this._liveSubscriptions.length>0||this._localSubscriptions.length>0)&&(yield this.teardownLiveSync()),this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),this._syncMode=i,i==="live"?yield this.startLiveSync(s):yield this.startPollSync(s)})}stopSync(){return He(this,arguments,void 0,function*(e=2e3){this._engineGeneration++;let r=0;for(;this._syncLock;){if(r>=e)throw new Error(`SyncEngineLevel: Existing sync operation did not complete within ${e} milliseconds.`);r+=100,yield new Promise(n=>{setTimeout(n,e<100?e:100)})}this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,yield this.teardownLiveSync(),this._syncMode=void 0})}startPollSync(e){return He(this,void 0,void 0,function*(){let r=this._engineGeneration,n=()=>He(this,void 0,void 0,function*(){if(this._engineGeneration!==r||this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{yield this.sync()}catch(s){console.error("SyncEngineLevel: Error during sync operation",s)}let i=Math.min(Math.pow(2,this._consecutiveFailures),t.MAX_BACKOFF_MULTIPLIER),a=this._consecutiveFailures>0?e*i:e;this._engineGeneration===r&&(this._syncIntervalId||(this._syncIntervalId=setInterval(n,a)))});this._syncIntervalId&&clearInterval(this._syncIntervalId),this._syncIntervalId=setInterval(n,e),this._syncLock||(yield this.sync())})}startLiveSync(e){return He(this,void 0,void 0,function*(){this.startBrowserConnectivityListeners();try{yield this.sync()}catch(i){console.error("SyncEngineLevel: Error during initial live-sync catch-up",i)}let r=yield this.getSyncTargets();yield Promise.allSettled(r.map(i=>this.initializeLinkTarget(i)));let n=()=>He(this,void 0,void 0,function*(){if(!this._syncLock)try{yield this.sync()}catch(i){console.error("SyncEngineLevel: Error during SMT integrity check",i)}});this._syncIntervalId=setInterval(n,e)})}getOrCreateRuntime(e){let r=this._linkRuntimes.get(e);return r||(r={nextDeliveryOrdinal:0,nextCommitOrdinal:0,inflight:new Map},this._linkRuntimes.set(e,r)),r}drainCommittedPull(e){let r=this._linkRuntimes.get(e),n=this._activeLinks.get(e);if(!r||!n)return 0;let i=0;for(;;){let a=r.inflight.get(r.nextCommitOrdinal);if(!a?.committed)break;zi.commitContiguousToken(n.pull,a.token),zi.setReceivedToken(n.pull,a.token),r.inflight.delete(r.nextCommitOrdinal),r.nextCommitOrdinal++,i++}return i}transitionToRepairing(e,r,n){return He(this,void 0,void 0,function*(){let i=r.status,a=r.connectivity;r.connectivity="offline",yield this.ledger.setStatus(r,"repairing"),this.emitEvent({type:"link:status-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:i,to:"repairing"}),a!=="offline"&&this.emitEvent({type:"link:connectivity-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:a,to:"offline"}),n?.resumeToken&&this._repairContext.set(e,{resumeToken:n.resumeToken});let s=this._linkRuntimes.get(e);s&&(s.inflight.clear(),s.nextCommitOrdinal=s.nextDeliveryOrdinal),this.repairLink(e).catch(()=>{this.scheduleRepairRetry(e)})})}scheduleRepairRetry(e){var r;let n=this._activeLinks.get(e);if(!n||n.status==="degraded_poll"||this._repairRetryTimers.has(e))return;let i=(r=this._repairAttempts.get(e))!==null&&r!==void 0?r:1,a=t.REPAIR_BACKOFF_MS,s=a[Math.min(i-1,a.length-1)],o=this._engineGeneration,c=setTimeout(()=>He(this,void 0,void 0,function*(){if(this._repairRetryTimers.delete(e),this._engineGeneration!==o)return;let l=this._activeLinks.get(e);if(l?.status==="repairing")try{yield this.repairLink(e)}catch{l.status==="repairing"&&this.scheduleRepairRetry(e)}}),s);this._repairRetryTimers.set(e,c)}repairLink(e){let r=this._activeRepairs.get(e);if(r)return r;let n=this.doRepairLink(e).finally(()=>{this._activeRepairs.delete(e);let i=this._activeLinks.get(e);i?.needsReconcile&&i.status==="live"&&this.scheduleReconcile(e,500)});return this._activeRepairs.set(e,n),n}doRepairLink(e){return He(this,void 0,void 0,function*(){var r,n,i,a;let s=this._activeLinks.get(e);if(!s)return;let o=this._engineGeneration,c=()=>this._activeLinks.get(e)!==s,{tenantDid:l,remoteEndpoint:d,delegateDid:u,protocol:f}=s;this.emitEvent({type:"repair:started",tenantDid:l,remoteEndpoint:d,protocol:f,attempt:((r=this._repairAttempts.get(e))!==null&&r!==void 0?r:0)+1});let p=((n=this._repairAttempts.get(e))!==null&&n!==void 0?n:0)+1;if(this._repairAttempts.set(e,p),yield this.closeLinkSubscriptions(s),this._engineGeneration!==o||c())return;let h=this.getOrCreateRuntime(e);h.inflight.clear(),h.nextDeliveryOrdinal=0,h.nextCommitOrdinal=0;try{if((yield this.createLinkReconciler(()=>this._engineGeneration===o&&!c()).reconcile({did:l,dwnUrl:d,delegateDid:u,protocol:f})).aborted)return;let g=this._repairContext.get(e),_=(i=g?.resumeToken)!==null&&i!==void 0?i:s.pull.contiguousAppliedToken;if(zi.resetCheckpoint(s.pull,_),yield this.ledger.saveLink(s),this._engineGeneration!==o||c()||(s.needsReconcile=!0,yield this.ledger.saveLink(s),this._engineGeneration!==o||c()))return;let w={did:l,dwnUrl:d,delegateDid:u,protocol:f,linkKey:e};try{yield this.openLivePullSubscription(w)}catch(D){if(D.isProgressGap){if(console.warn(`SyncEngineLevel: Stale pull resume token for ${l} -> ${d}, resetting to start fresh`),zi.resetCheckpoint(s.pull),yield this.ledger.saveLink(s),this._engineGeneration!==o||c())return;yield this.openLivePullSubscription(w)}else throw D}if(this._engineGeneration!==o||c())return;try{yield this.openLocalPushSubscription(w)}catch(D){let R=this._liveSubscriptions.find(U=>U.linkKey===e);if(R){try{yield R.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(U=>U!==R)}throw D}if(this._engineGeneration!==o||c())return;this._repairContext.delete(e),this._repairAttempts.delete(e);let E=this._repairRetryTimers.get(e);E&&(clearTimeout(E),this._repairRetryTimers.delete(e));let k=s.connectivity;s.connectivity="online",yield this.ledger.setStatus(s,"live"),this.clearDeadLettersForLink(l,d,f),this.emitEvent({type:"repair:completed",tenantDid:l,remoteEndpoint:d,protocol:f}),k!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:l,remoteEndpoint:d,protocol:f,from:k,to:"online"}),this.emitEvent({type:"link:status-change",tenantDid:l,remoteEndpoint:d,protocol:f,from:"repairing",to:"live"})}catch(m){if(this._engineGeneration!==o||c())return;if(console.error(`SyncEngineLevel: Repair failed for ${l} -> ${d} (attempt ${p})`,m),this.emitEvent({type:"repair:failed",tenantDid:l,remoteEndpoint:d,protocol:f,attempt:p,error:String((a=m.message)!==null&&a!==void 0?a:m)}),p>=t.MAX_REPAIR_ATTEMPTS){console.warn(`SyncEngineLevel: Max repair attempts reached for ${l} -> ${d}, entering degraded_poll`),yield this.enterDegradedPoll(e);return}throw m}})}closeLinkSubscriptions(e){return He(this,void 0,void 0,function*(){let{tenantDid:r,remoteEndpoint:n}=e,i=this.buildLinkKey(r,n,e.scopeId),a=this._liveSubscriptions.find(o=>o.linkKey===i);if(a){try{yield a.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(o=>o!==a)}let s=this._localSubscriptions.find(o=>o.linkKey===i);if(s){try{yield s.close()}catch{}this._localSubscriptions=this._localSubscriptions.filter(o=>o!==s)}})}enterDegradedPoll(e){return He(this,void 0,void 0,function*(){let r=this._activeLinks.get(e);if(!r)return;r.connectivity="offline";let n=r.status;yield this.ledger.setStatus(r,"degraded_poll"),this._repairAttempts.delete(e),this.emitEvent({type:"link:status-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:n,to:"degraded_poll"}),this.emitEvent({type:"degraded-poll:entered",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol});let i=this._degradedPollTimers.get(e);i&&clearInterval(i);let a=15e3,s=new Uint32Array(1),o;do crypto.getRandomValues(s),o=s[0]&16383;while(o>=a);let c=a+o,l=this._engineGeneration,d=setInterval(()=>He(this,void 0,void 0,function*(){if(this._engineGeneration!==l){clearInterval(d),this._degradedPollTimers.delete(e);return}let u=this._activeLinks.get(e);if(u?.status!=="degraded_poll"){clearInterval(d),this._degradedPollTimers.delete(e);return}try{this._repairAttempts.set(e,0),yield this.ledger.setStatus(u,"repairing"),yield this.repairLink(e),u.status==="live"&&(clearInterval(d),this._degradedPollTimers.delete(e))}catch{this._activeLinks.get(e)===u&&(yield this.ledger.setStatus(u,"degraded_poll"))}}),c);this._degradedPollTimers.set(e,d)})}startBrowserConnectivityListeners(){if(this.stopBrowserConnectivityListeners(),typeof globalThis.addEventListener!="function")return;let e=this._engineGeneration;this._onOnline=()=>{this._engineGeneration===e&&(console.info("SyncEngineLevel: browser online \u2014 triggering immediate integrity check"),this._syncLock||this.sync().catch(r=>{console.error("SyncEngineLevel: post-online sync failed",r)}))},this._onOffline=()=>{if(this._engineGeneration===e){console.info("SyncEngineLevel: browser offline"),this._connectivityState="offline";for(let r of this._activeLinks.values()){let n=r.connectivity;n!=="offline"&&(r.connectivity="offline",this.emitEvent({type:"link:connectivity-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:n,to:"offline"}))}}},this._onVisibilityChange=()=>{this._engineGeneration===e&&(typeof document>"u"||document.visibilityState!=="visible"||(console.info("SyncEngineLevel: page became visible \u2014 triggering integrity check"),this._syncLock||this.sync().catch(r=>{console.error("SyncEngineLevel: post-visibility sync failed",r)})))},globalThis.addEventListener("online",this._onOnline),globalThis.addEventListener("offline",this._onOffline),typeof document<"u"&&document.addEventListener("visibilitychange",this._onVisibilityChange)}stopBrowserConnectivityListeners(){this._onOnline&&(globalThis.removeEventListener("online",this._onOnline),this._onOnline=void 0),this._onOffline&&(globalThis.removeEventListener("offline",this._onOffline),this._onOffline=void 0),this._onVisibilityChange&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this._onVisibilityChange),this._onVisibilityChange=void 0)}teardownLiveSync(){return He(this,void 0,void 0,function*(){this.stopBrowserConnectivityListeners(),this._engineGeneration++;for(let e of this._pushRuntimes.values())e.timer&&clearTimeout(e.timer);this._pushRuntimes.clear();for(let e of this._liveSubscriptions)try{yield e.close()}catch{}this._liveSubscriptions=[];for(let e of this._localSubscriptions)try{yield e.close()}catch{}this._localSubscriptions=[];for(let e of this._degradedPollTimers.values())clearInterval(e);this._degradedPollTimers.clear(),this._repairAttempts.clear(),this._activeRepairs.clear();for(let e of this._repairRetryTimers.values())clearTimeout(e);this._repairRetryTimers.clear(),this._repairContext.clear();for(let e of this._reconcileTimers.values())clearTimeout(e);this._reconcileTimers.clear(),this._reconcileInFlight.clear(),this._closureContexts.clear(),this._recentlyPulledCids.clear(),this._activeLinks.clear(),this._linkRuntimes.clear()})}initializeLinkTarget(e){return He(this,void 0,void 0,function*(){var r;let n;try{let i=e.protocol?{kind:"protocol",protocol:e.protocol}:{kind:"full"};n=yield this.ledger.getOrCreateLink({tenantDid:e.did,remoteEndpoint:e.dwnUrl,scope:i,delegateDid:e.delegateDid,protocol:e.protocol});let a=this.buildLinkKey(e.did,e.dwnUrl,n.scopeId);if(!n.pull.contiguousAppliedToken){let o=xv(e.did,e.dwnUrl,e.protocol),c=yield this.getCursor(o);c&&(zi.resetCheckpoint(n.pull,c),yield this.ledger.saveLink(n),yield this.deleteLegacyCursor(o))}this._activeLinks.set(a,n);let s=Object.assign(Object.assign({},e),{linkKey:a});yield this.openLivePullSubscription(s);try{yield this.openLocalPushSubscription(s)}catch(o){let c=this._liveSubscriptions.find(l=>l.linkKey===a);if(c){try{yield c.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(l=>l!==c)}throw o}this.emitEvent({type:"link:status-change",tenantDid:e.did,remoteEndpoint:e.dwnUrl,protocol:e.protocol,from:"initializing",to:"live"}),yield this.ledger.setStatus(n,"live"),n.needsReconcile&&this.scheduleReconcile(a,1e3)}catch(i){let a=n?this.buildLinkKey(e.did,e.dwnUrl,n.scopeId):xv(e.did,e.dwnUrl,e.protocol);if(i.isProgressGap&&n){console.warn(`SyncEngineLevel: ProgressGap detected for ${e.did} -> ${e.dwnUrl}, initiating repair`),this.emitEvent({type:"gap:detected",tenantDid:e.did,remoteEndpoint:e.dwnUrl,protocol:e.protocol,reason:"ProgressGap"}),yield this.transitionToRepairing(a,n,{resumeToken:(r=i.gapInfo)===null||r===void 0?void 0:r.latestAvailable});return}console.error(`SyncEngineLevel: Failed to open live subscription for ${e.did} -> ${e.dwnUrl}`,i),this._activeLinks.delete(a),this._linkRuntimes.delete(a),this._liveSubscriptions.length===0&&(this._connectivityState="unknown")}})}isLinkKeyForDid(e,r){return e.startsWith(r+"^")||e.startsWith(r+"_")}hasActiveLinksForDid(e){for(let r of this._activeLinks.keys())if(this.isLinkKeyForDid(r,e))return!0;return!1}addIdentityToLiveSync(e,r){return He(this,void 0,void 0,function*(){let{protocols:n,delegateDid:i}=r,a=yield this.agent.dwn.getDwnEndpointUrlsForTarget(e);if(a.length===0)return;let s=[];for(let o of a)if(n==="all")s.push({did:e,delegateDid:i,dwnUrl:o});else for(let c of n)s.push({did:e,delegateDid:i,dwnUrl:o,protocol:c});yield Promise.allSettled(s.map(o=>this.initializeLinkTarget(o)))})}removeIdentityFromLiveSync(e){return He(this,void 0,void 0,function*(){for(let r of this._liveSubscriptions.filter(n=>n.did===e))try{yield r.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(r=>r.did!==e);for(let r of this._localSubscriptions.filter(n=>n.did===e))try{yield r.close()}catch{}this._localSubscriptions=this._localSubscriptions.filter(r=>r.did!==e);for(let[r,n]of this._pushRuntimes)n.did===e&&(n.timer&&clearTimeout(n.timer),this._pushRuntimes.delete(r));for(let[r,n]of this._degradedPollTimers)this.isLinkKeyForDid(r,e)&&(clearInterval(n),this._degradedPollTimers.delete(r));for(let r of this._repairAttempts.keys())this.isLinkKeyForDid(r,e)&&this._repairAttempts.delete(r);for(let r of this._activeRepairs.keys())this.isLinkKeyForDid(r,e)&&this._activeRepairs.delete(r);for(let r of this._repairContext.keys())this.isLinkKeyForDid(r,e)&&this._repairContext.delete(r);for(let[r,n]of this._repairRetryTimers)this.isLinkKeyForDid(r,e)&&(clearTimeout(n),this._repairRetryTimers.delete(r));for(let[r,n]of this._reconcileTimers)this.isLinkKeyForDid(r,e)&&(clearTimeout(n),this._reconcileTimers.delete(r));for(let r of this._reconcileInFlight.keys())this.isLinkKeyForDid(r,e)&&this._reconcileInFlight.delete(r);for(let r of this._activeLinks.keys())this.isLinkKeyForDid(r,e)&&(this._activeLinks.delete(r),this._linkRuntimes.delete(r));this._closureContexts.delete(e)})}openLivePullSubscription(e){return He(this,void 0,void 0,function*(){var r;let{did:n,delegateDid:i,dwnUrl:a,protocol:s}=e,o=e.linkKey,c=this._activeLinks.get(o),l=c?.pull.contiguousAppliedToken;l&&(!l.streamId||!l.messageCid||!l.epoch||!l.position)&&(console.warn(`SyncEngineLevel: Discarding stored cursor with empty field(s) for ${n} -> ${a}`),l=void 0,c&&(zi.resetCheckpoint(c.pull),yield this.ledger.saveLink(c)));let d=c?.scope.kind==="protocol"?(r=c.scope.protocolPathPrefixes)===null||r===void 0?void 0:r[0]:void 0,u=s?[Object.assign({protocol:s},d?{protocolPathPrefix:d}:{})]:[],f;i&&(f=(yield this._permissionsApi.getPermissionForRequest({connectedDid:n,messageType:Se.MessagesSubscribe,delegateDid:i,protocol:s,cached:!0})).grant.id);let p=this._engineGeneration,h=c,m=()=>this._engineGeneration!==p||!this._activeLinks.has(o)||h!==void 0&&this._activeLinks.get(o)!==h,g=C=>He(this,void 0,void 0,function*(){var F;if(!m()){if(C.type==="eose"){if(c){if(c.status!=="live"&&c.status!=="initializing")return;if(!zi.validateTokenDomain(c.pull,C.cursor)){console.warn(`SyncEngineLevel: Token domain mismatch on EOSE for ${n} -> ${a}, transitioning to repairing`),m()||(yield this.transitionToRepairing(o,c));return}if(zi.setReceivedToken(c.pull,C.cursor),this.drainCommittedPull(o),m())return;yield this.ledger.saveLink(c)}if(c){let L=c.connectivity;c.connectivity="online",L!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:n,remoteEndpoint:a,protocol:s,from:L,to:"online"}),c.needsReconcile&&this.scheduleReconcile(o,500)}else this._connectivityState="online";return}if(C.type==="event"){let L=C.event;if(c&&c.status!=="live"&&c.status!=="initializing")return;if(c&&!zi.validateTokenDomain(c.pull,C.cursor)){console.warn(`SyncEngineLevel: Token domain mismatch for ${n} -> ${a}, transitioning to repairing`),m()||(yield this.transitionToRepairing(o,c));return}if(c&&!S7(L.message,c.scope)){m()||(zi.setReceivedToken(c.pull,C.cursor),zi.commitContiguousToken(c.pull,C.cursor),yield this.ledger.saveLink(c));return}let j=c?this.getOrCreateRuntime(o):void 0,V=j?j.nextDeliveryOrdinal++:-1;j&&j.inflight.set(V,{ordinal:V,token:C.cursor,committed:!1});try{let ee=this.extractDataStream(L);if(!ee&&oh(L)&&L.message.descriptor.dataCid){let x=yield be.getCid(L.message),P=yield kx({did:n,dwnUrl:a,delegateDid:i,protocol:s,messageCids:[x],agent:this.agent,permissionsApi:this._permissionsApi});P.length>0&&P[0].dataStream&&(ee=P[0].dataStream)}if(yield this.agent.dwn.processRawMessage(n,L.message,{dataStream:ee}),m())return;let A=this._closureContexts.get(n);if(A&&s7(A,L.message),c?.scope.kind==="protocol"){let x=this.agent.dwn.node.storage.messageStore,P=this._closureContexts.get(n);P||(P=wx(n,void 0,{isDelegateSession:!!i}),this._closureContexts.set(n,P));let b=yield dR(L.message,x,c.scope,P);if(m())return;if(!b.complete){let S=b.failure.code,I=b.failure.detail;console.warn(`SyncEngineLevel: Closure incomplete for ${n} -> ${a}: ${S} \u2014 ${I}`);let M=yield be.getCid(L.message);this.recordDeadLetter({messageCid:M,tenantDid:n,remoteEndpoint:a,protocol:s,category:"closure",errorCode:S,errorDetail:I}),m()||(yield this.transitionToRepairing(o,c));return}}let O=yield be.getCid(L.message);if(this._recentlyPulledCids.set(`${O}|${a}`,Date.now()+t.ECHO_SUPPRESS_TTL_MS),this.evictExpiredEchoEntries(),this.clearFailedMessage(O,a).catch(()=>{}),c&&j&&c.status==="live"&&!m()){let x=j.inflight.get(V);x&&(x.committed=!0),zi.setReceivedToken(c.pull,C.cursor),this.drainCommittedPull(o)>0&&(yield this.ledger.saveLink(c),c.pull.contiguousAppliedToken&&this.emitEvent({type:"checkpoint:pull-advance",tenantDid:c.tenantDid,remoteEndpoint:c.remoteEndpoint,protocol:c.protocol,position:c.pull.contiguousAppliedToken.position,messageCid:c.pull.contiguousAppliedToken.messageCid})),j.inflight.size>sR&&(console.warn(`SyncEngineLevel: Pull in-flight overflow for ${n} -> ${a}, transitioning to repairing`),yield this.transitionToRepairing(o,c))}}catch(ee){console.error(`SyncEngineLevel: Error processing live-pull event for ${n}`,ee);try{let A=yield be.getCid(L.message);this.recordDeadLetter({messageCid:A,tenantDid:n,remoteEndpoint:a,protocol:s,category:"pull-processing",errorDetail:(F=ee.message)!==null&&F!==void 0?F:String(ee)})}catch{}c&&!m()&&(yield this.transitionToRepairing(o,c))}}}}),_={store:!1,author:n,target:n,messageType:Se.MessagesSubscribe,granteeDid:i,messageParams:{filters:u,cursor:l,permissionGrantId:f}},{message:w}=yield this.agent.dwn.processRequest(_);if(!w)throw new Error(`SyncEngineLevel: Failed to construct MessagesSubscribe for ${a}`);let E=C=>He(this,void 0,void 0,function*(){var F;let L=(F=C??c?.pull.contiguousAppliedToken)!==null&&F!==void 0?F:l;L&&(!L.streamId||!L.messageCid||!L.epoch||!L.position)&&(L=void 0);let j=Object.assign(Object.assign({},_),{messageParams:Object.assign(Object.assign({},_.messageParams),{cursor:L})}),{message:V}=yield this.agent.dwn.processRequest(j);if(!V)throw new Error(`SyncEngineLevel: Failed to construct resume MessagesSubscribe for ${a}`);return V}),k=new URL(a);k.protocol=k.protocol==="http:"?"ws:":"wss:";let D=k.toString(),R=yield this.agent.rpc.sendDwnRequest({dwnUrl:D,targetDid:n,message:w,subscription:{handler:g,resubscribeFactory:E}});if(R.status.code===410){let C=new Error(`SyncEngineLevel: ProgressGap for ${n} -> ${a}: ${R.status.detail}`);throw C.isProgressGap=!0,C.gapInfo=R.error,C}if(R.status.code!==200||!R.subscription)throw new Error(`SyncEngineLevel: MessagesSubscribe failed for ${n} -> ${a}: ${R.status.code} ${R.status.detail}`);this._liveSubscriptions.push({linkKey:o,did:n,dwnUrl:a,delegateDid:i,protocol:s,close:()=>He(this,void 0,void 0,function*(){yield R.subscription.close()})});let U=this._activeLinks.get(o);if(U){let C=U.connectivity;U.connectivity="online",C!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:n,remoteEndpoint:a,protocol:s,from:C,to:"online"})}})}openLocalPushSubscription(e){return He(this,void 0,void 0,function*(){var r;let{did:n,delegateDid:i,dwnUrl:a,protocol:s}=e,o=s?[{protocol:s}]:[],c;i&&(c=(yield this._permissionsApi.getPermissionForRequest({connectedDid:n,messageType:Se.MessagesSubscribe,delegateDid:i,protocol:s,cached:!0})).grant.id);let l=this._engineGeneration,d=this._activeLinks.get(e.linkKey),u=()=>this._engineGeneration!==l||!this._activeLinks.has(e.linkKey)||d!==void 0&&this._activeLinks.get(e.linkKey)!==d,f=m=>He(this,void 0,void 0,function*(){if(u()||m.type!=="event")return;let g=e.linkKey,_=this._activeLinks.get(g);if(_&&!S7(m.event.message,_.scope))return;let w=g,E=yield be.getCid(m.event.message);if(E===void 0||u()||this.isRecentlyPulled(E,a))return;let k=this.getOrCreatePushRuntime(w,{did:n,dwnUrl:a,delegateDid:i,protocol:s});k.entries.push({cid:E}),!k.flushing&&!k.timer&&this.flushPendingPushesForLink(w)}),h=(yield this.agent.dwn.processRequest({author:n,target:n,messageType:Se.MessagesSubscribe,granteeDid:i,messageParams:{filters:o,permissionGrantId:c},subscriptionHandler:f})).reply;if(h.status.code!==200||!h.subscription)throw new Error(`SyncEngineLevel: Local MessagesSubscribe failed for ${n}: ${h.status.code} ${h.status.detail}`);this._localSubscriptions.push({linkKey:(r=e.linkKey)!==null&&r!==void 0?r:xv(n,a,s),did:n,dwnUrl:a,delegateDid:i,protocol:s,close:()=>He(this,void 0,void 0,function*(){yield h.subscription.close()})})})}flushPendingPushes(){return He(this,void 0,void 0,function*(){yield Promise.all([...this._pushRuntimes.keys()].map(e=>He(this,void 0,void 0,function*(){yield this.flushPendingPushesForLink(e)})))})}flushPendingPushesForLink(e){return He(this,void 0,void 0,function*(){var r,n;if(!this._activeLinks.has(e))return;let i=this._pushRuntimes.get(e);if(!i)return;let a=this._activeLinks.get(e),s=()=>!this._activeLinks.has(e)||a!==void 0&&this._activeLinks.get(e)!==a,{did:o,dwnUrl:c,delegateDid:l,protocol:d,entries:u,retryCount:f}=i;if(i.entries=[],u.length===0){!i.timer&&!i.flushing&&f===0&&this._pushRuntimes.delete(e);return}let p=u.map(h=>h.cid);i.flushing=!0;try{let h=yield yR({did:o,dwnUrl:c,delegateDid:l,protocol:d,messageCids:p,agent:this.agent,permissionsApi:this._permissionsApi});if(s())return;for(let m of h.succeeded)this.clearFailedMessage(m,c).catch(()=>{});for(let m of h.permanentlyFailed)yield this.recordDeadLetter({messageCid:m.cid,tenantDid:o,remoteEndpoint:c,protocol:d,category:"push-permanent",errorCode:String((r=m.statusCode)!==null&&r!==void 0?r:""),errorDetail:(n=m.detail)!==null&&n!==void 0?n:"permanent push failure"});if(h.failed.length>0){if(s())return;let m=new Set(h.failed),g=u.filter(_=>m.has(_.cid));this.requeueOrReconcile(e,{did:o,dwnUrl:c,delegateDid:l,protocol:d,entries:g,retryCount:f+1})}else i.retryCount=0,!i.timer&&i.entries.length===0&&this._pushRuntimes.delete(e)}catch(h){if(s())return;console.error(`SyncEngineLevel: Push batch failed for ${o} -> ${c}`,h),this.requeueOrReconcile(e,{did:o,dwnUrl:c,delegateDid:l,protocol:d,entries:u,retryCount:f+1})}finally{i.flushing=!1;let h=this._pushRuntimes.get(e);h&&h.entries.length>0&&!h.timer&&(h.timer=setTimeout(()=>{h.timer=void 0,this.flushPendingPushesForLink(e)},$he))}})}requeueOrReconcile(e,r){var n;let i=t.PUSH_RETRY_BACKOFF_MS.length,a=this.getOrCreatePushRuntime(e,r);if(r.retryCount>=i){for(let c of r.entries)this.recordDeadLetter({messageCid:c.cid,tenantDid:r.did,remoteEndpoint:r.dwnUrl,protocol:r.protocol,category:"push-exhausted",errorDetail:`push retries exhausted after ${i} attempts`});a.timer&&clearTimeout(a.timer),this._pushRuntimes.delete(e);let o=this._activeLinks.get(e);o&&!o.needsReconcile&&(o.needsReconcile=!0,this.ledger.saveLink(o).then(()=>{this.emitEvent({type:"reconcile:needed",tenantDid:r.did,remoteEndpoint:r.dwnUrl,protocol:r.protocol,reason:"push-retry-exhausted"}),this.scheduleReconcile(e)}));return}a.entries.push(...r.entries),a.retryCount=r.retryCount;let s=(n=t.PUSH_RETRY_BACKOFF_MS[r.retryCount])!==null&&n!==void 0?n:2e3;a.timer&&clearTimeout(a.timer),a.timer=setTimeout(()=>{a.timer=void 0,this.flushPendingPushesForLink(e)},s)}createLinkReconciler(e){return new Ex({getLocalRoot:(r,n,i)=>He(this,void 0,void 0,function*(){return this.getLocalRoot(r,n,i)}),getRemoteRoot:(r,n,i,a)=>He(this,void 0,void 0,function*(){return this.getRemoteRoot(r,n,i,a)}),diffWithRemote:r=>He(this,void 0,void 0,function*(){return this.diffWithRemote(r)}),pullMessages:r=>He(this,void 0,void 0,function*(){return this.pullMessages(r)}),pushMessages:r=>He(this,void 0,void 0,function*(){return this.pushMessages(r)}),shouldContinue:e})}scheduleReconcile(e,r=1500){if(this._reconcileTimers.has(e)||this._reconcileInFlight.has(e)||this._activeRepairs.has(e))return;let n=this._engineGeneration,i=setTimeout(()=>{this._reconcileTimers.delete(e),this._engineGeneration===n&&this._activeLinks.has(e)&&this.reconcileLink(e).catch(()=>{})},r);this._reconcileTimers.set(e,i)}reconcileLink(e){return He(this,void 0,void 0,function*(){let r=this._reconcileInFlight.get(e);if(r)return r;let n=this.doReconcileLink(e).finally(()=>{this._reconcileInFlight.delete(e)});return this._reconcileInFlight.set(e,n),n})}doReconcileLink(e){return He(this,void 0,void 0,function*(){let r=this._activeLinks.get(e);if(!r||r.status!=="live"||this._activeRepairs.has(e))return;let n=this._engineGeneration,i=()=>this._activeLinks.get(e)!==r,{tenantDid:a,remoteEndpoint:s,delegateDid:o,protocol:c}=r;try{let l=yield this.createLinkReconciler(()=>this._engineGeneration===n&&!i()).reconcile({did:a,dwnUrl:s,delegateDid:o,protocol:c},{verifyConvergence:!0});if(l.aborted||i())return;l.converged?(yield this.ledger.clearNeedsReconcile(r),this.clearDeadLettersForLink(a,s,c),this.emitEvent({type:"reconcile:completed",tenantDid:a,remoteEndpoint:s,protocol:c})):i()||this.scheduleReconcile(e,5e3)}catch(l){if(i())return;console.error(`SyncEngineLevel: Reconciliation failed for ${a} -> ${s}`,l),this.scheduleReconcile(e,5e3)}})}getOrCreatePushRuntime(e,r){let n=this._pushRuntimes.get(e);return n||(n=Object.assign(Object.assign({},r),{entries:[],retryCount:0}),this._pushRuntimes.set(e,n)),n}buildLinkKey(e,r,n){return n?P7(e,r,n):xv(e,r)}getCursor(e){return He(this,void 0,void 0,function*(){let r=this._db.sublevel("syncCursors");try{let n=yield r.get(e);try{let i=JSON.parse(n);if(i&&typeof i=="object"&&typeof i.streamId=="string"&&i.streamId.length>0&&typeof i.epoch=="string"&&i.epoch.length>0&&typeof i.position=="string"&&i.position.length>0&&typeof i.messageCid=="string"&&i.messageCid.length>0)return i}catch{}yield this.deleteLegacyCursor(e);return}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}})}deleteLegacyCursor(e){return He(this,void 0,void 0,function*(){let r=this._db.sublevel("syncCursors");try{yield r.del(e)}catch{}})}extractDataStream(e){if(!oh(e))return;let r=e.message.encodedData;if(r){delete e.message.encodedData;let n=ke.base64UrlToBytes(r);return new ReadableStream({start(i){i.enqueue(n),i.close()}})}if(e.data)return e.data}getDefaultHashHex(e){return He(this,void 0,void 0,function*(){var r;if(this._defaultHashHex===void 0){let n=yield zg(),i=new Map;for(let a=0;a<=Che;a++)i.set(a,Pd(n[a]));this._defaultHashHex=i}return(r=this._defaultHashHex.get(e))!==null&&r!==void 0?r:""})}static parseBitPrefix(e){return Array.from(e,r=>r==="1")}get stateIndex(){if(!this.agent.dwn.isRemoteMode)return this.agent.dwn.node.storage.stateIndex}getLocalRoot(e,r,n){return He(this,void 0,void 0,function*(){var i;let a=this.stateIndex;if(a){let l=n===void 0?yield a.getRoot(e):yield a.getProtocolRoot(e,n);return Pd(l)}let s=yield this.getSyncPermissionGrantId(e,r,n);return(i=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Se.MessagesSync,granteeDid:r,messageParams:{action:"root",protocol:n,permissionGrantId:s}})).reply.root)!==null&&i!==void 0?i:""})}getRemoteRoot(e,r,n,i){return He(this,void 0,void 0,function*(){var a;let s=yield this.getSyncPermissionGrantId(e,n,i),o=yield this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Se.MessagesSync,granteeDid:n,messageParams:{action:"root",protocol:i,permissionGrantId:s}});return(a=(yield this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message})).root)!==null&&a!==void 0?a:""})}diffWithRemote(e){return He(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a}){var s,o;let c=yield this.collectLocalSubtreeHashes(r,a,E7),l=yield this.getSyncPermissionGrantId(r,i,a),d=yield this.agent.dwn.processRequest({store:!1,author:r,target:r,messageType:Se.MessagesSync,granteeDid:i,messageParams:{action:"diff",protocol:a,hashes:c,depth:E7,permissionGrantId:l}}),u=yield this.agent.rpc.sendDwnRequest({dwnUrl:n,targetDid:r,message:d.message});if(u.status.code!==200)throw new Error(`SyncEngineLevel: diff failed with ${u.status.code}: ${u.status.detail}`);let f=l,p=[];for(let h of(s=u.onlyLocal)!==null&&s!==void 0?s:[]){let m=yield this.getLocalLeaves(r,h,i,a,f);p.push(...m)}return{onlyRemote:(o=u.onlyRemote)!==null&&o!==void 0?o:[],onlyLocal:p}})}collectLocalSubtreeHashes(e,r,n){return He(this,void 0,void 0,function*(){let i={},a=yield this.getDefaultHashHex(n),s=this.stateIndex,o=(c,l)=>He(this,void 0,void 0,function*(){let d;if(s){let u=t.parseBitPrefix(c),f=r===void 0?yield s.getSubtreeHash(e,u):yield s.getProtocolSubtreeHash(e,r,u);d=Pd(f)}else d=yield this.getLocalSubtreeHash(e,c,void 0,r);if(d!==a){if(l>=n){i[c]=d;return}yield Promise.all([o(c+"0",l+1),o(c+"1",l+1)])}});return yield o("",0),i})}getLocalSubtreeHash(e,r,n,i,a){return He(this,void 0,void 0,function*(){var s;let o=this.stateIndex;if(o){let d=t.parseBitPrefix(r),u=i===void 0?yield o.getSubtreeHash(e,d):yield o.getProtocolSubtreeHash(e,i,d);return Pd(u)}return(s=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Se.MessagesSync,granteeDid:n,messageParams:{action:"subtree",prefix:r,protocol:i,permissionGrantId:a}})).reply.hash)!==null&&s!==void 0?s:""})}getLocalLeaves(e,r,n,i,a){return He(this,void 0,void 0,function*(){var s;let o=this.stateIndex;if(o){let d=t.parseBitPrefix(r);return i===void 0?yield o.getLeaves(e,d):yield o.getProtocolLeaves(e,i,d)}return(s=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Se.MessagesSync,granteeDid:n,messageParams:{action:"leaves",prefix:r,protocol:i,permissionGrantId:a}})).reply.entries)!==null&&s!==void 0?s:[]})}pullMessages(e){return He(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,prefetched:o}){let c=yield _7({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,prefetched:o,agent:this.agent,permissionsApi:this._permissionsApi});for(let l of c)yield this.recordDeadLetter({messageCid:l,tenantDid:r,remoteEndpoint:n,protocol:a,category:"pull-processing",errorDetail:"pull processing failed after retry passes exhausted"})})}evictExpiredEchoEntries(){let e=Date.now();for(let[r,n]of this._recentlyPulledCids)e>=n&&this._recentlyPulledCids.delete(r);if(this._recentlyPulledCids.size>t.ECHO_SUPPRESS_MAX_ENTRIES){let r=this._recentlyPulledCids.size-t.ECHO_SUPPRESS_MAX_ENTRIES,n=0;for(let i of this._recentlyPulledCids.keys()){if(n>=r)break;this._recentlyPulledCids.delete(i),n++}}}isRecentlyPulled(e,r){let n=`${e}|${r}`,i=this._recentlyPulledCids.get(n);return i===void 0?!1:Date.now()>=i?(this._recentlyPulledCids.delete(n),!1):!0}pushMessages(e){return He(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s}){return yR({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,agent:this.agent,permissionsApi:this._permissionsApi})})}static topologicalSort(e){return Am(e)}clearDeadLettersForLink(e,r,n){return He(this,void 0,void 0,function*(){var i,a,s,o;let c=[];try{try{for(var l=!0,d=Rm(this._deadLetters.iterator()),u;u=yield d.next(),i=u.done,!i;l=!0){o=u.value,l=!1;let[f,p]=o,h=JSON.parse(p);h.tenantDid===e&&h.remoteEndpoint===r&&h.protocol===n&&c.push({type:"del",key:f})}}catch(f){a={error:f}}finally{try{!l&&!i&&(s=d.return)&&(yield s.call(d))}finally{if(a)throw a.error}}c.length>0&&(yield this._deadLetters.batch(c))}catch(f){if(f.code!=="LEVEL_DATABASE_NOT_OPEN")throw f}})}static deadLetterKey(e,r){return r?`${e}|${r}`:e}recordDeadLetter(e){return He(this,void 0,void 0,function*(){let r=Object.assign(Object.assign({},e),{failedAt:new Date().toISOString()}),n=t.deadLetterKey(e.messageCid,e.remoteEndpoint);try{yield this._deadLetters.put(n,JSON.stringify(r))}catch(i){if(i.code!=="LEVEL_DATABASE_NOT_OPEN")throw i}})}getFailedMessages(e){return He(this,void 0,void 0,function*(){var r,n,i,a;let s=[];try{for(var o=!0,c=Rm(this._deadLetters.iterator()),l;l=yield c.next(),r=l.done,!r;o=!0){a=l.value,o=!1;let[,d]=a,u=JSON.parse(d);(!e||u.tenantDid===e)&&s.push(u)}}catch(d){n={error:d}}finally{try{!o&&!r&&(i=c.return)&&(yield i.call(c))}finally{if(n)throw n.error}}return s.sort((d,u)=>u.failedAt.localeCompare(d.failedAt)),s})}clearFailedMessage(e,r){return He(this,void 0,void 0,function*(){var n,i,a,s;if(r){let f=t.deadLetterKey(e,r);try{return yield this._deadLetters.get(f),yield this._deadLetters.del(f),!0}catch(p){if(p.code==="LEVEL_NOT_FOUND")return!1;throw p}}let o=!1,c=[];try{for(var l=!0,d=Rm(this._deadLetters.iterator()),u;u=yield d.next(),n=u.done,!n;l=!0){s=u.value,l=!1;let[f,p]=s;JSON.parse(p).messageCid===e&&(c.push({type:"del",key:f}),o=!0)}}catch(f){i={error:f}}finally{try{!l&&!n&&(a=d.return)&&(yield a.call(d))}finally{if(i)throw i.error}}return c.length>0&&(yield this._deadLetters.batch(c)),o})}clearAllFailedMessages(e){return He(this,void 0,void 0,function*(){var r,n,i,a;if(!e){yield this._deadLetters.clear();return}let s=[];try{for(var o=!0,c=Rm(this._deadLetters.iterator()),l;l=yield c.next(),r=l.done,!r;o=!0){a=l.value,o=!1;let[d,u]=a;JSON.parse(u).tenantDid===e&&s.push({type:"del",key:d})}}catch(d){n={error:d}}finally{try{!o&&!r&&(i=c.return)&&(yield i.call(c))}finally{if(n)throw n.error}}s.length>0&&(yield this._deadLetters.batch(s))})}getSyncHealth(){return He(this,void 0,void 0,function*(){var e,r,n,i;let a=0;try{for(var s=!0,o=Rm(this._deadLetters.iterator()),c;c=yield o.next(),e=c.done,!e;s=!0){i=c.value,s=!1;let u=i;a++}}catch(u){r={error:u}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(r)throw r.error}}let l=0,d=yield this.ledger.getAllLinks();for(let u of d)(u.status==="repairing"||u.status==="degraded_poll")&&l++;return{connectivity:this.connectivityState,failedMessageCount:a,degradedLinkCount:l}})}getSyncTargets(){return He(this,void 0,void 0,function*(){var e,r,n,i;if(this._syncTargetsCache&&Date.now()-this._syncTargetsCache.timestamp<t.SYNC_TARGETS_CACHE_TTL_MS)return this._syncTargetsCache.targets;let a=this._syncTargetsCacheGeneration,s=[],o=!1,c=!1;try{for(var l=!0,d=Rm(this._db.sublevel("registeredIdentities").iterator()),u;u=yield d.next(),e=u.done,!e;l=!0){i=u.value,l=!1;let[p,h]=i;o=!0;let m;try{m=JSON.parse(h)}catch(E){console.warn(`SyncEngineLevel: Corrupt sync options for ${p}, skipping identity:`,E);continue}let{protocols:g,delegateDid:_}=m,w=yield this.agent.dwn.getDwnEndpointUrlsForTarget(p);if(w.length===0){c=!0;continue}for(let E of w)if(g==="all")s.push({did:p,delegateDid:_,dwnUrl:E});else for(let k of g)s.push({did:p,delegateDid:_,dwnUrl:E,protocol:k})}}catch(p){r={error:p}}finally{try{!l&&!e&&(n=d.return)&&(yield n.call(d))}finally{if(r)throw r.error}}let f=o&&!c;return s.length>0&&f&&this._syncTargetsCacheGeneration===a&&(this._syncTargetsCache={targets:s,timestamp:Date.now()}),s})}getSyncPermissionGrantId(e,r,n){return He(this,void 0,void 0,function*(){return r?(yield this._permissionsApi.getPermissionForRequest({connectedDid:e,messageType:Se.MessagesSync,delegateDid:r,protocol:n,cached:!0})).grant.id:void 0})}};oa.ECHO_SUPPRESS_TTL_MS=6e4;oa.ECHO_SUPPRESS_MAX_ENTRIES=1e4;oa.SYNC_TARGETS_CACHE_TTL_MS=3e4;oa.MAX_CONSECUTIVE_FAILURES=5;oa.MAX_BACKOFF_MULTIPLIER=4;oa.MAX_REPAIR_ATTEMPTS=3;oa.REPAIR_BACKOFF_MS=[1e3,3e3,1e4];oa.PUSH_RETRY_BACKOFF_MS=[0,250,1e3,2e3];y();Nn();Ho();jt();import{Level as rVe}from"level";y();y();y();jt();nn();y();y();var T7=wn(xx(),1);jt();var Cm=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Tx=class{constructor({ttl:e="15m"}={}){this.cache=new Gu.default({ttl:(0,T7.default)(e)})}get(e){return Cm(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,r){return Cm(this,void 0,void 0,function*(){this.cache.set(e,r)})}delete(e){return Cm(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return Cm(this,void 0,void 0,function*(){this.cache.clear()})}open(){return Cm(this,void 0,void 0,function*(){})}close(){return Cm(this,void 0,void 0,function*(){})}};y();nn();Nn();y();var $m=class extends Error{constructor(e,r){super(r??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};y();var Om;(function(t){t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.ParseError=-32700]="ParseError",t[t.TransportError=-32300]="TransportError",t[t.BadRequest=-50400]="BadRequest",t[t.Unauthorized=-50401]="Unauthorized",t[t.Forbidden=-50403]="Forbidden",t[t.Conflict=-50409]="Conflict",t[t.TooManyRequests=-50429]="TooManyRequests"})(Om||(Om={}));var Bm=(t,e,r)=>({jsonrpc:"2.0",id:t,method:e,params:r}),Dx=(t,e,r,n)=>({jsonrpc:"2.0",id:t,method:e,params:r,subscription:{id:n??null}}),D7=(t,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:t}});function ch(t){try{return JSON.parse(t)}catch{return null}}var gR=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Ohe=3,Bhe=500,jhe=1e4,Mhe=3e4,I7=new Set([408,429,500,502,503,504]);function Nhe(t,e){return t instanceof TypeError?!0:e?I7.has(e.status):!1}function Uhe(t,e,r){let n=Math.min(e*Math.pow(2,t),r),i=Math.floor(n/2);return i+crypto.getRandomValues(new Uint32Array(1))[0]%(i||1)}function Khe(t){let e=t.headers.get("retry-after");if(e===null)return;let r=Number(e);if(!Number.isNaN(r)&&r>=0)return r*1e3;let n=new Date(e);if(!Number.isNaN(n.getTime())){let i=n.getTime()-Date.now();return i>0?i:0}}var Ix=class t{constructor(e,r){var n,i,a;this.serverInfoCache=e??new Tx,this._retryOptions={maxRetries:(n=r?.maxRetries)!==null&&n!==void 0?n:Ohe,baseDelayMs:(i=r?.baseDelayMs)!==null&&i!==void 0?i:Bhe,maxDelayMs:(a=r?.maxDelayMs)!==null&&a!==void 0?a:jhe}}static isBunRuntime(){return typeof globalThis.Bun<"u"}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return gR(this,void 0,void 0,function*(){var r,n,i;let a=vi.randomUuid(),s=Bm(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),o={"dwn-request":JSON.stringify(s)},c={method:"POST",headers:o};if(e.data){o["content-type"]="application/octet-stream";let p=e.data;if(p instanceof ReadableStream)if(t.isBunRuntime()){let h=yield Zi.toBytes(p);p=new Blob([h],{type:"application/octet-stream"})}else c.duplex="half";c.body=p}let l=yield this.fetchWithRetry(e.dwnUrl,c);if(l.status===429){let p=parseInt((r=l.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new $m(p)}let d,u=l.headers.has("dwn-response");if(u){let p=ch(l.headers.get("dwn-response"));if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);d=p}else{let p=yield l.text(),h=ch(p);if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${l.status}`);d=h}if(d.error){let{code:p,message:h}=d.error;if(p===Om.TooManyRequests){let m=(i=(n=d.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new $m(m)}throw new Error(`(${p}) - ${h}`)}let{reply:f}=d.result;if(u){let p=new Uint8Array(yield l.arrayBuffer()),h=Zi.fromBytes(p);f.record?f.record.data=h:f.entry&&(f.entry.data=h)}return f})}getServerInfo(e){return gR(this,void 0,void 0,function*(){var r;let n=yield this.serverInfoCache.get(e);if(n)return n;let i=new URL(e);i.pathname.endsWith("/")?i.pathname+="info":i.pathname+="/info";try{let a=yield this.fetchWithRetry(i.toString());if(a.status===429){let s=parseInt((r=a.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new $m(s)}if(a.ok){let s=yield a.json(),o={maxFileSize:s.maxFileSize,maxInFlight:s.maxInFlight,providerAuth:s.providerAuth,registrationRequirements:s.registrationRequirements,server:s.server,sdkVersion:s.sdkVersion,url:s.url,version:s.version,webSocketSupport:s.webSocketSupport};return this.serverInfoCache.set(e,o),o}else throw new Error(`HTTP (${a.status}) - ${a.statusText}`)}catch(a){throw new Error(`Error encountered while processing response from ${i.toString()}: ${a.message}`)}})}fetchWithRetry(e,r){return gR(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,s,o;for(let c=0;c<=n;c++){try{let f=AbortSignal.timeout(Mhe),p=Object.assign(Object.assign({},r),{signal:r?.signal?AbortSignal.any([r.signal,f]):f}),h=yield fetch(e,p);if(!I7.has(h.status)||c===n)return h;o=h}catch(f){if(!Nhe(f)||c===n)throw f;s=f}let l=o?Khe(o):void 0,d=Uhe(c,i,a),u=l===void 0?d:Math.max(l,d);yield new Promise(f=>{setTimeout(f,u)})}if(o)return o;throw s})}};y();nn();var _v=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})};function wR(t){return typeof t=="string"?t:t instanceof ArrayBuffer?new TextDecoder().decode(t):t instanceof Uint8Array?new TextDecoder().decode(t):String(t)}var A7=3e3,Lhe=3e4,qhe=1e3,zhe=3e4,Fhe=1/0,Ghe=3e4,Whe=1e4,Ax=class t{constructor(e,r,n,i){this.socket=e,this.responseTimeout=r,this.messageHandlers=new Map,this.subscriptionHandlerIds=new Set,this.closedByUser=!1,this.reconnecting=!1,this._isConnected=!1,this._awaitingPong=!1,this.url=n,this.options=i,this._isConnected=!0}get isConnected(){return this._isConnected}static connect(e){return _v(this,arguments,void 0,function*(r,n={}){var i;let{connectTimeout:a=A7,responseTimeout:s=Lhe}=n,o;try{o=yield t.createWebSocket(r,a)}catch(l){throw(i=n.onerror)===null||i===void 0||i.call(n,l),l}let c=new t(o,s,r,n);return c.wireSocket(o),c.startHeartbeat(),c})}close(){this.closedByUser=!0,this._isConnected=!1,this.stopHeartbeat(),this.socket.close()}request(e){return _v(this,void 0,void 0,function*(){return new Promise((r,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=vi.randomUuid());let a=s=>{let o=ch(wR(s.data));if(o.id===e.id)return this.messageHandlers.delete(e.id),r(o)};this.messageHandlers.set(e.id,a),this.send(e),setTimeout(()=>{this.messageHandlers.delete(e.id),n(new Error("request timed out"))},this.responseTimeout)})})}subscribe(e,r){return _v(this,void 0,void 0,function*(){if(!e.method.startsWith("rpc.subscribe."))throw new Error("subscribe rpc requests must include the `rpc.subscribe` prefix");if(!e.subscription)throw new Error("subscribe rpc requests must include subscribe options");let n=e.subscription.id,i=this.messageHandlers.get(n),a=c=>{let l=ch(wR(c.data));l.id===n&&(l.error!==void 0&&(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),this.closeSubscription(n).catch(()=>{})),r(l))};this.messageHandlers.set(n,a),this.subscriptionHandlerIds.add(n);let s=yield this.request(e);return s.error?(i?this.messageHandlers.set(n,i):(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n)),{response:s}):{response:s,close:()=>_v(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let r=vi.randomUuid(),n=Dx(r,"rpc.subscribe.close",{},e);return this.request(n)}send(e){this.socket.send(JSON.stringify(e))}static createWebSocket(e,r){return new Promise((n,i)=>{let a=new WebSocket(e),s=()=>{l(),n(a)},o=d=>{l(),i(d)},c=setTimeout(()=>{l(),a.close(),i(new Error("connect timed out"))},r),l=()=>{clearTimeout(c),a.removeEventListener("open",s),a.removeEventListener("error",o)};a.addEventListener("open",s),a.addEventListener("error",o)})}wireSocket(e){e.addEventListener("message",r=>{let n=ch(wR(r.data));if(n===null)return;let i=this.messageHandlers.get(n.id);i&&i(r)}),e.addEventListener("close",()=>{var r,n,i,a,s;if(this._isConnected=!1,this.stopHeartbeat(),this.closedByUser){(n=(r=this.options).onclose)===null||n===void 0||n.call(r);return}this.rejectPendingRequests(),(a=(i=this.options).onclose)===null||a===void 0||a.call(i),((s=this.options.autoReconnect)!==null&&s!==void 0?s:!0)&&!this.reconnecting&&this.attemptReconnect()}),e.addEventListener("error",r=>{var n,i;(i=(n=this.options).onerror)===null||i===void 0||i.call(n,r)})}rejectPendingRequests(){for(let[e,r]of this.messageHandlers)if(!this.subscriptionHandlerIds.has(e)){let n=JSON.stringify({jsonrpc:"2.0",id:e,error:{code:Om.TransportError,message:"WebSocket connection closed unexpectedly"}});r({data:n}),this.messageHandlers.delete(e)}}startHeartbeat(){var e,r;this.stopHeartbeat();let n=(e=this.options.heartbeatInterval)!==null&&e!==void 0?e:Ghe;if(n<=0)return;let i=(r=this.options.heartbeatTimeout)!==null&&r!==void 0?r:Whe;this._heartbeatInterval=setInterval(()=>{if(!this._isConnected||this._awaitingPong)return;this._awaitingPong=!0;let a=`hb-${Date.now()}`,s={jsonrpc:"2.0",id:a,method:"rpc.ping"};this.messageHandlers.set(a,()=>{this._awaitingPong=!1,this.messageHandlers.delete(a),this._heartbeatTimeout&&(clearTimeout(this._heartbeatTimeout),this._heartbeatTimeout=void 0)});try{this.send(s)}catch{this.messageHandlers.delete(a),this._awaitingPong=!1;return}this._heartbeatTimeout=setTimeout(()=>{if(this._heartbeatTimeout=void 0,this.messageHandlers.delete(a),this._awaitingPong=!1,!this.closedByUser&&this._isConnected){console.warn("JsonRpcSocket: heartbeat timeout \u2014 closing dead connection"),this._isConnected=!1;try{this.socket.close()}catch{}}},i)},n)}stopHeartbeat(){this._heartbeatInterval&&(clearInterval(this._heartbeatInterval),this._heartbeatInterval=void 0),this._heartbeatTimeout&&(clearTimeout(this._heartbeatTimeout),this._heartbeatTimeout=void 0),this._awaitingPong=!1}attemptReconnect(){var e,r,n,i;this.reconnecting=!0;let a=(e=this.options.baseReconnectDelay)!==null&&e!==void 0?e:qhe,s=(r=this.options.maxReconnectDelay)!==null&&r!==void 0?r:zhe,o=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:Fhe,c=(i=this.options.connectTimeout)!==null&&i!==void 0?i:A7,l=0,d=()=>_v(this,void 0,void 0,function*(){var u,f,p,h;if(this.closedByUser){this.reconnecting=!1;return}if(l++,l>o){this.reconnecting=!1;return}(f=(u=this.options).onreconnecting)===null||f===void 0||f.call(u,l);let m=Math.min(a*Math.pow(2,l-1),s),g=Math.floor(m/2),_=g+crypto.getRandomValues(new Uint32Array(1))[0]%(g||1);if(yield new Promise(w=>setTimeout(w,_)),this.closedByUser){this.reconnecting=!1;return}try{let w=yield t.createWebSocket(this.url,c);this.socket=w,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(w),this.startHeartbeat(),(h=(p=this.options).onreconnected)===null||h===void 0||h.call(p)}catch{yield d()}});d()}};y();y();y();nn();y();nn();var jm=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Ev=class t{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return jm(this,void 0,void 0,function*(){let r=new URL(e.dwnUrl);if(r.protocol!=="ws:"&&r.protocol!=="wss:")throw new Error(`Invalid websocket protocol ${r.protocol}`);if(!t.connections.has(r.host))try{let c=yield t.createConnection(r);t.connections.set(r.host,c)}catch(c){throw new Error(`Error connecting to ${r.host}: ${c.message}`)}let i=t.connections.get(r.host),{targetDid:a,message:s,subscription:o}=e;return o?t.subscriptionRequest(i,a,s,o.handler,o.resubscribeFactory):t.processMessage(i,a,s)})}static createConnection(e){return jm(this,void 0,void 0,function*(){let r=e.host,n=new Map,i=yield Ax.connect(e.toString(),{onclose:()=>{t.connections.delete(r);for(let a of n.values())a.handler({type:"disconnected"})},onreconnecting:a=>{for(let s of n.values())s.handler({type:"reconnecting",attempt:a})},onreconnected:()=>{let a={socket:i,subscriptions:n,url:e.toString()};t.connections.set(r,a),t.resubscribeAll(a)}});return{socket:i,subscriptions:n,url:e.toString()}})}static processMessage(e,r,n){return jm(this,void 0,void 0,function*(){let i=vi.randomUuid(),a=Bm(i,"dwn.processMessage",{target:r,message:n}),{socket:s}=e,o=yield s.request(a),{error:c,result:l}=o;if(c!==void 0)throw new Error(`error sending DWN request: ${c.message}`);return l.reply})}static subscriptionRequest(e,r,n,i,a){return jm(this,void 0,void 0,function*(){let s=vi.randomUuid(),o=vi.randomUuid(),c=Dx(s,"rpc.subscribe.dwn.processMessage",{target:r,message:n},o),{socket:l,subscriptions:d}=e,{response:u,close:f}=yield l.subscribe(c,g=>{let{result:_,error:w}=g;if(w){let k=d.get(o);k&&k.subscription.close(),d.delete(o);return}let E=_.subscription;if(i(E),"cursor"in E&&E.cursor){let k=d.get(o);k&&(k.lastCursor=E.cursor),l.send(D7(o,E.cursor))}}),{error:p,result:h}=u;if(p)throw new Error(`could not subscribe via jsonrpc socket: ${p.message}`);let{reply:m}=h;if(m.subscription&&f){let g=()=>jm(this,void 0,void 0,function*(){d.delete(o),yield f()}),_={subscription:Object.assign(Object.assign({},m.subscription),{close:g}),target:r,message:n,handler:i,resubscribeFactory:a};d.set(o,_),m.subscription.close=g}return m})}static resubscribeAll(e){return jm(this,void 0,void 0,function*(){let r=[...e.subscriptions.entries()];e.subscriptions.clear();for(let[,n]of r)try{let i;n.resubscribeFactory?i=yield n.resubscribeFactory(n.lastCursor):i=n.message,yield t.subscriptionRequest(e,n.target,i,n.handler,n.resubscribeFactory),n.handler({type:"reconnected"})}catch{}})}};Ev.connections=new Map;var Sv=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},R7;(function(t){t.Create="did.create",t.Resolve="did.resolve"})(R7||(R7={}));var Mm=class{constructor(e=[]){this.transportClients=new Map,e=[new vR,new bR,...e];for(let r of e)for(let n of r.transportProtocols)this.transportClients.set(n,r)}get transportProtocols(){return Array.from(this.transportClients.keys())}sendDidRequest(e){return Sv(this,void 0,void 0,function*(){let r=new URL(e.url),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.sendDidRequest(e)})}sendDwnRequest(e){let r=new URL(e.dwnUrl),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.sendDwnRequest(e)}getServerInfo(e){return Sv(this,void 0,void 0,function*(){let r=new URL(e),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.getServerInfo(e)})}},vR=class extends Ix{sendDidRequest(e){return Sv(this,void 0,void 0,function*(){let r=vi.randomUuid(),n=Bm(r,e.method,{data:e.data}),i=new Request(e.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a;try{let s=yield fetch(i,{signal:AbortSignal.timeout(3e4)});if(s.ok){if(a=yield s.json(),a.error){let{code:o,message:c}=a.error;throw new Error(`JSON RPC (${o}) - ${c}`)}}else throw new Error(`HTTP (${s.status}) - ${s.statusText}`)}catch(s){throw new Error(`Error encountered while processing response from ${e.url}: ${s.message}`)}return a.result})}},bR=class extends Ev{sendDidRequest(e){return Sv(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return Sv(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};y();y();Ho();jt();nn();Nn();y();jt();Ho();var Rx=class{constructor(e){this.agent=e.agent,this.connectedDid=e.connectedDid}async create(e){let{result:r,...n}=await this.agent.processDidRequest({messageType:Pv.Create,messageParams:{...e}});return{did:r,...n}}async resolve(e,r){let{result:n}=await this.agent.processDidRequest({messageParams:{didUri:e,options:r},messageType:Pv.Resolve});return n}};y();y();jt();var kv=class{constructor(e){let{rawMessage:r,initialWrite:n,encodedData:i,data:a,remoteOrigin:s,anonymousDwn:o}=e;this._anonymousDwn=o,this._remoteOrigin=s;try{this._author=Jo(r)??"unknown"}catch{this._author="unknown"}try{this._creator=n?Jo(n)??this._author:this._author}catch{this._creator=this._author}this._descriptor=r.descriptor,this._recordId=r.recordId,this._contextId=r.contextId,this._initialWrite=n,this._authorization=r.authorization,this._attestation=r.attestation,this._encryption=r.encryption,i&&(this._encodedData=new Blob([Me.base64Url(i).toUint8Array()],{type:this.dataFormat})),a&&(this._readableStream=a)}get id(){return this._recordId}get contextId(){return this._contextId}get dateCreated(){return this._descriptor.dateCreated}get parentId(){return this._descriptor.parentId}get protocol(){return this._descriptor.protocol}get protocolPath(){return this._descriptor.protocolPath}get recipient(){return this._descriptor.recipient}get schema(){return this._descriptor.schema}get dataFormat(){return this._descriptor.dataFormat}get dataCid(){return this._descriptor.dataCid}get dataSize(){return this._descriptor.dataSize}get datePublished(){return this._descriptor.datePublished}get published(){return this._descriptor.published}get tags(){return this._descriptor.tags}get author(){return this._author}get creator(){return this._creator}get timestamp(){return this._descriptor.messageTimestamp}get encryption(){return this._encryption}get authorization(){return this._authorization}get attestation(){return this._attestation}get initialWrite(){return this._initialWrite}get remoteOrigin(){return this._remoteOrigin}get data(){let e=this;return{async blob(){return new Blob([await Bo.consumeToBytes({readableStream:await this.stream()})],{type:e.dataFormat})},async bytes(){return await Bo.consumeToBytes({readableStream:await this.stream()})},async json(){return await Bo.consumeToJson({readableStream:await this.stream()})},async text(){return await Bo.consumeToText({readableStream:await this.stream()})},async stream(){if(e._encodedData)return Bo.fromBlob(e._encodedData);if(e._readableStream){let n=e._readableStream;return e._readableStream=void 0,n}else return await e.readRecordData()},then(n,i){return this.stream().then(n,i)},catch(n){return this.stream().catch(n)}}}toJSON(){return{attestation:this.attestation,author:this.author,authorization:this.authorization,contextId:this.contextId,dataCid:this.dataCid,dataFormat:this.dataFormat,dataSize:this.dataSize,dateCreated:this.dateCreated,datePublished:this.datePublished,encryption:this.encryption,parentId:this.parentId,protocol:this.protocol,protocolPath:this.protocolPath,published:this.published,recipient:this.recipient,recordId:this.id,schema:this.schema,tags:this.tags,timestamp:this.timestamp}}toString(){let e=`ReadOnlyRecord: {
2058
+ `);Ho();jt();y();y();nn();y();jt();nn();y();jt();nn();y();nn();nn();Nn();y();jt();nn();y();Ho();y();jt();y();y();var k7=wn(xx(),1);Nn();import{Level as Rhe}from"level";y();var She=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})};function khe(t){let e=[],r=[];for(let n of t)n.message?n.message.descriptor.interface==="Records"&&n.message.descriptor.method==="Write"&&n.message.descriptor.dataCid&&!n.encodedData?r.push(n.messageCid):e.push(n):r.push(n.messageCid);return{prefetched:e,needsFetchCids:r}}var Ex=class{constructor(e){this._deps=e}reconcile(e,r){return She(this,void 0,void 0,function*(){var n;let{did:i,dwnUrl:a,delegateDid:s,protocol:o}=e,c=r?.direction,l=(n=r?.verifyConvergence)!==null&&n!==void 0?n:!1,d=this._deps.shouldContinue,u=yield this._deps.getLocalRoot(i,s,o);if(d&&!d())return{aborted:!0,changed:!1,didPull:!1,didPush:!1};let f=yield this._deps.getRemoteRoot(i,a,s,o);if(d&&!d())return{aborted:!0,changed:!1,didPull:!1,didPush:!1};let p=!1,h=!1,m;if(u!==f){let w=yield this._deps.diffWithRemote(e);if(d&&!d())return{aborted:!0,changed:!0,didPull:!1,didPush:!1,localRoot:u,remoteRoot:f};if((!c||c==="pull")&&w.onlyRemote.length>0){let{prefetched:E,needsFetchCids:k}=khe(w.onlyRemote);if(yield this._deps.pullMessages({did:i,dwnUrl:a,delegateDid:s,protocol:o,messageCids:k,prefetched:E}),d&&!d())return{aborted:!0,changed:!0,didPull:!0,didPush:!1,localRoot:u,remoteRoot:f};p=!0}if((!c||c==="push")&&w.onlyLocal.length>0){if(m=yield this._deps.pushMessages({did:i,dwnUrl:a,delegateDid:s,protocol:o,messageCids:w.onlyLocal}),d&&!d())return{aborted:!0,changed:!0,didPull:p,didPush:!0,localRoot:u,remoteRoot:f,pushResult:m};h=!0}}if(!l)return{changed:u!==f,didPull:p,didPush:h,localRoot:u,remoteRoot:f,pushResult:m};let g=yield this._deps.getLocalRoot(i,s,o);if(d&&!d())return{aborted:!0,changed:u!==f,didPull:p,didPush:h,localRoot:u,remoteRoot:f,pushResult:m};let _=yield this._deps.getRemoteRoot(i,a,s,o);return d&&!d()?{aborted:!0,changed:u!==f,didPull:p,didPush:h,localRoot:u,remoteRoot:f,pushResult:m}:{changed:u!==f,didPull:p,didPush:h,localRoot:u,remoteRoot:f,postLocalRoot:g,postRemoteRoot:_,converged:g===_,pushResult:m}})}};y();Nn();function b7(t){let e=t.descriptor;return e.interface!==Le.Records||e.method!==Ue.Write?!1:e.dateCreated===e.messageTimestamp}function Am(t){var e;if(t.length<=1)return t;let r=new Map,n=new Map,i=new Map,a=new Map;for(let u=0;u<t.length;u++){let f=t[u];r.set(u,f);let p=f.message.descriptor;if(p.interface===Le.Protocols&&p.method===Ue.Configure){let h=(e=p.definition)===null||e===void 0?void 0:e.protocol;h&&n.set(h,u)}if(p.interface===Le.Records&&p.method===Ue.Write){let h=f.message.recordId;b7(f.message)&&h&&i.set(h,u),p.protocol===Et.uri&&p.protocolPath===Et.grantPath&&h&&a.set(h,u)}}let s=new Map,o=new Array(t.length).fill(0),c=(u,f)=>{if(u===f)return;s.has(u)||s.set(u,new Set);let p=s.get(u);p.has(f)||(p.add(f),o[f]++)};for(let u=0;u<t.length;u++){let f=t[u].message.descriptor;if(f.interface===Le.Records){let h=f.protocol;h&&n.has(h)&&c(n.get(h),u)}if(f.interface===Le.Records&&f.parentId){let h=f.parentId;i.has(h)&&c(i.get(h),u)}if(f.interface===Le.Records&&f.method===Ue.Write){let h=t[u].message.recordId;h&&!b7(t[u].message)&&i.has(h)&&c(i.get(h),u)}if(f.interface===Le.Records&&f.method===Ue.Delete){let h=f.recordId;h&&i.has(h)&&c(i.get(h),u)}let p=f.permissionGrantId;p&&a.has(p)&&c(a.get(p),u)}let l=[];for(let u=0;u<t.length;u++)o[u]===0&&l.push(u);let d=[];for(;l.length>0;){let u=l.shift();d.push(r.get(u));let f=s.get(u);if(f)for(let p of f)o[p]--,o[p]===0&&l.push(p)}if(d.length<t.length){let u=new Set(d);for(let f=0;f<t.length;f++){let p=r.get(f);u.has(p)||d.push(p)}}return d}y();var Sx="^";function P7(t,e,r){return`${t}${Sx}${e}${Sx}${r}`}function xv(t,e,r){let n=`${t}${Sx}${e}`;return r?`${n}${Sx}${r}`:n}y();Nn();var ah=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},The=1048576;function x7(t,e){var r,n;return t.status.code===202||t.status.code===204||t.status.code===409||t.status.code===404&&(e?.descriptor.interface===Le.Records&&e?.descriptor.method===Ue.Delete||((r=t.entry)===null||r===void 0?void 0:r.message.descriptor.interface)===Le.Records&&((n=t.entry)===null||n===void 0?void 0:n.message.descriptor.method)===Ue.Delete)}function Dhe(t){return t.status.code===400||t.status.code===401||t.status.code===403}function mR(t){return ah(this,void 0,void 0,function*(){try{return yield be.getCid(t)}catch{return"unknown"}})}function _7(t){return ah(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s,agent:o,permissionsApi:c}){let l=[];if(s)for(let g of s){if(!g.message)continue;let _={message:g.message};if(g.encodedData){let w=ke.base64UrlToBytes(g.encodedData);_.bufferedData=w,_.dataStream=new ReadableStream({start(E){E.enqueue(w),E.close()}})}l.push(_)}let d=a.length>0?yield kx({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:o,permissionsApi:c}):[],u=[...l,...d],f=Am(u);yield Ihe(f);let p=3,h=f;for(let g=0;g<=p&&h.length>0;g++){let _=[];for(let w of h){let E=w.bufferedData?new ReadableStream({start(D){D.enqueue(w.bufferedData),D.close()}}):w.dataStream,k=yield o.dwn.processRawMessage(e,w.message,{dataStream:E});x7(k)||_.push(w)}if(_.length>0){let w=[],E=[];for(let k of _)if(k.bufferedData||!k.dataStream)E.push(k);else{let D=yield mR(k.message);w.push(D)}if(w.length>0){let k=yield kx({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:w,agent:o,permissionsApi:c});E.push(...k)}h=Am(E)}else h=[]}let m=[];for(let g of h){let _=yield mR(g.message);m.push(_)}return m})}function Ihe(t){return ah(this,void 0,void 0,function*(){for(let e of t){if(!e.dataStream)continue;let r=[],n=0,i=!1,a=e.dataStream.getReader();try{for(;;){let{done:c,value:l}=yield a.read();if(c)break;if(n+=l.byteLength,n>The){i=!0;break}r.push(l)}}finally{a.releaseLock()}if(i){e.dataStream=void 0;continue}let s=new Uint8Array(n),o=0;for(let c of r)s.set(c,o),o+=c.byteLength;e.bufferedData=s,e.dataStream=new ReadableStream({start(c){c.enqueue(s),c.close()}})}})}function kx(t){return ah(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:s,permissionsApi:o}){let c=[],l;n&&(l=(yield o.getPermissionForRequest({connectedDid:e,messageType:Se.MessagesRead,delegateDid:n,protocol:i,cached:!0})).grant.id);let d=4,u=0;for(;u<a.length;){let f=a.slice(u,u+d);u+=d;let p=yield Promise.all(f.map(h=>ah(this,void 0,void 0,function*(){var m,g;let _=yield s.processDwnRequest({store:!1,author:e,target:e,messageType:Se.MessagesRead,granteeDid:n,messageParams:{messageCid:h,permissionGrantId:l}}),w;try{w=yield s.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:_.message})}catch(D){console.error(`SyncEngineLevel: pull - failed to read ${h} from ${r}:`,(m=D.message)!==null&&m!==void 0?m:D);return}if(w.status.code!==200||!(!((g=w.entry)===null||g===void 0)&&g.message))return;let E=w.entry,k;return oh(E)&&E.data&&(k=E.data),{message:E.message,dataStream:k}})));for(let h of p)h&&c.push(h)}return c})}function yR(t){return ah(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:s,permissionsApi:o}){var c,l,d;let u=[],f=[],p=[],h=[];for(let g of a){let _=yield Ahe({author:e,messageCid:g,delegateDid:n,protocol:i,agent:s,permissionsApi:o});_?h.push(_):f.push(g)}let m=Am(h);for(let g of m){let _=yield mR(g.message);try{let w=yield s.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,data:g.dataStream,message:g.message});x7(w,g.message)?u.push(_):Dhe(w)?(w.status.code===400&&(!((c=w.status.detail)===null||c===void 0)&&c.includes("record limit"))?console.debug(`SyncEngineLevel: singleton already exists on remote, skipping push for ${_}`):console.warn(`SyncEngineLevel: push permanently failed for ${_}: ${w.status.code} ${w.status.detail}`),p.push({cid:_,statusCode:w.status.code,detail:(l=w.status.detail)!==null&&l!==void 0?l:""})):(console.error(`SyncEngineLevel: push failed for ${_}: ${w.status.code} ${w.status.detail}`),f.push(_))}catch(w){console.error(`SyncEngineLevel: push error for ${_}: ${(d=w.message)!==null&&d!==void 0?d:w}`),f.push(_)}}return{succeeded:u,failed:f,permanentlyFailed:p}})}function Ahe(t){return ah(this,arguments,void 0,function*({author:e,delegateDid:r,protocol:n,messageCid:i,agent:a,permissionsApi:s}){let o;r&&(o=(yield s.getPermissionForRequest({connectedDid:e,messageType:Se.MessagesRead,delegateDid:r,protocol:n,cached:!0})).grant.id);let{reply:c}=yield a.dwn.processRequest({author:e,target:e,messageType:Se.MessagesRead,granteeDid:r,messageParams:{messageCid:i,permissionGrantId:o}});if(c.status.code!==200||!c.entry)return;let l=c.entry,d={message:l.message};return oh(l)&&l.data&&(d.dataStream=l.data),d})}var He=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Rm=function(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof __values=="function"?__values(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(a){r[a]=t[a]&&function(s){return new Promise(function(o,c){s=t[a](s),i(o,c,s.done,s.value)})}}function i(a,s,o,c){Promise.resolve(c).then(function(l){a({value:l,done:o})},s)}},Che=16,E7=8,$he=100;function S7(t,e){if(e.kind==="full"||!e.protocolPathPrefixes&&!e.contextIdPrefixes)return!0;let r=t.descriptor;if(e.protocolPathPrefixes&&e.protocolPathPrefixes.length>0){let n=r.protocolPath;if(!n||!e.protocolPathPrefixes.some(a=>n===a||n.startsWith(a+"/")))return!1}if(e.contextIdPrefixes&&e.contextIdPrefixes.length>0){let n=t.contextId;if(!n||!e.contextIdPrefixes.some(a=>n===a||n.startsWith(a+"/")))return!1}return!0}var oa=class t{static validateSyncIdentityOptions(e){if(!e||!("protocols"in e))throw new Error("SyncEngineLevel: options.protocols is required \u2014 pass 'all' for a full replica or a non-empty protocol list.");if(e.protocols!=="all"&&!Array.isArray(e.protocols))throw new Error("SyncEngineLevel: protocols must be 'all' or a non-empty string array.");if(Array.isArray(e.protocols)&&e.protocols.length===0)throw new Error("SyncEngineLevel: protocols must be 'all' or a non-empty array of protocol URIs. An empty array is ambiguous.")}constructor({agent:e,dataPath:r,db:n}){this._syncLock=!1,this._activeLinks=new Map,this._linkRuntimes=new Map,this._syncMode="poll",this._engineGeneration=0,this._liveSubscriptions=[],this._localSubscriptions=[],this._connectivityState="unknown",this._eventListeners=new Set,this._pushRuntimes=new Map,this._recentlyPulledCids=new Map,this._closureContexts=new Map,this._syncTargetsCacheGeneration=0,this._consecutiveFailures=0,this._degradedPollTimers=new Map,this._repairAttempts=new Map,this._activeRepairs=new Map,this._repairRetryTimers=new Map,this._repairContext=new Map,this._reconcileTimers=new Map,this._reconcileInFlight=new Map,this._agent=e,this._permissionsApi=new Xn({agent:e}),this._db=n||new Rhe(r??"DATA/AGENT/SYNC_STORE")}get ledger(){return this._ledger||(this._ledger=new zi(this._db)),this._ledger}get _deadLetters(){return this._db.sublevel("deadLetters")}get agent(){if(this._agent===void 0)throw new Error("SyncEngineLevel: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,this._permissionsApi=new Xn({agent:e}),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++}get hasActiveSubscriptions(){return this._liveSubscriptions.length>0||this._localSubscriptions.length>0}get connectivityState(){if(this._activeLinks.size===0)return this._connectivityState;let e=!1,r=!1;for(let n of this._activeLinks.values())n.connectivity==="online"&&(e=!0),n.connectivity==="offline"&&(r=!0);return e?"online":r?"offline":"unknown"}on(e){return this._eventListeners.add(e),()=>{this._eventListeners.delete(e)}}emitEvent(e){for(let r of this._eventListeners)try{r(e)}catch{}}clear(){return He(this,void 0,void 0,function*(){this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,yield this.teardownLiveSync(),this._syncMode=void 0,yield this._permissionsApi.clear(),yield this._db.clear()})}close(){return He(this,void 0,void 0,function*(){this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,yield this.teardownLiveSync(),yield this._db.close()})}registerIdentity(e){return He(this,arguments,void 0,function*({did:r,options:n}){t.validateSyncIdentityOptions(n);let i=this._db.sublevel("registeredIdentities");if(yield this.getIdentityOptions(r))throw new Error(`SyncEngineLevel: Identity with DID ${r} is already registered.`);yield i.put(r,JSON.stringify(n)),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,this._syncMode==="live"&&(yield this.addIdentityToLiveSync(r,n))})}unregisterIdentity(e){return He(this,void 0,void 0,function*(){let r=this._db.sublevel("registeredIdentities");if(!(yield this.getIdentityOptions(e)))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);this._syncMode==="live"&&(yield this.removeIdentityFromLiveSync(e)),yield r.del(e),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++})}getIdentityOptions(e){return He(this,void 0,void 0,function*(){let r=this._db.sublevel("registeredIdentities");try{let n=yield r.get(e);if(n)return JSON.parse(n)}catch(n){let i=n;if(i.code==="LEVEL_NOT_FOUND")return;throw new Error(`SyncEngineLevel: Error reading level: ${i.code}.`)}})}updateIdentityOptions(e){return He(this,arguments,void 0,function*({did:r,options:n}){t.validateSyncIdentityOptions(n);let i=this._db.sublevel("registeredIdentities");if(!(yield this.getIdentityOptions(r)))throw new Error(`SyncEngineLevel: Identity with DID ${r} is not registered.`);yield i.put(r,JSON.stringify(n)),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,yield this.ledger.updateDelegateDid(r,n.delegateDid),this._syncMode==="live"&&this.hasActiveLinksForDid(r)&&(yield this.removeIdentityFromLiveSync(r),yield this.addIdentityToLiveSync(r,n))})}sync(e){return He(this,void 0,void 0,function*(){if(this._syncLock)throw new Error("SyncEngineLevel: Sync operation is already in progress.");this._syncLock=!0;try{let r=yield this.getSyncTargets(),n=new Map;for(let o of r){let c=n.get(o.dwnUrl);c||(c=[],n.set(o.dwnUrl,c)),c.push(o)}let i=0,a=0,s=yield Promise.allSettled([...n.entries()].map(o=>He(this,[o],void 0,function*([c,l]){for(let d of l){let{did:u,delegateDid:f,protocol:p}=d;try{yield this.createLinkReconciler().reconcile({did:u,dwnUrl:c,delegateDid:f,protocol:p},{direction:e})}catch(h){a++,console.error(`SyncEngineLevel: Error syncing ${u} with ${c}`,h);return}}i++})));for(let o of s)o.status==="rejected"&&a++;i>0?(this._consecutiveFailures=0,this._connectivityState="online"):a>0?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):r.length>0&&(this._consecutiveFailures=0,this._connectivityState="online")}finally{this._syncLock=!1}})}startSync(e){return He(this,void 0,void 0,function*(){var r,n;let i=(r=e.mode)!==null&&r!==void 0?r:"poll",a=(n=e.interval)!==null&&n!==void 0?n:i==="live"?"5m":"2m",s=(0,k7.default)(a);(this._liveSubscriptions.length>0||this._localSubscriptions.length>0)&&(yield this.teardownLiveSync()),this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),this._syncMode=i,i==="live"?yield this.startLiveSync(s):yield this.startPollSync(s)})}stopSync(){return He(this,arguments,void 0,function*(e=2e3){this._engineGeneration++;let r=0;for(;this._syncLock;){if(r>=e)throw new Error(`SyncEngineLevel: Existing sync operation did not complete within ${e} milliseconds.`);r+=100,yield new Promise(n=>{setTimeout(n,e<100?e:100)})}this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),this._syncTargetsCache=void 0,this._syncTargetsCacheGeneration++,yield this.teardownLiveSync(),this._syncMode=void 0})}startPollSync(e){return He(this,void 0,void 0,function*(){let r=this._engineGeneration,n=()=>He(this,void 0,void 0,function*(){if(this._engineGeneration!==r||this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{yield this.sync()}catch(s){console.error("SyncEngineLevel: Error during sync operation",s)}let i=Math.min(Math.pow(2,this._consecutiveFailures),t.MAX_BACKOFF_MULTIPLIER),a=this._consecutiveFailures>0?e*i:e;this._engineGeneration===r&&(this._syncIntervalId||(this._syncIntervalId=setInterval(n,a)))});this._syncIntervalId&&clearInterval(this._syncIntervalId),this._syncIntervalId=setInterval(n,e),this._syncLock||(yield this.sync())})}startLiveSync(e){return He(this,void 0,void 0,function*(){this.startBrowserConnectivityListeners();try{yield this.sync()}catch(i){console.error("SyncEngineLevel: Error during initial live-sync catch-up",i)}let r=yield this.getSyncTargets();yield Promise.allSettled(r.map(i=>this.initializeLinkTarget(i)));let n=()=>He(this,void 0,void 0,function*(){if(!this._syncLock)try{yield this.sync()}catch(i){console.error("SyncEngineLevel: Error during SMT integrity check",i)}});this._syncIntervalId=setInterval(n,e)})}getOrCreateRuntime(e){let r=this._linkRuntimes.get(e);return r||(r={nextDeliveryOrdinal:0,nextCommitOrdinal:0,inflight:new Map},this._linkRuntimes.set(e,r)),r}drainCommittedPull(e){let r=this._linkRuntimes.get(e),n=this._activeLinks.get(e);if(!r||!n)return 0;let i=0;for(;;){let a=r.inflight.get(r.nextCommitOrdinal);if(!a?.committed)break;zi.commitContiguousToken(n.pull,a.token),zi.setReceivedToken(n.pull,a.token),r.inflight.delete(r.nextCommitOrdinal),r.nextCommitOrdinal++,i++}return i}transitionToRepairing(e,r,n){return He(this,void 0,void 0,function*(){let i=r.status,a=r.connectivity;r.connectivity="offline",yield this.ledger.setStatus(r,"repairing"),this.emitEvent({type:"link:status-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:i,to:"repairing"}),a!=="offline"&&this.emitEvent({type:"link:connectivity-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:a,to:"offline"}),n?.resumeToken&&this._repairContext.set(e,{resumeToken:n.resumeToken});let s=this._linkRuntimes.get(e);s&&(s.inflight.clear(),s.nextCommitOrdinal=s.nextDeliveryOrdinal),this.repairLink(e).catch(()=>{this.scheduleRepairRetry(e)})})}scheduleRepairRetry(e){var r;let n=this._activeLinks.get(e);if(!n||n.status==="degraded_poll"||this._repairRetryTimers.has(e))return;let i=(r=this._repairAttempts.get(e))!==null&&r!==void 0?r:1,a=t.REPAIR_BACKOFF_MS,s=a[Math.min(i-1,a.length-1)],o=this._engineGeneration,c=setTimeout(()=>He(this,void 0,void 0,function*(){if(this._repairRetryTimers.delete(e),this._engineGeneration!==o)return;let l=this._activeLinks.get(e);if(l?.status==="repairing")try{yield this.repairLink(e)}catch{l.status==="repairing"&&this.scheduleRepairRetry(e)}}),s);this._repairRetryTimers.set(e,c)}repairLink(e){let r=this._activeRepairs.get(e);if(r)return r;let n=this.doRepairLink(e).finally(()=>{this._activeRepairs.delete(e);let i=this._activeLinks.get(e);i?.needsReconcile&&i.status==="live"&&this.scheduleReconcile(e,500)});return this._activeRepairs.set(e,n),n}doRepairLink(e){return He(this,void 0,void 0,function*(){var r,n,i,a;let s=this._activeLinks.get(e);if(!s)return;let o=this._engineGeneration,c=()=>this._activeLinks.get(e)!==s,{tenantDid:l,remoteEndpoint:d,delegateDid:u,protocol:f}=s;this.emitEvent({type:"repair:started",tenantDid:l,remoteEndpoint:d,protocol:f,attempt:((r=this._repairAttempts.get(e))!==null&&r!==void 0?r:0)+1});let p=((n=this._repairAttempts.get(e))!==null&&n!==void 0?n:0)+1;if(this._repairAttempts.set(e,p),yield this.closeLinkSubscriptions(s),this._engineGeneration!==o||c())return;let h=this.getOrCreateRuntime(e);h.inflight.clear(),h.nextDeliveryOrdinal=0,h.nextCommitOrdinal=0;try{if((yield this.createLinkReconciler(()=>this._engineGeneration===o&&!c()).reconcile({did:l,dwnUrl:d,delegateDid:u,protocol:f})).aborted)return;let g=this._repairContext.get(e),_=(i=g?.resumeToken)!==null&&i!==void 0?i:s.pull.contiguousAppliedToken;if(zi.resetCheckpoint(s.pull,_),yield this.ledger.saveLink(s),this._engineGeneration!==o||c()||(s.needsReconcile=!0,yield this.ledger.saveLink(s),this._engineGeneration!==o||c()))return;let w={did:l,dwnUrl:d,delegateDid:u,protocol:f,linkKey:e};try{yield this.openLivePullSubscription(w)}catch(D){if(D.isProgressGap){if(console.warn(`SyncEngineLevel: Stale pull resume token for ${l} -> ${d}, resetting to start fresh`),zi.resetCheckpoint(s.pull),yield this.ledger.saveLink(s),this._engineGeneration!==o||c())return;yield this.openLivePullSubscription(w)}else throw D}if(this._engineGeneration!==o||c())return;try{yield this.openLocalPushSubscription(w)}catch(D){let R=this._liveSubscriptions.find(U=>U.linkKey===e);if(R){try{yield R.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(U=>U!==R)}throw D}if(this._engineGeneration!==o||c())return;this._repairContext.delete(e),this._repairAttempts.delete(e);let E=this._repairRetryTimers.get(e);E&&(clearTimeout(E),this._repairRetryTimers.delete(e));let k=s.connectivity;s.connectivity="online",yield this.ledger.setStatus(s,"live"),this.clearDeadLettersForLink(l,d,f),this.emitEvent({type:"repair:completed",tenantDid:l,remoteEndpoint:d,protocol:f}),k!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:l,remoteEndpoint:d,protocol:f,from:k,to:"online"}),this.emitEvent({type:"link:status-change",tenantDid:l,remoteEndpoint:d,protocol:f,from:"repairing",to:"live"})}catch(m){if(this._engineGeneration!==o||c())return;if(console.error(`SyncEngineLevel: Repair failed for ${l} -> ${d} (attempt ${p})`,m),this.emitEvent({type:"repair:failed",tenantDid:l,remoteEndpoint:d,protocol:f,attempt:p,error:String((a=m.message)!==null&&a!==void 0?a:m)}),p>=t.MAX_REPAIR_ATTEMPTS){console.warn(`SyncEngineLevel: Max repair attempts reached for ${l} -> ${d}, entering degraded_poll`),yield this.enterDegradedPoll(e);return}throw m}})}closeLinkSubscriptions(e){return He(this,void 0,void 0,function*(){let{tenantDid:r,remoteEndpoint:n}=e,i=this.buildLinkKey(r,n,e.scopeId),a=this._liveSubscriptions.find(o=>o.linkKey===i);if(a){try{yield a.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(o=>o!==a)}let s=this._localSubscriptions.find(o=>o.linkKey===i);if(s){try{yield s.close()}catch{}this._localSubscriptions=this._localSubscriptions.filter(o=>o!==s)}})}enterDegradedPoll(e){return He(this,void 0,void 0,function*(){let r=this._activeLinks.get(e);if(!r)return;r.connectivity="offline";let n=r.status;yield this.ledger.setStatus(r,"degraded_poll"),this._repairAttempts.delete(e),this.emitEvent({type:"link:status-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:n,to:"degraded_poll"}),this.emitEvent({type:"degraded-poll:entered",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol});let i=this._degradedPollTimers.get(e);i&&clearInterval(i);let a=15e3,s=new Uint32Array(1),o;do crypto.getRandomValues(s),o=s[0]&16383;while(o>=a);let c=a+o,l=this._engineGeneration,d=setInterval(()=>He(this,void 0,void 0,function*(){if(this._engineGeneration!==l){clearInterval(d),this._degradedPollTimers.delete(e);return}let u=this._activeLinks.get(e);if(u?.status!=="degraded_poll"){clearInterval(d),this._degradedPollTimers.delete(e);return}try{this._repairAttempts.set(e,0),yield this.ledger.setStatus(u,"repairing"),yield this.repairLink(e),u.status==="live"&&(clearInterval(d),this._degradedPollTimers.delete(e))}catch{this._activeLinks.get(e)===u&&(yield this.ledger.setStatus(u,"degraded_poll"))}}),c);this._degradedPollTimers.set(e,d)})}startBrowserConnectivityListeners(){if(this.stopBrowserConnectivityListeners(),typeof globalThis.addEventListener!="function")return;let e=this._engineGeneration;this._onOnline=()=>{this._engineGeneration===e&&(console.info("SyncEngineLevel: browser online \u2014 triggering immediate integrity check"),this._syncLock||this.sync().catch(r=>{console.error("SyncEngineLevel: post-online sync failed",r)}))},this._onOffline=()=>{if(this._engineGeneration===e){console.info("SyncEngineLevel: browser offline"),this._connectivityState="offline";for(let r of this._activeLinks.values()){let n=r.connectivity;n!=="offline"&&(r.connectivity="offline",this.emitEvent({type:"link:connectivity-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:n,to:"offline"}))}}},this._onVisibilityChange=()=>{this._engineGeneration===e&&(typeof document>"u"||document.visibilityState!=="visible"||(console.info("SyncEngineLevel: page became visible \u2014 triggering integrity check"),this._syncLock||this.sync().catch(r=>{console.error("SyncEngineLevel: post-visibility sync failed",r)})))},globalThis.addEventListener("online",this._onOnline),globalThis.addEventListener("offline",this._onOffline),typeof document<"u"&&document.addEventListener("visibilitychange",this._onVisibilityChange)}stopBrowserConnectivityListeners(){this._onOnline&&(globalThis.removeEventListener("online",this._onOnline),this._onOnline=void 0),this._onOffline&&(globalThis.removeEventListener("offline",this._onOffline),this._onOffline=void 0),this._onVisibilityChange&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this._onVisibilityChange),this._onVisibilityChange=void 0)}teardownLiveSync(){return He(this,void 0,void 0,function*(){this.stopBrowserConnectivityListeners(),this._engineGeneration++;for(let e of this._pushRuntimes.values())e.timer&&clearTimeout(e.timer);this._pushRuntimes.clear();for(let e of this._liveSubscriptions)try{yield e.close()}catch{}this._liveSubscriptions=[];for(let e of this._localSubscriptions)try{yield e.close()}catch{}this._localSubscriptions=[];for(let e of this._degradedPollTimers.values())clearInterval(e);this._degradedPollTimers.clear(),this._repairAttempts.clear(),this._activeRepairs.clear();for(let e of this._repairRetryTimers.values())clearTimeout(e);this._repairRetryTimers.clear(),this._repairContext.clear();for(let e of this._reconcileTimers.values())clearTimeout(e);this._reconcileTimers.clear(),this._reconcileInFlight.clear(),this._closureContexts.clear(),this._recentlyPulledCids.clear(),this._activeLinks.clear(),this._linkRuntimes.clear()})}initializeLinkTarget(e){return He(this,void 0,void 0,function*(){var r;let n;try{let i=e.protocol?{kind:"protocol",protocol:e.protocol}:{kind:"full"};n=yield this.ledger.getOrCreateLink({tenantDid:e.did,remoteEndpoint:e.dwnUrl,scope:i,delegateDid:e.delegateDid,protocol:e.protocol});let a=this.buildLinkKey(e.did,e.dwnUrl,n.scopeId);if(!n.pull.contiguousAppliedToken){let o=xv(e.did,e.dwnUrl,e.protocol),c=yield this.getCursor(o);c&&(zi.resetCheckpoint(n.pull,c),yield this.ledger.saveLink(n),yield this.deleteLegacyCursor(o))}this._activeLinks.set(a,n);let s=Object.assign(Object.assign({},e),{linkKey:a});yield this.openLivePullSubscription(s);try{yield this.openLocalPushSubscription(s)}catch(o){let c=this._liveSubscriptions.find(l=>l.linkKey===a);if(c){try{yield c.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(l=>l!==c)}throw o}this.emitEvent({type:"link:status-change",tenantDid:e.did,remoteEndpoint:e.dwnUrl,protocol:e.protocol,from:"initializing",to:"live"}),yield this.ledger.setStatus(n,"live"),n.needsReconcile&&this.scheduleReconcile(a,1e3)}catch(i){let a=n?this.buildLinkKey(e.did,e.dwnUrl,n.scopeId):xv(e.did,e.dwnUrl,e.protocol);if(i.isProgressGap&&n){console.warn(`SyncEngineLevel: ProgressGap detected for ${e.did} -> ${e.dwnUrl}, initiating repair`),this.emitEvent({type:"gap:detected",tenantDid:e.did,remoteEndpoint:e.dwnUrl,protocol:e.protocol,reason:"ProgressGap"}),yield this.transitionToRepairing(a,n,{resumeToken:(r=i.gapInfo)===null||r===void 0?void 0:r.latestAvailable});return}console.error(`SyncEngineLevel: Failed to open live subscription for ${e.did} -> ${e.dwnUrl}`,i),this._activeLinks.delete(a),this._linkRuntimes.delete(a),this._liveSubscriptions.length===0&&(this._connectivityState="unknown")}})}isLinkKeyForDid(e,r){return e.startsWith(r+"^")||e.startsWith(r+"_")}hasActiveLinksForDid(e){for(let r of this._activeLinks.keys())if(this.isLinkKeyForDid(r,e))return!0;return!1}addIdentityToLiveSync(e,r){return He(this,void 0,void 0,function*(){let{protocols:n,delegateDid:i}=r,a=yield this.agent.dwn.getDwnEndpointUrlsForTarget(e);if(a.length===0)return;let s=[];for(let o of a)if(n==="all")s.push({did:e,delegateDid:i,dwnUrl:o});else for(let c of n)s.push({did:e,delegateDid:i,dwnUrl:o,protocol:c});yield Promise.allSettled(s.map(o=>this.initializeLinkTarget(o)))})}removeIdentityFromLiveSync(e){return He(this,void 0,void 0,function*(){for(let r of this._liveSubscriptions.filter(n=>n.did===e))try{yield r.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(r=>r.did!==e);for(let r of this._localSubscriptions.filter(n=>n.did===e))try{yield r.close()}catch{}this._localSubscriptions=this._localSubscriptions.filter(r=>r.did!==e);for(let[r,n]of this._pushRuntimes)n.did===e&&(n.timer&&clearTimeout(n.timer),this._pushRuntimes.delete(r));for(let[r,n]of this._degradedPollTimers)this.isLinkKeyForDid(r,e)&&(clearInterval(n),this._degradedPollTimers.delete(r));for(let r of this._repairAttempts.keys())this.isLinkKeyForDid(r,e)&&this._repairAttempts.delete(r);for(let r of this._activeRepairs.keys())this.isLinkKeyForDid(r,e)&&this._activeRepairs.delete(r);for(let r of this._repairContext.keys())this.isLinkKeyForDid(r,e)&&this._repairContext.delete(r);for(let[r,n]of this._repairRetryTimers)this.isLinkKeyForDid(r,e)&&(clearTimeout(n),this._repairRetryTimers.delete(r));for(let[r,n]of this._reconcileTimers)this.isLinkKeyForDid(r,e)&&(clearTimeout(n),this._reconcileTimers.delete(r));for(let r of this._reconcileInFlight.keys())this.isLinkKeyForDid(r,e)&&this._reconcileInFlight.delete(r);for(let r of this._activeLinks.keys())this.isLinkKeyForDid(r,e)&&(this._activeLinks.delete(r),this._linkRuntimes.delete(r));this._closureContexts.delete(e)})}openLivePullSubscription(e){return He(this,void 0,void 0,function*(){var r;let{did:n,delegateDid:i,dwnUrl:a,protocol:s}=e,o=e.linkKey,c=this._activeLinks.get(o),l=c?.pull.contiguousAppliedToken;l&&(!l.streamId||!l.messageCid||!l.epoch||!l.position)&&(console.warn(`SyncEngineLevel: Discarding stored cursor with empty field(s) for ${n} -> ${a}`),l=void 0,c&&(zi.resetCheckpoint(c.pull),yield this.ledger.saveLink(c)));let d=c?.scope.kind==="protocol"?(r=c.scope.protocolPathPrefixes)===null||r===void 0?void 0:r[0]:void 0,u=s?[Object.assign({protocol:s},d?{protocolPathPrefix:d}:{})]:[],f;i&&(f=(yield this._permissionsApi.getPermissionForRequest({connectedDid:n,messageType:Se.MessagesSubscribe,delegateDid:i,protocol:s,cached:!0})).grant.id);let p=this._engineGeneration,h=c,m=()=>this._engineGeneration!==p||!this._activeLinks.has(o)||h!==void 0&&this._activeLinks.get(o)!==h,g=C=>He(this,void 0,void 0,function*(){var F;if(!m()){if(C.type==="eose"){if(c){if(c.status!=="live"&&c.status!=="initializing")return;if(!zi.validateTokenDomain(c.pull,C.cursor)){console.warn(`SyncEngineLevel: Token domain mismatch on EOSE for ${n} -> ${a}, transitioning to repairing`),m()||(yield this.transitionToRepairing(o,c));return}if(zi.setReceivedToken(c.pull,C.cursor),this.drainCommittedPull(o),m())return;yield this.ledger.saveLink(c)}if(c){let L=c.connectivity;c.connectivity="online",L!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:n,remoteEndpoint:a,protocol:s,from:L,to:"online"}),c.needsReconcile&&this.scheduleReconcile(o,500)}else this._connectivityState="online";return}if(C.type==="event"){let L=C.event;if(c&&c.status!=="live"&&c.status!=="initializing")return;if(c&&!zi.validateTokenDomain(c.pull,C.cursor)){console.warn(`SyncEngineLevel: Token domain mismatch for ${n} -> ${a}, transitioning to repairing`),m()||(yield this.transitionToRepairing(o,c));return}if(c&&!S7(L.message,c.scope)){m()||(zi.setReceivedToken(c.pull,C.cursor),zi.commitContiguousToken(c.pull,C.cursor),yield this.ledger.saveLink(c));return}let j=c?this.getOrCreateRuntime(o):void 0,V=j?j.nextDeliveryOrdinal++:-1;j&&j.inflight.set(V,{ordinal:V,token:C.cursor,committed:!1});try{let ee=this.extractDataStream(L);if(!ee&&oh(L)&&L.message.descriptor.dataCid){let x=yield be.getCid(L.message),P=yield kx({did:n,dwnUrl:a,delegateDid:i,protocol:s,messageCids:[x],agent:this.agent,permissionsApi:this._permissionsApi});P.length>0&&P[0].dataStream&&(ee=P[0].dataStream)}if(yield this.agent.dwn.processRawMessage(n,L.message,{dataStream:ee}),m())return;let A=this._closureContexts.get(n);if(A&&s7(A,L.message),c?.scope.kind==="protocol"){let x=this.agent.dwn.node.storage.messageStore,P=this._closureContexts.get(n);P||(P=wx(n,void 0,{isDelegateSession:!!i}),this._closureContexts.set(n,P));let b=yield dR(L.message,x,c.scope,P);if(m())return;if(!b.complete){let S=b.failure.code,I=b.failure.detail;console.warn(`SyncEngineLevel: Closure incomplete for ${n} -> ${a}: ${S} \u2014 ${I}`);let M=yield be.getCid(L.message);this.recordDeadLetter({messageCid:M,tenantDid:n,remoteEndpoint:a,protocol:s,category:"closure",errorCode:S,errorDetail:I}),m()||(yield this.transitionToRepairing(o,c));return}}let O=yield be.getCid(L.message);if(this._recentlyPulledCids.set(`${O}|${a}`,Date.now()+t.ECHO_SUPPRESS_TTL_MS),this.evictExpiredEchoEntries(),this.clearFailedMessage(O,a).catch(()=>{}),c&&j&&c.status==="live"&&!m()){let x=j.inflight.get(V);x&&(x.committed=!0),zi.setReceivedToken(c.pull,C.cursor),this.drainCommittedPull(o)>0&&(yield this.ledger.saveLink(c),c.pull.contiguousAppliedToken&&this.emitEvent({type:"checkpoint:pull-advance",tenantDid:c.tenantDid,remoteEndpoint:c.remoteEndpoint,protocol:c.protocol,position:c.pull.contiguousAppliedToken.position,messageCid:c.pull.contiguousAppliedToken.messageCid})),j.inflight.size>sR&&(console.warn(`SyncEngineLevel: Pull in-flight overflow for ${n} -> ${a}, transitioning to repairing`),yield this.transitionToRepairing(o,c))}}catch(ee){console.error(`SyncEngineLevel: Error processing live-pull event for ${n}`,ee);try{let A=yield be.getCid(L.message);this.recordDeadLetter({messageCid:A,tenantDid:n,remoteEndpoint:a,protocol:s,category:"pull-processing",errorDetail:(F=ee.message)!==null&&F!==void 0?F:String(ee)})}catch{}c&&!m()&&(yield this.transitionToRepairing(o,c))}}}}),_={store:!1,author:n,target:n,messageType:Se.MessagesSubscribe,granteeDid:i,messageParams:{filters:u,cursor:l,permissionGrantId:f}},{message:w}=yield this.agent.dwn.processRequest(_);if(!w)throw new Error(`SyncEngineLevel: Failed to construct MessagesSubscribe for ${a}`);let E=C=>He(this,void 0,void 0,function*(){var F;let L=(F=C??c?.pull.contiguousAppliedToken)!==null&&F!==void 0?F:l;L&&(!L.streamId||!L.messageCid||!L.epoch||!L.position)&&(L=void 0);let j=Object.assign(Object.assign({},_),{messageParams:Object.assign(Object.assign({},_.messageParams),{cursor:L})}),{message:V}=yield this.agent.dwn.processRequest(j);if(!V)throw new Error(`SyncEngineLevel: Failed to construct resume MessagesSubscribe for ${a}`);return V}),k=new URL(a);k.protocol=k.protocol==="http:"?"ws:":"wss:";let D=k.toString(),R=yield this.agent.rpc.sendDwnRequest({dwnUrl:D,targetDid:n,message:w,subscription:{handler:g,resubscribeFactory:E}});if(R.status.code===410){let C=new Error(`SyncEngineLevel: ProgressGap for ${n} -> ${a}: ${R.status.detail}`);throw C.isProgressGap=!0,C.gapInfo=R.error,C}if(R.status.code!==200||!R.subscription)throw new Error(`SyncEngineLevel: MessagesSubscribe failed for ${n} -> ${a}: ${R.status.code} ${R.status.detail}`);this._liveSubscriptions.push({linkKey:o,did:n,dwnUrl:a,delegateDid:i,protocol:s,close:()=>He(this,void 0,void 0,function*(){yield R.subscription.close()})});let U=this._activeLinks.get(o);if(U){let C=U.connectivity;U.connectivity="online",C!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:n,remoteEndpoint:a,protocol:s,from:C,to:"online"})}})}openLocalPushSubscription(e){return He(this,void 0,void 0,function*(){var r;let{did:n,delegateDid:i,dwnUrl:a,protocol:s}=e,o=s?[{protocol:s}]:[],c;i&&(c=(yield this._permissionsApi.getPermissionForRequest({connectedDid:n,messageType:Se.MessagesSubscribe,delegateDid:i,protocol:s,cached:!0})).grant.id);let l=this._engineGeneration,d=this._activeLinks.get(e.linkKey),u=()=>this._engineGeneration!==l||!this._activeLinks.has(e.linkKey)||d!==void 0&&this._activeLinks.get(e.linkKey)!==d,f=m=>He(this,void 0,void 0,function*(){if(u()||m.type!=="event")return;let g=e.linkKey,_=this._activeLinks.get(g);if(_&&!S7(m.event.message,_.scope))return;let w=g,E=yield be.getCid(m.event.message);if(E===void 0||u()||this.isRecentlyPulled(E,a))return;let k=this.getOrCreatePushRuntime(w,{did:n,dwnUrl:a,delegateDid:i,protocol:s});k.entries.push({cid:E}),!k.flushing&&!k.timer&&this.flushPendingPushesForLink(w)}),h=(yield this.agent.dwn.processRequest({author:n,target:n,messageType:Se.MessagesSubscribe,granteeDid:i,messageParams:{filters:o,permissionGrantId:c},subscriptionHandler:f})).reply;if(h.status.code!==200||!h.subscription)throw new Error(`SyncEngineLevel: Local MessagesSubscribe failed for ${n}: ${h.status.code} ${h.status.detail}`);this._localSubscriptions.push({linkKey:(r=e.linkKey)!==null&&r!==void 0?r:xv(n,a,s),did:n,dwnUrl:a,delegateDid:i,protocol:s,close:()=>He(this,void 0,void 0,function*(){yield h.subscription.close()})})})}flushPendingPushes(){return He(this,void 0,void 0,function*(){yield Promise.all([...this._pushRuntimes.keys()].map(e=>He(this,void 0,void 0,function*(){yield this.flushPendingPushesForLink(e)})))})}flushPendingPushesForLink(e){return He(this,void 0,void 0,function*(){var r,n;if(!this._activeLinks.has(e))return;let i=this._pushRuntimes.get(e);if(!i)return;let a=this._activeLinks.get(e),s=()=>!this._activeLinks.has(e)||a!==void 0&&this._activeLinks.get(e)!==a,{did:o,dwnUrl:c,delegateDid:l,protocol:d,entries:u,retryCount:f}=i;if(i.entries=[],u.length===0){!i.timer&&!i.flushing&&f===0&&this._pushRuntimes.delete(e);return}let p=u.map(h=>h.cid);i.flushing=!0;try{let h=yield yR({did:o,dwnUrl:c,delegateDid:l,protocol:d,messageCids:p,agent:this.agent,permissionsApi:this._permissionsApi});if(s())return;for(let m of h.succeeded)this.clearFailedMessage(m,c).catch(()=>{});for(let m of h.permanentlyFailed)yield this.recordDeadLetter({messageCid:m.cid,tenantDid:o,remoteEndpoint:c,protocol:d,category:"push-permanent",errorCode:String((r=m.statusCode)!==null&&r!==void 0?r:""),errorDetail:(n=m.detail)!==null&&n!==void 0?n:"permanent push failure"});if(h.failed.length>0){if(s())return;let m=new Set(h.failed),g=u.filter(_=>m.has(_.cid));this.requeueOrReconcile(e,{did:o,dwnUrl:c,delegateDid:l,protocol:d,entries:g,retryCount:f+1})}else i.retryCount=0,!i.timer&&i.entries.length===0&&this._pushRuntimes.delete(e)}catch(h){if(s())return;console.error(`SyncEngineLevel: Push batch failed for ${o} -> ${c}`,h),this.requeueOrReconcile(e,{did:o,dwnUrl:c,delegateDid:l,protocol:d,entries:u,retryCount:f+1})}finally{i.flushing=!1;let h=this._pushRuntimes.get(e);h&&h.entries.length>0&&!h.timer&&(h.timer=setTimeout(()=>{h.timer=void 0,this.flushPendingPushesForLink(e)},$he))}})}requeueOrReconcile(e,r){var n;let i=t.PUSH_RETRY_BACKOFF_MS.length,a=this.getOrCreatePushRuntime(e,r);if(r.retryCount>=i){for(let c of r.entries)this.recordDeadLetter({messageCid:c.cid,tenantDid:r.did,remoteEndpoint:r.dwnUrl,protocol:r.protocol,category:"push-exhausted",errorDetail:`push retries exhausted after ${i} attempts`});a.timer&&clearTimeout(a.timer),this._pushRuntimes.delete(e);let o=this._activeLinks.get(e);o&&!o.needsReconcile&&(o.needsReconcile=!0,this.ledger.saveLink(o).then(()=>{this.emitEvent({type:"reconcile:needed",tenantDid:r.did,remoteEndpoint:r.dwnUrl,protocol:r.protocol,reason:"push-retry-exhausted"}),this.scheduleReconcile(e)}));return}a.entries.push(...r.entries),a.retryCount=r.retryCount;let s=(n=t.PUSH_RETRY_BACKOFF_MS[r.retryCount])!==null&&n!==void 0?n:2e3;a.timer&&clearTimeout(a.timer),a.timer=setTimeout(()=>{a.timer=void 0,this.flushPendingPushesForLink(e)},s)}createLinkReconciler(e){return new Ex({getLocalRoot:(r,n,i)=>He(this,void 0,void 0,function*(){return this.getLocalRoot(r,n,i)}),getRemoteRoot:(r,n,i,a)=>He(this,void 0,void 0,function*(){return this.getRemoteRoot(r,n,i,a)}),diffWithRemote:r=>He(this,void 0,void 0,function*(){return this.diffWithRemote(r)}),pullMessages:r=>He(this,void 0,void 0,function*(){return this.pullMessages(r)}),pushMessages:r=>He(this,void 0,void 0,function*(){return this.pushMessages(r)}),shouldContinue:e})}scheduleReconcile(e,r=1500){if(this._reconcileTimers.has(e)||this._reconcileInFlight.has(e)||this._activeRepairs.has(e))return;let n=this._engineGeneration,i=setTimeout(()=>{this._reconcileTimers.delete(e),this._engineGeneration===n&&this._activeLinks.has(e)&&this.reconcileLink(e).catch(()=>{})},r);this._reconcileTimers.set(e,i)}reconcileLink(e){return He(this,void 0,void 0,function*(){let r=this._reconcileInFlight.get(e);if(r)return r;let n=this.doReconcileLink(e).finally(()=>{this._reconcileInFlight.delete(e)});return this._reconcileInFlight.set(e,n),n})}doReconcileLink(e){return He(this,void 0,void 0,function*(){let r=this._activeLinks.get(e);if(!r||r.status!=="live"||this._activeRepairs.has(e))return;let n=this._engineGeneration,i=()=>this._activeLinks.get(e)!==r,{tenantDid:a,remoteEndpoint:s,delegateDid:o,protocol:c}=r;try{let l=yield this.createLinkReconciler(()=>this._engineGeneration===n&&!i()).reconcile({did:a,dwnUrl:s,delegateDid:o,protocol:c},{verifyConvergence:!0});if(l.aborted||i())return;l.converged?(yield this.ledger.clearNeedsReconcile(r),this.clearDeadLettersForLink(a,s,c),this.emitEvent({type:"reconcile:completed",tenantDid:a,remoteEndpoint:s,protocol:c})):i()||this.scheduleReconcile(e,5e3)}catch(l){if(i())return;console.error(`SyncEngineLevel: Reconciliation failed for ${a} -> ${s}`,l),this.scheduleReconcile(e,5e3)}})}getOrCreatePushRuntime(e,r){let n=this._pushRuntimes.get(e);return n||(n=Object.assign(Object.assign({},r),{entries:[],retryCount:0}),this._pushRuntimes.set(e,n)),n}buildLinkKey(e,r,n){return n?P7(e,r,n):xv(e,r)}getCursor(e){return He(this,void 0,void 0,function*(){let r=this._db.sublevel("syncCursors");try{let n=yield r.get(e);try{let i=JSON.parse(n);if(i&&typeof i=="object"&&typeof i.streamId=="string"&&i.streamId.length>0&&typeof i.epoch=="string"&&i.epoch.length>0&&typeof i.position=="string"&&i.position.length>0&&typeof i.messageCid=="string"&&i.messageCid.length>0)return i}catch{}yield this.deleteLegacyCursor(e);return}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}})}deleteLegacyCursor(e){return He(this,void 0,void 0,function*(){let r=this._db.sublevel("syncCursors");try{yield r.del(e)}catch{}})}extractDataStream(e){if(!oh(e))return;let r=e.message.encodedData;if(r){delete e.message.encodedData;let n=ke.base64UrlToBytes(r);return new ReadableStream({start(i){i.enqueue(n),i.close()}})}if(e.data)return e.data}getDefaultHashHex(e){return He(this,void 0,void 0,function*(){var r;if(this._defaultHashHex===void 0){let n=yield zg(),i=new Map;for(let a=0;a<=Che;a++)i.set(a,Pd(n[a]));this._defaultHashHex=i}return(r=this._defaultHashHex.get(e))!==null&&r!==void 0?r:""})}static parseBitPrefix(e){return Array.from(e,r=>r==="1")}get stateIndex(){if(!this.agent.dwn.isRemoteMode)return this.agent.dwn.node.storage.stateIndex}getLocalRoot(e,r,n){return He(this,void 0,void 0,function*(){var i;let a=this.stateIndex;if(a){let l=n===void 0?yield a.getRoot(e):yield a.getProtocolRoot(e,n);return Pd(l)}let s=yield this.getSyncPermissionGrantId(e,r,n);return(i=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Se.MessagesSync,granteeDid:r,messageParams:{action:"root",protocol:n,permissionGrantId:s}})).reply.root)!==null&&i!==void 0?i:""})}getRemoteRoot(e,r,n,i){return He(this,void 0,void 0,function*(){var a;let s=yield this.getSyncPermissionGrantId(e,n,i),o=yield this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Se.MessagesSync,granteeDid:n,messageParams:{action:"root",protocol:i,permissionGrantId:s}});return(a=(yield this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message})).root)!==null&&a!==void 0?a:""})}diffWithRemote(e){return He(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a}){var s,o;let c=yield this.collectLocalSubtreeHashes(r,a,E7),l=yield this.getSyncPermissionGrantId(r,i,a),d=yield this.agent.dwn.processRequest({store:!1,author:r,target:r,messageType:Se.MessagesSync,granteeDid:i,messageParams:{action:"diff",protocol:a,hashes:c,depth:E7,permissionGrantId:l}}),u=yield this.agent.rpc.sendDwnRequest({dwnUrl:n,targetDid:r,message:d.message});if(u.status.code!==200)throw new Error(`SyncEngineLevel: diff failed with ${u.status.code}: ${u.status.detail}`);let f=l,p=[];for(let h of(s=u.onlyLocal)!==null&&s!==void 0?s:[]){let m=yield this.getLocalLeaves(r,h,i,a,f);p.push(...m)}return{onlyRemote:(o=u.onlyRemote)!==null&&o!==void 0?o:[],onlyLocal:p}})}collectLocalSubtreeHashes(e,r,n){return He(this,void 0,void 0,function*(){let i={},a=yield this.getDefaultHashHex(n),s=this.stateIndex,o=(c,l)=>He(this,void 0,void 0,function*(){let d;if(s){let u=t.parseBitPrefix(c),f=r===void 0?yield s.getSubtreeHash(e,u):yield s.getProtocolSubtreeHash(e,r,u);d=Pd(f)}else d=yield this.getLocalSubtreeHash(e,c,void 0,r);if(d!==a){if(l>=n){i[c]=d;return}yield Promise.all([o(c+"0",l+1),o(c+"1",l+1)])}});return yield o("",0),i})}getLocalSubtreeHash(e,r,n,i,a){return He(this,void 0,void 0,function*(){var s;let o=this.stateIndex;if(o){let d=t.parseBitPrefix(r),u=i===void 0?yield o.getSubtreeHash(e,d):yield o.getProtocolSubtreeHash(e,i,d);return Pd(u)}return(s=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Se.MessagesSync,granteeDid:n,messageParams:{action:"subtree",prefix:r,protocol:i,permissionGrantId:a}})).reply.hash)!==null&&s!==void 0?s:""})}getLocalLeaves(e,r,n,i,a){return He(this,void 0,void 0,function*(){var s;let o=this.stateIndex;if(o){let d=t.parseBitPrefix(r);return i===void 0?yield o.getLeaves(e,d):yield o.getProtocolLeaves(e,i,d)}return(s=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Se.MessagesSync,granteeDid:n,messageParams:{action:"leaves",prefix:r,protocol:i,permissionGrantId:a}})).reply.entries)!==null&&s!==void 0?s:[]})}pullMessages(e){return He(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,prefetched:o}){let c=yield _7({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,prefetched:o,agent:this.agent,permissionsApi:this._permissionsApi});for(let l of c)yield this.recordDeadLetter({messageCid:l,tenantDid:r,remoteEndpoint:n,protocol:a,category:"pull-processing",errorDetail:"pull processing failed after retry passes exhausted"})})}evictExpiredEchoEntries(){let e=Date.now();for(let[r,n]of this._recentlyPulledCids)e>=n&&this._recentlyPulledCids.delete(r);if(this._recentlyPulledCids.size>t.ECHO_SUPPRESS_MAX_ENTRIES){let r=this._recentlyPulledCids.size-t.ECHO_SUPPRESS_MAX_ENTRIES,n=0;for(let i of this._recentlyPulledCids.keys()){if(n>=r)break;this._recentlyPulledCids.delete(i),n++}}}isRecentlyPulled(e,r){let n=`${e}|${r}`,i=this._recentlyPulledCids.get(n);return i===void 0?!1:Date.now()>=i?(this._recentlyPulledCids.delete(n),!1):!0}pushMessages(e){return He(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s}){return yR({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,agent:this.agent,permissionsApi:this._permissionsApi})})}static topologicalSort(e){return Am(e)}clearDeadLettersForLink(e,r,n){return He(this,void 0,void 0,function*(){var i,a,s,o;let c=[];try{try{for(var l=!0,d=Rm(this._deadLetters.iterator()),u;u=yield d.next(),i=u.done,!i;l=!0){o=u.value,l=!1;let[f,p]=o,h=JSON.parse(p);h.tenantDid===e&&h.remoteEndpoint===r&&h.protocol===n&&c.push({type:"del",key:f})}}catch(f){a={error:f}}finally{try{!l&&!i&&(s=d.return)&&(yield s.call(d))}finally{if(a)throw a.error}}c.length>0&&(yield this._deadLetters.batch(c))}catch(f){if(f.code!=="LEVEL_DATABASE_NOT_OPEN")throw f}})}static deadLetterKey(e,r){return r?`${e}|${r}`:e}recordDeadLetter(e){return He(this,void 0,void 0,function*(){let r=Object.assign(Object.assign({},e),{failedAt:new Date().toISOString()}),n=t.deadLetterKey(e.messageCid,e.remoteEndpoint);try{yield this._deadLetters.put(n,JSON.stringify(r))}catch(i){if(i.code!=="LEVEL_DATABASE_NOT_OPEN")throw i}})}getFailedMessages(e){return He(this,void 0,void 0,function*(){var r,n,i,a;let s=[];try{for(var o=!0,c=Rm(this._deadLetters.iterator()),l;l=yield c.next(),r=l.done,!r;o=!0){a=l.value,o=!1;let[,d]=a,u=JSON.parse(d);(!e||u.tenantDid===e)&&s.push(u)}}catch(d){n={error:d}}finally{try{!o&&!r&&(i=c.return)&&(yield i.call(c))}finally{if(n)throw n.error}}return s.sort((d,u)=>u.failedAt.localeCompare(d.failedAt)),s})}clearFailedMessage(e,r){return He(this,void 0,void 0,function*(){var n,i,a,s;if(r){let f=t.deadLetterKey(e,r);try{return yield this._deadLetters.get(f),yield this._deadLetters.del(f),!0}catch(p){if(p.code==="LEVEL_NOT_FOUND")return!1;throw p}}let o=!1,c=[];try{for(var l=!0,d=Rm(this._deadLetters.iterator()),u;u=yield d.next(),n=u.done,!n;l=!0){s=u.value,l=!1;let[f,p]=s;JSON.parse(p).messageCid===e&&(c.push({type:"del",key:f}),o=!0)}}catch(f){i={error:f}}finally{try{!l&&!n&&(a=d.return)&&(yield a.call(d))}finally{if(i)throw i.error}}return c.length>0&&(yield this._deadLetters.batch(c)),o})}clearAllFailedMessages(e){return He(this,void 0,void 0,function*(){var r,n,i,a;if(!e){yield this._deadLetters.clear();return}let s=[];try{for(var o=!0,c=Rm(this._deadLetters.iterator()),l;l=yield c.next(),r=l.done,!r;o=!0){a=l.value,o=!1;let[d,u]=a;JSON.parse(u).tenantDid===e&&s.push({type:"del",key:d})}}catch(d){n={error:d}}finally{try{!o&&!r&&(i=c.return)&&(yield i.call(c))}finally{if(n)throw n.error}}s.length>0&&(yield this._deadLetters.batch(s))})}getSyncHealth(){return He(this,void 0,void 0,function*(){var e,r,n,i;let a=0;try{for(var s=!0,o=Rm(this._deadLetters.iterator()),c;c=yield o.next(),e=c.done,!e;s=!0){i=c.value,s=!1;let u=i;a++}}catch(u){r={error:u}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(r)throw r.error}}let l=0,d=yield this.ledger.getAllLinks();for(let u of d)(u.status==="repairing"||u.status==="degraded_poll")&&l++;return{connectivity:this.connectivityState,failedMessageCount:a,degradedLinkCount:l}})}getSyncTargets(){return He(this,void 0,void 0,function*(){var e,r,n,i;if(this._syncTargetsCache&&Date.now()-this._syncTargetsCache.timestamp<t.SYNC_TARGETS_CACHE_TTL_MS)return this._syncTargetsCache.targets;let a=this._syncTargetsCacheGeneration,s=[],o=!1,c=!1;try{for(var l=!0,d=Rm(this._db.sublevel("registeredIdentities").iterator()),u;u=yield d.next(),e=u.done,!e;l=!0){i=u.value,l=!1;let[p,h]=i;o=!0;let m;try{m=JSON.parse(h)}catch(E){console.warn(`SyncEngineLevel: Corrupt sync options for ${p}, skipping identity:`,E);continue}let{protocols:g,delegateDid:_}=m,w=yield this.agent.dwn.getDwnEndpointUrlsForTarget(p);if(w.length===0){c=!0;continue}for(let E of w)if(g==="all")s.push({did:p,delegateDid:_,dwnUrl:E});else for(let k of g)s.push({did:p,delegateDid:_,dwnUrl:E,protocol:k})}}catch(p){r={error:p}}finally{try{!l&&!e&&(n=d.return)&&(yield n.call(d))}finally{if(r)throw r.error}}let f=o&&!c;return s.length>0&&f&&this._syncTargetsCacheGeneration===a&&(this._syncTargetsCache={targets:s,timestamp:Date.now()}),s})}getSyncPermissionGrantId(e,r,n){return He(this,void 0,void 0,function*(){return r?(yield this._permissionsApi.getPermissionForRequest({connectedDid:e,messageType:Se.MessagesSync,delegateDid:r,protocol:n,cached:!0})).grant.id:void 0})}};oa.ECHO_SUPPRESS_TTL_MS=6e4;oa.ECHO_SUPPRESS_MAX_ENTRIES=1e4;oa.SYNC_TARGETS_CACHE_TTL_MS=3e4;oa.MAX_CONSECUTIVE_FAILURES=5;oa.MAX_BACKOFF_MULTIPLIER=4;oa.MAX_REPAIR_ATTEMPTS=3;oa.REPAIR_BACKOFF_MS=[1e3,3e3,1e4];oa.PUSH_RETRY_BACKOFF_MS=[0,250,1e3,2e3];y();Nn();Ho();jt();import{Level as rVe}from"level";y();y();y();jt();nn();y();y();var T7=wn(xx(),1);jt();var Cm=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Tx=class{constructor({ttl:e="15m"}={}){this.cache=new Gu.default({ttl:(0,T7.default)(e)})}get(e){return Cm(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,r){return Cm(this,void 0,void 0,function*(){this.cache.set(e,r)})}delete(e){return Cm(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return Cm(this,void 0,void 0,function*(){this.cache.clear()})}open(){return Cm(this,void 0,void 0,function*(){})}close(){return Cm(this,void 0,void 0,function*(){})}};y();nn();Nn();y();var $m=class extends Error{constructor(e,r){super(r??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};y();var Om;(function(t){t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.ParseError=-32700]="ParseError",t[t.TransportError=-32300]="TransportError",t[t.BadRequest=-50400]="BadRequest",t[t.Unauthorized=-50401]="Unauthorized",t[t.Forbidden=-50403]="Forbidden",t[t.Conflict=-50409]="Conflict",t[t.TooManyRequests=-50429]="TooManyRequests"})(Om||(Om={}));var Bm=(t,e,r)=>({jsonrpc:"2.0",id:t,method:e,params:r}),Dx=(t,e,r,n)=>({jsonrpc:"2.0",id:t,method:e,params:r,subscription:{id:n??null}}),D7=(t,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:t}});function ch(t){try{return JSON.parse(t)}catch{return null}}var gR=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Ohe=3,Bhe=500,jhe=1e4,Mhe=3e4,I7=new Set([408,429,500,502,503,504]);function Nhe(t,e){return t instanceof TypeError?!0:e?I7.has(e.status):!1}function Uhe(t,e,r){let n=Math.min(e*Math.pow(2,t),r),i=Math.floor(n/2);return i+crypto.getRandomValues(new Uint32Array(1))[0]%(i||1)}function Khe(t){let e=t.headers.get("retry-after");if(e===null)return;let r=Number(e);if(!Number.isNaN(r)&&r>=0)return r*1e3;let n=new Date(e);if(!Number.isNaN(n.getTime())){let i=n.getTime()-Date.now();return i>0?i:0}}var Ix=class t{constructor(e,r){var n,i,a;this.serverInfoCache=e??new Tx,this._retryOptions={maxRetries:(n=r?.maxRetries)!==null&&n!==void 0?n:Ohe,baseDelayMs:(i=r?.baseDelayMs)!==null&&i!==void 0?i:Bhe,maxDelayMs:(a=r?.maxDelayMs)!==null&&a!==void 0?a:jhe}}static isBunRuntime(){return typeof globalThis.Bun<"u"}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return gR(this,void 0,void 0,function*(){var r,n,i;let a=vi.randomUuid(),s=Bm(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),o={"dwn-request":JSON.stringify(s)},c=Object.assign({method:"POST",headers:o},e.signal?{signal:e.signal}:{});if(e.data){o["content-type"]="application/octet-stream";let p=e.data;if(p instanceof ReadableStream)if(t.isBunRuntime()){let h=yield Zi.toBytes(p);p=new Blob([h],{type:"application/octet-stream"})}else c.duplex="half";c.body=p}let l=yield this.fetchWithRetry(e.dwnUrl,c);if(l.status===429){let p=parseInt((r=l.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new $m(p)}let d,u=l.headers.has("dwn-response");if(u){let p=ch(l.headers.get("dwn-response"));if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);d=p}else{let p=yield l.text(),h=ch(p);if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${l.status}`);d=h}if(d.error){let{code:p,message:h}=d.error;if(p===Om.TooManyRequests){let m=(i=(n=d.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new $m(m)}throw new Error(`(${p}) - ${h}`)}let{reply:f}=d.result;if(u){let p=new Uint8Array(yield l.arrayBuffer()),h=Zi.fromBytes(p);f.record?f.record.data=h:f.entry&&(f.entry.data=h)}return f})}getServerInfo(e){return gR(this,void 0,void 0,function*(){var r;let n=yield this.serverInfoCache.get(e);if(n)return n;let i=new URL(e);i.pathname.endsWith("/")?i.pathname+="info":i.pathname+="/info";try{let a=yield this.fetchWithRetry(i.toString());if(a.status===429){let s=parseInt((r=a.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new $m(s)}if(a.ok){let s=yield a.json(),o={maxFileSize:s.maxFileSize,maxInFlight:s.maxInFlight,providerAuth:s.providerAuth,registrationRequirements:s.registrationRequirements,server:s.server,sdkVersion:s.sdkVersion,url:s.url,version:s.version,webSocketSupport:s.webSocketSupport};return this.serverInfoCache.set(e,o),o}else throw new Error(`HTTP (${a.status}) - ${a.statusText}`)}catch(a){throw new Error(`Error encountered while processing response from ${i.toString()}: ${a.message}`)}})}fetchWithRetry(e,r){return gR(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,s,o;for(let c=0;c<=n;c++){try{let f=AbortSignal.timeout(Mhe),p=Object.assign(Object.assign({},r),{signal:r?.signal?AbortSignal.any([r.signal,f]):f}),h=yield fetch(e,p);if(!I7.has(h.status)||c===n)return h;o=h}catch(f){if(!Nhe(f)||c===n)throw f;s=f}let l=o?Khe(o):void 0,d=Uhe(c,i,a),u=l===void 0?d:Math.max(l,d);yield new Promise(f=>{setTimeout(f,u)})}if(o)return o;throw s})}};y();nn();var _v=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})};function wR(t){return typeof t=="string"?t:t instanceof ArrayBuffer?new TextDecoder().decode(t):t instanceof Uint8Array?new TextDecoder().decode(t):String(t)}var A7=3e3,Lhe=3e4,qhe=1e3,zhe=3e4,Fhe=1/0,Ghe=3e4,Whe=1e4,Ax=class t{constructor(e,r,n,i){this.socket=e,this.responseTimeout=r,this.messageHandlers=new Map,this.subscriptionHandlerIds=new Set,this.closedByUser=!1,this.reconnecting=!1,this._isConnected=!1,this._awaitingPong=!1,this.url=n,this.options=i,this._isConnected=!0}get isConnected(){return this._isConnected}static connect(e){return _v(this,arguments,void 0,function*(r,n={}){var i;let{connectTimeout:a=A7,responseTimeout:s=Lhe}=n,o;try{o=yield t.createWebSocket(r,a)}catch(l){throw(i=n.onerror)===null||i===void 0||i.call(n,l),l}let c=new t(o,s,r,n);return c.wireSocket(o),c.startHeartbeat(),c})}close(){this.closedByUser=!0,this._isConnected=!1,this.stopHeartbeat(),this.socket.close()}request(e){return _v(this,void 0,void 0,function*(){return new Promise((r,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=vi.randomUuid());let a=s=>{let o=ch(wR(s.data));if(o.id===e.id)return this.messageHandlers.delete(e.id),r(o)};this.messageHandlers.set(e.id,a),this.send(e),setTimeout(()=>{this.messageHandlers.delete(e.id),n(new Error("request timed out"))},this.responseTimeout)})})}subscribe(e,r){return _v(this,void 0,void 0,function*(){if(!e.method.startsWith("rpc.subscribe."))throw new Error("subscribe rpc requests must include the `rpc.subscribe` prefix");if(!e.subscription)throw new Error("subscribe rpc requests must include subscribe options");let n=e.subscription.id,i=this.messageHandlers.get(n),a=c=>{let l=ch(wR(c.data));l.id===n&&(l.error!==void 0&&(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),this.closeSubscription(n).catch(()=>{})),r(l))};this.messageHandlers.set(n,a),this.subscriptionHandlerIds.add(n);let s=yield this.request(e);return s.error?(i?this.messageHandlers.set(n,i):(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n)),{response:s}):{response:s,close:()=>_v(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let r=vi.randomUuid(),n=Dx(r,"rpc.subscribe.close",{},e);return this.request(n)}send(e){this.socket.send(JSON.stringify(e))}static createWebSocket(e,r){return new Promise((n,i)=>{let a=new WebSocket(e),s=()=>{l(),n(a)},o=d=>{l(),i(d)},c=setTimeout(()=>{l(),a.close(),i(new Error("connect timed out"))},r),l=()=>{clearTimeout(c),a.removeEventListener("open",s),a.removeEventListener("error",o)};a.addEventListener("open",s),a.addEventListener("error",o)})}wireSocket(e){e.addEventListener("message",r=>{let n=ch(wR(r.data));if(n===null)return;let i=this.messageHandlers.get(n.id);i&&i(r)}),e.addEventListener("close",()=>{var r,n,i,a,s;if(this._isConnected=!1,this.stopHeartbeat(),this.closedByUser){(n=(r=this.options).onclose)===null||n===void 0||n.call(r);return}this.rejectPendingRequests(),(a=(i=this.options).onclose)===null||a===void 0||a.call(i),((s=this.options.autoReconnect)!==null&&s!==void 0?s:!0)&&!this.reconnecting&&this.attemptReconnect()}),e.addEventListener("error",r=>{var n,i;(i=(n=this.options).onerror)===null||i===void 0||i.call(n,r)})}rejectPendingRequests(){for(let[e,r]of this.messageHandlers)if(!this.subscriptionHandlerIds.has(e)){let n=JSON.stringify({jsonrpc:"2.0",id:e,error:{code:Om.TransportError,message:"WebSocket connection closed unexpectedly"}});r({data:n}),this.messageHandlers.delete(e)}}startHeartbeat(){var e,r;this.stopHeartbeat();let n=(e=this.options.heartbeatInterval)!==null&&e!==void 0?e:Ghe;if(n<=0)return;let i=(r=this.options.heartbeatTimeout)!==null&&r!==void 0?r:Whe;this._heartbeatInterval=setInterval(()=>{if(!this._isConnected||this._awaitingPong)return;this._awaitingPong=!0;let a=`hb-${Date.now()}`,s={jsonrpc:"2.0",id:a,method:"rpc.ping"};this.messageHandlers.set(a,()=>{this._awaitingPong=!1,this.messageHandlers.delete(a),this._heartbeatTimeout&&(clearTimeout(this._heartbeatTimeout),this._heartbeatTimeout=void 0)});try{this.send(s)}catch{this.messageHandlers.delete(a),this._awaitingPong=!1;return}this._heartbeatTimeout=setTimeout(()=>{if(this._heartbeatTimeout=void 0,this.messageHandlers.delete(a),this._awaitingPong=!1,!this.closedByUser&&this._isConnected){console.warn("JsonRpcSocket: heartbeat timeout \u2014 closing dead connection"),this._isConnected=!1;try{this.socket.close()}catch{}}},i)},n)}stopHeartbeat(){this._heartbeatInterval&&(clearInterval(this._heartbeatInterval),this._heartbeatInterval=void 0),this._heartbeatTimeout&&(clearTimeout(this._heartbeatTimeout),this._heartbeatTimeout=void 0),this._awaitingPong=!1}attemptReconnect(){var e,r,n,i;this.reconnecting=!0;let a=(e=this.options.baseReconnectDelay)!==null&&e!==void 0?e:qhe,s=(r=this.options.maxReconnectDelay)!==null&&r!==void 0?r:zhe,o=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:Fhe,c=(i=this.options.connectTimeout)!==null&&i!==void 0?i:A7,l=0,d=()=>_v(this,void 0,void 0,function*(){var u,f,p,h;if(this.closedByUser){this.reconnecting=!1;return}if(l++,l>o){this.reconnecting=!1;return}(f=(u=this.options).onreconnecting)===null||f===void 0||f.call(u,l);let m=Math.min(a*Math.pow(2,l-1),s),g=Math.floor(m/2),_=g+crypto.getRandomValues(new Uint32Array(1))[0]%(g||1);if(yield new Promise(w=>setTimeout(w,_)),this.closedByUser){this.reconnecting=!1;return}try{let w=yield t.createWebSocket(this.url,c);this.socket=w,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(w),this.startHeartbeat(),(h=(p=this.options).onreconnected)===null||h===void 0||h.call(p)}catch{yield d()}});d()}};y();y();y();nn();y();nn();var jm=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Ev=class t{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return jm(this,void 0,void 0,function*(){let r=new URL(e.dwnUrl);if(r.protocol!=="ws:"&&r.protocol!=="wss:")throw new Error(`Invalid websocket protocol ${r.protocol}`);if(!t.connections.has(r.host))try{let c=yield t.createConnection(r);t.connections.set(r.host,c)}catch(c){throw new Error(`Error connecting to ${r.host}: ${c.message}`)}let i=t.connections.get(r.host),{targetDid:a,message:s,subscription:o}=e;return o?t.subscriptionRequest(i,a,s,o.handler,o.resubscribeFactory):t.processMessage(i,a,s)})}static createConnection(e){return jm(this,void 0,void 0,function*(){let r=e.host,n=new Map,i=yield Ax.connect(e.toString(),{onclose:()=>{t.connections.delete(r);for(let a of n.values())a.handler({type:"disconnected"})},onreconnecting:a=>{for(let s of n.values())s.handler({type:"reconnecting",attempt:a})},onreconnected:()=>{let a={socket:i,subscriptions:n,url:e.toString()};t.connections.set(r,a),t.resubscribeAll(a)}});return{socket:i,subscriptions:n,url:e.toString()}})}static processMessage(e,r,n){return jm(this,void 0,void 0,function*(){let i=vi.randomUuid(),a=Bm(i,"dwn.processMessage",{target:r,message:n}),{socket:s}=e,o=yield s.request(a),{error:c,result:l}=o;if(c!==void 0)throw new Error(`error sending DWN request: ${c.message}`);return l.reply})}static subscriptionRequest(e,r,n,i,a){return jm(this,void 0,void 0,function*(){let s=vi.randomUuid(),o=vi.randomUuid(),c=Dx(s,"rpc.subscribe.dwn.processMessage",{target:r,message:n},o),{socket:l,subscriptions:d}=e,{response:u,close:f}=yield l.subscribe(c,g=>{let{result:_,error:w}=g;if(w){let k=d.get(o);k&&k.subscription.close(),d.delete(o);return}let E=_.subscription;if(i(E),"cursor"in E&&E.cursor){let k=d.get(o);k&&(k.lastCursor=E.cursor),l.send(D7(o,E.cursor))}}),{error:p,result:h}=u;if(p)throw new Error(`could not subscribe via jsonrpc socket: ${p.message}`);let{reply:m}=h;if(m.subscription&&f){let g=()=>jm(this,void 0,void 0,function*(){d.delete(o),yield f()}),_={subscription:Object.assign(Object.assign({},m.subscription),{close:g}),target:r,message:n,handler:i,resubscribeFactory:a};d.set(o,_),m.subscription.close=g}return m})}static resubscribeAll(e){return jm(this,void 0,void 0,function*(){let r=[...e.subscriptions.entries()];e.subscriptions.clear();for(let[,n]of r)try{let i;n.resubscribeFactory?i=yield n.resubscribeFactory(n.lastCursor):i=n.message,yield t.subscriptionRequest(e,n.target,i,n.handler,n.resubscribeFactory),n.handler({type:"reconnected"})}catch{}})}};Ev.connections=new Map;var Sv=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},R7;(function(t){t.Create="did.create",t.Resolve="did.resolve"})(R7||(R7={}));var Mm=class{constructor(e=[]){this.transportClients=new Map,e=[new vR,new bR,...e];for(let r of e)for(let n of r.transportProtocols)this.transportClients.set(n,r)}get transportProtocols(){return Array.from(this.transportClients.keys())}sendDidRequest(e){return Sv(this,void 0,void 0,function*(){let r=new URL(e.url),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.sendDidRequest(e)})}sendDwnRequest(e){let r=new URL(e.dwnUrl),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.sendDwnRequest(e)}getServerInfo(e){return Sv(this,void 0,void 0,function*(){let r=new URL(e),n=this.transportClients.get(r.protocol);if(!n){let i=new Error(`no ${r.protocol} transport client available`);throw i.name="NO_TRANSPORT_CLIENT",i}return n.getServerInfo(e)})}},vR=class extends Ix{sendDidRequest(e){return Sv(this,void 0,void 0,function*(){let r=vi.randomUuid(),n=Bm(r,e.method,{data:e.data}),i=new Request(e.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a;try{let s=yield fetch(i,{signal:AbortSignal.timeout(3e4)});if(s.ok){if(a=yield s.json(),a.error){let{code:o,message:c}=a.error;throw new Error(`JSON RPC (${o}) - ${c}`)}}else throw new Error(`HTTP (${s.status}) - ${s.statusText}`)}catch(s){throw new Error(`Error encountered while processing response from ${e.url}: ${s.message}`)}return a.result})}},bR=class extends Ev{sendDidRequest(e){return Sv(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return Sv(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};y();y();Ho();jt();nn();Nn();y();jt();Ho();var Rx=class{constructor(e){this.agent=e.agent,this.connectedDid=e.connectedDid}async create(e){let{result:r,...n}=await this.agent.processDidRequest({messageType:Pv.Create,messageParams:{...e}});return{did:r,...n}}async resolve(e,r){let{result:n}=await this.agent.processDidRequest({messageParams:{didUri:e,options:r},messageType:Pv.Resolve});return n}};y();y();jt();var kv=class{constructor(e){let{rawMessage:r,initialWrite:n,encodedData:i,data:a,remoteOrigin:s,anonymousDwn:o}=e;this._anonymousDwn=o,this._remoteOrigin=s;try{this._author=Jo(r)??"unknown"}catch{this._author="unknown"}try{this._creator=n?Jo(n)??this._author:this._author}catch{this._creator=this._author}this._descriptor=r.descriptor,this._recordId=r.recordId,this._contextId=r.contextId,this._initialWrite=n,this._authorization=r.authorization,this._attestation=r.attestation,this._encryption=r.encryption,i&&(this._encodedData=new Blob([Me.base64Url(i).toUint8Array()],{type:this.dataFormat})),a&&(this._readableStream=a)}get id(){return this._recordId}get contextId(){return this._contextId}get dateCreated(){return this._descriptor.dateCreated}get parentId(){return this._descriptor.parentId}get protocol(){return this._descriptor.protocol}get protocolPath(){return this._descriptor.protocolPath}get recipient(){return this._descriptor.recipient}get schema(){return this._descriptor.schema}get dataFormat(){return this._descriptor.dataFormat}get dataCid(){return this._descriptor.dataCid}get dataSize(){return this._descriptor.dataSize}get datePublished(){return this._descriptor.datePublished}get published(){return this._descriptor.published}get tags(){return this._descriptor.tags}get author(){return this._author}get creator(){return this._creator}get timestamp(){return this._descriptor.messageTimestamp}get encryption(){return this._encryption}get authorization(){return this._authorization}get attestation(){return this._attestation}get initialWrite(){return this._initialWrite}get remoteOrigin(){return this._remoteOrigin}get data(){let e=this;return{async blob(){return new Blob([await Bo.consumeToBytes({readableStream:await this.stream()})],{type:e.dataFormat})},async bytes(){return await Bo.consumeToBytes({readableStream:await this.stream()})},async json(){return await Bo.consumeToJson({readableStream:await this.stream()})},async text(){return await Bo.consumeToText({readableStream:await this.stream()})},async stream(){if(e._encodedData)return Bo.fromBlob(e._encodedData);if(e._readableStream){let n=e._readableStream;return e._readableStream=void 0,n}else return await e.readRecordData()},then(n,i){return this.stream().then(n,i)},catch(n){return this.stream().catch(n)}}}toJSON(){return{attestation:this.attestation,author:this.author,authorization:this.authorization,contextId:this.contextId,dataCid:this.dataCid,dataFormat:this.dataFormat,dataSize:this.dataSize,dateCreated:this.dateCreated,datePublished:this.datePublished,encryption:this.encryption,parentId:this.parentId,protocol:this.protocol,protocolPath:this.protocolPath,published:this.published,recipient:this.recipient,recordId:this.id,schema:this.schema,tags:this.tags,timestamp:this.timestamp}}toString(){let e=`ReadOnlyRecord: {
2059
2059
  `;return e+=` ID: ${this.id}
2060
2060
  `,e+=this.contextId?` Context ID: ${this.contextId}
2061
2061
  `:"",e+=this.protocol?` Protocol: ${this.protocol}
@@ -2076,7 +2076,7 @@ zoo`.split(`
2076
2076
  `),e+=` Deleted: ${this.deleted}
2077
2077
  `,e+=` Created: ${this.dateCreated}
2078
2078
  `,e+=` Timestamp: ${this.timestamp}
2079
- `,e+="}",e}async paginationCursor(e){return hR(Se.RecordsWrite,this.rawMessage)?u7(this.rawMessage,e):void 0}async update({timestamp:e,data:r,encryption:n,protocolRole:i,store:a=!0,...s}){if(this.deleted)throw new Error("Record: Cannot revive a deleted record.");let o=n??this._encryption!==void 0,{parentId:c,...l}=this._recordsWriteDescriptor,d=c?this._contextId.split("/").slice(0,-1).join("/"):void 0,u={...l,...s,parentContextId:d,protocolRole:i??this._protocolRole,messageTimestamp:e,recordId:this._recordId};(M3(u.tags)||u.tags===null)&&delete u.tags;let f;r!==void 0&&(delete u.dataCid,delete u.dataSize,{dataBlob:f}=Dv(r,u.dataFormat));let p=new Set(["data","dataCid","dataFormat","dataSize","datePublished","messageTimestamp","published","tags"]);lu.verifyPermittedMutation(Object.keys(s),p),s.published===!1&&u.datePublished!==void 0&&delete u.datePublished;let h={author:this._connectedDid,dataStream:f,messageParams:{...u},messageType:Se.RecordsWrite,target:this._connectedDid,store:a,encryption:o||void 0};await this.applyDelegateGrant(h);let m=await this._agent.processDwnRequest(h),{message:g,reply:{status:_}}=m;if(!(200<=_.code&&_.code<=299))return{status:_,record:this};let w=this._initialWrite??{...this.rawMessage},E=new lu(this._agent,{author:this._author,connectedDid:this._connectedDid,delegateDid:this._delegateDid,remoteOrigin:this._remoteOrigin,protocolRole:i??this._protocolRole,initialWrite:w,encodedData:r===void 0?this._encodedData:f,...g},this._permissionsApi),k=g;return this._descriptor=k.descriptor,this._attestation=k.attestation,this._authorization=k.authorization,this._encryption=k.encryption,this._contextId=k.contextId,this._initialWrite=w,this._protocolRole=i??this._protocolRole,this._encodedData=r===void 0?this._encodedData:f,this._readableStream=void 0,this._rawMessageDirty=!0,{status:_,record:E}}async delete(e){let{store:r=!0,signAsOwner:n,timestamp:i,prune:a=!1}=e||{},s=n&&this._delegateDid===void 0,o=n&&this._delegateDid!==void 0;if(this.deleted&&!this._initialWrite)throw new Error("Record: Record is in an invalid state, initial write is missing.");this._initialWrite||(this._initialWrite={...this.rawMessage}),await this.processInitialWriteIfNeeded({store:r,signAsOwner:n});let c={messageType:Se.RecordsDelete,author:this._connectedDid,target:this._connectedDid,signAsOwner:s,signAsOwnerDelegate:o,store:r},l=e?.protocolRole?l7(this.rawMessage)!==e.protocolRole:!1;this.deleted&&!l?c.rawMessage=this.rawMessage:c.messageParams={prune:a,recordId:this._recordId,messageTimestamp:i,protocolRole:e?.protocolRole??this._protocolRole},await this.applyDelegateGrant(c);let d=await this._agent.processDwnRequest(c),{message:u,reply:{status:f}}=d;if(f.code!==202)return{status:f,record:this};let p=this._initialWrite,h=new lu(this._agent,{author:Jo(u),connectedDid:this._connectedDid,delegateDid:this._delegateDid,remoteOrigin:this._remoteOrigin,protocolRole:e?.protocolRole??this._protocolRole,initialWrite:p,...u},this._permissionsApi),m=u;return this._descriptor=m.descriptor,this._authorization=m.authorization,this._protocolRole=e?.protocolRole??this._protocolRole,this._encodedData=void 0,this._readableStream=void 0,this._rawMessageDirty=!0,{status:f,record:h}}async processInitialWriteIfNeeded({store:e,signAsOwner:r}){if(this.initialWrite&&(r&&!this._initialWriteSigned||e&&!this._initialWriteStored)){let n=r&&this._delegateDid===void 0,i=r&&this._delegateDid!==void 0,a={messageType:Se.RecordsWrite,rawMessage:this.initialWrite,author:this._connectedDid,target:this._connectedDid,signAsOwner:n,signAsOwnerDelegate:i,store:e};await this.applyDelegateGrant(a);let s=await this._agent.processDwnRequest(a),{message:o,reply:{status:c}}=s,l=o;200<=c.code&&c.code<=299&&(e&&(this._initialWriteStored=!0),r&&(this._initialWriteSigned=!0,this.initialWrite.authorization=l.authorization))}}async processRecord({store:e,signAsOwner:r}){let n=r&&this._delegateDid===void 0,i=r&&this._delegateDid!==void 0;await this.processInitialWriteIfNeeded({store:e,signAsOwner:r});let a;this.deleted?a={messageType:Se.RecordsDelete,rawMessage:this.rawMessage,author:this._connectedDid,target:this._connectedDid,signAsOwner:n,signAsOwnerDelegate:i,store:e}:a={messageType:Se.RecordsWrite,rawMessage:this.rawMessage,author:this._connectedDid,target:this._connectedDid,dataStream:await this.data.blob(),signAsOwner:n,signAsOwnerDelegate:i,store:e},await this.applyDelegateGrant(a);let s=await this._agent.processDwnRequest(a),{message:o,reply:{status:c}}=s,l=o;return 200<=c.code&&c.code<=299&&r&&(this._authorization=l.authorization,this._rawMessageDirty=!0),{status:c}}async readRecordData({target:e,isRemote:r}){let n={author:this._connectedDid,messageParams:{filter:{recordId:this.id},protocolRole:this._protocolRole},messageType:Se.RecordsRead,target:e,...this._encryption?{encryption:!0}:{}};if(this._delegateDid)try{await this.applyDelegateGrant(n)}catch{n.author=this._delegateDid}let i=r?this._agent.sendDwnRequest(n):this._agent.processDwnRequest(n);try{let{reply:{status:a,entry:s}}=await i;if(a.code!==200)throw new Error(`${a.code}: ${a.detail}`);return s.data}catch(a){throw new Error(`Error encountered while attempting to read data: ${a.message}`)}}async applyDelegateGrant(e){if(!this._delegateDid)return;let{message:r}=await this._permissionsApi.getPermissionForRequest({connectedDid:this._connectedDid,delegateDid:this._delegateDid,protocol:this.protocol,delegate:!0,cached:!0,messageType:e.messageType});e.messageParams={...e.messageParams,delegatedGrant:r},e.granteeDid=this._delegateDid}static verifyPermittedMutation(e,r){for(let n of e)if(!r.has(n))throw new Error(`${n} is an immutable property. Its value cannot be changed.`)}isRecordsDeleteDescriptor(e){return e.interface+e.method===Se.RecordsDelete}};lu._sendCache=Tv;var zd=lu;var PR=class extends CustomEvent{constructor(e){super(e.type,{detail:e})}},$x=class extends EventTarget{constructor(r){super();this._closed=!1;this._connected=!0;let{agent:n,connectedDid:i,cursor:a,delegateDid:s,protocolRole:o,remoteOrigin:c,permissionsApi:l,initialEntries:d,subscription:u}=r;this._subscription=u,this.cursor=a,this.records=d.map(f=>new zd(n,{author:Jo(f),connectedDid:i,remoteOrigin:c,delegateDid:s,protocolRole:o,...f},l)),this._knownRecords=new Map;for(let f of this.records)this._knownRecords.set(f.id,f.timestamp)}get isConnected(){return this._connected}handleEvent(r){if(this._closed)return;let n;if(r.deleted)n="delete",this._knownRecords.delete(r.id);else{let a=this._knownRecords.get(r.id);if(a===void 0)n="create";else{if(r.timestamp<=a)return;n="update"}this._knownRecords.set(r.id,r.timestamp)}let i={type:n,record:r};this.dispatchEvent(new PR(i)),this.dispatchEvent(new CustomEvent("change",{detail:i}))}handleLifecycleEvent(r,n){this._closed||(r==="disconnected"?this._connected=!1:r==="reconnected"&&(this._connected=!0),this.dispatchEvent(new CustomEvent(r,{detail:n})))}on(r,n){let i=a=>{let s=a.detail;r==="change"?n(s):r==="create"||r==="update"||r==="delete"?n(s.record):r==="reconnecting"?n(s):n()};return this.addEventListener(r,i),()=>{this.removeEventListener(r,i)}}async close(){this._closed||(this._closed=!0,await this._subscription.close())}};y();jt();y();jt();var Ox=class t{constructor(e,r){this._permissions=e,this._connectedDid=r.connectedDid,this._message=r.message}get author(){return Jo(this._message)}static async parse({connectedDid:e,agent:r,message:n}){let i=new Xn({agent:r});return new t(i,{connectedDid:e,message:n})}get agent(){return this._permissions.agent}get rawMessage(){return this._message}async send(e){e??=this._connectedDid;let{encodedData:r,...n}=this._message,i=new Blob([Me.base64Url(r).toUint8Array()]),a={messageType:Se.RecordsWrite,author:this._connectedDid,target:e,dataStream:i,rawMessage:n},{reply:s}=await this.agent.sendDwnRequest(a);return s}async store(e){let{encodedData:r,...n}=this.rawMessage,i=new Blob([Me.base64Url(r).toUint8Array()]),{reply:a,message:s}=await this.agent.processDwnRequest({author:this._connectedDid,target:this._connectedDid,messageType:Se.RecordsWrite,signAsOwner:e,rawMessage:n,dataStream:i});return this._message={...s,encodedData:r},{status:a.status}}};var dh=class t{constructor({api:e,connectedDid:r,message:n,grant:i}){this._permissions=e,this._connectedDid=r,this._message=n,this._grant=i}static parse(e){let r=sr.parse(e.message),n=new Xn({agent:e.agent});return new t({...e,grant:r,api:n})}get agent(){return this._permissions.agent}get id(){return this._grant.id}get grantor(){return this._grant.grantor}get grantee(){return this._grant.grantee}get dateGranted(){return this._grant.dateGranted}get description(){return this._grant.description}get requestId(){return this._grant.requestId}get dateExpires(){return this._grant.dateExpires}get delegated(){return this._grant.delegated}get scope(){return this._grant.scope}get conditions(){return this._grant.conditions}get rawMessage(){return this._message}async send(e){e??=this._connectedDid;let{encodedData:r,...n}=this._message,i=new Blob([Me.base64Url(r).toUint8Array()]),a={messageType:Se.RecordsWrite,author:this._connectedDid,target:e,dataStream:i,rawMessage:n},{reply:s}=await this.agent.sendDwnRequest(a);return s}async store(e=!1){let{encodedData:r,...n}=this.rawMessage,i=new Blob([Me.base64Url(r).toUint8Array()]),{reply:a,message:s}=await this.agent.processDwnRequest({store:!0,author:this._connectedDid,target:this._connectedDid,messageType:Se.RecordsWrite,signAsOwner:e,rawMessage:n,dataStream:i});return this._message={...s,encodedData:r},{status:a.status}}async import(e=!1){let{encodedData:r,...n}=this.rawMessage,i=new Blob([Me.base64Url(r).toUint8Array()]),{reply:a,message:s}=await this.agent.processDwnRequest({store:e,author:this._connectedDid,target:this._connectedDid,messageType:Se.RecordsWrite,signAsOwner:!0,rawMessage:n,dataStream:i});return this._message={...s,encodedData:r},{status:a.status}}async revoke(e=!0){let r=await this._permissions.createRevocation({store:e,author:this._connectedDid,grant:this._grant});return Ox.parse({connectedDid:this._connectedDid,agent:this.agent,message:r.message})}isRevoked(e=!1){return this._permissions.isGrantRevoked({author:this._connectedDid,target:this.grantor,grantRecordId:this.id,remote:e})}toJSON(){return{id:this.id,grantor:this.grantor,grantee:this.grantee,dateGranted:this.dateGranted,description:this.description,requestId:this.requestId,dateExpires:this.dateExpires,delegated:this.delegated,scope:this.scope,conditions:this.conditions}}};y();jt();var Iv=class t{constructor({api:e,connectedDid:r,message:n,request:i}){this._permissions=e,this._connectedDid=r,this._request=i,this._message=n}static parse({connectedDid:e,agent:r,message:n}){let i=Oa.parse(n),a=new Xn({agent:r});return new t({api:a,connectedDid:e,message:n,request:i})}get agent(){return this._permissions.agent}get id(){return this._request.id}get requester(){return this._request.requester}get description(){return this._request.description}get delegated(){return this._request.delegated}get scope(){return this._request.scope}get conditions(){return this._request.conditions}get rawMessage(){return this._message}async send(e){e??=this._connectedDid;let{encodedData:r,...n}=this._message,i=new Blob([Me.base64Url(r).toUint8Array()]),a={messageType:Se.RecordsWrite,author:this._connectedDid,target:e,dataStream:i,rawMessage:n},{reply:s}=await this.agent.sendDwnRequest(a);return s}async store(){let{encodedData:e,...r}=this.rawMessage,n=new Blob([Me.base64Url(e).toUint8Array()]),{reply:i,message:a}=await this.agent.processDwnRequest({author:this._connectedDid,target:this._connectedDid,messageType:Se.RecordsWrite,rawMessage:r,dataStream:n});return this._message={...a,encodedData:e},{status:i.status}}async grant(e,r=!0){let{message:n}=await this._permissions.createGrant({requestId:this.id,grantedTo:this.requester,scope:this.scope,delegated:this.delegated,author:this._connectedDid,store:r,dateExpires:e});return dh.parse({connectedDid:this._connectedDid,agent:this.agent,message:n})}toJSON(){return this._request}};y();var Av=class{constructor(e,r,n){this._agent=e,this._metadata=n,this._protocolsConfigureMessage=r}get definition(){return this._protocolsConfigureMessage.descriptor.definition}toJSON(){return this._protocolsConfigureMessage}async send(e){let{reply:r}=await this._agent.sendDwnRequest({author:this._metadata.author,messageCid:this._metadata.messageCid,messageType:Se.ProtocolsConfigure,target:e});return{status:r.status}}};var Bx=class{get connectedDid(){return this._connectedDid}set connectedDid(e){this._connectedDid=e}constructor(e){this.agent=e.agent,this._connectedDid=e.connectedDid,this.delegateDid=e.delegateDid,this.permissionsApi=new Xn({agent:this.agent})}get isDelegate(){return this.delegateDid!==void 0}get permissions(){return{request:async e=>{let{message:r}=await this.permissionsApi.createRequest({...e,author:this.delegateDid??this.connectedDid}),n={connectedDid:this.delegateDid??this.connectedDid,agent:this.agent,message:r};return Iv.parse(n)},grant:async e=>{let{message:r}=await this.permissionsApi.createGrant({...e,author:this.delegateDid??this.connectedDid}),n={connectedDid:this.delegateDid??this.connectedDid,agent:this.agent,message:r};return dh.parse(n)},queryRequests:async(e={})=>{let{from:r,...n}=e,i=await this.permissionsApi.fetchRequests({...n,author:this.delegateDid??this.connectedDid,target:r??this.delegateDid??this.connectedDid,remote:r!==void 0}),a=[];for(let s of i){let o={connectedDid:this.delegateDid??this.connectedDid,agent:this.agent,message:s.message};a.push(Iv.parse(o))}return a},queryGrants:async(e={})=>{let{from:r,...n}=e,i=r!==void 0,a=this.delegateDid??this.connectedDid,s=r??this.delegateDid??this.connectedDid,o=await this.permissionsApi.fetchGrants({...n,author:a,target:s,remote:i}),c=[];for(let l of o){let d={connectedDid:this.delegateDid??this.connectedDid,agent:this.agent,message:l.message};c.push(dh.parse(d))}return c}}}get protocols(){return{configure:async e=>{let{encryption:r,...n}=e,i={author:this.connectedDid,messageParams:n,messageType:Se.ProtocolsConfigure,target:this.connectedDid,encryption:r};if(this.delegateDid){let{message:d}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n.definition.protocol,delegate:!0,cached:!0,messageType:i.messageType});i.messageParams={...i.messageParams,delegatedGrant:d},i.granteeDid=this.delegateDid}let a=await this.agent.processDwnRequest(i),{message:s,messageCid:o,reply:{status:c}}=a,l={status:c};if(c.code<300){let d={author:this.connectedDid,messageCid:o};l.protocol=new Av(this.agent,s,d)}return l},query:async e=>{let{from:r,...n}=e,i={author:this.connectedDid,messageParams:n,messageType:Se.ProtocolsQuery,target:r||this.connectedDid};if(this.delegateDid)try{let{grant:{id:d}}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n.filter.protocol,cached:!0,messageType:i.messageType});i.messageParams={...i.messageParams,permissionGrantId:d},i.granteeDid=this.delegateDid}catch{i.author=this.delegateDid}let a;r?a=await this.agent.sendDwnRequest(i):a=await this.agent.processDwnRequest(i);let s=a.reply,{entries:o=[],status:c}=s;return{protocols:o.map(d=>{let u={author:this.connectedDid};return new Av(this.agent,d,u)}),status:c}}}}get records(){return{delete:async e=>{let{from:r,protocol:n,...i}=e,a={author:this.connectedDid,messageParams:i,messageType:Se.RecordsDelete,target:r||this.connectedDid};if(this.delegateDid){let{message:c}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n,delegate:!0,cached:!0,messageType:a.messageType});a.messageParams={...a.messageParams,delegatedGrant:c},a.granteeDid=this.delegateDid}let s;r?s=await this.agent.sendDwnRequest(a):s=await this.agent.processDwnRequest(a);let{reply:{status:o}}=s;return{status:o}},query:async e=>{let{from:r,encryption:n,...i}=e,a={author:this.connectedDid,messageParams:i,messageType:Se.RecordsQuery,target:r||this.connectedDid,encryption:n};if(this.delegateDid)try{let{message:f}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:i.filter?.protocol,delegate:!0,cached:!0,messageType:a.messageType});a.messageParams={...a.messageParams,delegatedGrant:f},a.granteeDid=this.delegateDid}catch{a.author=this.delegateDid}let s;r?s=await this.agent.sendDwnRequest(a):s=await this.agent.processDwnRequest(a);let o=s.reply,{entries:c=[],status:l,cursor:d}=o;return{records:c.map(f=>{let p={author:Jo(f),connectedDid:this.connectedDid,remoteOrigin:r,delegateDid:this.delegateDid,protocolRole:a.messageParams.protocolRole,...f};return new zd(this.agent,p,this.permissionsApi)}),status:l,cursor:d}},read:async e=>{let{from:r,protocol:n,encryption:i,...a}=e,s={author:this.connectedDid,messageParams:a,messageType:Se.RecordsRead,target:r||this.connectedDid,encryption:i};if(this.delegateDid)try{let{message:u}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n,delegate:!0,cached:!0,messageType:s.messageType});s.messageParams={...s.messageParams,delegatedGrant:u},s.granteeDid=this.delegateDid}catch{s.author=this.delegateDid}let o;r?o=await this.agent.sendDwnRequest(s):o=await this.agent.processDwnRequest(s);let{reply:{entry:c,status:l}}=o,d;if(200<=l.code&&l.code<=299){let u={author:Jo(c.recordsWrite),connectedDid:this.connectedDid,remoteOrigin:r,delegateDid:this.delegateDid,data:c.data,initialWrite:c.initialWrite,...c.recordsWrite};d=new zd(this.agent,u,this.permissionsApi)}return{record:d,status:l}},subscribe:async e=>{let{from:r,...n}=e,i,a=r,s=n.protocolRole,o=m=>{if(m.type==="eose"){i?.handleLifecycleEvent("eose");return}if(m.type==="disconnected"){i?.handleLifecycleEvent("disconnected");return}if(m.type==="reconnected"){i?.handleLifecycleEvent("reconnected");return}if(m.type==="reconnecting"){i?.handleLifecycleEvent("reconnecting",{attempt:m.attempt});return}let{message:g,initialWrite:_}=m.event,w=new zd(this.agent,{...g,author:Jo(g),connectedDid:this.connectedDid,remoteOrigin:a,initialWrite:_,protocolRole:s,delegateDid:this.delegateDid},this.permissionsApi);i?.handleEvent(w)},c={author:this.connectedDid,messageParams:n,messageType:Se.RecordsSubscribe,target:r||this.connectedDid,subscriptionHandler:o};if(this.delegateDid)try{let{message:m}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n.filter?.protocol,delegate:!0,cached:!0,messageType:c.messageType});c.messageParams={...c.messageParams,delegatedGrant:m},c.granteeDid=this.delegateDid}catch{c.author=this.delegateDid}let l;r?l=await this.agent.sendDwnRequest(c):l=await this.agent.processDwnRequest(c);let d=l.reply,{status:u,subscription:f,entries:p=[],cursor:h}=d;return f&&(i=new $x({agent:this.agent,connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocolRole:s,remoteOrigin:a,permissionsApi:this.permissionsApi,initialEntries:p,cursor:h,subscription:f})),{status:u,liveQuery:i}},write:async e=>{let{data:r,store:n,encryption:i,...a}=e,{dataBlob:s,dataFormat:o}=Dv(r,a.dataFormat),c={...a,dataFormat:o},l={store:n,messageType:Se.RecordsWrite,messageParams:c,author:this.connectedDid,target:this.connectedDid,dataStream:s,encryption:i};if(this.delegateDid){let{message:h}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:c.protocol,delegate:!0,cached:!0,messageType:l.messageType});l.messageParams={...l.messageParams,delegatedGrant:h},l.granteeDid=this.delegateDid}let d=await this.agent.processDwnRequest(l),{message:u,reply:{status:f}}=d,p;if(200<=f.code&&f.code<=299){let h={author:this.connectedDid,connectedDid:this.connectedDid,encodedData:s,delegateDid:this.delegateDid,...u};p=new zd(this.agent,h,this.permissionsApi)}return{record:p,status:f}}}}};y();y();y();var Nc=class t{constructor(e){this._record=e}get rawRecord(){return this._record}get data(){let e=this._record.data;return{blob:()=>e.blob(),bytes:()=>e.bytes(),json:()=>e.json(),text:()=>e.text(),stream:()=>e.stream(),then:e.then.bind(e),catch:e.catch.bind(e)}}async update(e){let{status:r,record:n}=await this._record.update(e);return{status:r,record:new t(n)}}async delete(e){let{status:r,record:n}=await this._record.delete(e);return{status:r,record:new t(n)}}async store(e=!1){return this._record.store(e)}async import(e=!0){return this._record.import(e)}async send(e){return this._record.send(e)}toJSON(){return this._record.toJSON()}toString(){return this._record.toString()}async paginationCursor(e){return this._record.paginationCursor(e)}get id(){return this._record.id}get contextId(){return this._record.contextId}get dateCreated(){return this._record.dateCreated}get parentId(){return this._record.parentId}get protocol(){return this._record.protocol}get protocolPath(){return this._record.protocolPath}get recipient(){return this._record.recipient}get schema(){return this._record.schema}get dataFormat(){return this._record.dataFormat}get dataCid(){return this._record.dataCid}get dataSize(){return this._record.dataSize}get datePublished(){return this._record.datePublished}get published(){return this._record.published}get tags(){return this._record.tags}get author(){return this._record.author}get creator(){return this._record.creator}get timestamp(){return this._record.timestamp}get encryption(){return this._record.encryption}get authorization(){return this._record.authorization}get attestation(){return this._record.attestation}get protocolRole(){return this._record.protocolRole}get deleted(){return this._record.deleted}get initialWrite(){return this._record.initialWrite}get rawMessage(){return this._record.rawMessage}};var jx=class{constructor(e){this._liveQuery=e}get rawLiveQuery(){return this._liveQuery}get records(){return this._typedRecords||(this._typedRecords=this._liveQuery.records.map(e=>new Nc(e))),this._typedRecords}get cursor(){return this._liveQuery.cursor}get isConnected(){return this._liveQuery.isConnected}on(e,r){return e==="disconnected"?this._liveQuery.on("disconnected",r):e==="reconnected"?this._liveQuery.on("reconnected",r):e==="eose"?this._liveQuery.on("eose",r):e==="reconnecting"?this._liveQuery.on("reconnecting",r):e==="change"?this._liveQuery.on("change",n=>{r({type:n.type,record:new Nc(n.record)})}):this._liveQuery.on(e,n=>{r(new Nc(n))})}async close(){return this._liveQuery.close()}};var Nx=class{constructor(e,r){this._configured=!1;this._ensureReadyPromise=null;this._dwn=e,this._definition=r.definition,this._validPaths=j7(this._definition.structure),this._hasEncryptedTypes=Object.values(this._definition.types).some(n=>n.encryptionRequired===!0)}get protocol(){return this._definition.protocol}get definition(){return this._definition}async configure(e){let{protocols:r}=await this._dwn.protocols.query({filter:{protocol:this._definition.protocol}});if(r.length>0){let a=r[0];if(B7(a.definition,this._definition))return this._configured=!0,{status:{code:200,detail:"OK"},protocol:a}}if(this._dwn.isDelegate&&this._hasEncryptedTypes)throw new Error(`TypedEnbox: Protocol '${this._definition.protocol}' requires encryption but is not installed or has changed. In delegate mode, encrypted protocols must be installed by the wallet during the connect flow. Ensure the sync engine has completed its initial sync before performing record operations.`);let n=!this._dwn.isDelegate&&this._hasEncryptedTypes,i=await this._dwn.protocols.configure({definition:this._definition,encryption:e?.encryption??(n||void 0)});return i.status.code===202&&(this._configured=!0),i}get isConfigured(){return this._configured}async subscribe(e){await this._autoConfigureOnce();let{liveQuery:r}=await this._dwn.records.subscribe({from:e?.from,filter:{protocol:this._definition.protocol}});return r}_assertValidPath(e){if(!this._validPaths.has(e))throw new Error(`TypedEnbox: invalid protocol path '${e}'. Valid paths are: ${[...this._validPaths].join(", ")}.`)}async _ensureReady(e){if(this._configured){this._assertValidPath(e);return}this._ensureReadyPromise===null&&(this._ensureReadyPromise=this._autoConfigureOnce()),await this._ensureReadyPromise,this._assertValidPath(e)}async _autoConfigureOnce(){let{protocols:e}=await this._dwn.protocols.query({filter:{protocol:this._definition.protocol}});if(e.length>0){let i=e[0];if(B7(i.definition,this._definition)){this._configured=!0;return}console.warn(`TypedEnbox: installed protocol '${this._definition.protocol}' differs from the provided definition. Call configure() to update it.`),this._configured=!0;return}if(this._dwn.isDelegate){if(await this._autoConfigureDelegateProtocol())return;if(this._hasEncryptedTypes)throw new Error(`TypedEnbox: delegate cannot install protocol '${this._definition.protocol}' because it contains types with encryptionRequired but the owner's remote protocol definition (with $encryption keys) could not be fetched. Ensure the owner has installed the protocol on their DWN and that the delegate has network access to the owner's DWN endpoints.`);(await this._dwn.protocols.configure({definition:this._definition})).status.code===202&&(this._configured=!0);return}let r=Object.values(this._definition.types).some(i=>i?.encryptionRequired===!0);(await this._dwn.protocols.configure({definition:this._definition,encryption:r||void 0})).status.code===202&&(this._configured=!0)}async _autoConfigureDelegateProtocol(){try{let{protocols:e}=await this._dwn.protocols.query({from:this._dwn.connectedDid,filter:{protocol:this._definition.protocol}});if(e.length===0)return!1;let r=e[0].definition;return(await this._dwn.protocols.configure({definition:r})).status.code===202?(this._configured=!0,!0):!1}catch{return!1}}get records(){if(this._records!==void 0)return this._records;let e={create:async(r,n)=>{let i=Rv(r);await this._ensureReady(i);let a=Mx(i),s=this._definition.types[a],o=s?.encryptionRequired===!0?!0:void 0,{status:c,record:l}=await this._dwn.records.write({data:n.data,store:n.store,encryption:n.encryption??o,parentContextId:n.parentContextId,published:n.published,datePublished:n.datePublished,recipient:n.recipient,protocolRole:n.protocolRole,tags:n.tags,protocol:this._definition.protocol,protocolPath:i,...s?.schema===void 0?{}:{schema:s.schema},dataFormat:n.dataFormat??s?.dataFormats?.[0]});return{status:c,record:l?new Nc(l):void 0}},query:async(r,n)=>{let i=Rv(r);await this._ensureReady(i);let a=Mx(i),s=this._definition.types[a],o=xR(n?.filter),c=s?.encryptionRequired===!0?!0:void 0,{status:l,records:d,cursor:u}=await this._dwn.records.query({from:n?.from,encryption:n?.encryption??c,filter:{...o,protocol:this._definition.protocol,protocolPath:i,...s?.schema===void 0?{}:{schema:s.schema}},dateSort:n?.dateSort,pagination:n?.pagination,protocolRole:n?.protocolRole});return{status:l,records:d.map(f=>new Nc(f)),cursor:u}},read:async(r,n)=>{let i=Rv(r);await this._ensureReady(i);let a=Mx(i),s=this._definition.types[a],o=xR(n.filter),c=s?.encryptionRequired===!0?!0:void 0,{status:l,record:d}=await this._dwn.records.read({from:n.from,encryption:n.encryption??c,protocol:this._definition.protocol,filter:{...o,protocol:this._definition.protocol,protocolPath:i,...s?.schema===void 0?{}:{schema:s.schema}}});return{status:l,record:d?new Nc(d):void 0}},delete:async(r,n)=>(await this._ensureReady(Rv(r)),this._dwn.records.delete({from:n.from,protocol:this._definition.protocol,recordId:n.recordId})),subscribe:async(r,n)=>{let i=Rv(r);await this._ensureReady(i);let a=Mx(i),s=this._definition.types[a],o=xR(n?.filter),{status:c,liveQuery:l}=await this._dwn.records.subscribe({from:n?.from,filter:{...o,protocol:this._definition.protocol,protocolPath:i,...s?.schema===void 0?{}:{schema:s.schema}},protocolRole:n?.protocolRole});return{status:c,liveQuery:l?new jx(l):void 0}}};return this._records=e,e}};function xR(t){if(!t)return;let{parentContextId:e,...r}=t;return e!==void 0&&r.parentId===void 0&&(r.parentId=e),r}function B7(t,e){return Kx(Ux(t))===Kx(Ux(e))}function Ux(t){if(t==null||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>Ux(r));let e={};for(let[r,n]of Object.entries(t))r!=="$encryption"&&(e[r]=Ux(n));return e}function Rv(t){let e=0;for(;e<t.length&&t.codePointAt(e)===47;)e++;let r=t.length;for(;r>e&&t.codePointAt(r-1)===47;)r--;return t.slice(e,r)}function Mx(t){let e=t.split("/");return e[e.length-1]}function j7(t,e=""){let r=new Set;for(let n of Object.keys(t)){if(n.startsWith("$"))continue;let i=e?`${e}/${n}`:n;r.add(i);let a=t[n];if(a!==null&&typeof a=="object")for(let s of j7(a,i))r.add(s)}return r}function Kx(t){return t==null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?"["+t.map(n=>Kx(n)).join(",")+"]":"{"+Object.keys(t).sort((n,i)=>n.localeCompare(i)).map(n=>JSON.stringify(n)+":"+Kx(t[n])).join(",")+"}"}y();var Lx=class{constructor(e){this.agent=e.agent,this.connectedDid=e.connectedDid}async create(){throw new Error("Not implemented.")}};var M7=class t{constructor({agent:e,connectedDid:r,delegateDid:n}){this._typedInstances=new Map;this.agent=e,this.did=new Rx({agent:e,connectedDid:r}),this._dwn=new Bx({agent:e,connectedDid:r,delegateDid:n}),this.vc=new Lx({agent:e,connectedDid:r})}using(e){let r=e.definition.protocol,n=this._typedInstances.get(r);if(n)return n;let i=new Nx(this._dwn,e);return this._typedInstances.set(r,i),i}async disconnect(e){"sync"in this.agent&&typeof this.agent.sync?.stopSync=="function"&&await this.agent.sync.stopSync(e),this._typedInstances.clear()}static anonymous(e){let r=new uv({didResolvers:e?.didResolvers??[su,eh,VP,UA],cache:new JP}),n=new Mm,i=new bx({didResolver:r,rpcClient:n});return{dwn:new Cx(i)}}static connect(e){if("session"in e){let{session:r}=e;return new t({agent:r.agent,connectedDid:r.did,delegateDid:r.delegateDid})}return new t(e)}};y();y();y();function N7(t){return t.code===400&&t.detail.includes("record limit")}function ipe(t,e){let r=e.split("/"),n=t.structure;for(let a of r){if(!n||typeof n!="object")return!1;n=n[a]}if(!n||typeof n!="object")return!1;let i=n.$recordLimit;return i!==void 0&&typeof i=="object"&&i!==null&&i.max===1}function ope(t,e){let r=e.split("/"),n=t.structure;for(let i of r){if(!n||typeof n!="object")return[];n=n[i]}return!n||typeof n!="object"?[]:Object.keys(n).filter(i=>!i.startsWith("$"))}function spe(t,e){return{async create(r){let{status:n,record:i}=await t.records.create(e,r);return{status:n,record:i}},async query(r){let{status:n,records:i,cursor:a}=await t.records.query(e,r);return{status:n,records:i,cursor:a}},async get(r){let{record:n}=await t.records.read(e,{filter:{recordId:r}});return n},async delete(r){return t.records.delete(e,{recordId:r})},async subscribe(r){let{liveQuery:n}=await t.records.subscribe(e,r);return n}}}function ape(t,e){return{async set(r){let n=await t.records.create(e,r);if(N7(n.status)){let{records:i}=await t.records.query(e);if(i.length>0){let{status:a,record:s}=await i[0].update({data:r.data,...r.tags===void 0?{}:{tags:r.tags}});return{status:a,record:s}}}return{status:n.status,record:n.record}},async get(){let{records:r}=await t.records.query(e);return r.length>0?r[0]:void 0},async delete(r){return t.records.delete(e,{recordId:r})}}}function cpe(t,e){return{async create(r,n){let{status:i,record:a}=await t.records.create(e,{...n,parentContextId:r});return{status:i,record:a}},async query(r,n){let{status:i,records:a,cursor:s}=await t.records.query(e,{...n,filter:{...n?.filter,contextId:r}});return{status:i,records:a,cursor:s}},async get(r){let{record:n}=await t.records.read(e,{filter:{recordId:r}});return n},async delete(r){return t.records.delete(e,{recordId:r})},async subscribe(r,n){let{liveQuery:i}=await t.records.subscribe(e,{...n,filter:{...n?.filter,contextId:r}});return i}}}function dpe(t,e){return{async set(r,n){let i=await t.records.create(e,{...n,parentContextId:r});if(N7(i.status)){let{records:a}=await t.records.query(e,{filter:{contextId:r}});if(a.length>0){let{status:s,record:o}=await a[0].update({data:n.data,...n.tags===void 0?{}:{tags:n.tags}});return{status:s,record:o}}}return{status:i.status,record:i.record}},async get(r){let{records:n}=await t.records.query(e,{filter:{contextId:r}});return n.length>0?n[0]:void 0},async delete(r){return t.records.delete(e,{recordId:r})}}}function U7(t,e,r,n){let i=ipe(e,r),a;n?a=i?dpe(t,r):cpe(t,r):a=i?ape(t,r):spe(t,r);let s=ope(e,r),o={};return new Proxy(a,{get(c,l){if(typeof l=="string"){if(l in c)return c[l];if(s.includes(l))return l in o||(o[l]=U7(t,e,`${r}/${l}`,!0)),o[l]}}})}function nYe(t){let e=t.definition,r=Object.keys(e.structure).filter(a=>!a.startsWith("$")),n={};return new Proxy({},{get(a,s){if(typeof s=="string"){if(s==="configure")return async o=>await t.configure(o);if(r.includes(s))return s in n||(n[s]=U7(t,e,s,!1)),n[s]}}})}y();export{Rx as DidApi,Cx as DwnReaderApi,M7 as Enbox,$x as LiveQuery,dh as PermissionGrant,Ox as PermissionGrantRevocation,Iv as PermissionRequest,Av as Protocol,kv as ReadOnlyRecord,zd as Record,PR as RecordChangeEvent,Nx as TypedEnbox,jx as TypedLiveQuery,Nc as TypedRecord,Lx as VcApi,O7 as createRecordData,bpe as defineProtocol,B7 as definitionsEqual,C7 as isOk,nYe as repository,$7 as utils};
2079
+ `,e+="}",e}async paginationCursor(e){return hR(Se.RecordsWrite,this.rawMessage)?u7(this.rawMessage,e):void 0}async update({timestamp:e,data:r,encryption:n,protocolRole:i,store:a=!0,...s}){if(this.deleted)throw new Error("Record: Cannot revive a deleted record.");let o=n??this._encryption!==void 0,{parentId:c,...l}=this._recordsWriteDescriptor,d=c?this._contextId.split("/").slice(0,-1).join("/"):void 0,u={...l,...s,parentContextId:d,protocolRole:i??this._protocolRole,messageTimestamp:e,recordId:this._recordId};(M3(u.tags)||u.tags===null)&&delete u.tags;let f;r!==void 0&&(delete u.dataCid,delete u.dataSize,{dataBlob:f}=Dv(r,u.dataFormat));let p=new Set(["data","dataCid","dataFormat","dataSize","datePublished","messageTimestamp","published","tags"]);lu.verifyPermittedMutation(Object.keys(s),p),s.published===!1&&u.datePublished!==void 0&&delete u.datePublished;let h={author:this._connectedDid,dataStream:f,messageParams:{...u},messageType:Se.RecordsWrite,target:this._connectedDid,store:a,encryption:o||void 0};await this.applyDelegateGrant(h);let m=await this._agent.processDwnRequest(h),{message:g,reply:{status:_}}=m;if(!(200<=_.code&&_.code<=299))return{status:_,record:this};let w=this._initialWrite??{...this.rawMessage},E=new lu(this._agent,{author:this._author,connectedDid:this._connectedDid,delegateDid:this._delegateDid,remoteOrigin:this._remoteOrigin,protocolRole:i??this._protocolRole,initialWrite:w,encodedData:r===void 0?this._encodedData:f,...g},this._permissionsApi),k=g;return this._descriptor=k.descriptor,this._attestation=k.attestation,this._authorization=k.authorization,this._encryption=k.encryption,this._contextId=k.contextId,this._initialWrite=w,this._protocolRole=i??this._protocolRole,this._encodedData=r===void 0?this._encodedData:f,this._readableStream=void 0,this._rawMessageDirty=!0,{status:_,record:E}}async delete(e){let{store:r=!0,signAsOwner:n,timestamp:i,prune:a=!1}=e||{},s=n&&this._delegateDid===void 0,o=n&&this._delegateDid!==void 0;if(this.deleted&&!this._initialWrite)throw new Error("Record: Record is in an invalid state, initial write is missing.");this._initialWrite||(this._initialWrite={...this.rawMessage}),await this.processInitialWriteIfNeeded({store:r,signAsOwner:n});let c={messageType:Se.RecordsDelete,author:this._connectedDid,target:this._connectedDid,signAsOwner:s,signAsOwnerDelegate:o,store:r},l=e?.protocolRole?l7(this.rawMessage)!==e.protocolRole:!1;this.deleted&&!l?c.rawMessage=this.rawMessage:c.messageParams={prune:a,recordId:this._recordId,messageTimestamp:i,protocolRole:e?.protocolRole??this._protocolRole},await this.applyDelegateGrant(c);let d=await this._agent.processDwnRequest(c),{message:u,reply:{status:f}}=d;if(f.code!==202)return{status:f,record:this};let p=this._initialWrite,h=new lu(this._agent,{author:Jo(u),connectedDid:this._connectedDid,delegateDid:this._delegateDid,remoteOrigin:this._remoteOrigin,protocolRole:e?.protocolRole??this._protocolRole,initialWrite:p,...u},this._permissionsApi),m=u;return this._descriptor=m.descriptor,this._authorization=m.authorization,this._protocolRole=e?.protocolRole??this._protocolRole,this._encodedData=void 0,this._readableStream=void 0,this._rawMessageDirty=!0,{status:f,record:h}}async processInitialWriteIfNeeded({store:e,signAsOwner:r}){if(this.initialWrite&&(r&&!this._initialWriteSigned||e&&!this._initialWriteStored)){let n=r&&this._delegateDid===void 0,i=r&&this._delegateDid!==void 0,a={messageType:Se.RecordsWrite,rawMessage:this.initialWrite,author:this._connectedDid,target:this._connectedDid,signAsOwner:n,signAsOwnerDelegate:i,store:e};await this.applyDelegateGrant(a);let s=await this._agent.processDwnRequest(a),{message:o,reply:{status:c}}=s,l=o;200<=c.code&&c.code<=299&&(e&&(this._initialWriteStored=!0),r&&(this._initialWriteSigned=!0,this.initialWrite.authorization=l.authorization))}}async processRecord({store:e,signAsOwner:r}){let n=r&&this._delegateDid===void 0,i=r&&this._delegateDid!==void 0;await this.processInitialWriteIfNeeded({store:e,signAsOwner:r});let a;this.deleted?a={messageType:Se.RecordsDelete,rawMessage:this.rawMessage,author:this._connectedDid,target:this._connectedDid,signAsOwner:n,signAsOwnerDelegate:i,store:e}:a={messageType:Se.RecordsWrite,rawMessage:this.rawMessage,author:this._connectedDid,target:this._connectedDid,dataStream:await this.data.blob(),signAsOwner:n,signAsOwnerDelegate:i,store:e},await this.applyDelegateGrant(a);let s=await this._agent.processDwnRequest(a),{message:o,reply:{status:c}}=s,l=o;return 200<=c.code&&c.code<=299&&r&&(this._authorization=l.authorization,this._rawMessageDirty=!0),{status:c}}async readRecordData({target:e,isRemote:r}){let n={author:this._connectedDid,messageParams:{filter:{recordId:this.id},protocolRole:this._protocolRole},messageType:Se.RecordsRead,target:e,...this._encryption?{encryption:!0}:{}};if(this._delegateDid)try{await this.applyDelegateGrant(n)}catch{n.author=this._delegateDid}let i=r?this._agent.sendDwnRequest(n):this._agent.processDwnRequest(n);try{let{reply:{status:a,entry:s}}=await i;if(a.code!==200)throw new Error(`${a.code}: ${a.detail}`);return s.data}catch(a){throw new Error(`Error encountered while attempting to read data: ${a.message}`)}}async applyDelegateGrant(e){if(!this._delegateDid)return;let{message:r}=await this._permissionsApi.getPermissionForRequest({connectedDid:this._connectedDid,delegateDid:this._delegateDid,protocol:this.protocol,delegate:!0,cached:!0,messageType:e.messageType});e.messageParams={...e.messageParams,delegatedGrant:r},e.granteeDid=this._delegateDid}static verifyPermittedMutation(e,r){for(let n of e)if(!r.has(n))throw new Error(`${n} is an immutable property. Its value cannot be changed.`)}isRecordsDeleteDescriptor(e){return e.interface+e.method===Se.RecordsDelete}};lu._sendCache=Tv;var zd=lu;var PR=class extends CustomEvent{constructor(e){super(e.type,{detail:e})}},$x=class extends EventTarget{constructor(r){super();this._closed=!1;this._connected=!0;let{agent:n,connectedDid:i,cursor:a,delegateDid:s,protocolRole:o,remoteOrigin:c,permissionsApi:l,initialEntries:d,subscription:u}=r;this._subscription=u,this.cursor=a,this.records=d.map(f=>new zd(n,{author:Jo(f),connectedDid:i,remoteOrigin:c,delegateDid:s,protocolRole:o,...f},l)),this._knownRecords=new Map;for(let f of this.records)this._knownRecords.set(f.id,f.timestamp)}get isConnected(){return this._connected}handleEvent(r){if(this._closed)return;let n;if(r.deleted)n="delete",this._knownRecords.delete(r.id);else{let a=this._knownRecords.get(r.id);if(a===void 0)n="create";else{if(r.timestamp<=a)return;n="update"}this._knownRecords.set(r.id,r.timestamp)}let i={type:n,record:r};this.dispatchEvent(new PR(i)),this.dispatchEvent(new CustomEvent("change",{detail:i}))}handleLifecycleEvent(r,n){this._closed||(r==="disconnected"?this._connected=!1:r==="reconnected"&&(this._connected=!0),this.dispatchEvent(new CustomEvent(r,{detail:n})))}on(r,n){let i=a=>{let s=a.detail;r==="change"?n(s):r==="create"||r==="update"||r==="delete"?n(s.record):r==="reconnecting"?n(s):n()};return this.addEventListener(r,i),()=>{this.removeEventListener(r,i)}}async close(){this._closed||(this._closed=!0,await this._subscription.close())}};y();jt();y();jt();var Ox=class t{constructor(e,r){this._permissions=e,this._connectedDid=r.connectedDid,this._message=r.message}get author(){return Jo(this._message)}static async parse({connectedDid:e,agent:r,message:n}){let i=new Xn({agent:r});return new t(i,{connectedDid:e,message:n})}get agent(){return this._permissions.agent}get rawMessage(){return this._message}async send(e){e??=this._connectedDid;let{encodedData:r,...n}=this._message,i=new Blob([Me.base64Url(r).toUint8Array()]),a={messageType:Se.RecordsWrite,author:this._connectedDid,target:e,dataStream:i,rawMessage:n},{reply:s}=await this.agent.sendDwnRequest(a);return s}async store(e){let{encodedData:r,...n}=this.rawMessage,i=new Blob([Me.base64Url(r).toUint8Array()]),{reply:a,message:s}=await this.agent.processDwnRequest({author:this._connectedDid,target:this._connectedDid,messageType:Se.RecordsWrite,signAsOwner:e,rawMessage:n,dataStream:i});return this._message={...s,encodedData:r},{status:a.status}}};var dh=class t{constructor({api:e,connectedDid:r,message:n,grant:i}){this._permissions=e,this._connectedDid=r,this._message=n,this._grant=i}static parse(e){let r=sr.parse(e.message),n=new Xn({agent:e.agent});return new t({...e,grant:r,api:n})}get agent(){return this._permissions.agent}get id(){return this._grant.id}get grantor(){return this._grant.grantor}get grantee(){return this._grant.grantee}get dateGranted(){return this._grant.dateGranted}get description(){return this._grant.description}get requestId(){return this._grant.requestId}get dateExpires(){return this._grant.dateExpires}get delegated(){return this._grant.delegated}get scope(){return this._grant.scope}get conditions(){return this._grant.conditions}get rawMessage(){return this._message}async send(e){e??=this._connectedDid;let{encodedData:r,...n}=this._message,i=new Blob([Me.base64Url(r).toUint8Array()]),a={messageType:Se.RecordsWrite,author:this._connectedDid,target:e,dataStream:i,rawMessage:n},{reply:s}=await this.agent.sendDwnRequest(a);return s}async store(e=!1){let{encodedData:r,...n}=this.rawMessage,i=new Blob([Me.base64Url(r).toUint8Array()]),{reply:a,message:s}=await this.agent.processDwnRequest({store:!0,author:this._connectedDid,target:this._connectedDid,messageType:Se.RecordsWrite,signAsOwner:e,rawMessage:n,dataStream:i});return this._message={...s,encodedData:r},{status:a.status}}async import(e=!1){let{encodedData:r,...n}=this.rawMessage,i=new Blob([Me.base64Url(r).toUint8Array()]),{reply:a,message:s}=await this.agent.processDwnRequest({store:e,author:this._connectedDid,target:this._connectedDid,messageType:Se.RecordsWrite,signAsOwner:!0,rawMessage:n,dataStream:i});return this._message={...s,encodedData:r},{status:a.status}}async revoke(e=!0){let r=await this._permissions.createRevocation({store:e,author:this._connectedDid,grant:this._grant});return Ox.parse({connectedDid:this._connectedDid,agent:this.agent,message:r.message})}isRevoked(e=!1){return this._permissions.isGrantRevoked({author:this._connectedDid,target:this.grantor,grantRecordId:this.id,remote:e})}toJSON(){return{id:this.id,grantor:this.grantor,grantee:this.grantee,dateGranted:this.dateGranted,description:this.description,requestId:this.requestId,dateExpires:this.dateExpires,delegated:this.delegated,scope:this.scope,conditions:this.conditions}}};y();jt();var Iv=class t{constructor({api:e,connectedDid:r,message:n,request:i}){this._permissions=e,this._connectedDid=r,this._request=i,this._message=n}static parse({connectedDid:e,agent:r,message:n}){let i=Oa.parse(n),a=new Xn({agent:r});return new t({api:a,connectedDid:e,message:n,request:i})}get agent(){return this._permissions.agent}get id(){return this._request.id}get requester(){return this._request.requester}get description(){return this._request.description}get delegated(){return this._request.delegated}get scope(){return this._request.scope}get conditions(){return this._request.conditions}get rawMessage(){return this._message}async send(e){e??=this._connectedDid;let{encodedData:r,...n}=this._message,i=new Blob([Me.base64Url(r).toUint8Array()]),a={messageType:Se.RecordsWrite,author:this._connectedDid,target:e,dataStream:i,rawMessage:n},{reply:s}=await this.agent.sendDwnRequest(a);return s}async store(){let{encodedData:e,...r}=this.rawMessage,n=new Blob([Me.base64Url(e).toUint8Array()]),{reply:i,message:a}=await this.agent.processDwnRequest({author:this._connectedDid,target:this._connectedDid,messageType:Se.RecordsWrite,rawMessage:r,dataStream:n});return this._message={...a,encodedData:e},{status:i.status}}async grant(e,r=!0){let{message:n}=await this._permissions.createGrant({requestId:this.id,grantedTo:this.requester,scope:this.scope,delegated:this.delegated,author:this._connectedDid,store:r,dateExpires:e});return dh.parse({connectedDid:this._connectedDid,agent:this.agent,message:n})}toJSON(){return this._request}};y();var Av=class{constructor(e,r,n){this._agent=e,this._metadata=n,this._protocolsConfigureMessage=r}get definition(){return this._protocolsConfigureMessage.descriptor.definition}toJSON(){return this._protocolsConfigureMessage}async send(e){let{reply:r}=await this._agent.sendDwnRequest({author:this._metadata.author,messageCid:this._metadata.messageCid,messageType:Se.ProtocolsConfigure,target:e});return{status:r.status}}};var Bx=class{get connectedDid(){return this._connectedDid}set connectedDid(e){this._connectedDid=e}constructor(e){this.agent=e.agent,this._connectedDid=e.connectedDid,this.delegateDid=e.delegateDid,this.permissionsApi=new Xn({agent:this.agent})}get isDelegate(){return this.delegateDid!==void 0}get permissions(){return{request:async e=>{let{message:r}=await this.permissionsApi.createRequest({...e,author:this.delegateDid??this.connectedDid}),n={connectedDid:this.delegateDid??this.connectedDid,agent:this.agent,message:r};return Iv.parse(n)},grant:async e=>{let{message:r}=await this.permissionsApi.createGrant({...e,author:this.delegateDid??this.connectedDid}),n={connectedDid:this.delegateDid??this.connectedDid,agent:this.agent,message:r};return dh.parse(n)},queryRequests:async(e={})=>{let{from:r,...n}=e,i=await this.permissionsApi.fetchRequests({...n,author:this.delegateDid??this.connectedDid,target:r??this.delegateDid??this.connectedDid,remote:r!==void 0}),a=[];for(let s of i){let o={connectedDid:this.delegateDid??this.connectedDid,agent:this.agent,message:s.message};a.push(Iv.parse(o))}return a},queryGrants:async(e={})=>{let{from:r,...n}=e,i=r!==void 0,a=this.delegateDid??this.connectedDid,s=r??this.delegateDid??this.connectedDid,o=await this.permissionsApi.fetchGrants({...n,author:a,target:s,remote:i}),c=[];for(let l of o){let d={connectedDid:this.delegateDid??this.connectedDid,agent:this.agent,message:l.message};c.push(dh.parse(d))}return c}}}get protocols(){return{configure:async e=>{let{encryption:r,...n}=e,i={author:this.connectedDid,messageParams:n,messageType:Se.ProtocolsConfigure,target:this.connectedDid,encryption:r};if(this.delegateDid){let{message:d}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n.definition.protocol,delegate:!0,cached:!0,messageType:i.messageType});i.messageParams={...i.messageParams,delegatedGrant:d},i.granteeDid=this.delegateDid}let a=await this.agent.processDwnRequest(i),{message:s,messageCid:o,reply:{status:c}}=a,l={status:c};if(c.code<300){let d={author:this.connectedDid,messageCid:o};l.protocol=new Av(this.agent,s,d)}return l},query:async e=>{let{from:r,...n}=e,i={author:this.connectedDid,messageParams:n,messageType:Se.ProtocolsQuery,target:r||this.connectedDid};if(this.delegateDid)try{let{grant:{id:d}}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n.filter.protocol,cached:!0,messageType:i.messageType});i.messageParams={...i.messageParams,permissionGrantId:d},i.granteeDid=this.delegateDid}catch{i.author=this.delegateDid}let a;r?a=await this.agent.sendDwnRequest(i):a=await this.agent.processDwnRequest(i);let s=a.reply,{entries:o=[],status:c}=s;return{protocols:o.map(d=>{let u={author:this.connectedDid};return new Av(this.agent,d,u)}),status:c}}}}get records(){return{delete:async e=>{let{from:r,protocol:n,...i}=e,a={author:this.connectedDid,messageParams:i,messageType:Se.RecordsDelete,target:r||this.connectedDid};if(this.delegateDid){let{message:c}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n,delegate:!0,cached:!0,messageType:a.messageType});a.messageParams={...a.messageParams,delegatedGrant:c},a.granteeDid=this.delegateDid}let s;r?s=await this.agent.sendDwnRequest(a):s=await this.agent.processDwnRequest(a);let{reply:{status:o}}=s;return{status:o}},query:async e=>{let{from:r,encryption:n,...i}=e,a={author:this.connectedDid,messageParams:i,messageType:Se.RecordsQuery,target:r||this.connectedDid,encryption:n};if(this.delegateDid)try{let{message:f}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:i.filter?.protocol,delegate:!0,cached:!0,messageType:a.messageType});a.messageParams={...a.messageParams,delegatedGrant:f},a.granteeDid=this.delegateDid}catch{a.author=this.delegateDid}let s;r?s=await this.agent.sendDwnRequest(a):s=await this.agent.processDwnRequest(a);let o=s.reply,{entries:c=[],status:l,cursor:d}=o;return{records:c.map(f=>{let p={author:Jo(f),connectedDid:this.connectedDid,remoteOrigin:r,delegateDid:this.delegateDid,protocolRole:a.messageParams.protocolRole,...f};return new zd(this.agent,p,this.permissionsApi)}),status:l,cursor:d}},read:async e=>{let{from:r,protocol:n,encryption:i,...a}=e,s={author:this.connectedDid,messageParams:a,messageType:Se.RecordsRead,target:r||this.connectedDid,encryption:i};if(this.delegateDid)try{let{message:u}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n,delegate:!0,cached:!0,messageType:s.messageType});s.messageParams={...s.messageParams,delegatedGrant:u},s.granteeDid=this.delegateDid}catch{s.author=this.delegateDid}let o;r?o=await this.agent.sendDwnRequest(s):o=await this.agent.processDwnRequest(s);let{reply:{entry:c,status:l}}=o,d;if(200<=l.code&&l.code<=299){let u={author:Jo(c.recordsWrite),connectedDid:this.connectedDid,remoteOrigin:r,delegateDid:this.delegateDid,data:c.data,initialWrite:c.initialWrite,...c.recordsWrite};d=new zd(this.agent,u,this.permissionsApi)}return{record:d,status:l}},subscribe:async e=>{let{from:r,...n}=e,i,a=r,s=n.protocolRole,o=m=>{if(m.type==="eose"){i?.handleLifecycleEvent("eose");return}if(m.type==="disconnected"){i?.handleLifecycleEvent("disconnected");return}if(m.type==="reconnected"){i?.handleLifecycleEvent("reconnected");return}if(m.type==="reconnecting"){i?.handleLifecycleEvent("reconnecting",{attempt:m.attempt});return}let{message:g,initialWrite:_}=m.event,w=new zd(this.agent,{...g,author:Jo(g),connectedDid:this.connectedDid,remoteOrigin:a,initialWrite:_,protocolRole:s,delegateDid:this.delegateDid},this.permissionsApi);i?.handleEvent(w)},c={author:this.connectedDid,messageParams:n,messageType:Se.RecordsSubscribe,target:r||this.connectedDid,subscriptionHandler:o};if(this.delegateDid)try{let{message:m}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:n.filter?.protocol,delegate:!0,cached:!0,messageType:c.messageType});c.messageParams={...c.messageParams,delegatedGrant:m},c.granteeDid=this.delegateDid}catch{c.author=this.delegateDid}let l;r?l=await this.agent.sendDwnRequest(c):l=await this.agent.processDwnRequest(c);let d=l.reply,{status:u,subscription:f,entries:p=[],cursor:h}=d;return f&&(i=new $x({agent:this.agent,connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocolRole:s,remoteOrigin:a,permissionsApi:this.permissionsApi,initialEntries:p,cursor:h,subscription:f})),{status:u,liveQuery:i}},write:async e=>{let{data:r,store:n,encryption:i,...a}=e,{dataBlob:s,dataFormat:o}=Dv(r,a.dataFormat),c={...a,dataFormat:o},l={store:n,messageType:Se.RecordsWrite,messageParams:c,author:this.connectedDid,target:this.connectedDid,dataStream:s,encryption:i};if(this.delegateDid){let{message:h}=await this.permissionsApi.getPermissionForRequest({connectedDid:this.connectedDid,delegateDid:this.delegateDid,protocol:c.protocol,delegate:!0,cached:!0,messageType:l.messageType});l.messageParams={...l.messageParams,delegatedGrant:h},l.granteeDid=this.delegateDid}let d=await this.agent.processDwnRequest(l),{message:u,reply:{status:f}}=d,p;if(200<=f.code&&f.code<=299){let h={author:this.connectedDid,connectedDid:this.connectedDid,encodedData:s,delegateDid:this.delegateDid,...u};p=new zd(this.agent,h,this.permissionsApi)}return{record:p,status:f}}}}};y();y();y();var Nc=class t{constructor(e){this._record=e}get rawRecord(){return this._record}get data(){let e=this._record.data;return{blob:()=>e.blob(),bytes:()=>e.bytes(),json:()=>e.json(),text:()=>e.text(),stream:()=>e.stream(),then:e.then.bind(e),catch:e.catch.bind(e)}}async update(e){let{status:r,record:n}=await this._record.update(e);return{status:r,record:new t(n)}}async delete(e){let{status:r,record:n}=await this._record.delete(e);return{status:r,record:new t(n)}}async store(e=!1){return this._record.store(e)}async import(e=!0){return this._record.import(e)}async send(e){return this._record.send(e)}toJSON(){return this._record.toJSON()}toString(){return this._record.toString()}async paginationCursor(e){return this._record.paginationCursor(e)}get id(){return this._record.id}get contextId(){return this._record.contextId}get dateCreated(){return this._record.dateCreated}get parentId(){return this._record.parentId}get protocol(){return this._record.protocol}get protocolPath(){return this._record.protocolPath}get recipient(){return this._record.recipient}get schema(){return this._record.schema}get dataFormat(){return this._record.dataFormat}get dataCid(){return this._record.dataCid}get dataSize(){return this._record.dataSize}get datePublished(){return this._record.datePublished}get published(){return this._record.published}get tags(){return this._record.tags}get author(){return this._record.author}get creator(){return this._record.creator}get timestamp(){return this._record.timestamp}get encryption(){return this._record.encryption}get authorization(){return this._record.authorization}get attestation(){return this._record.attestation}get protocolRole(){return this._record.protocolRole}get deleted(){return this._record.deleted}get initialWrite(){return this._record.initialWrite}get rawMessage(){return this._record.rawMessage}};var jx=class{constructor(e){this._liveQuery=e}get rawLiveQuery(){return this._liveQuery}get records(){return this._typedRecords||(this._typedRecords=this._liveQuery.records.map(e=>new Nc(e))),this._typedRecords}get cursor(){return this._liveQuery.cursor}get isConnected(){return this._liveQuery.isConnected}on(e,r){return e==="disconnected"?this._liveQuery.on("disconnected",r):e==="reconnected"?this._liveQuery.on("reconnected",r):e==="eose"?this._liveQuery.on("eose",r):e==="reconnecting"?this._liveQuery.on("reconnecting",r):e==="change"?this._liveQuery.on("change",n=>{r({type:n.type,record:new Nc(n.record)})}):this._liveQuery.on(e,n=>{r(new Nc(n))})}async close(){return this._liveQuery.close()}};var Nx=class{constructor(e,r){this._configured=!1;this._ensureReadyPromise=null;this._dwn=e,this._definition=r.definition,this._validPaths=j7(this._definition.structure),this._hasEncryptedTypes=Object.values(this._definition.types).some(n=>n.encryptionRequired===!0)}get protocol(){return this._definition.protocol}get definition(){return this._definition}async configure(e){let{protocols:r}=await this._dwn.protocols.query({filter:{protocol:this._definition.protocol}});if(r.length>0){let a=r[0];if(B7(a.definition,this._definition))return this._configured=!0,{status:{code:200,detail:"OK"},protocol:a}}if(this._dwn.isDelegate&&this._hasEncryptedTypes)throw new Error(`TypedEnbox: Protocol '${this._definition.protocol}' requires encryption but is not installed or has changed. In delegate mode, encrypted protocols must be installed by the wallet during the connect flow. Ensure the sync engine has completed its initial sync before performing record operations.`);let n=!this._dwn.isDelegate&&this._hasEncryptedTypes,i=await this._dwn.protocols.configure({definition:this._definition,encryption:e?.encryption??(n||void 0)});return i.status.code===202&&(this._configured=!0),i}get isConfigured(){return this._configured}async subscribe(e){await this._autoConfigureOnce();let{liveQuery:r}=await this._dwn.records.subscribe({from:e?.from,filter:{protocol:this._definition.protocol}});return r}_assertValidPath(e){if(!this._validPaths.has(e))throw new Error(`TypedEnbox: invalid protocol path '${e}'. Valid paths are: ${[...this._validPaths].join(", ")}.`)}async _ensureReady(e){if(this._configured){this._assertValidPath(e);return}this._ensureReadyPromise===null&&(this._ensureReadyPromise=this._autoConfigureOnce()),await this._ensureReadyPromise,this._assertValidPath(e)}async _autoConfigureOnce(){let{protocols:e}=await this._dwn.protocols.query({filter:{protocol:this._definition.protocol}});if(e.length>0){let i=e[0];if(B7(i.definition,this._definition)){this._configured=!0;return}console.warn(`TypedEnbox: installed protocol '${this._definition.protocol}' differs from the provided definition. Call configure() to update it.`),this._configured=!0;return}if(this._dwn.isDelegate){if(await this._autoConfigureDelegateProtocol())return;if(this._hasEncryptedTypes)throw new Error(`TypedEnbox: delegate cannot install protocol '${this._definition.protocol}' because it contains types with encryptionRequired but the owner's remote protocol definition (with $encryption keys) could not be fetched. Ensure the owner has installed the protocol on their DWN and that the delegate has network access to the owner's DWN endpoints.`);(await this._dwn.protocols.configure({definition:this._definition})).status.code===202&&(this._configured=!0);return}let r=Object.values(this._definition.types).some(i=>i?.encryptionRequired===!0);(await this._dwn.protocols.configure({definition:this._definition,encryption:r||void 0})).status.code===202&&(this._configured=!0)}async _autoConfigureDelegateProtocol(){try{let{protocols:e}=await this._dwn.protocols.query({from:this._dwn.connectedDid,filter:{protocol:this._definition.protocol}});if(e.length===0)return!1;let r=e[0].definition;return(await this._dwn.protocols.configure({definition:r})).status.code===202?(this._configured=!0,!0):!1}catch{return!1}}get records(){if(this._records!==void 0)return this._records;let e={create:async(r,n)=>{let i=Rv(r);await this._ensureReady(i);let a=Mx(i),s=this._definition.types[a],o=s?.encryptionRequired===!0?!0:void 0,{status:c,record:l}=await this._dwn.records.write({data:n.data,store:n.store,encryption:n.encryption??o,parentContextId:n.parentContextId,published:n.published,datePublished:n.datePublished,recipient:n.recipient,protocolRole:n.protocolRole,tags:n.tags,protocol:this._definition.protocol,protocolPath:i,...s?.schema===void 0?{}:{schema:s.schema},dataFormat:n.dataFormat??s?.dataFormats?.[0]});return{status:c,record:l?new Nc(l):void 0}},query:async(r,n)=>{let i=Rv(r);await this._ensureReady(i);let a=Mx(i),s=this._definition.types[a],o=xR(n?.filter),c=s?.encryptionRequired===!0?!0:void 0,{status:l,records:d,cursor:u}=await this._dwn.records.query({from:n?.from,encryption:n?.encryption??c,filter:{...o,protocol:this._definition.protocol,protocolPath:i,...s?.schema===void 0?{}:{schema:s.schema}},dateSort:n?.dateSort,pagination:n?.pagination,protocolRole:n?.protocolRole});return{status:l,records:d.map(f=>new Nc(f)),cursor:u}},read:async(r,n)=>{let i=Rv(r);await this._ensureReady(i);let a=Mx(i),s=this._definition.types[a],o=xR(n.filter),c=s?.encryptionRequired===!0?!0:void 0,{status:l,record:d}=await this._dwn.records.read({from:n.from,encryption:n.encryption??c,protocol:this._definition.protocol,filter:{...o,protocol:this._definition.protocol,protocolPath:i,...s?.schema===void 0?{}:{schema:s.schema}}});return{status:l,record:d?new Nc(d):void 0}},delete:async(r,n)=>(await this._ensureReady(Rv(r)),this._dwn.records.delete({from:n.from,protocol:this._definition.protocol,recordId:n.recordId})),subscribe:async(r,n)=>{let i=Rv(r);await this._ensureReady(i);let a=Mx(i),s=this._definition.types[a],o=xR(n?.filter),{status:c,liveQuery:l}=await this._dwn.records.subscribe({from:n?.from,filter:{...o,protocol:this._definition.protocol,protocolPath:i,...s?.schema===void 0?{}:{schema:s.schema}},protocolRole:n?.protocolRole});return{status:c,liveQuery:l?new jx(l):void 0}}};return this._records=e,e}};function xR(t){if(!t)return;let{parentContextId:e,...r}=t;return e!==void 0&&r.parentId===void 0&&(r.parentId=e),r}function B7(t,e){return Kx(Ux(t))===Kx(Ux(e))}function Ux(t){if(t==null||typeof t!="object")return t;if(Array.isArray(t))return t.map(r=>Ux(r));let e={};for(let[r,n]of Object.entries(t))r!=="$encryption"&&(e[r]=Ux(n));return e}function Rv(t){let e=0;for(;e<t.length&&t.codePointAt(e)===47;)e++;let r=t.length;for(;r>e&&t.codePointAt(r-1)===47;)r--;return t.slice(e,r)}function Mx(t){let e=t.split("/");return e[e.length-1]}function j7(t,e=""){let r=new Set;for(let n of Object.keys(t)){if(n.startsWith("$"))continue;let i=e?`${e}/${n}`:n;r.add(i);let a=t[n];if(a!==null&&typeof a=="object")for(let s of j7(a,i))r.add(s)}return r}function Kx(t){return t==null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?"["+t.map(n=>Kx(n)).join(",")+"]":"{"+Object.keys(t).sort((n,i)=>n.localeCompare(i)).map(n=>JSON.stringify(n)+":"+Kx(t[n])).join(",")+"}"}y();var Lx=class{constructor(e){this.agent=e.agent,this.connectedDid=e.connectedDid}async create(){throw new Error("Not implemented.")}};var M7=class t{constructor({agent:e,connectedDid:r,delegateDid:n}){this._typedInstances=new Map;this.agent=e,this.did=new Rx({agent:e,connectedDid:r}),this._dwn=new Bx({agent:e,connectedDid:r,delegateDid:n}),this.vc=new Lx({agent:e,connectedDid:r})}using(e){let r=e.definition.protocol,n=this._typedInstances.get(r);if(n)return n;let i=new Nx(this._dwn,e);return this._typedInstances.set(r,i),i}async disconnect(e){"sync"in this.agent&&typeof this.agent.sync?.stopSync=="function"&&await this.agent.sync.stopSync(e),this._typedInstances.clear()}static anonymous(e){let r=new uv({didResolvers:e?.didResolvers??[su,eh,VP,UA],cache:new JP}),n=new Mm,i=new bx({didResolver:r,rpcClient:n});return{dwn:new Cx(i)}}static connect(e){if("session"in e){let{session:r}=e;return new t({agent:r.agent,connectedDid:r.did,delegateDid:r.delegateDid})}return new t(e)}};y();y();y();function N7(t){return t.code===400&&t.detail.includes("record limit")}function ipe(t,e){let r=e.split("/"),n=t.structure;for(let a of r){if(!n||typeof n!="object")return!1;n=n[a]}if(!n||typeof n!="object")return!1;let i=n.$recordLimit;return i!==void 0&&typeof i=="object"&&i!==null&&i.max===1}function ope(t,e){let r=e.split("/"),n=t.structure;for(let i of r){if(!n||typeof n!="object")return[];n=n[i]}return!n||typeof n!="object"?[]:Object.keys(n).filter(i=>!i.startsWith("$"))}function spe(t,e){return{async create(r){let{status:n,record:i}=await t.records.create(e,r);return{status:n,record:i}},async query(r){let{status:n,records:i,cursor:a}=await t.records.query(e,r);return{status:n,records:i,cursor:a}},async get(r){let{record:n}=await t.records.read(e,{filter:{recordId:r}});return n},async delete(r){return t.records.delete(e,{recordId:r})},async subscribe(r){let{liveQuery:n}=await t.records.subscribe(e,r);return n}}}function ape(t,e){return{async set(r){let n=await t.records.create(e,r);if(N7(n.status)){let{records:i}=await t.records.query(e);if(i.length>0){let{status:a,record:s}=await i[0].update({data:r.data,...r.tags===void 0?{}:{tags:r.tags}});return{status:a,record:s}}}return{status:n.status,record:n.record}},async get(){let{records:r}=await t.records.query(e);return r.length>0?r[0]:void 0},async delete(r){return t.records.delete(e,{recordId:r})}}}function cpe(t,e){return{async create(r,n){let{status:i,record:a}=await t.records.create(e,{...n,parentContextId:r});return{status:i,record:a}},async query(r,n){let{status:i,records:a,cursor:s}=await t.records.query(e,{...n,filter:{...n?.filter,contextId:r}});return{status:i,records:a,cursor:s}},async get(r){let{record:n}=await t.records.read(e,{filter:{recordId:r}});return n},async delete(r){return t.records.delete(e,{recordId:r})},async subscribe(r,n){let{liveQuery:i}=await t.records.subscribe(e,{...n,filter:{...n?.filter,contextId:r}});return i}}}function dpe(t,e){return{async set(r,n){let i=await t.records.create(e,{...n,parentContextId:r});if(N7(i.status)){let{records:a}=await t.records.query(e,{filter:{contextId:r}});if(a.length>0){let{status:s,record:o}=await a[0].update({data:n.data,...n.tags===void 0?{}:{tags:n.tags}});return{status:s,record:o}}}return{status:i.status,record:i.record}},async get(r){let{records:n}=await t.records.query(e,{filter:{contextId:r}});return n.length>0?n[0]:void 0},async delete(r){return t.records.delete(e,{recordId:r})}}}function U7(t,e,r,n){let i=ipe(e,r),a;n?a=i?dpe(t,r):cpe(t,r):a=i?ape(t,r):spe(t,r);let s=ope(e,r),o={};return new Proxy(a,{get(c,l){if(typeof l=="string"){if(l in c)return c[l];if(s.includes(l))return l in o||(o[l]=U7(t,e,`${r}/${l}`,!0)),o[l]}}})}function oYe(t){let e=t.definition,r=Object.keys(e.structure).filter(a=>!a.startsWith("$")),n={};return new Proxy({},{get(a,s){if(typeof s=="string"){if(s==="configure")return async o=>await t.configure(o);if(r.includes(s))return s in n||(n[s]=U7(t,e,s,!1)),n[s]}}})}y();export{Rx as DidApi,Cx as DwnReaderApi,M7 as Enbox,$x as LiveQuery,dh as PermissionGrant,Ox as PermissionGrantRevocation,Iv as PermissionRequest,Av as Protocol,kv as ReadOnlyRecord,zd as Record,PR as RecordChangeEvent,Nx as TypedEnbox,jx as TypedLiveQuery,Nc as TypedRecord,Lx as VcApi,O7 as createRecordData,bpe as defineProtocol,B7 as definitionsEqual,C7 as isOk,oYe as repository,$7 as utils};
2080
2080
  /*! Bundled license information:
2081
2081
 
2082
2082
  ieee754/index.js: