@enbox/api 0.6.0 → 0.6.1
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 +1 -1
- package/dist/browser.mjs.map +2 -2
- package/package.json +3 -3
package/dist/browser.mjs
CHANGED
|
@@ -2055,7 +2055,7 @@ zebra
|
|
|
2055
2055
|
zero
|
|
2056
2056
|
zone
|
|
2057
2057
|
zoo`.split(`
|
|
2058
|
-
`);Fo();Kt();y();y();rn();y();Kt();rn();y();Kt();rn();y();rn();rn();Jn();y();Kt();rn();y();Fo();y();Kt();y();Jn();Kt();var Cc=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(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},Yz=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},fi=class t{get agent(){if(!this._agent)throw new Error("AgentPermissionsApi: Agent is not set");return this._agent}set agent(e){this._agent=e}constructor({agent:e}={}){this._cachedPermissions=new Kl.default({ttl:60*1e3}),this._agent=e}getPermissionForRequest(e){return Cc(this,arguments,void 0,function*({connectedDid:r,delegateDid:n,delegate:i,messageType:a,protocol:s,cached:o=!1}){let d=[r,n,a,s].join("~"),u=o?this._cachedPermissions.get(d):void 0;if(u)return u;let c=yield this.fetchGrants({author:n,target:n,grantor:r,grantee:n}),l=yield t.matchGrantFromArray(r,n,{messageType:a,protocol:s},c,i);if(!l)throw new Error(`CachedPermissions: No permissions found for ${a}: ${s}`);return this._cachedPermissions.set(d,l),l})}fetchGrants(e){return Cc(this,arguments,void 0,function*({author:r,target:n,grantee:i,grantor:a,protocol:s,remote:o=!1,checkRevoked:d=!0}){let u=s?{protocol:s}:void 0,c={author:r,target:n,messageType:Te.RecordsQuery,messageParams:{filter:{author:a,recipient:i,protocol:zt.uri,protocolPath:zt.grantPath,tags:u}}},{reply:l}=o?yield this.agent.sendDwnRequest(c):yield this.agent.processDwnRequest(c);if(l.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${l.status.detail}`);let f=d?yield this.fetchRevokedGrantIds({author:r,target:n,grantor:a,remote:o,tags:u}):new Set,h=[];for(let p of l.entries){if(f.has(p.recordId))continue;let m=dr.parse(p);h.push({grant:m,message:p})}return h})}fetchRevokedGrantIds(e){return Cc(this,arguments,void 0,function*({author:r,target:n,grantor:i,remote:a,tags:s}){let o={author:r,target:n,messageType:Te.RecordsQuery,messageParams:{filter:{author:i,protocol:zt.uri,protocolPath:zt.revocationPath,tags:s}}},{reply:d}=a?yield this.agent.sendDwnRequest(o):yield this.agent.processDwnRequest(o);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch revocations: ${d.status.detail}`);let u=new Set;for(let c of d.entries)c.descriptor.parentId!==void 0&&u.add(c.descriptor.parentId);return u})}fetchRequests(e){return Cc(this,arguments,void 0,function*({author:r,target:n,protocol:i,remote:a=!1}){let s=i?{protocol:i}:void 0,o={author:r,target:n,messageType:Te.RecordsQuery,messageParams:{filter:{protocol:zt.uri,protocolPath:zt.requestPath,tags:s}}},{reply:d}=a?yield this.agent.sendDwnRequest(o):yield this.agent.processDwnRequest(o);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch requests: ${d.status.detail}`);let u=[];for(let c of d.entries){let l=Ia.parse(c);u.push({request:l,message:c})}return u})}isGrantRevoked(e){return Cc(this,arguments,void 0,function*({author:r,target:n,grantRecordId:i,remote:a=!1}){let s={author:r,target:n,messageType:Te.RecordsRead,messageParams:{filter:{parentId:i,protocol:zt.uri,protocolPath:zt.revocationPath}}},{reply:o}=a?yield this.agent.sendDwnRequest(s):yield this.agent.processDwnRequest(s);if(o.status.code===404)return!1;if(o.status.code===200)return!0;throw new Error(`PermissionsApi: Failed to check if grant is revoked: ${o.status.detail}`)})}createGrant(e){return Cc(this,void 0,void 0,function*(){let{author:r,store:n=!1,delegated:i=!1}=e,a=Yz(e,["author","store","delegated"]),s;zt.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={dateExpires:a.dateExpires,requestId:a.requestId,description:a.description,delegated:i,scope:a.scope},d=Ue.object(o).toUint8Array(),u={recipient:a.grantedTo,protocol:zt.uri,protocolPath:zt.grantPath,dataFormat:"application/json",tags:s},{reply:c,message:l}=yield this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Te.RecordsWrite,messageParams:u,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${c.status.detail}`);let f=Object.assign(Object.assign({},l),{encodedData:Ue.uint8Array(d).toBase64Url()});return{grant:dr.parse(f),message:f}})}createRequest(e){return Cc(this,void 0,void 0,function*(){let{author:r,store:n=!1,delegated:i=!1}=e,a=Yz(e,["author","store","delegated"]),s;zt.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={description:a.description,delegated:i,scope:a.scope},d=Ue.object(o).toUint8Array(),u={protocol:zt.uri,protocolPath:zt.requestPath,dataFormat:"application/json",tags:s},{reply:c,message:l}=yield this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Te.RecordsWrite,messageParams:u,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${c.status.detail}`);let f=Object.assign(Object.assign({},l),{encodedData:Ue.uint8Array(d).toBase64Url()});return{request:Ia.parse(f),message:f}})}createRevocation(e){return Cc(this,void 0,void 0,function*(){let{author:r,store:n=!1,grant:i,description:a}=e,s={description:a},o=Ue.object(s).toUint8Array(),d;zt.hasProtocolScope(i.scope)&&(d={protocol:i.scope.protocol});let u={parentContextId:i.id,protocol:zt.uri,protocolPath:zt.revocationPath,dataFormat:"application/json",tags:d},{reply:c,message:l}=yield this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Te.RecordsWrite,messageParams:u,dataStream:new Blob([o])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${c.status.detail}`);return{message:Object.assign(Object.assign({},l),{encodedData:Ue.uint8Array(o).toBase64Url()})}})}clear(){return Cc(this,void 0,void 0,function*(){this._cachedPermissions.clear()})}static matchGrantFromArray(e,r,n,i){return Cc(this,arguments,void 0,function*(a,s,o,d,u=!1){let c;for(let l of d){let{grant:f,message:h}=l;if(u===!0&&f.delegated!==!0)continue;let{messageType:p,protocol:m,protocolPath:g,contextId:_}=o;if(this.matchScopeFromGrant(a,s,p,f,m,g,_)){if(f.scope.interface+f.scope.method===p)return{grant:f,message:h};c||(c={grant:f,message:h})}}return c})}static matchScopeFromGrant(e,r,n,i,a,s,o){if(i.grantee!==r||i.grantor!==e)return!1;let d=i.scope,u=d.interface+d.method;if(u===n||u===Te.MessagesRead&&(n===Te.MessagesSync||n===Te.MessagesSubscribe))if(YI(n)){let l=d;if(l.protocol!==a)return!1;if(this.isUnrestrictedProtocolScope(l)||l.protocolPath!==void 0&&l.protocolPath===s||l.contextId!==void 0&&o?.startsWith(l.contextId))return!0}else{let l=d;return l.protocol===void 0?!0:l.protocol!==a?!1:this.isUnrestrictedProtocolScope(l)}return!1}static isUnrestrictedProtocolScope(e){return e.contextId===void 0&&e.protocolPath===void 0}};y();var s7=wn(pP(),1);Jn();import{Level as Xfe}from"level";y();Jn();function Qz(t){let e=t.descriptor;return e.interface!==Ge.Records||e.method!==ze.Write?!1:e.dateCreated===e.messageTimestamp}function Em(t){var e;if(t.length<=1)return t;let r=new Map,n=new Map,i=new Map,a=new Map;for(let l=0;l<t.length;l++){let f=t[l];r.set(l,f);let h=f.message.descriptor;if(h.interface===Ge.Protocols&&h.method===ze.Configure){let p=(e=h.definition)===null||e===void 0?void 0:e.protocol;p&&n.set(p,l)}if(h.interface===Ge.Records&&h.method===ze.Write){let p=f.message.recordId;Qz(f.message)&&p&&i.set(p,l),h.protocol===zt.uri&&h.protocolPath===zt.grantPath&&p&&a.set(p,l)}}let s=new Map,o=new Array(t.length).fill(0),d=(l,f)=>{if(l===f)return;s.has(l)||s.set(l,new Set);let h=s.get(l);h.has(f)||(h.add(f),o[f]++)};for(let l=0;l<t.length;l++){let f=t[l].message.descriptor;if(f.interface===Ge.Records){let p=f.protocol;p&&n.has(p)&&d(n.get(p),l)}if(f.interface===Ge.Records&&f.parentId){let p=f.parentId;i.has(p)&&d(i.get(p),l)}if(f.interface===Ge.Records&&f.method===ze.Write){let p=t[l].message.recordId;p&&!Qz(t[l].message)&&i.has(p)&&d(i.get(p),l)}if(f.interface===Ge.Records&&f.method===ze.Delete){let p=f.recordId;p&&i.has(p)&&d(i.get(p),l)}let h=f.permissionGrantId;h&&a.has(h)&&d(a.get(h),l)}let u=[];for(let l=0;l<t.length;l++)o[l]===0&&u.push(l);let c=[];for(;u.length>0;){let l=u.shift();c.push(r.get(l));let f=s.get(l);if(f)for(let h of f)o[h]--,o[h]===0&&u.push(h)}if(c.length<t.length){let l=new Set(c);for(let f=0;f<t.length;f++){let h=r.get(f);l.has(h)||c.push(h)}}return c}y();Jn();var tp=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(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},Jfe=1048576;function e7(t){var e,r;return t.status.code===202||t.status.code===204||t.status.code===409||((e=t.entry)===null||e===void 0?void 0:e.message.descriptor.interface)===Ge.Records&&((r=t.entry)===null||r===void 0?void 0:r.message.descriptor.method)===ze.Delete&&t.status.code===404}function t7(t){return tp(this,void 0,void 0,function*(){try{return yield Se.getCid(t)}catch{return"unknown"}})}function r7(t){return tp(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s,agent:o,permissionsApi:d}){let u=[];if(s)for(let m of s){if(!m.message)continue;let g={message:m.message};if(m.encodedData){let _=ke.base64UrlToBytes(m.encodedData);g.bufferedData=_,g.dataStream=new ReadableStream({start(v){v.enqueue(_),v.close()}})}u.push(g)}let c=a.length>0?yield Xz({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:o,permissionsApi:d}):[],l=[...u,...c],f=Em(l);yield Zfe(f);let h=3,p=f;for(let m=0;m<=h&&p.length>0;m++){let g=[];for(let _ of p){let v=_.bufferedData?new ReadableStream({start(T){T.enqueue(_.bufferedData),T.close()}}):_.dataStream,E=yield o.dwn.processRawMessage(e,_.message,{dataStream:v});e7(E)||g.push(_)}if(g.length>0){let _=[],v=[];for(let E of g)if(E.bufferedData||!E.dataStream)v.push(E);else{let T=yield t7(E.message);_.push(T)}if(_.length>0){let E=yield Xz({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:_,agent:o,permissionsApi:d});v.push(...E)}p=Em(v)}else p=[]}})}function Zfe(t){return tp(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:d,value:u}=yield a.read();if(d)break;if(n+=u.byteLength,n>Jfe){i=!0;break}r.push(u)}}finally{a.releaseLock()}if(i){e.dataStream=void 0;continue}let s=new Uint8Array(n),o=0;for(let d of r)s.set(d,o),o+=d.byteLength;e.bufferedData=s,e.dataStream=new ReadableStream({start(d){d.enqueue(s),d.close()}})}})}function Xz(t){return tp(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:s,permissionsApi:o}){let d=[],u;n&&(u=(yield o.getPermissionForRequest({connectedDid:e,messageType:Te.MessagesRead,delegateDid:n,protocol:i,cached:!0})).grant.id);let c=4,l=0;for(;l<a.length;){let f=a.slice(l,l+c);l+=c;let h=yield Promise.all(f.map(p=>tp(this,void 0,void 0,function*(){var m,g;let _=yield s.processDwnRequest({store:!1,author:e,target:e,messageType:Te.MessagesRead,granteeDid:n,messageParams:{messageCid:p,permissionGrantId:u}}),v;try{v=yield s.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:_.message})}catch(D){console.error(`SyncEngineLevel: pull - failed to read ${p} from ${r}:`,(m=D.message)!==null&&m!==void 0?m:D);return}if(v.status.code!==200||!(!((g=v.entry)===null||g===void 0)&&g.message))return;let E=v.entry,T;return vm(E)&&E.data&&(T=E.data),{message:E.message,dataStream:T}})));for(let p of h)p&&d.push(p)}return d})}function QI(t){return tp(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:s,permissionsApi:o}){var d;let u=[];for(let l of a){let f=yield Yfe({author:e,messageCid:l,delegateDid:n,protocol:i,agent:s,permissionsApi:o});f&&u.push(f)}let c=Em(u);for(let l of c)try{let f=yield s.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,data:l.dataStream,message:l.message});if(!e7(f)){let h=yield t7(l.message);console.error(`SyncEngineLevel: push failed for ${h}: ${f.status.code} ${f.status.detail}`)}}catch(f){let h=(d=f.message)!==null&&d!==void 0?d:f;throw new Error(`SyncEngineLevel: push to ${r} failed: ${h}`)}})}function Yfe(t){return tp(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:Te.MessagesRead,delegateDid:r,protocol:n,cached:!0})).grant.id);let{reply:d}=yield a.dwn.processRequest({author:e,target:e,messageType:Te.MessagesRead,granteeDid:r,messageParams:{messageCid:i,permissionGrantId:o}});if(d.status.code!==200||!d.entry)return;let u=d.entry,c={message:u.message};return vm(u)&&u.data&&(c.dataStream=u.data),c})}var Rt=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(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},Qfe=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,d){s=t[a](s),i(o,d,s.done,s.value)})}}function i(a,s,o,d){Promise.resolve(d).then(function(u){a({value:u,done:o})},s)}},n7=16,i7=8,epe=4,XI=class{constructor(e){this._waiting=[],this._permits=e}acquire(){return Rt(this,void 0,void 0,function*(){if(this._permits>0){this._permits--;return}return new Promise(e=>{this._waiting.push(e)})})}release(){let e=this._waiting.shift();e?e():this._permits++}run(e){return Rt(this,void 0,void 0,function*(){yield this.acquire();try{return yield e()}finally{this.release()}})}},o7="^",tpe=250,Sm=class t{constructor({agent:e,dataPath:r,db:n}){this._syncLock=!1,this._syncMode="poll",this._liveSubscriptions=[],this._localSubscriptions=[],this._connectivityState="unknown",this._pendingPushCids=new Map,this._consecutiveFailures=0,this._agent=e,this._permissionsApi=new fi({agent:e}),this._db=n||new Xfe(r??"DATA/AGENT/SYNC_STORE")}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 fi({agent:e})}get connectivityState(){return this._connectivityState}clear(){return Rt(this,void 0,void 0,function*(){yield this._permissionsApi.clear(),yield this._db.clear()})}close(){return Rt(this,void 0,void 0,function*(){yield this._db.close()})}registerIdentity(e){return Rt(this,arguments,void 0,function*({did:r,options:n}){let i=this._db.sublevel("registeredIdentities");if(yield this.getIdentityOptions(r))throw new Error(`SyncEngineLevel: Identity with DID ${r} is already registered.`);n??(n={protocols:[]}),yield i.put(r,JSON.stringify(n))})}unregisterIdentity(e){return Rt(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.`);yield r.del(e)})}getIdentityOptions(e){return Rt(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 Rt(this,arguments,void 0,function*({did:r,options: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))})}sync(e){return Rt(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 Set,i=!1;for(let a of r){let{did:s,delegateDid:o,dwnUrl:d,protocol:u}=a;if(!n.has(d))try{let c=yield this.getLocalRoot(s,o,u),l=yield this.getRemoteRoot(s,d,o,u);if(c===l)continue;let f=yield this.diffWithRemote({did:s,dwnUrl:d,delegateDid:o,protocol:u});if((!e||e==="pull")&&f.onlyRemote.length>0){let h=[],p=[];for(let m of f.onlyRemote)m.message?m.message.descriptor.interface==="Records"&&m.message.descriptor.method==="Write"&&m.message.descriptor.dataCid&&!m.encodedData?p.push(m.messageCid):h.push(m):p.push(m.messageCid);yield this.pullMessages({did:s,dwnUrl:d,delegateDid:o,protocol:u,messageCids:p,prefetched:h})}(!e||e==="push")&&f.onlyLocal.length>0&&(yield this.pushMessages({did:s,dwnUrl:d,delegateDid:o,protocol:u,messageCids:f.onlyLocal}))}catch(c){n.add(d),i=!0,console.error(`SyncEngineLevel: Error syncing ${s} with ${d}`,c)}}i?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):(this._consecutiveFailures=0,r.length>0&&(this._connectivityState="online"))}finally{this._syncLock=!1}})}startSync(e){return Rt(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,s7.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 Rt(this,arguments,void 0,function*(e=2e3){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),yield this.teardownLiveSync()})}startPollSync(e){return Rt(this,void 0,void 0,function*(){let r=()=>Rt(this,void 0,void 0,function*(){if(this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{yield this.sync()}catch(a){console.error("SyncEngineLevel: Error during sync operation",a)}let n=Math.min(Math.pow(2,this._consecutiveFailures),t.MAX_BACKOFF_MULTIPLIER),i=this._consecutiveFailures>0?e*n:e;this._syncIntervalId||(this._syncIntervalId=setInterval(r,i))});this._syncIntervalId&&clearInterval(this._syncIntervalId),this._syncIntervalId=setInterval(r,e),this._syncLock||(yield this.sync())})}startLiveSync(e){return Rt(this,void 0,void 0,function*(){try{yield this.sync()}catch(i){console.error("SyncEngineLevel: Error during initial live-sync catch-up",i)}let r=yield this.getSyncTargets();for(let i of r)try{yield this.openLivePullSubscription(i),yield this.openLocalPushSubscription(i)}catch(a){console.error(`SyncEngineLevel: Failed to open live subscription for ${i.did} -> ${i.dwnUrl}`,a)}let n=()=>Rt(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)})}teardownLiveSync(){return Rt(this,void 0,void 0,function*(){this._pushDebounceTimer&&(clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=void 0),this._pendingPushCids.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=[]})}openLivePullSubscription(e){return Rt(this,void 0,void 0,function*(){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=this.buildCursorKey(r,i,a),o=yield this.getCursor(s),d=a?[{protocol:a}]:[],u;if(n)try{u=(yield this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Te.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{try{u=(yield this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Te.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}catch(p){console.error("SyncEngineLevel: Could not find permission grant for live pull subscription",p);return}}let c=h=>Rt(this,void 0,void 0,function*(){if(h.type==="eose"){yield this.setCursor(s,h.cursor),this._connectivityState="online";return}if(h.type==="event"){let p=h.event;try{let m=this.extractDataStream(p);yield this.agent.dwn.processRawMessage(r,p.message,{dataStream:m})}catch(m){console.error(`SyncEngineLevel: Error processing live-pull event for ${r}`,m)}yield this.setCursor(s,h.cursor)}}),f=(yield this.agent.dwn.sendRequest({author:r,target:r,messageType:Te.MessagesSubscribe,granteeDid:n,messageParams:{filters:d,cursor:o,permissionGrantId:u},subscriptionHandler:c})).reply;if(f.status.code!==200||!f.subscription){console.error(`SyncEngineLevel: MessagesSubscribe failed for ${r} -> ${i}: ${f.status.code} ${f.status.detail}`);return}this._liveSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:()=>Rt(this,void 0,void 0,function*(){yield f.subscription.close()})}),this._connectivityState="online"})}openLocalPushSubscription(e){return Rt(this,void 0,void 0,function*(){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=a?[{protocol:a}]:[],o;if(n)try{o=(yield this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Te.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{return}let d=l=>{if(l.type!=="event")return;let f=this.buildCursorKey(r,i,a),h=this.tryGetCidSync(l.event.message);if(h===void 0)return;let p=this._pendingPushCids.get(f);p||(p={did:r,dwnUrl:i,delegateDid:n,protocol:a,cids:[]},this._pendingPushCids.set(f,p)),p.cids.push(h),this._pushDebounceTimer&&clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=setTimeout(()=>{this.flushPendingPushes()},tpe)},c=(yield this.agent.dwn.processRequest({author:r,target:r,messageType:Te.MessagesSubscribe,granteeDid:n,messageParams:{filters:s,permissionGrantId:o},subscriptionHandler:d})).reply;if(c.status.code!==200||!c.subscription){console.error(`SyncEngineLevel: Local MessagesSubscribe failed for ${r}: ${c.status.code} ${c.status.detail}`);return}this._localSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:()=>Rt(this,void 0,void 0,function*(){yield c.subscription.close()})})})}flushPendingPushes(){return Rt(this,void 0,void 0,function*(){this._pushDebounceTimer=void 0;let e=[...this._pendingPushCids.entries()];this._pendingPushCids.clear();for(let[,r]of e){let{did:n,dwnUrl:i,delegateDid:a,protocol:s,cids:o}=r;if(o.length!==0)try{yield QI({did:n,dwnUrl:i,delegateDid:a,protocol:s,messageCids:o,agent:this.agent,permissionsApi:this._permissionsApi})}catch(d){console.error(`SyncEngineLevel: Push-on-write failed for ${n} -> ${i}`,d)}}})}buildCursorKey(e,r,n){let i=`${e}${o7}${r}`;return n?`${i}${o7}${n}`:i}getCursor(e){return Rt(this,void 0,void 0,function*(){let r=this._db.sublevel("syncCursors");try{return yield r.get(e)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}})}setCursor(e,r){return Rt(this,void 0,void 0,function*(){yield this._db.sublevel("syncCursors").put(e,r)})}extractDataStream(e){if(vm(e)&&e.data)return e.data}tryGetCidSync(e){var r;let n;return Se.getCid(e).then(i=>{n=i}),(r=n??e.messageCid)!==null&&r!==void 0?r:void 0}getDefaultHashHex(e){return Rt(this,void 0,void 0,function*(){var r;if(this._defaultHashHex===void 0){let n=yield Ng(),i=new Map;for(let a=0;a<=n7;a++)i.set(a,md(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 Rt(this,void 0,void 0,function*(){var i;let a=this.stateIndex;if(a){let u=n!==void 0?yield a.getProtocolRoot(e,n):yield a.getRoot(e);return md(u)}let s=yield this.getSyncPermissionGrantId(e,r,n);return(i=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Te.MessagesSync,granteeDid:r,messageParams:{action:"root",protocol:n,permissionGrantId:s}})).reply.root)!==null&&i!==void 0?i:""})}getRemoteRoot(e,r,n,i){return Rt(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:Te.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:""})}walkTreeDiff(e){return Rt(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a}){let s=[],o=[],d=yield this.getSyncPermissionGrantId(r,i,a),u=new XI(epe),c=l=>Rt(this,void 0,void 0,function*(){let[f,h]=yield Promise.all([this.getLocalSubtreeHash(r,l,i,a,d),u.run(()=>this.getRemoteSubtreeHash(r,n,l,i,a,d))]);if(f===h)return;let p=yield this.getDefaultHashHex(l.length);if(h===p&&f!==p){let m=yield this.getLocalLeaves(r,l,i,a,d);s.push(...m);return}if(f===p&&h!==p){let m=yield u.run(()=>this.getRemoteLeaves(r,n,l,i,a,d));o.push(...m);return}if(l.length>=n7){let[m,g]=yield Promise.all([this.getLocalLeaves(r,l,i,a,d),u.run(()=>this.getRemoteLeaves(r,n,l,i,a,d))]),_=new Set(m),v=new Set(g);for(let E of m)v.has(E)||s.push(E);for(let E of g)_.has(E)||o.push(E);return}yield Promise.all([c(l+"0"),c(l+"1")])});return yield c(""),{onlyLocal:s,onlyRemote:o}})}diffWithRemote(e){return Rt(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a}){var s,o;let d=yield this.collectLocalSubtreeHashes(r,a,i7),u=yield this.getSyncPermissionGrantId(r,i,a),c=yield this.agent.dwn.processRequest({store:!1,author:r,target:r,messageType:Te.MessagesSync,granteeDid:i,messageParams:{action:"diff",protocol:a,hashes:d,depth:i7,permissionGrantId:u}}),l=yield this.agent.rpc.sendDwnRequest({dwnUrl:n,targetDid:r,message:c.message});if(l.status.code!==200)throw new Error(`SyncEngineLevel: diff failed with ${l.status.code}: ${l.status.detail}`);let f=yield this.getSyncPermissionGrantId(r,i,a),h=[];for(let p of(s=l.onlyLocal)!==null&&s!==void 0?s:[]){let m=yield this.getLocalLeaves(r,p,i,a,f);h.push(...m)}return{onlyRemote:(o=l.onlyRemote)!==null&&o!==void 0?o:[],onlyLocal:h}})}collectLocalSubtreeHashes(e,r,n){return Rt(this,void 0,void 0,function*(){let i={},a=yield this.getDefaultHashHex(n),s=this.stateIndex,o=(d,u)=>Rt(this,void 0,void 0,function*(){let c;if(s){let l=t.parseBitPrefix(d),f=r!==void 0?yield s.getProtocolSubtreeHash(e,r,l):yield s.getSubtreeHash(e,l);c=md(f)}else c=yield this.getLocalSubtreeHash(e,d,void 0,r);if(c!==a){if(u>=n){i[d]=c;return}yield Promise.all([o(d+"0",u+1),o(d+"1",u+1)])}});return yield o("",0),i})}getLocalSubtreeHash(e,r,n,i,a){return Rt(this,void 0,void 0,function*(){var s;let o=this.stateIndex;if(o){let c=t.parseBitPrefix(r),l=i!==void 0?yield o.getProtocolSubtreeHash(e,i,c):yield o.getSubtreeHash(e,c);return md(l)}return(s=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Te.MessagesSync,granteeDid:n,messageParams:{action:"subtree",prefix:r,protocol:i,permissionGrantId:a}})).reply.hash)!==null&&s!==void 0?s:""})}getRemoteSubtreeHash(e,r,n,i,a,s){return Rt(this,void 0,void 0,function*(){var o;let d=yield this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Te.MessagesSync,granteeDid:i,messageParams:{action:"subtree",prefix:n,protocol:a,permissionGrantId:s}});return(o=(yield this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:d.message})).hash)!==null&&o!==void 0?o:""})}getLocalLeaves(e,r,n,i,a){return Rt(this,void 0,void 0,function*(){var s;let o=this.stateIndex;if(o){let c=t.parseBitPrefix(r);return i!==void 0?yield o.getProtocolLeaves(e,i,c):yield o.getLeaves(e,c)}return(s=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Te.MessagesSync,granteeDid:n,messageParams:{action:"leaves",prefix:r,protocol:i,permissionGrantId:a}})).reply.entries)!==null&&s!==void 0?s:[]})}getRemoteLeaves(e,r,n,i,a,s){return Rt(this,void 0,void 0,function*(){var o;let d=yield this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Te.MessagesSync,granteeDid:i,messageParams:{action:"leaves",prefix:n,protocol:a,permissionGrantId:s}});return(o=(yield this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:d.message})).entries)!==null&&o!==void 0?o:[]})}pullMessages(e){return Rt(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,prefetched:o}){return r7({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,prefetched:o,agent:this.agent,permissionsApi:this._permissionsApi})})}pushMessages(e){return Rt(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s}){return QI({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,agent:this.agent,permissionsApi:this._permissionsApi})})}static topologicalSort(e){return Em(e)}getSyncTargets(){return Rt(this,void 0,void 0,function*(){var e,r,n,i;let a=[];try{for(var s=!0,o=Qfe(this._db.sublevel("registeredIdentities").iterator()),d;d=yield o.next(),e=d.done,!e;s=!0){i=d.value,s=!1;let[u,c]=i,l;try{l=JSON.parse(c)}catch{l={protocols:[]}}let{protocols:f,delegateDid:h}=l,p=yield this.agent.dwn.getDwnEndpointUrlsForTarget(u);if(p.length!==0)for(let m of p)if(f.length===0)a.push({did:u,delegateDid:h,dwnUrl:m});else for(let g of f)a.push({did:u,delegateDid:h,dwnUrl:m,protocol:g})}}catch(u){r={error:u}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(r)throw r.error}}return a})}getSyncPermissionGrantId(e,r,n){return Rt(this,void 0,void 0,function*(){return r?(yield this._permissionsApi.getPermissionForRequest({connectedDid:e,messageType:Te.MessagesSync,delegateDid:r,protocol:n,cached:!0})).grant.id:void 0})}};Sm.MAX_CONSECUTIVE_FAILURES=5;Sm.MAX_BACKOFF_MULTIPLIER=4;y();Jn();Fo();Kt();import{Level as VWe}from"level";y();y();y();Kt();rn();y();y();var a7=wn(pP(),1);Kt();var Tm=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(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},mP=class{constructor({ttl:e="15m"}={}){this.cache=new Kl.default({ttl:(0,a7.default)(e)})}get(e){return Tm(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,r){return Tm(this,void 0,void 0,function*(){this.cache.set(e,r)})}delete(e){return Tm(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return Tm(this,void 0,void 0,function*(){this.cache.clear()})}open(){return Tm(this,void 0,void 0,function*(){})}close(){return Tm(this,void 0,void 0,function*(){})}};y();rn();Jn();y();var km=class extends Error{constructor(e,r){super(r??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};y();var Am;(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"})(Am||(Am={}));var Dm=(t,e,r)=>({jsonrpc:"2.0",id:t,method:e,params:r}),yP=(t,e,r,n)=>({jsonrpc:"2.0",id:t,method:e,params:r,subscription:{id:n??null}}),c7=(t,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:t}});function rp(t){try{return JSON.parse(t)}catch{return null}}var eR=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(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},rpe=3,npe=500,ipe=1e4,ope=3e4,d7=new Set([408,429,500,502,503,504]);function spe(t,e){return t instanceof TypeError?!0:e?d7.has(e.status):!1}function ape(t,e,r){let n=Math.min(e*Math.pow(2,t),r),i=.5+Math.random()*.5;return n*i}function cpe(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 gP=class t{constructor(e,r){var n,i,a;this.serverInfoCache=e??new mP,this._retryOptions={maxRetries:(n=r?.maxRetries)!==null&&n!==void 0?n:rpe,baseDelayMs:(i=r?.baseDelayMs)!==null&&i!==void 0?i:npe,maxDelayMs:(a=r?.maxDelayMs)!==null&&a!==void 0?a:ipe}}static isBunRuntime(){return typeof globalThis.Bun<"u"}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return eR(this,void 0,void 0,function*(){var r,n,i;let a=gi.randomUuid(),s=Dm(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),o={"dwn-request":JSON.stringify(s)},d={method:"POST",headers:o};if(e.data){o["content-type"]="application/octet-stream";let h=e.data;if(h instanceof ReadableStream)if(t.isBunRuntime()){let p=yield Hi.toBytes(h);h=new Blob([p],{type:"application/octet-stream"})}else d.duplex="half";d.body=h}let u=yield this.fetchWithRetry(e.dwnUrl,d);if(u.status===429){let h=parseInt((r=u.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new km(h)}let c,l=u.headers.has("dwn-response");if(l){let h=rp(u.headers.get("dwn-response"));if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);c=h}else{let h=yield u.text(),p=rp(h);if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${u.status}`);c=p}if(c.error){let{code:h,message:p}=c.error;if(h===Am.TooManyRequests){let m=(i=(n=c.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new km(m)}throw new Error(`(${h}) - ${p}`)}let{reply:f}=c.result;if(l){let h=new Uint8Array(yield u.arrayBuffer()),p=Hi.fromBytes(h);f.record?f.record.data=p:f.entry&&(f.entry.data=p)}return f})}getServerInfo(e){return eR(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 km(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 eR(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,s,o;for(let d=0;d<=n;d++){try{let f=AbortSignal.timeout(ope),h=Object.assign(Object.assign({},r),{signal:r?.signal?AbortSignal.any([r.signal,f]):f}),p=yield fetch(e,h);if(!d7.has(p.status)||d===n)return p;o=p}catch(f){if(!spe(f)||d===n)throw f;s=f}let u=o?cpe(o):void 0,c=ape(d,i,a),l=u!==void 0?Math.max(u,c):c;yield new Promise(f=>{setTimeout(f,l)})}if(o)return o;throw s})}};y();rn();var g0=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(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})};function tR(t){return typeof t=="string"?t:t instanceof ArrayBuffer?new TextDecoder().decode(t):t instanceof Uint8Array?new TextDecoder().decode(t):String(t)}var u7=3e3,dpe=3e4,upe=1e3,lpe=3e4,fpe=1/0,wP=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.url=n,this.options=i,this._isConnected=!0}get isConnected(){return this._isConnected}static connect(e){return g0(this,arguments,void 0,function*(r,n={}){var i;let{connectTimeout:a=u7,responseTimeout:s=dpe}=n,o;try{o=yield t.createWebSocket(r,a)}catch(u){throw(i=n.onerror)===null||i===void 0||i.call(n,u),u}let d=new t(o,s,r,n);return d.wireSocket(o),d})}close(){this.closedByUser=!0,this._isConnected=!1,this.socket.close()}request(e){return g0(this,void 0,void 0,function*(){return new Promise((r,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=gi.randomUuid());let a=s=>{let o=rp(tR(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 g0(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=d=>{let u=rp(tR(d.data));u.id===n&&(u.error!==void 0&&(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),this.closeSubscription(n).catch(()=>{})),r(u))};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:()=>g0(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let r=gi.randomUuid(),n=yP(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=()=>{u(),n(a)},o=c=>{u(),i(c)},d=setTimeout(()=>{u(),a.close(),i(new Error("connect timed out"))},r),u=()=>{clearTimeout(d),a.removeEventListener("open",s),a.removeEventListener("error",o)};a.addEventListener("open",s),a.addEventListener("error",o)})}wireSocket(e){e.addEventListener("message",r=>{let n=rp(tR(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.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:Am.TransportError,message:"WebSocket connection closed unexpectedly"}});r({data:n}),this.messageHandlers.delete(e)}}attemptReconnect(){var e,r,n,i;this.reconnecting=!0;let a=(e=this.options.baseReconnectDelay)!==null&&e!==void 0?e:upe,s=(r=this.options.maxReconnectDelay)!==null&&r!==void 0?r:lpe,o=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:fpe,d=(i=this.options.connectTimeout)!==null&&i!==void 0?i:u7,u=0,c=()=>g0(this,void 0,void 0,function*(){var l,f,h,p;if(this.closedByUser){this.reconnecting=!1;return}if(u++,u>o){this.reconnecting=!1;return}(f=(l=this.options).onreconnecting)===null||f===void 0||f.call(l,u);let g=Math.min(a*Math.pow(2,u-1),s)*(.5+Math.random()*.5);if(yield new Promise(_=>setTimeout(_,g)),this.closedByUser){this.reconnecting=!1;return}try{let _=yield t.createWebSocket(this.url,d);this.socket=_,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(_),(p=(h=this.options).onreconnected)===null||p===void 0||p.call(h)}catch{yield c()}});c()}};y();y();y();rn();y();rn();var Im=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(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},w0=class t{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return Im(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 d=yield t.createConnection(r);t.connections.set(r.host,d)}catch(d){throw new Error(`Error connecting to ${r.host}: ${d.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 Im(this,void 0,void 0,function*(){let r=e.host,n=new Map,i=yield wP.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 Im(this,void 0,void 0,function*(){let i=gi.randomUuid(),a=Dm(i,"dwn.processMessage",{target:r,message:n}),{socket:s}=e,o=yield s.request(a),{error:d,result:u}=o;if(d!==void 0)throw new Error(`error sending DWN request: ${d.message}`);return u.reply})}static subscriptionRequest(e,r,n,i,a){return Im(this,void 0,void 0,function*(){let s=gi.randomUuid(),o=gi.randomUuid(),d=yP(s,"rpc.subscribe.dwn.processMessage",{target:r,message:n},o),{socket:u,subscriptions:c}=e,{response:l,close:f}=yield u.subscribe(d,g=>{let{result:_,error:v}=g;if(v){let T=c.get(o);T&&T.subscription.close(),c.delete(o);return}let E=_.subscription;if(i(E),"cursor"in E&&E.cursor){let T=c.get(o);T&&(T.lastCursor=E.cursor),u.send(c7(o,E.cursor))}}),{error:h,result:p}=l;if(h)throw new Error(`could not subscribe via jsonrpc socket: ${h.message}`);let{reply:m}=p;if(m.subscription&&f){let g=()=>Im(this,void 0,void 0,function*(){c.delete(o),yield f()}),_={subscription:Object.assign(Object.assign({},m.subscription),{close:g}),target:r,message:n,handler:i,resubscribeFactory:a};c.set(o,_),m.subscription.close=g}return m})}static resubscribeAll(e){return Im(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{}})}};w0.connections=new Map;var v0=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(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},l7;(function(t){t.Create="did.create",t.Resolve="did.resolve"})(l7||(l7={}));var Rm=class{constructor(e=[]){this.transportClients=new Map,e=[new rR,new nR,...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 v0(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 v0(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)})}},rR=class extends gP{sendDidRequest(e){return v0(this,void 0,void 0,function*(){let r=gi.randomUuid(),n=Dm(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:d}=a.error;throw new Error(`JSON RPC (${o}) - ${d}`)}}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})}},nR=class extends w0{sendDidRequest(e){return v0(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return v0(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};y();y();Fo();Kt();rn();Jn();y();Kt();Fo();var vP=class{constructor(e){this.agent=e.agent,this.connectedDid=e.connectedDid}async create(e){let{result:r,...n}=await this.agent.processDidRequest({messageType:y0.Create,messageParams:{...e}});return{did:r,...n}}async resolve(e,r){let{result:n}=await this.agent.processDidRequest({messageParams:{didUri:e,options:r},messageType:y0.Resolve});return n}};y();y();Kt();var b0=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=Wo(r)??"unknown"}catch{this._author="unknown"}try{this._creator=n?Wo(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([Ue.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 Co.consumeToBytes({readableStream:await this.stream()})],{type:e.dataFormat})},async bytes(){return await Co.consumeToBytes({readableStream:await this.stream()})},async json(){return await Co.consumeToJson({readableStream:await this.stream()})},async text(){return await Co.consumeToText({readableStream:await this.stream()})},async stream(){if(e._encodedData)return Co.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
|
+
`);Fo();Kt();y();y();rn();y();Kt();rn();y();Kt();rn();y();rn();rn();Jn();y();Kt();rn();y();Fo();y();Kt();y();Jn();Kt();var Cc=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(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},Yz=function(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r},fi=class t{get agent(){if(!this._agent)throw new Error("AgentPermissionsApi: Agent is not set");return this._agent}set agent(e){this._agent=e}constructor({agent:e}={}){this._cachedPermissions=new Kl.default({ttl:60*1e3}),this._agent=e}getPermissionForRequest(e){return Cc(this,arguments,void 0,function*({connectedDid:r,delegateDid:n,delegate:i,messageType:a,protocol:s,cached:o=!1}){let d=[r,n,a,s].join("~"),u=o?this._cachedPermissions.get(d):void 0;if(u)return u;let c=yield this.fetchGrants({author:n,target:n,grantor:r,grantee:n}),l=yield t.matchGrantFromArray(r,n,{messageType:a,protocol:s},c,i);if(!l)throw new Error(`CachedPermissions: No permissions found for ${a}: ${s}`);return this._cachedPermissions.set(d,l),l})}fetchGrants(e){return Cc(this,arguments,void 0,function*({author:r,target:n,grantee:i,grantor:a,protocol:s,remote:o=!1,checkRevoked:d=!0}){let u=s?{protocol:s}:void 0,c={author:r,target:n,messageType:Te.RecordsQuery,messageParams:{filter:{author:a,recipient:i,protocol:zt.uri,protocolPath:zt.grantPath,tags:u}}},{reply:l}=o?yield this.agent.sendDwnRequest(c):yield this.agent.processDwnRequest(c);if(l.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${l.status.detail}`);let f=d?yield this.fetchRevokedGrantIds({author:r,target:n,grantor:a,remote:o,tags:u}):new Set,h=[];for(let p of l.entries){if(f.has(p.recordId))continue;let m=dr.parse(p);h.push({grant:m,message:p})}return h})}fetchRevokedGrantIds(e){return Cc(this,arguments,void 0,function*({author:r,target:n,grantor:i,remote:a,tags:s}){let o={author:r,target:n,messageType:Te.RecordsQuery,messageParams:{filter:{author:i,protocol:zt.uri,protocolPath:zt.revocationPath,tags:s}}},{reply:d}=a?yield this.agent.sendDwnRequest(o):yield this.agent.processDwnRequest(o);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch revocations: ${d.status.detail}`);let u=new Set;for(let c of d.entries)c.descriptor.parentId!==void 0&&u.add(c.descriptor.parentId);return u})}fetchRequests(e){return Cc(this,arguments,void 0,function*({author:r,target:n,protocol:i,remote:a=!1}){let s=i?{protocol:i}:void 0,o={author:r,target:n,messageType:Te.RecordsQuery,messageParams:{filter:{protocol:zt.uri,protocolPath:zt.requestPath,tags:s}}},{reply:d}=a?yield this.agent.sendDwnRequest(o):yield this.agent.processDwnRequest(o);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch requests: ${d.status.detail}`);let u=[];for(let c of d.entries){let l=Ia.parse(c);u.push({request:l,message:c})}return u})}isGrantRevoked(e){return Cc(this,arguments,void 0,function*({author:r,target:n,grantRecordId:i,remote:a=!1}){let s={author:r,target:n,messageType:Te.RecordsRead,messageParams:{filter:{parentId:i,protocol:zt.uri,protocolPath:zt.revocationPath}}},{reply:o}=a?yield this.agent.sendDwnRequest(s):yield this.agent.processDwnRequest(s);if(o.status.code===404)return!1;if(o.status.code===200)return!0;throw new Error(`PermissionsApi: Failed to check if grant is revoked: ${o.status.detail}`)})}createGrant(e){return Cc(this,void 0,void 0,function*(){let{author:r,store:n=!1,delegated:i=!1}=e,a=Yz(e,["author","store","delegated"]),s;zt.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={dateExpires:a.dateExpires,requestId:a.requestId,description:a.description,delegated:i,scope:a.scope},d=Ue.object(o).toUint8Array(),u={recipient:a.grantedTo,protocol:zt.uri,protocolPath:zt.grantPath,dataFormat:"application/json",tags:s},{reply:c,message:l}=yield this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Te.RecordsWrite,messageParams:u,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${c.status.detail}`);let f=Object.assign(Object.assign({},l),{encodedData:Ue.uint8Array(d).toBase64Url()});return{grant:dr.parse(f),message:f}})}createRequest(e){return Cc(this,void 0,void 0,function*(){let{author:r,store:n=!1,delegated:i=!1}=e,a=Yz(e,["author","store","delegated"]),s;zt.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={description:a.description,delegated:i,scope:a.scope},d=Ue.object(o).toUint8Array(),u={protocol:zt.uri,protocolPath:zt.requestPath,dataFormat:"application/json",tags:s},{reply:c,message:l}=yield this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Te.RecordsWrite,messageParams:u,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${c.status.detail}`);let f=Object.assign(Object.assign({},l),{encodedData:Ue.uint8Array(d).toBase64Url()});return{request:Ia.parse(f),message:f}})}createRevocation(e){return Cc(this,void 0,void 0,function*(){let{author:r,store:n=!1,grant:i,description:a}=e,s={description:a},o=Ue.object(s).toUint8Array(),d;zt.hasProtocolScope(i.scope)&&(d={protocol:i.scope.protocol});let u={parentContextId:i.id,protocol:zt.uri,protocolPath:zt.revocationPath,dataFormat:"application/json",tags:d},{reply:c,message:l}=yield this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Te.RecordsWrite,messageParams:u,dataStream:new Blob([o])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${c.status.detail}`);return{message:Object.assign(Object.assign({},l),{encodedData:Ue.uint8Array(o).toBase64Url()})}})}clear(){return Cc(this,void 0,void 0,function*(){this._cachedPermissions.clear()})}static matchGrantFromArray(e,r,n,i){return Cc(this,arguments,void 0,function*(a,s,o,d,u=!1){let c;for(let l of d){let{grant:f,message:h}=l;if(u===!0&&f.delegated!==!0)continue;let{messageType:p,protocol:m,protocolPath:g,contextId:_}=o;if(this.matchScopeFromGrant(a,s,p,f,m,g,_)){if(f.scope.interface+f.scope.method===p)return{grant:f,message:h};c||(c={grant:f,message:h})}}return c})}static matchScopeFromGrant(e,r,n,i,a,s,o){if(i.grantee!==r||i.grantor!==e)return!1;let d=i.scope,u=d.interface+d.method;if(u===n||u===Te.MessagesRead&&(n===Te.MessagesSync||n===Te.MessagesSubscribe))if(YI(n)){let l=d;if(l.protocol!==a)return!1;if(this.isUnrestrictedProtocolScope(l)||l.protocolPath!==void 0&&l.protocolPath===s||l.contextId!==void 0&&o?.startsWith(l.contextId))return!0}else{let l=d;return l.protocol===void 0?!0:l.protocol!==a?!1:this.isUnrestrictedProtocolScope(l)}return!1}static isUnrestrictedProtocolScope(e){return e.contextId===void 0&&e.protocolPath===void 0}};y();var s7=wn(pP(),1);Jn();import{Level as Xfe}from"level";y();Jn();function Qz(t){let e=t.descriptor;return e.interface!==Ge.Records||e.method!==ze.Write?!1:e.dateCreated===e.messageTimestamp}function Em(t){var e;if(t.length<=1)return t;let r=new Map,n=new Map,i=new Map,a=new Map;for(let l=0;l<t.length;l++){let f=t[l];r.set(l,f);let h=f.message.descriptor;if(h.interface===Ge.Protocols&&h.method===ze.Configure){let p=(e=h.definition)===null||e===void 0?void 0:e.protocol;p&&n.set(p,l)}if(h.interface===Ge.Records&&h.method===ze.Write){let p=f.message.recordId;Qz(f.message)&&p&&i.set(p,l),h.protocol===zt.uri&&h.protocolPath===zt.grantPath&&p&&a.set(p,l)}}let s=new Map,o=new Array(t.length).fill(0),d=(l,f)=>{if(l===f)return;s.has(l)||s.set(l,new Set);let h=s.get(l);h.has(f)||(h.add(f),o[f]++)};for(let l=0;l<t.length;l++){let f=t[l].message.descriptor;if(f.interface===Ge.Records){let p=f.protocol;p&&n.has(p)&&d(n.get(p),l)}if(f.interface===Ge.Records&&f.parentId){let p=f.parentId;i.has(p)&&d(i.get(p),l)}if(f.interface===Ge.Records&&f.method===ze.Write){let p=t[l].message.recordId;p&&!Qz(t[l].message)&&i.has(p)&&d(i.get(p),l)}if(f.interface===Ge.Records&&f.method===ze.Delete){let p=f.recordId;p&&i.has(p)&&d(i.get(p),l)}let h=f.permissionGrantId;h&&a.has(h)&&d(a.get(h),l)}let u=[];for(let l=0;l<t.length;l++)o[l]===0&&u.push(l);let c=[];for(;u.length>0;){let l=u.shift();c.push(r.get(l));let f=s.get(l);if(f)for(let h of f)o[h]--,o[h]===0&&u.push(h)}if(c.length<t.length){let l=new Set(c);for(let f=0;f<t.length;f++){let h=r.get(f);l.has(h)||c.push(h)}}return c}y();Jn();var tp=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(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},Jfe=1048576;function e7(t){var e,r;return t.status.code===202||t.status.code===204||t.status.code===409||((e=t.entry)===null||e===void 0?void 0:e.message.descriptor.interface)===Ge.Records&&((r=t.entry)===null||r===void 0?void 0:r.message.descriptor.method)===ze.Delete&&t.status.code===404}function t7(t){return tp(this,void 0,void 0,function*(){try{return yield Se.getCid(t)}catch{return"unknown"}})}function r7(t){return tp(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s,agent:o,permissionsApi:d}){let u=[];if(s)for(let m of s){if(!m.message)continue;let g={message:m.message};if(m.encodedData){let _=ke.base64UrlToBytes(m.encodedData);g.bufferedData=_,g.dataStream=new ReadableStream({start(v){v.enqueue(_),v.close()}})}u.push(g)}let c=a.length>0?yield Xz({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:o,permissionsApi:d}):[],l=[...u,...c],f=Em(l);yield Zfe(f);let h=3,p=f;for(let m=0;m<=h&&p.length>0;m++){let g=[];for(let _ of p){let v=_.bufferedData?new ReadableStream({start(T){T.enqueue(_.bufferedData),T.close()}}):_.dataStream,E=yield o.dwn.processRawMessage(e,_.message,{dataStream:v});e7(E)||g.push(_)}if(g.length>0){let _=[],v=[];for(let E of g)if(E.bufferedData||!E.dataStream)v.push(E);else{let T=yield t7(E.message);_.push(T)}if(_.length>0){let E=yield Xz({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:_,agent:o,permissionsApi:d});v.push(...E)}p=Em(v)}else p=[]}})}function Zfe(t){return tp(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:d,value:u}=yield a.read();if(d)break;if(n+=u.byteLength,n>Jfe){i=!0;break}r.push(u)}}finally{a.releaseLock()}if(i){e.dataStream=void 0;continue}let s=new Uint8Array(n),o=0;for(let d of r)s.set(d,o),o+=d.byteLength;e.bufferedData=s,e.dataStream=new ReadableStream({start(d){d.enqueue(s),d.close()}})}})}function Xz(t){return tp(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:s,permissionsApi:o}){let d=[],u;n&&(u=(yield o.getPermissionForRequest({connectedDid:e,messageType:Te.MessagesRead,delegateDid:n,protocol:i,cached:!0})).grant.id);let c=4,l=0;for(;l<a.length;){let f=a.slice(l,l+c);l+=c;let h=yield Promise.all(f.map(p=>tp(this,void 0,void 0,function*(){var m,g;let _=yield s.processDwnRequest({store:!1,author:e,target:e,messageType:Te.MessagesRead,granteeDid:n,messageParams:{messageCid:p,permissionGrantId:u}}),v;try{v=yield s.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:_.message})}catch(D){console.error(`SyncEngineLevel: pull - failed to read ${p} from ${r}:`,(m=D.message)!==null&&m!==void 0?m:D);return}if(v.status.code!==200||!(!((g=v.entry)===null||g===void 0)&&g.message))return;let E=v.entry,T;return vm(E)&&E.data&&(T=E.data),{message:E.message,dataStream:T}})));for(let p of h)p&&d.push(p)}return d})}function QI(t){return tp(this,arguments,void 0,function*({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:s,permissionsApi:o}){var d;let u=[];for(let l of a){let f=yield Yfe({author:e,messageCid:l,delegateDid:n,protocol:i,agent:s,permissionsApi:o});f&&u.push(f)}let c=Em(u);for(let l of c)try{let f=yield s.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,data:l.dataStream,message:l.message});if(!e7(f)){let h=yield t7(l.message);console.error(`SyncEngineLevel: push failed for ${h}: ${f.status.code} ${f.status.detail}`)}}catch(f){let h=(d=f.message)!==null&&d!==void 0?d:f;throw new Error(`SyncEngineLevel: push to ${r} failed: ${h}`)}})}function Yfe(t){return tp(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:Te.MessagesRead,delegateDid:r,protocol:n,cached:!0})).grant.id);let{reply:d}=yield a.dwn.processRequest({author:e,target:e,messageType:Te.MessagesRead,granteeDid:r,messageParams:{messageCid:i,permissionGrantId:o}});if(d.status.code!==200||!d.entry)return;let u=d.entry,c={message:u.message};return vm(u)&&u.data&&(c.dataStream=u.data),c})}var Rt=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(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},Qfe=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,d){s=t[a](s),i(o,d,s.done,s.value)})}}function i(a,s,o,d){Promise.resolve(d).then(function(u){a({value:u,done:o})},s)}},n7=16,i7=8,epe=4,XI=class{constructor(e){this._waiting=[],this._permits=e}acquire(){return Rt(this,void 0,void 0,function*(){if(this._permits>0){this._permits--;return}return new Promise(e=>{this._waiting.push(e)})})}release(){let e=this._waiting.shift();e?e():this._permits++}run(e){return Rt(this,void 0,void 0,function*(){yield this.acquire();try{return yield e()}finally{this.release()}})}},o7="^",tpe=250,Sm=class t{constructor({agent:e,dataPath:r,db:n}){this._syncLock=!1,this._syncMode="poll",this._liveSubscriptions=[],this._localSubscriptions=[],this._connectivityState="unknown",this._pendingPushCids=new Map,this._consecutiveFailures=0,this._agent=e,this._permissionsApi=new fi({agent:e}),this._db=n||new Xfe(r??"DATA/AGENT/SYNC_STORE")}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 fi({agent:e})}get connectivityState(){return this._connectivityState}clear(){return Rt(this,void 0,void 0,function*(){yield this._permissionsApi.clear(),yield this._db.clear()})}close(){return Rt(this,void 0,void 0,function*(){yield this._db.close()})}registerIdentity(e){return Rt(this,arguments,void 0,function*({did:r,options:n}){let i=this._db.sublevel("registeredIdentities");if(yield this.getIdentityOptions(r))throw new Error(`SyncEngineLevel: Identity with DID ${r} is already registered.`);n??(n={protocols:[]}),yield i.put(r,JSON.stringify(n))})}unregisterIdentity(e){return Rt(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.`);yield r.del(e)})}getIdentityOptions(e){return Rt(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 Rt(this,arguments,void 0,function*({did:r,options: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))})}sync(e){return Rt(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 Set,i=!1;for(let a of r){let{did:s,delegateDid:o,dwnUrl:d,protocol:u}=a;if(!n.has(d))try{let c=yield this.getLocalRoot(s,o,u),l=yield this.getRemoteRoot(s,d,o,u);if(c===l)continue;let f=yield this.diffWithRemote({did:s,dwnUrl:d,delegateDid:o,protocol:u});if((!e||e==="pull")&&f.onlyRemote.length>0){let h=[],p=[];for(let m of f.onlyRemote)m.message?m.message.descriptor.interface==="Records"&&m.message.descriptor.method==="Write"&&m.message.descriptor.dataCid&&!m.encodedData?p.push(m.messageCid):h.push(m):p.push(m.messageCid);yield this.pullMessages({did:s,dwnUrl:d,delegateDid:o,protocol:u,messageCids:p,prefetched:h})}(!e||e==="push")&&f.onlyLocal.length>0&&(yield this.pushMessages({did:s,dwnUrl:d,delegateDid:o,protocol:u,messageCids:f.onlyLocal}))}catch(c){n.add(d),i=!0,console.error(`SyncEngineLevel: Error syncing ${s} with ${d}`,c)}}i?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):(this._consecutiveFailures=0,r.length>0&&(this._connectivityState="online"))}finally{this._syncLock=!1}})}startSync(e){return Rt(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,s7.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 Rt(this,arguments,void 0,function*(e=2e3){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),yield this.teardownLiveSync()})}startPollSync(e){return Rt(this,void 0,void 0,function*(){let r=()=>Rt(this,void 0,void 0,function*(){if(this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{yield this.sync()}catch(a){console.error("SyncEngineLevel: Error during sync operation",a)}let n=Math.min(Math.pow(2,this._consecutiveFailures),t.MAX_BACKOFF_MULTIPLIER),i=this._consecutiveFailures>0?e*n:e;this._syncIntervalId||(this._syncIntervalId=setInterval(r,i))});this._syncIntervalId&&clearInterval(this._syncIntervalId),this._syncIntervalId=setInterval(r,e),this._syncLock||(yield this.sync())})}startLiveSync(e){return Rt(this,void 0,void 0,function*(){try{yield this.sync()}catch(i){console.error("SyncEngineLevel: Error during initial live-sync catch-up",i)}let r=yield this.getSyncTargets();for(let i of r)try{yield this.openLivePullSubscription(i),yield this.openLocalPushSubscription(i)}catch(a){console.error(`SyncEngineLevel: Failed to open live subscription for ${i.did} -> ${i.dwnUrl}`,a)}let n=()=>Rt(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)})}teardownLiveSync(){return Rt(this,void 0,void 0,function*(){this._pushDebounceTimer&&(clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=void 0),this._pendingPushCids.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=[]})}openLivePullSubscription(e){return Rt(this,void 0,void 0,function*(){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=this.buildCursorKey(r,i,a),o=yield this.getCursor(s),d=a?[{protocol:a}]:[],u;if(n)try{u=(yield this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Te.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{u=(yield this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Te.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}let c=h=>Rt(this,void 0,void 0,function*(){if(h.type==="eose"){yield this.setCursor(s,h.cursor),this._connectivityState="online";return}if(h.type==="event"){let p=h.event;try{let m=this.extractDataStream(p);yield this.agent.dwn.processRawMessage(r,p.message,{dataStream:m})}catch(m){console.error(`SyncEngineLevel: Error processing live-pull event for ${r}`,m)}yield this.setCursor(s,h.cursor)}}),f=(yield this.agent.dwn.sendRequest({author:r,target:r,messageType:Te.MessagesSubscribe,granteeDid:n,messageParams:{filters:d,cursor:o,permissionGrantId:u},subscriptionHandler:c})).reply;if(f.status.code!==200||!f.subscription){console.error(`SyncEngineLevel: MessagesSubscribe failed for ${r} -> ${i}: ${f.status.code} ${f.status.detail}`);return}this._liveSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:()=>Rt(this,void 0,void 0,function*(){yield f.subscription.close()})}),this._connectivityState="online"})}openLocalPushSubscription(e){return Rt(this,void 0,void 0,function*(){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=a?[{protocol:a}]:[],o;n&&(o=(yield this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Te.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id);let d=l=>{if(l.type!=="event")return;let f=this.buildCursorKey(r,i,a),h=this.tryGetCidSync(l.event.message);if(h===void 0)return;let p=this._pendingPushCids.get(f);p||(p={did:r,dwnUrl:i,delegateDid:n,protocol:a,cids:[]},this._pendingPushCids.set(f,p)),p.cids.push(h),this._pushDebounceTimer&&clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=setTimeout(()=>{this.flushPendingPushes()},tpe)},c=(yield this.agent.dwn.processRequest({author:r,target:r,messageType:Te.MessagesSubscribe,granteeDid:n,messageParams:{filters:s,permissionGrantId:o},subscriptionHandler:d})).reply;if(c.status.code!==200||!c.subscription){console.error(`SyncEngineLevel: Local MessagesSubscribe failed for ${r}: ${c.status.code} ${c.status.detail}`);return}this._localSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:()=>Rt(this,void 0,void 0,function*(){yield c.subscription.close()})})})}flushPendingPushes(){return Rt(this,void 0,void 0,function*(){this._pushDebounceTimer=void 0;let e=[...this._pendingPushCids.entries()];this._pendingPushCids.clear();for(let[,r]of e){let{did:n,dwnUrl:i,delegateDid:a,protocol:s,cids:o}=r;if(o.length!==0)try{yield QI({did:n,dwnUrl:i,delegateDid:a,protocol:s,messageCids:o,agent:this.agent,permissionsApi:this._permissionsApi})}catch(d){console.error(`SyncEngineLevel: Push-on-write failed for ${n} -> ${i}`,d)}}})}buildCursorKey(e,r,n){let i=`${e}${o7}${r}`;return n?`${i}${o7}${n}`:i}getCursor(e){return Rt(this,void 0,void 0,function*(){let r=this._db.sublevel("syncCursors");try{return yield r.get(e)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}})}setCursor(e,r){return Rt(this,void 0,void 0,function*(){yield this._db.sublevel("syncCursors").put(e,r)})}extractDataStream(e){if(vm(e)&&e.data)return e.data}tryGetCidSync(e){var r;let n;return Se.getCid(e).then(i=>{n=i}),(r=n??e.messageCid)!==null&&r!==void 0?r:void 0}getDefaultHashHex(e){return Rt(this,void 0,void 0,function*(){var r;if(this._defaultHashHex===void 0){let n=yield Ng(),i=new Map;for(let a=0;a<=n7;a++)i.set(a,md(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 Rt(this,void 0,void 0,function*(){var i;let a=this.stateIndex;if(a){let u=n!==void 0?yield a.getProtocolRoot(e,n):yield a.getRoot(e);return md(u)}let s=yield this.getSyncPermissionGrantId(e,r,n);return(i=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Te.MessagesSync,granteeDid:r,messageParams:{action:"root",protocol:n,permissionGrantId:s}})).reply.root)!==null&&i!==void 0?i:""})}getRemoteRoot(e,r,n,i){return Rt(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:Te.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:""})}walkTreeDiff(e){return Rt(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a}){let s=[],o=[],d=yield this.getSyncPermissionGrantId(r,i,a),u=new XI(epe),c=l=>Rt(this,void 0,void 0,function*(){let[f,h]=yield Promise.all([this.getLocalSubtreeHash(r,l,i,a,d),u.run(()=>this.getRemoteSubtreeHash(r,n,l,i,a,d))]);if(f===h)return;let p=yield this.getDefaultHashHex(l.length);if(h===p&&f!==p){let m=yield this.getLocalLeaves(r,l,i,a,d);s.push(...m);return}if(f===p&&h!==p){let m=yield u.run(()=>this.getRemoteLeaves(r,n,l,i,a,d));o.push(...m);return}if(l.length>=n7){let[m,g]=yield Promise.all([this.getLocalLeaves(r,l,i,a,d),u.run(()=>this.getRemoteLeaves(r,n,l,i,a,d))]),_=new Set(m),v=new Set(g);for(let E of m)v.has(E)||s.push(E);for(let E of g)_.has(E)||o.push(E);return}yield Promise.all([c(l+"0"),c(l+"1")])});return yield c(""),{onlyLocal:s,onlyRemote:o}})}diffWithRemote(e){return Rt(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a}){var s,o;let d=yield this.collectLocalSubtreeHashes(r,a,i7),u=yield this.getSyncPermissionGrantId(r,i,a),c=yield this.agent.dwn.processRequest({store:!1,author:r,target:r,messageType:Te.MessagesSync,granteeDid:i,messageParams:{action:"diff",protocol:a,hashes:d,depth:i7,permissionGrantId:u}}),l=yield this.agent.rpc.sendDwnRequest({dwnUrl:n,targetDid:r,message:c.message});if(l.status.code!==200)throw new Error(`SyncEngineLevel: diff failed with ${l.status.code}: ${l.status.detail}`);let f=yield this.getSyncPermissionGrantId(r,i,a),h=[];for(let p of(s=l.onlyLocal)!==null&&s!==void 0?s:[]){let m=yield this.getLocalLeaves(r,p,i,a,f);h.push(...m)}return{onlyRemote:(o=l.onlyRemote)!==null&&o!==void 0?o:[],onlyLocal:h}})}collectLocalSubtreeHashes(e,r,n){return Rt(this,void 0,void 0,function*(){let i={},a=yield this.getDefaultHashHex(n),s=this.stateIndex,o=(d,u)=>Rt(this,void 0,void 0,function*(){let c;if(s){let l=t.parseBitPrefix(d),f=r!==void 0?yield s.getProtocolSubtreeHash(e,r,l):yield s.getSubtreeHash(e,l);c=md(f)}else c=yield this.getLocalSubtreeHash(e,d,void 0,r);if(c!==a){if(u>=n){i[d]=c;return}yield Promise.all([o(d+"0",u+1),o(d+"1",u+1)])}});return yield o("",0),i})}getLocalSubtreeHash(e,r,n,i,a){return Rt(this,void 0,void 0,function*(){var s;let o=this.stateIndex;if(o){let c=t.parseBitPrefix(r),l=i!==void 0?yield o.getProtocolSubtreeHash(e,i,c):yield o.getSubtreeHash(e,c);return md(l)}return(s=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Te.MessagesSync,granteeDid:n,messageParams:{action:"subtree",prefix:r,protocol:i,permissionGrantId:a}})).reply.hash)!==null&&s!==void 0?s:""})}getRemoteSubtreeHash(e,r,n,i,a,s){return Rt(this,void 0,void 0,function*(){var o;let d=yield this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Te.MessagesSync,granteeDid:i,messageParams:{action:"subtree",prefix:n,protocol:a,permissionGrantId:s}});return(o=(yield this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:d.message})).hash)!==null&&o!==void 0?o:""})}getLocalLeaves(e,r,n,i,a){return Rt(this,void 0,void 0,function*(){var s;let o=this.stateIndex;if(o){let c=t.parseBitPrefix(r);return i!==void 0?yield o.getProtocolLeaves(e,i,c):yield o.getLeaves(e,c)}return(s=(yield this.agent.dwn.processRequest({author:e,target:e,messageType:Te.MessagesSync,granteeDid:n,messageParams:{action:"leaves",prefix:r,protocol:i,permissionGrantId:a}})).reply.entries)!==null&&s!==void 0?s:[]})}getRemoteLeaves(e,r,n,i,a,s){return Rt(this,void 0,void 0,function*(){var o;let d=yield this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Te.MessagesSync,granteeDid:i,messageParams:{action:"leaves",prefix:n,protocol:a,permissionGrantId:s}});return(o=(yield this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:d.message})).entries)!==null&&o!==void 0?o:[]})}pullMessages(e){return Rt(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,prefetched:o}){return r7({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,prefetched:o,agent:this.agent,permissionsApi:this._permissionsApi})})}pushMessages(e){return Rt(this,arguments,void 0,function*({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s}){return QI({did:r,dwnUrl:n,delegateDid:i,protocol:a,messageCids:s,agent:this.agent,permissionsApi:this._permissionsApi})})}static topologicalSort(e){return Em(e)}getSyncTargets(){return Rt(this,void 0,void 0,function*(){var e,r,n,i;let a=[];try{for(var s=!0,o=Qfe(this._db.sublevel("registeredIdentities").iterator()),d;d=yield o.next(),e=d.done,!e;s=!0){i=d.value,s=!1;let[u,c]=i,l;try{l=JSON.parse(c)}catch(m){console.warn(`SyncEngineLevel: Corrupt sync options for ${u}, falling back to global sync:`,m),l={protocols:[]}}let{protocols:f,delegateDid:h}=l,p=yield this.agent.dwn.getDwnEndpointUrlsForTarget(u);if(p.length!==0)for(let m of p)if(f.length===0)a.push({did:u,delegateDid:h,dwnUrl:m});else for(let g of f)a.push({did:u,delegateDid:h,dwnUrl:m,protocol:g})}}catch(u){r={error:u}}finally{try{!s&&!e&&(n=o.return)&&(yield n.call(o))}finally{if(r)throw r.error}}return a})}getSyncPermissionGrantId(e,r,n){return Rt(this,void 0,void 0,function*(){return r?(yield this._permissionsApi.getPermissionForRequest({connectedDid:e,messageType:Te.MessagesSync,delegateDid:r,protocol:n,cached:!0})).grant.id:void 0})}};Sm.MAX_CONSECUTIVE_FAILURES=5;Sm.MAX_BACKOFF_MULTIPLIER=4;y();Jn();Fo();Kt();import{Level as VWe}from"level";y();y();y();Kt();rn();y();y();var a7=wn(pP(),1);Kt();var Tm=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(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},mP=class{constructor({ttl:e="15m"}={}){this.cache=new Kl.default({ttl:(0,a7.default)(e)})}get(e){return Tm(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,r){return Tm(this,void 0,void 0,function*(){this.cache.set(e,r)})}delete(e){return Tm(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return Tm(this,void 0,void 0,function*(){this.cache.clear()})}open(){return Tm(this,void 0,void 0,function*(){})}close(){return Tm(this,void 0,void 0,function*(){})}};y();rn();Jn();y();var km=class extends Error{constructor(e,r){super(r??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};y();var Am;(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"})(Am||(Am={}));var Dm=(t,e,r)=>({jsonrpc:"2.0",id:t,method:e,params:r}),yP=(t,e,r,n)=>({jsonrpc:"2.0",id:t,method:e,params:r,subscription:{id:n??null}}),c7=(t,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:t}});function rp(t){try{return JSON.parse(t)}catch{return null}}var eR=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(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},rpe=3,npe=500,ipe=1e4,ope=3e4,d7=new Set([408,429,500,502,503,504]);function spe(t,e){return t instanceof TypeError?!0:e?d7.has(e.status):!1}function ape(t,e,r){let n=Math.min(e*Math.pow(2,t),r),i=.5+Math.random()*.5;return n*i}function cpe(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 gP=class t{constructor(e,r){var n,i,a;this.serverInfoCache=e??new mP,this._retryOptions={maxRetries:(n=r?.maxRetries)!==null&&n!==void 0?n:rpe,baseDelayMs:(i=r?.baseDelayMs)!==null&&i!==void 0?i:npe,maxDelayMs:(a=r?.maxDelayMs)!==null&&a!==void 0?a:ipe}}static isBunRuntime(){return typeof globalThis.Bun<"u"}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return eR(this,void 0,void 0,function*(){var r,n,i;let a=gi.randomUuid(),s=Dm(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),o={"dwn-request":JSON.stringify(s)},d={method:"POST",headers:o};if(e.data){o["content-type"]="application/octet-stream";let h=e.data;if(h instanceof ReadableStream)if(t.isBunRuntime()){let p=yield Hi.toBytes(h);h=new Blob([p],{type:"application/octet-stream"})}else d.duplex="half";d.body=h}let u=yield this.fetchWithRetry(e.dwnUrl,d);if(u.status===429){let h=parseInt((r=u.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new km(h)}let c,l=u.headers.has("dwn-response");if(l){let h=rp(u.headers.get("dwn-response"));if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);c=h}else{let h=yield u.text(),p=rp(h);if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${u.status}`);c=p}if(c.error){let{code:h,message:p}=c.error;if(h===Am.TooManyRequests){let m=(i=(n=c.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new km(m)}throw new Error(`(${h}) - ${p}`)}let{reply:f}=c.result;if(l){let h=new Uint8Array(yield u.arrayBuffer()),p=Hi.fromBytes(h);f.record?f.record.data=p:f.entry&&(f.entry.data=p)}return f})}getServerInfo(e){return eR(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 km(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 eR(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,s,o;for(let d=0;d<=n;d++){try{let f=AbortSignal.timeout(ope),h=Object.assign(Object.assign({},r),{signal:r?.signal?AbortSignal.any([r.signal,f]):f}),p=yield fetch(e,h);if(!d7.has(p.status)||d===n)return p;o=p}catch(f){if(!spe(f)||d===n)throw f;s=f}let u=o?cpe(o):void 0,c=ape(d,i,a),l=u!==void 0?Math.max(u,c):c;yield new Promise(f=>{setTimeout(f,l)})}if(o)return o;throw s})}};y();rn();var g0=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(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})};function tR(t){return typeof t=="string"?t:t instanceof ArrayBuffer?new TextDecoder().decode(t):t instanceof Uint8Array?new TextDecoder().decode(t):String(t)}var u7=3e3,dpe=3e4,upe=1e3,lpe=3e4,fpe=1/0,wP=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.url=n,this.options=i,this._isConnected=!0}get isConnected(){return this._isConnected}static connect(e){return g0(this,arguments,void 0,function*(r,n={}){var i;let{connectTimeout:a=u7,responseTimeout:s=dpe}=n,o;try{o=yield t.createWebSocket(r,a)}catch(u){throw(i=n.onerror)===null||i===void 0||i.call(n,u),u}let d=new t(o,s,r,n);return d.wireSocket(o),d})}close(){this.closedByUser=!0,this._isConnected=!1,this.socket.close()}request(e){return g0(this,void 0,void 0,function*(){return new Promise((r,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=gi.randomUuid());let a=s=>{let o=rp(tR(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 g0(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=d=>{let u=rp(tR(d.data));u.id===n&&(u.error!==void 0&&(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),this.closeSubscription(n).catch(()=>{})),r(u))};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:()=>g0(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let r=gi.randomUuid(),n=yP(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=()=>{u(),n(a)},o=c=>{u(),i(c)},d=setTimeout(()=>{u(),a.close(),i(new Error("connect timed out"))},r),u=()=>{clearTimeout(d),a.removeEventListener("open",s),a.removeEventListener("error",o)};a.addEventListener("open",s),a.addEventListener("error",o)})}wireSocket(e){e.addEventListener("message",r=>{let n=rp(tR(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.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:Am.TransportError,message:"WebSocket connection closed unexpectedly"}});r({data:n}),this.messageHandlers.delete(e)}}attemptReconnect(){var e,r,n,i;this.reconnecting=!0;let a=(e=this.options.baseReconnectDelay)!==null&&e!==void 0?e:upe,s=(r=this.options.maxReconnectDelay)!==null&&r!==void 0?r:lpe,o=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:fpe,d=(i=this.options.connectTimeout)!==null&&i!==void 0?i:u7,u=0,c=()=>g0(this,void 0,void 0,function*(){var l,f,h,p;if(this.closedByUser){this.reconnecting=!1;return}if(u++,u>o){this.reconnecting=!1;return}(f=(l=this.options).onreconnecting)===null||f===void 0||f.call(l,u);let g=Math.min(a*Math.pow(2,u-1),s)*(.5+Math.random()*.5);if(yield new Promise(_=>setTimeout(_,g)),this.closedByUser){this.reconnecting=!1;return}try{let _=yield t.createWebSocket(this.url,d);this.socket=_,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(_),(p=(h=this.options).onreconnected)===null||p===void 0||p.call(h)}catch{yield c()}});c()}};y();y();y();rn();y();rn();var Im=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(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},w0=class t{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return Im(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 d=yield t.createConnection(r);t.connections.set(r.host,d)}catch(d){throw new Error(`Error connecting to ${r.host}: ${d.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 Im(this,void 0,void 0,function*(){let r=e.host,n=new Map,i=yield wP.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 Im(this,void 0,void 0,function*(){let i=gi.randomUuid(),a=Dm(i,"dwn.processMessage",{target:r,message:n}),{socket:s}=e,o=yield s.request(a),{error:d,result:u}=o;if(d!==void 0)throw new Error(`error sending DWN request: ${d.message}`);return u.reply})}static subscriptionRequest(e,r,n,i,a){return Im(this,void 0,void 0,function*(){let s=gi.randomUuid(),o=gi.randomUuid(),d=yP(s,"rpc.subscribe.dwn.processMessage",{target:r,message:n},o),{socket:u,subscriptions:c}=e,{response:l,close:f}=yield u.subscribe(d,g=>{let{result:_,error:v}=g;if(v){let T=c.get(o);T&&T.subscription.close(),c.delete(o);return}let E=_.subscription;if(i(E),"cursor"in E&&E.cursor){let T=c.get(o);T&&(T.lastCursor=E.cursor),u.send(c7(o,E.cursor))}}),{error:h,result:p}=l;if(h)throw new Error(`could not subscribe via jsonrpc socket: ${h.message}`);let{reply:m}=p;if(m.subscription&&f){let g=()=>Im(this,void 0,void 0,function*(){c.delete(o),yield f()}),_={subscription:Object.assign(Object.assign({},m.subscription),{close:g}),target:r,message:n,handler:i,resubscribeFactory:a};c.set(o,_),m.subscription.close=g}return m})}static resubscribeAll(e){return Im(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{}})}};w0.connections=new Map;var v0=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(c){try{u(n.next(c))}catch(l){s(l)}}function d(c){try{u(n.throw(c))}catch(l){s(l)}}function u(c){c.done?a(c.value):i(c.value).then(o,d)}u((n=n.apply(t,e||[])).next())})},l7;(function(t){t.Create="did.create",t.Resolve="did.resolve"})(l7||(l7={}));var Rm=class{constructor(e=[]){this.transportClients=new Map,e=[new rR,new nR,...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 v0(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 v0(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)})}},rR=class extends gP{sendDidRequest(e){return v0(this,void 0,void 0,function*(){let r=gi.randomUuid(),n=Dm(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:d}=a.error;throw new Error(`JSON RPC (${o}) - ${d}`)}}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})}},nR=class extends w0{sendDidRequest(e){return v0(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return v0(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};y();y();Fo();Kt();rn();Jn();y();Kt();Fo();var vP=class{constructor(e){this.agent=e.agent,this.connectedDid=e.connectedDid}async create(e){let{result:r,...n}=await this.agent.processDidRequest({messageType:y0.Create,messageParams:{...e}});return{did:r,...n}}async resolve(e,r){let{result:n}=await this.agent.processDidRequest({messageParams:{didUri:e,options:r},messageType:y0.Resolve});return n}};y();y();Kt();var b0=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=Wo(r)??"unknown"}catch{this._author="unknown"}try{this._creator=n?Wo(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([Ue.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 Co.consumeToBytes({readableStream:await this.stream()})],{type:e.dataFormat})},async bytes(){return await Co.consumeToBytes({readableStream:await this.stream()})},async json(){return await Co.consumeToJson({readableStream:await this.stream()})},async text(){return await Co.consumeToText({readableStream:await this.stream()})},async stream(){if(e._encodedData)return Co.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}
|