@enbox/agent 0.5.14 → 0.5.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.mjs
CHANGED
|
@@ -2057,7 +2057,7 @@ zone
|
|
|
2057
2057
|
zoo`.split(`
|
|
2058
2058
|
`);Qo();Sr();g();Xh();g();Xh();Zb();Ha();function tge(t,e,r,n){Wb(t);let i=T8({dkLen:32,asyncTick:10},n),{c:a,dkLen:s,asyncTick:o}=i;if(Ql(a),Ql(s),Ql(o),a<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let c=eu(e),l=eu(r),d=new Uint8Array(s),u=tu.create(t,c),f=u._cloneInto().update(l);return{c:a,dkLen:s,asyncTick:o,DK:d,PRF:u,PRFSalt:f}}function rge(t,e,r,n,i){return t.destroy(),e.destroy(),n&&n.destroy(),i.fill(0),r}async function wH(t,e,r,n){let{c:i,dkLen:a,asyncTick:s,DK:o,PRF:c,PRFSalt:l}=tge(t,e,r,n),d,u=new Uint8Array(4),f=zd(u),h=new Uint8Array(c.outputLen);for(let p=1,m=0;m<a;p++,m+=c.outputLen){let y=o.subarray(m,m+c.outputLen);f.setInt32(0,p,!1),(d=l._cloneInto(d)).update(u).digestInto(h),y.set(h.subarray(0,y.length)),await _8(i-1,s,()=>{c._cloneInto(d).update(h).digestInto(h);for(let v=0;v<y.length;v++)y[v]^=h[v]})}return rge(c,l,o,d,h)}Vg();dP();Ha();g();function Ch(t){if(!Number.isSafeInteger(t))throw new Error(`Wrong integer: ${t}`)}function rS(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function nge(...t){let e=a=>a,r=(a,s)=>o=>a(s(o)),n=t.map(a=>a.encode).reduceRight(r,e),i=t.map(a=>a.decode).reduce(r,e);return{encode:n,decode:i}}function ige(t){return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("alphabet.encode input should be an array of numbers");return e.map(r=>{if(r<0||r>=t.length)throw new Error(`Digit index outside alphabet: ${r} (alphabet: ${t.length})`);return t[r]})},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("alphabet.decode input should be array of strings");return e.map(r=>{if(typeof r!="string")throw new Error(`alphabet.decode: not string element=${r}`);let n=t.indexOf(r);if(n===-1)throw new Error(`Unknown letter: "${r}". Allowed: ${t}`);return n})}}}function sge(t=""){if(typeof t!="string")throw new Error("join separator should be string");return{encode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="string")throw new Error("join.encode input should be array of strings");for(let r of e)if(typeof r!="string")throw new Error(`join.encode: non-string input=${r}`);return e.join(t)},decode:e=>{if(typeof e!="string")throw new Error("join.decode input should be string");return e.split(t)}}}function oge(t,e="="){if(typeof e!="string")throw new Error("padding chr should be string");return{encode(r){if(!Array.isArray(r)||r.length&&typeof r[0]!="string")throw new Error("padding.encode input should be array of strings");for(let n of r)if(typeof n!="string")throw new Error(`padding.encode: non-string input=${n}`);for(;r.length*t%8;)r.push(e);return r},decode(r){if(!Array.isArray(r)||r.length&&typeof r[0]!="string")throw new Error("padding.encode input should be array of strings");for(let i of r)if(typeof i!="string")throw new Error(`padding.decode: non-string input=${i}`);let n=r.length;if(n*t%8)throw new Error("Invalid padding: string should have whole number of bytes");for(;n>0&&r[n-1]===e;n--)if(!((n-1)*t%8))throw new Error("Invalid padding: string has too much padding");return r.slice(0,n)}}}function q6(t,e,r){if(e<2)throw new Error(`convertRadix: wrong from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: wrong to=${r}, base cannot be less than 2`);if(!Array.isArray(t))throw new Error("convertRadix: data should be array");if(!t.length)return[];let n=0,i=[],a=Array.from(t);for(a.forEach(s=>{if(s<0||s>=e)throw new Error(`Wrong integer: ${s}`)});;){let s=0,o=!0;for(let c=n;c<a.length;c++){let l=a[c],d=e*s+l;if(!Number.isSafeInteger(d)||e*s/e!==s||d-l!==e*s)throw new Error("convertRadix: carry overflow");s=d%r;let u=Math.floor(d/r);if(a[c]=u,!Number.isSafeInteger(u)||u*r+s!==d)throw new Error("convertRadix: carry overflow");if(o)u?o=!1:n=c;else continue}if(i.push(s),o)break}for(let s=0;s<t.length-1&&t[s]===0;s++)i.push(0);return i.reverse()}var vH=(t,e)=>e?vH(e,t%e):t,nS=(t,e)=>t+(e-vH(t,e));function z6(t,e,r,n){if(!Array.isArray(t))throw new Error("convertRadix2: data should be array");if(e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(nS(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${nS(e,r)}`);let i=0,a=0,s=2**r-1,o=[];for(let c of t){if(c>=2**e)throw new Error(`convertRadix2: invalid data word=${c} from=${e}`);if(i=i<<e|c,a+e>32)throw new Error(`convertRadix2: carry overflow pos=${a} from=${e}`);for(a+=e;a>=r;a-=r)o.push((i>>a-r&s)>>>0);i&=2**a-1}if(i=i<<r-a&s,!n&&a>=e)throw new Error("Excess padding");if(!n&&i)throw new Error(`Non-zero padding: ${i}`);return n&&a>0&&o.push(i>>>0),o}function age(t){return{encode:e=>{if(!rS(e))throw new Error("radix.encode input should be Uint8Array");return q6(Array.from(e),2**8,t)},decode:e=>{if(!Array.isArray(e)||e.length&&typeof e[0]!="number")throw new Error("radix.decode input should be array of numbers");return Uint8Array.from(q6(e,t,2**8))}}}function cge(t,e=!1){if(t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(nS(8,t)>32||nS(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!rS(r))throw new Error("radix2.encode input should be Uint8Array");return z6(Array.from(r),8,t,!e)},decode:r=>{if(!Array.isArray(r)||r.length&&typeof r[0]!="number")throw new Error("radix2.decode input should be array of numbers");return Uint8Array.from(z6(r,t,8,e))}}}function dge(t,e){if(typeof e!="function")throw new Error("checksum fn should be function");return{encode(r){if(!rS(r))throw new Error("checksum.encode: input should be Uint8Array");let n=e(r).slice(0,t),i=new Uint8Array(r.length+t);return i.set(r),i.set(n,r.length),i},decode(r){if(!rS(r))throw new Error("checksum.decode: input should be Uint8Array");let n=r.slice(0,-t),i=e(n).slice(0,t),a=r.slice(-t);for(let s=0;s<t;s++)if(i[s]!==a[s])throw new Error("Invalid checksum");return n}}}var xb={alphabet:ige,chain:nge,checksum:dge,convertRadix:q6,convertRadix2:z6,radix:age,radix2:cge,join:sge,padding:oge};var lge=t=>t[0]==="\u3042\u3044\u3053\u304F\u3057\u3093";function bH(t){if(typeof t!="string")throw new TypeError(`Invalid mnemonic type: ${typeof t}`);return t.normalize("NFKD")}function PH(t){let e=bH(t),r=e.split(" ");if(![12,15,18,21,24].includes(r.length))throw new Error("Invalid mnemonic");return{nfkd:e,words:r}}function xH(t){Ld(t,16,20,24,28,32)}function EH(t,e=128){if(Ql(e),e%32!==0||e>256)throw new TypeError("Invalid entropy");return pge(Vf(e/8),t)}var uge=t=>{let e=8-t.length/4;return new Uint8Array([ou(t)[0]>>e<<e])};function SH(t){if(!Array.isArray(t)||t.length!==2048||typeof t[0]!="string")throw new Error("Wordlist: expected array of 2048 strings");return t.forEach(e=>{if(typeof e!="string")throw new Error(`Wordlist: non-string element: ${e}`)}),xb.chain(xb.checksum(1,uge),xb.radix2(11,!0),xb.alphabet(t))}function fge(t,e){let{words:r}=PH(t),n=SH(e).decode(r);return xH(n),n}function pge(t,e){return xH(t),SH(e).encode(t).join(lge(e)?"\u3000":" ")}function kH(t,e){try{fge(t,e)}catch{return!1}return!0}var hge=t=>bH(`mnemonic${t}`);function AH(t,e=""){return wH(Iu,PH(t).nfkd,hge(e),{c:2048,dkLen:64})}g();Pn();g();Sr();Pn();g();Sr();Pn();function Sb(t){return typeof t=="object"&&t!==null&&"alg"in t&&t.alg!==void 0&&"enc"in t&&t.enc!==void 0}var Eb=class{static async decrypt({key:e,encryptedKey:r,joseHeader:n,crypto:i},a){let s=a?.minP2cCount??1e3;switch(n.alg){case"dir":{if(r!==void 0)throw new Fe(Le.InvalidJwe,'JWE "encrypted_key" is not allowed when using "dir" (Direct Encryption Mode).');if(e instanceof Uint8Array)throw new Fe(Le.InvalidJwe,'Key management "key" must be a Key URI or JWK when using "dir" (Direct Encryption Mode).');return e}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(typeof n.p2c!="number")throw new Fe(Le.InvalidJwe,'JOSE Header "p2c" (PBES2 Count) is missing or not a number.');if(n.p2c<s)throw new Fe(Le.InvalidJwe,`JOSE Header "p2c" (PBES2 Count) is ${n.p2c}, which is below the minimum of ${s}.`);if(typeof n.p2s!="string")throw new Fe(Le.InvalidJwe,'JOSE Header "p2s" (PBES2 salt) is missing or not a string.');if(!(e instanceof Uint8Array))throw new Fe(Le.InvalidJwe,'Key management "key" must be a Uint8Array when using "PBES2" (Key Encryption Mode).');if(r===void 0)throw new Fe(Le.InvalidJwe,'JWE "encrypted_key" is required when using "PBES2" (Key Encryption Mode).');let o;try{o=new Uint8Array([...he.string(n.alg).toUint8Array(),0,...he.base64Url(n.p2s).toUint8Array()])}catch{throw new Fe(Le.EncodingError,'Failed to decode the JOSE Header "p2s" (PBES2 salt) value.')}let c=await i.deriveKey({algorithm:n.alg,baseKeyBytes:e,iterations:n.p2c,salt:o});if(!(c.alg&&["A128KW","A192KW","A256KW"].includes(c.alg)))throw new Fe(Le.AlgorithmNotSupported,`Unsupported Key Encryption Algorithm (alg) value: ${c.alg}`);return await i.unwrapKey({decryptionKey:c,wrappedKeyBytes:r,wrappedKeyAlgorithm:n.enc})}default:throw new Fe(Le.AlgorithmNotSupported,`Unsupported "alg" (Algorithm) Header Parameter value: ${n.alg}`)}}static async encrypt({key:e,joseHeader:r,crypto:n}){let i,a;switch(r.alg){case"dir":{if(a!==void 0)throw new Fe(Le.InvalidJwe,'JWE "encrypted_key" is not allowed when using "dir" (Direct Encryption Mode).');if(e instanceof Uint8Array)throw new Fe(Le.InvalidJwe,'Key management "key" must be a Key URI or JWK when using "dir" (Direct Encryption Mode).');i=e;break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(typeof r.p2c!="number")throw new Fe(Le.InvalidJwe,'JOSE Header "p2c" (PBES2 Count) is missing or not a number.');if(typeof r.p2s!="string")throw new Fe(Le.InvalidJwe,'JOSE Header "p2s" (PBES2 salt) is missing or not a string.');if(!(e instanceof Uint8Array))throw new Fe(Le.InvalidJwe,'Key management "key" must be a Uint8Array when using "PBES2" (Key Encryption Mode).');i=await n.generateKey({algorithm:r.enc});let s;try{s=new Uint8Array([...he.string(r.alg).toUint8Array(),0,...he.base64Url(r.p2s).toUint8Array()])}catch{throw new Fe(Le.EncodingError,'Failed to decode the JOSE Header "p2s" (PBES2 salt) value.')}let o=await n.deriveKey({algorithm:r.alg,baseKeyBytes:e,iterations:r.p2c,salt:s});a=await n.wrapKey({encryptionKey:o,unwrappedKey:i});break}default:throw new Fe(Le.AlgorithmNotSupported,`Unsupported "alg" (Algorithm) Header Parameter value: ${r.alg}`)}return{cek:i,encryptedKey:a}}};function F6(t,e){if(e!==void 0)try{if(typeof e!="string")throw new Error;return he.base64Url(e).toUint8Array()}catch{throw new Fe(Le.InvalidJwe,`Failed to decode the JWE Header parameter '${t}' from Base64 URL format to Uint8Array. Ensure the value is properly encoded in Base64 URL format without padding.`)}}var kb=class t{constructor(e){this.ciphertext="";Object.assign(this,e)}static async decrypt({jwe:e,key:r,keyManager:n=new Vc,crypto:i=new bo,options:a={}}){if(!e0(i))throw new Fe(Le.OperationNotSupported,'Crypto API does not support the "encrypt" operation.');if(!e0(n))throw new Fe(Le.OperationNotSupported,'Key Manager does not support the "decrypt" operation.');if(!e.protected&&!e.header&&!e.unprotected)throw new Fe(Le.InvalidJwe,'JWE is missing the required JOSE header parameters. Please provide at least one of the following: "protected", "header", or "unprotected"');if(typeof e.ciphertext!="string")throw new Fe(Le.InvalidJwe,"JWE Ciphertext is missing or not a string.");let s;if(e.protected)try{s=he.base64Url(e.protected).toObject()}catch{throw new Error("JWE Protected Header is invalid")}if(_H(s,e.header,e.unprotected))throw new Error('Duplicate properties detected. Please ensure that each parameter is defined only once across the JWE "header", "protected", and "unprotected" objects.');let o={...s,...e.header,...e.unprotected};if(!Sb(o))throw new Error('JWE Header is missing required "alg" (Algorithm) and/or "enc" (Encryption) Header Parameters');if(Array.isArray(a.allowedAlgValues)&&!a.allowedAlgValues.includes(o.alg))throw new Error(`"alg" (Algorithm) Header Parameter value not allowed: ${o.alg}`);if(Array.isArray(a.allowedEncValues)&&!a.allowedEncValues.includes(o.enc))throw new Error(`"enc" (Encryption Algorithm) Header Parameter value not allowed: ${o.enc}`);let c;try{let p=e.encrypted_key?he.base64Url(e.encrypted_key).toUint8Array():void 0;c=await Eb.decrypt({key:r,encryptedKey:p,joseHeader:o,keyManager:n,crypto:i},{minP2cCount:a.minP2cCount})}catch(p){if(p instanceof Fe&&(p.code===Le.InvalidJwe||p.code===Le.AlgorithmNotSupported))throw p;c=typeof r=="string"?await n.generateKey({algorithm:o.enc}):await i.generateKey({algorithm:o.enc})}let l=F6("iv",e.iv),d=F6("tag",e.tag),u=d!==void 0?new Uint8Array([...he.base64Url(e.ciphertext).toUint8Array(),...d??[]]):he.base64Url(e.ciphertext).toUint8Array(),f=e.aad!==void 0?new Uint8Array([...he.string(e.protected??"").toUint8Array(),...he.string(".").toUint8Array(),...he.string(e.aad).toUint8Array()]):he.string(e.protected??"").toUint8Array();return{plaintext:typeof c=="string"?await n.decrypt({keyUri:c,data:u,iv:l,additionalData:f}):await i.decrypt({key:c,data:u,iv:l,additionalData:f}),protectedHeader:s,additionalAuthenticatedData:F6("aad",e.aad),sharedUnprotectedHeader:e.unprotected,unprotectedHeader:e.header}}static async encrypt({key:e,plaintext:r,additionalAuthenticatedData:n,protectedHeader:i,sharedUnprotectedHeader:a,unprotectedHeader:s,keyManager:o=new Vc,crypto:c=new bo}){if(!e0(c))throw new Fe(Le.OperationNotSupported,'Crypto API does not support the "encrypt" operation.');if(!e0(o))throw new Fe(Le.OperationNotSupported,'Key Manager does not support the "decrypt" operation.');if(!i&&!a&&!s)throw new Fe(Le.InvalidJwe,'JWE is missing the required JOSE header parameters. Please provide at least one of the following: "protectedHeader", "sharedUnprotectedHeader", or "unprotectedHeader"');if(!(r instanceof Uint8Array))throw new Fe(Le.InvalidJwe,"Plaintext is missing or not a byte array.");if(_H(i,a,s))throw new Error('Duplicate properties detected. Please ensure that each parameter is defined only once across the JWE "protectedHeader", "sharedUnprotectedHeader", and "unprotectedHeader" objects.');let l={...i,...a,...s};if(!Sb(l))throw new Error('JWE Header is missing required "alg" (Algorithm) and/or "enc" (Encryption) Header Parameters');let{cek:d,encryptedKey:u}=await Eb.encrypt({key:e,joseHeader:l,keyManager:o,crypto:c}),f;switch(l.enc){case"A128GCM":case"A192GCM":case"A256GCM":f=bn.randomBytes(12);break;default:f=new Uint8Array(0)}let h=i?he.object(i).toBase64Url():"",p,m;n?(m=he.uint8Array(n).toBase64Url(),p=he.string(h+"."+m).toUint8Array()):p=he.string(h).toUint8Array();let y=typeof d=="string"?await o.encrypt({keyUri:d,data:r,iv:f,additionalData:p}):await c.encrypt({key:d,data:r,iv:f,additionalData:p}),v=y.slice(0,-16),w=y.slice(-16),S=new t({ciphertext:he.uint8Array(v).toBase64Url()});return u&&(S.encrypted_key=he.uint8Array(u).toBase64Url()),i&&(S.protected=h),a&&(S.unprotected=a),s&&(S.header=s),f&&(S.iv=he.uint8Array(f).toBase64Url()),m&&(S.aad=m),w&&(S.tag=he.uint8Array(w).toBase64Url()),S}};function _H(...t){let e=new Set,r=t.filter(Boolean);for(let n of r)for(let i in n){if(e.has(i))return!0;e.add(i)}return!1}var Vl=class{static async decrypt({jwe:e,key:r,keyManager:n=new Vc,crypto:i=new bo,options:a={}}){if(typeof e!="string")throw new Fe(Le.InvalidJwe,"Invalid JWE format. JWE must be a string.");let{0:s,1:o,2:c,3:l,4:d,length:u}=e.split(".");if(u!==5)throw new Fe(Le.InvalidJwe,"Invalid JWE format. JWE must have 5 parts.");let f=await kb.decrypt({jwe:{ciphertext:l,encrypted_key:o||void 0,iv:c||void 0,protected:s,tag:d||void 0},key:r,keyManager:n,crypto:i,options:a});if(!Sb(f.protectedHeader))throw new Fe(Le.InvalidJwe,"Decrypt operation failed due to missing or malformed JWE Protected Header");return{plaintext:f.plaintext,protectedHeader:f.protectedHeader}}static async encrypt({plaintext:e,protectedHeader:r,key:n,keyManager:i=new Vc,crypto:a=new bo,options:s={}}){let o=await kb.encrypt({plaintext:e,protectedHeader:r,key:n,keyManager:i,crypto:a,options:s});return[o.protected,o.encrypted_key,o.iv,o.ciphertext,o.tag].join(".")}};g();Pn();Pn();Jn();g();Sr();Pn();var pg=class extends jf{constructor(){super(...arguments);this.name="DwnKeyStore";this._recordProtocolDefinition=VG;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"privateJwk",schema:this._recordProtocolDefinition.types.privateJwk.schema}}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async set(r){await super.set(r)}async list(r){return await super.list(r)}async getAllRecords({agent:r,tenantDid:n}){this._index.clear();let{reply:i}=await r.dwn.processRequest({author:n,target:n,messageType:Re.RecordsQuery,messageParams:{filter:{...this._recordProperties}}}),a=[];for(let s of i.entries??[]){let o;if(s.encryption){let{reply:c}=await r.dwn.processRequest({author:n,target:n,messageType:Re.RecordsRead,messageParams:{filter:{recordId:s.recordId}},encryption:!0}),l=c;if(!l.entry?.data)throw new Error(`${this.name}: Failed to read encrypted key record: ${s.recordId}`);o=await Cm.consumeToJson({readableStream:l.entry.data})}else{if(!s.encodedData)throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);o=he.base64Url(s.encodedData).toObject()}if(Pp(o)){let c=`${n}${Ti}${bp}${o.kid}`;this._index.set(c,s.recordId),this._cache.set(s.recordId,o),a.push(o)}}return a}},hg=class extends Mf{constructor(){super(...arguments);this.name="InMemoryKeyStore"}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async list(r){return await super.list(r)}async set(r){return await super.set(r)}};var G6={"AES-GCM":{implementation:Om,names:["A128GCM","A192GCM","A256GCM"]},"AES-KW":{implementation:jm,names:["A128KW","A192KW","A256KW"]},Ed25519:{implementation:Wc,names:["Ed25519"]},secp256k1:{implementation:dc,names:["ES256K","secp256k1"]},secp256r1:{implementation:dc,names:["ES256","secp256r1"]},"SHA-256":{implementation:Du,names:["SHA-256"]},X25519:{implementation:Cu,names:["X25519"]}},Po=class{constructor({agent:e,keyStore:r}={}){this._algorithmInstances=new Map;this._agent=e,this._keyStore=r??new hg}get agent(){if(this._agent===void 0)throw new Error("LocalKeyManager: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e}async decrypt({keyUri:e,...r}){let n=await this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return await this.getAlgorithm({algorithm:i}).decrypt({key:n,...r})}digest(e){throw new Error("Method not implemented.")}async encrypt({keyUri:e,...r}){let n=await this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return await this.getAlgorithm({algorithm:i}).encrypt({key:n,...r})}async exportKey({keyUri:e}){return await this.getPrivateKey({keyUri:e})}async generateKey({algorithm:e}){let r=this.getAlgorithmName({key:{alg:e}}),i=await this.getAlgorithm({algorithm:r}).generateKey({algorithm:e});i.kid??=await vt({jwk:i});let a=await this.getKeyUri({key:i});return await this._keyStore.set({id:a,data:i,agent:this.agent,preventDuplicates:!1,useCache:!0}),a}async getKeyUri({key:e}){let r=await vt({jwk:e});return`${bp}${r}`}async getPublicKey({keyUri:e}){let r=await this.getPrivateKey({keyUri:e}),n=this.getAlgorithmName({key:r});return await this.getAlgorithm({algorithm:n}).getPublicKey({key:r})}async derivePublicKey({keyUri:e,derivationPath:r}){let n=await this.getX25519PrivateKeyBytes({keyUri:e}),i=await js.derivePrivateKeyBytes(n,r),a=await Ht.bytesToPrivateKey({privateKeyBytes:i});return await Ht.getPublicKey({key:a})}async jweKeyUnwrap({keyUri:e,derivationPath:r,encryptedKey:n,ephemeralPublicKey:i}){let a=await this.getX25519PrivateKeyBytes({keyUri:e}),s=await js.derivePrivateKeyBytes(a,r),o=await Ht.bytesToPrivateKey({privateKeyBytes:s});return ji.ecdhEsUnwrapKey(o,i,n)}async derivePrivateKeyBytes({keyUri:e,derivationPath:r}){let n=await this.getX25519PrivateKeyBytes({keyUri:e});return js.derivePrivateKeyBytes(n,r)}async importKey({key:e}){if(!Pp(e))throw new TypeError("Invalid key provided. Must be a private key in JWK format.");let r=structuredClone(e);r.kid??=await vt({jwk:r});let n=await this.getKeyUri({key:r});return await this._keyStore.set({id:n,data:r,agent:this.agent,preventDuplicates:!0,useCache:!0}),n}async sign({keyUri:e,data:r}){let n=await this.getPrivateKey({keyUri:e}),i=this.getAlgorithmName({key:n});return this.getAlgorithm({algorithm:i}).sign({data:r,key:n})}async unwrapKey({wrappedKeyBytes:e,wrappedKeyAlgorithm:r,decryptionKeyUri:n}){let i=await this.getPrivateKey({keyUri:n}),a=this.getAlgorithmName({key:i});return await this.getAlgorithm({algorithm:a}).unwrapKey({wrappedKeyBytes:e,wrappedKeyAlgorithm:r,decryptionKey:i})}async verify({key:e,signature:r,data:n}){let i=this.getAlgorithmName({key:e});return this.getAlgorithm({algorithm:i}).verify({key:e,signature:r,data:n})}async wrapKey({unwrappedKey:e,encryptionKeyUri:r}){let n=await this.getPrivateKey({keyUri:r}),i=this.getAlgorithmName({key:n});return await this.getAlgorithm({algorithm:i}).wrapKey({unwrappedKey:e,encryptionKey:n})}async deleteKey({keyUri:e}){if(!await this._keyStore.get({id:e,agent:this.agent,useCache:!0}))throw new Error(`Key not found: ${e}`);await this._keyStore.delete({id:e,agent:this.agent})}getAlgorithm({algorithm:e}){let r=G6[e]?.implementation;if(!r)throw new Fe(Le.AlgorithmNotSupported,`Algorithm not supported: ${e}`);return this._algorithmInstances.has(r)||this._algorithmInstances.set(r,new r),this._algorithmInstances.get(r)}getAlgorithmName({key:e}){let r=e.alg,n=e.crv;for(let i of Object.keys(G6)){let a=G6[i].names;if(r&&a.includes(r))return i;if(n&&a.includes(n))return i}throw new Fe(Le.AlgorithmNotSupported,`Algorithm not supported based on provided input: alg=${r}, crv=${n}. Please check the documentation for the list of supported algorithms.`)}async getX25519PrivateKeyBytes({keyUri:e}){let r=await this.getPrivateKey({keyUri:e});return Ht.privateKeyToBytes({privateKey:r})}async getPrivateKey({keyUri:e}){try{let n=this.agent?.agentDid?.keyManager;if(n&&typeof n.exportKey=="function"){let i=await n.exportKey({keyUri:e});if(i&&Pp(i))return i}}catch{}let r=await this._keyStore.get({id:e,agent:this.agent,useCache:!0});if(!r)throw new Error(`Key not found: ${e}`);return r}};function TH(t){return typeof t!="string"||t.trim().length===0}function mge(t){return typeof t=="object"&&t!==null&&"dateCreated"in t&&typeof t.dateCreated=="string"&&"size"in t&&typeof t.size=="number"&&"data"in t&&typeof t.data=="string"}function yge(t){return typeof t=="object"&&t!==null&&"initialized"in t&&typeof t.initialized=="boolean"&&"lastBackup"in t&&"lastRestore"in t}var $h=class{constructor({keyDerivationWorkFactor:e,store:r}={}){this.crypto=new bo;this._keyDerivationWorkFactor=e??21e4,this._store=r??new Eu}async backup(){if(this.isLocked()||await this.isInitialized()===!1)throw new Error("HdIdentityVault: Unable to proceed with the backup operation because the identity vault has not been initialized and unlocked. Please ensure the vault is properly initialized with a secure password before attempting to backup its contents.");let e={did:await this.getStoredDid(),contentEncryptionKey:await this.getStoredContentEncryptionKey(),status:await this.getStatus()},r=he.object(e).toBase64Url(),n={data:r,dateCreated:new Date().toISOString(),size:r.length};return await this.setStatus({lastBackup:n.dateCreated}),n}async changePassword({oldPassword:e,newPassword:r}){if(await this.isInitialized()===!1)throw new Error("HdIdentityVault: Unable to proceed with the change password operation because the identity vault has not been initialized. Please ensure the vault is properly initialized with a secure password before trying again.");await this.lock();let n=await this.getStoredContentEncryptionKey(),i,a;try{let o;({plaintext:o,protectedHeader:i}=await Vl.decrypt({jwe:n,key:he.string(e).toUint8Array(),crypto:this.crypto,keyManager:new Po,options:{minP2cCount:1}})),a=he.uint8Array(o).toObject()}catch{throw new Error("HdIdentityVault: Unable to change the vault password due to an incorrectly entered old password.")}let s=await Vl.encrypt({key:he.string(r).toUint8Array(),protectedHeader:i,plaintext:he.object(a).toUint8Array(),crypto:this.crypto,keyManager:new Po});await this._store.set("contentEncryptionKey",s),this._contentEncryptionKey=a}async getDid(){if(this.isLocked())throw new Error("HdIdentityVault: Vault has not been initialized and unlocked.");let e=await this.getStoredDid(),{plaintext:r}=await Vl.decrypt({jwe:e,key:this._contentEncryptionKey,crypto:this.crypto,keyManager:new Po,options:{minP2cCount:1}}),n=he.uint8Array(r).toObject();if(!xh(n))throw new Error("HdIdentityVault: Unable to decode malformed DID in identity vault");return await Es.import({portableDid:n})}async getStatus(){let e=await this._store.get("vaultStatus");if(!e)return{initialized:!1,lastBackup:null,lastRestore:null};let r=he.string(e).toObject();if(!yge(r))throw new Error("HdIdentityVault: Invalid IdentityVaultStatus object in store");return r.initialized&&(this._cachedInitialized=!0),r}async initialize({password:e,recoveryPhrase:r,dwnEndpoints:n}){if(await this.isInitialized())throw new Error("HdIdentityVault: Vault has already been initialized.");if(TH(e))throw new Error(`HdIdentityVault: The password is required and cannot be blank. Please provide a ' +
|
|
2059
2059
|
'valid, non-empty password.`);if(r&&TH(r))throw new Error(`HdIdentityVault: The password is required and cannot be blank. Please provide a ' +
|
|
2060
|
-
'valid, non-empty password.`);if(r??=EH(L6,128),!kH(r,L6))throw new Error("HdIdentityVault: The provided recovery phrase is invalid. Please ensure that the recovery phrase is a correctly formatted series of 12 words.");let i=await AH(r),a=tS.fromMasterSeed(i),s=a.derive("m/44'/0'/0'/0'/0'"),o=await this.crypto.deriveKey({algorithm:"HKDF-512",baseKeyBytes:s.privateKey,salt:"",info:"vault_cek",derivedKeyAlgorithm:"A256GCM"}),c=await this.crypto.deriveKeyBytes({algorithm:"HKDF-512",baseKeyBytes:s.publicKey,salt:"",info:"vault_unlock_salt",length:256}),l={alg:"PBES2-HS512+A256KW",enc:"A256GCM",cty:"text/plain",p2c:this._keyDerivationWorkFactor,p2s:he.uint8Array(c).toBase64Url()},d=await Vl.encrypt({key:he.string(e).toUint8Array(),protectedHeader:l,plaintext:he.object(o).toUint8Array(),crypto:this.crypto,keyManager:new Po});await this._store.set("contentEncryptionKey",d);let u=a.derive("m/44'/0'/1708523827'/0'/0'"),f=await this.crypto.bytesToPrivateKey({algorithm:"Ed25519",privateKeyBytes:u.privateKey}),h=a.derive("m/44'/0'/1708523827'/0'/1'"),p=await this.crypto.bytesToPrivateKey({algorithm:"Ed25519",privateKeyBytes:h.privateKey}),m=a.derive("m/44'/0'/1708523827'/0'/2'"),y=await this.crypto.bytesToPrivateKey({algorithm:"X25519",privateKeyBytes:m.privateKey}),v=new HE;await v.addPredefinedKeys({privateKeys:[f,p,y]});let w={verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]};n&&n.length&&(w.services=[{id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:n}]);let A=await(await go.create({keyManager:v,options:w})).export(),_={alg:"dir",enc:"A256GCM",cty:"json"},D=await Vl.encrypt({key:o,plaintext:he.object(A).toUint8Array(),protectedHeader:_,crypto:this.crypto,keyManager:new Po});return await this._store.set("did",D),this._contentEncryptionKey=o,await this.setStatus({initialized:!0}),r}async isInitialized(){return this._cachedInitialized===!0?!0:this.getStatus().then(({initialized:e})=>e)}isLocked(){return!this._contentEncryptionKey}async lock(){if(await this.isInitialized()===!1)throw new Error("HdIdentityVault: Lock operation failed. Vault has not been initialized.");this._contentEncryptionKey&&(this._contentEncryptionKey.k=""),this._contentEncryptionKey=void 0}async restore({backup:e,password:r}){if(!mge(e))throw new Error("HdIdentityVault: Restore operation failed due to invalid backup object.");let n,i,a;try{a=await this.getStoredDid(),i=await this.getStoredContentEncryptionKey(),n=await this.getStatus()}catch{throw new Error("HdIdentityVault: The restore operation cannot proceed because the existing vault contents are missing or inaccessible. If the problem persists consider re-initializing the vault and retrying the restore.")}try{let s=he.base64Url(e.data).toObject();await this._store.set("did",s.did),await this._store.set("contentEncryptionKey",s.contentEncryptionKey),await this.setStatus(s.status),await this.unlock({password:r})}catch{throw await this.setStatus(n),await this._store.set("contentEncryptionKey",i),await this._store.set("did",a),new Error("HdIdentityVault: Restore operation failed due to invalid backup data or an incorrect password. Please verify the password is correct for the provided backup and try again.")}await this.setStatus({lastRestore:new Date().toISOString()})}async unlock({password:e}){await this.lock();let r=await this.getStoredContentEncryptionKey();try{let{plaintext:n}=await Vl.decrypt({jwe:r,key:he.string(e).toUint8Array(),crypto:this.crypto,keyManager:new Po,options:{minP2cCount:1}}),i=he.uint8Array(n).toObject();this._contentEncryptionKey=i}catch{throw new Error("HdIdentityVault: Unable to unlock the vault due to an incorrect password.")}}async getStoredDid(){let e=await this._store.get("did");if(!e)throw new Error("HdIdentityVault: Unable to retrieve the DID record from the vault. Please check the vault status and if the problem persists consider re-initializing the vault and restoring the contents from a previous backup.");return e}async getStoredContentEncryptionKey(){let e=await this._store.get("contentEncryptionKey");if(!e)throw new Error("HdIdentityVault: Unable to retrieve the Content Encryption Key record from the vault. Please check the vault status and if the problem persists consider re-initializing the vault and restoring the contents from a previous backup.");return e}async setStatus({initialized:e,lastBackup:r,lastRestore:n}){let i=await this.getStatus();return i.initialized=e??i.initialized,i.lastBackup=r??i.lastBackup,i.lastRestore=n??i.lastRestore,await this._store.set("vaultStatus",JSON.stringify(i)),this._cachedInitialized=i.initialized,!0}};g();Qo();g();Sr();function gge(t){return!(!t||typeof t!="object"||t===null)&&"name"in t}var mg=class extends jf{constructor(){super(...arguments);this.name="DwnIdentityStore";this._recordProtocolDefinition=GE;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"identityMetadata",schema:this._recordProtocolDefinition.types.identityMetadata.schema}}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async set(r){return await super.set(r)}async list(r){return await super.list(r)}async getAllRecords({agent:r,tenantDid:n}){this._index.clear();let{reply:i}=await r.dwn.processRequest({author:n,target:n,messageType:Re.RecordsQuery,messageParams:{filter:{...this._recordProperties}}}),a=[];for(let s of i.entries??[]){if(!s.encodedData)throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);let o=he.base64Url(s.encodedData).toObject();if(gge(o)){let c=`${n}${Ti}${o.uri}`;this._index.set(c,s.recordId),this._cache.set(s.recordId,o),a.push(o)}}return a}},yg=class extends Mf{constructor(){super(...arguments);this.name="InMemoryIdentityStore"}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async list(r){return await super.list(r)}async set(r){return await super.set(r)}};function aJe(t){return!(!t||typeof t!="object"||t===null)&&"did"in t&&"metadata"in t&&xh(t.did)}var Bh=class{constructor({agent:e,store:r}={}){this._agent=e,this._store=r??new yg}get agent(){if(this._agent===void 0)throw new Error("AgentIdentityApi: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e}get tenant(){if(!this._agent)throw new Error("AgentIdentityApi: The agent must be set to perform tenant specific actions.");return this._agent.agentDid.uri}async create({metadata:e,didMethod:r="dht",didOptions:n,store:i}){let a=await this.agent.did.create({method:r,options:n,tenant:this.tenant,store:i}),s=new ag({did:a,metadata:{...e,uri:a.uri,tenant:this.tenant}});return(i??!0)&&await this._store.set({id:s.did.uri,data:s.metadata,agent:this.agent,tenant:s.metadata.tenant,preventDuplicates:!1,useCache:!0}),s}async export({didUri:e}){let r=await this.get({didUri:e});if(!r)throw new Error(`AgentIdentityApi: Failed to export due to Identity not found: ${e}`);return await r.export()}async get({didUri:e}){let r=await this._store.get({id:e,agent:this.agent,useCache:!0});if(!r)return;let n=await this.agent.did.get({didUri:e,tenant:r.tenant});if(!n)throw new Error(`AgentIdentityApi: Identity is present in the store but DID is missing: ${e}`);return new ag({did:n,metadata:r})}async import({portableIdentity:e}){e.metadata.tenant=this.tenant;let r=await this.agent.did.import({portableDid:e.portableDid,tenant:e.metadata.tenant});if(!r)throw new Error(`AgentIdentityApi: Failed to import Identity: ${e.metadata.uri}`);let n=new ag({did:r,metadata:e.metadata});return await this._store.set({id:n.did.uri,data:n.metadata,agent:this.agent,tenant:n.metadata.tenant,preventDuplicates:!0,useCache:!0}),n}async list({tenant:e}={}){let r=await this._store.list({agent:this.agent,tenant:e});return(await Promise.all(r.map(i=>this.get({didUri:i.uri})))).filter(i=>typeof i<"u")}async delete({didUri:e}){if(!await this._store.get({id:e,agent:this.agent,useCache:!0}))throw new Error(`AgentIdentityApi: Failed to purge due to Identity not found: ${e}`);await this._store.delete({id:e,agent:this.agent})}getDwnEndpoints({didUri:e}){return this.agent.dwn.getDwnEndpointUrlsForTarget(e)}async setDwnEndpoints({didUri:e,endpoints:r}){let n=await this.agent.did.get({didUri:e});if(!n)throw new Error(`AgentIdentityApi: Failed to set DWN endpoints due to DID not found: ${e}`);let i=await n.export(),a=i.document.service?.find(s=>s.id.endsWith("dwn"));if(a)a.serviceEndpoint=r;else{let s={id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:r};i.document.service?i.document.service.push(s):i.document.service=[s]}await this.agent.did.update({portableDid:i,tenant:this.agent.agentDid.uri})}async setMetadataName({didUri:e,name:r}){if(!r)throw new Error("AgentIdentityApi: Failed to set metadata name due to missing name value.");let n=await this.get({didUri:e});if(!n)throw new Error(`AgentIdentityApi: Failed to set metadata name due to Identity not found: ${e}`);if(n.metadata.name===r)throw new Error("AgentIdentityApi: No changes detected.");await this._store.set({id:n.did.uri,data:{...n.metadata,name:r},agent:this.agent,tenant:n.metadata.tenant,updateExisting:!0,useCache:!0})}async connectedIdentity({connectedDid:e}={}){let r=await this.list();if(!(r.length<1))return e?r.find(n=>n.metadata.connectedDid===e):r.find(n=>n.metadata.connectedDid!==void 0)}};g();Jn();Sr();var La=class t{constructor({agent:e}={}){this._cachedPermissions=new us.default({ttl:60*1e3});this._agent=e}get agent(){if(!this._agent)throw new Error("AgentPermissionsApi: Agent is not set");return this._agent}set agent(e){this._agent=e}async getPermissionForRequest({connectedDid:e,delegateDid:r,delegate:n,messageType:i,protocol:a,cached:s=!1}){let o=[e,r,i,a].join("~"),c=s?this._cachedPermissions.get(o):void 0;if(c)return c;let l=await this.fetchGrants({author:r,target:r,grantor:e,grantee:r}),d=await t.matchGrantFromArray(e,r,{messageType:i,protocol:a},l,n);if(!d)throw new Error(`CachedPermissions: No permissions found for ${i}: ${a}`);return this._cachedPermissions.set(o,d),d}async fetchGrants({author:e,target:r,grantee:n,grantor:i,protocol:a,remote:s=!1,checkRevoked:o=!0}){let c=a?{protocol:a}:void 0,l={author:e,target:r,messageType:Re.RecordsQuery,messageParams:{filter:{author:i,recipient:n,protocol:dt.uri,protocolPath:dt.grantPath,tags:c}}},{reply:d}=s?await this.agent.sendDwnRequest(l):await this.agent.processDwnRequest(l);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${d.status.detail}`);let u=o?await this.fetchRevokedGrantIds({author:e,target:r,grantor:i,remote:s,tags:c}):new Set,f=[];for(let h of d.entries){if(u.has(h.recordId))continue;let p=Ir.parse(h);f.push({grant:p,message:h})}return f}async fetchRevokedGrantIds({author:e,target:r,grantor:n,remote:i,tags:a}){let s={author:e,target:r,messageType:Re.RecordsQuery,messageParams:{filter:{author:n,protocol:dt.uri,protocolPath:dt.revocationPath,tags:a}}},{reply:o}=i?await this.agent.sendDwnRequest(s):await this.agent.processDwnRequest(s);if(o.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch revocations: ${o.status.detail}`);let c=new Set;for(let l of o.entries)l.descriptor.parentId!==void 0&&c.add(l.descriptor.parentId);return c}async fetchRequests({author:e,target:r,protocol:n,remote:i=!1}){let a=n?{protocol:n}:void 0,s={author:e,target:r,messageType:Re.RecordsQuery,messageParams:{filter:{protocol:dt.uri,protocolPath:dt.requestPath,tags:a}}},{reply:o}=i?await this.agent.sendDwnRequest(s):await this.agent.processDwnRequest(s);if(o.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch requests: ${o.status.detail}`);let c=[];for(let l of o.entries){let d=ud.parse(l);c.push({request:d,message:l})}return c}async isGrantRevoked({author:e,target:r,grantRecordId:n,remote:i=!1}){let a={author:e,target:r,messageType:Re.RecordsRead,messageParams:{filter:{parentId:n,protocol:dt.uri,protocolPath:dt.revocationPath}}},{reply:s}=i?await this.agent.sendDwnRequest(a):await this.agent.processDwnRequest(a);if(s.status.code===404)return!1;if(s.status.code===200)return!0;throw new Error(`PermissionsApi: Failed to check if grant is revoked: ${s.status.detail}`)}async createGrant(e){let{author:r,store:n=!1,delegated:i=!1,...a}=e,s;dt.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={dateExpires:a.dateExpires,requestId:a.requestId,description:a.description,delegated:i,scope:a.scope},c=he.object(o).toUint8Array(),l={recipient:a.grantedTo,protocol:dt.uri,protocolPath:dt.grantPath,dataFormat:"application/json",tags:s},{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([c])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${d.status.detail}`);let f={...u,encodedData:he.uint8Array(c).toBase64Url()};return{grant:Ir.parse(f),message:f}}async createRequest(e){let{author:r,store:n=!1,delegated:i=!1,...a}=e,s;dt.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={description:a.description,delegated:i,scope:a.scope},c=he.object(o).toUint8Array(),l={protocol:dt.uri,protocolPath:dt.requestPath,dataFormat:"application/json",tags:s},{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([c])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${d.status.detail}`);let f={...u,encodedData:he.uint8Array(c).toBase64Url()};return{request:ud.parse(f),message:f}}async createRevocation(e){let{author:r,store:n=!1,grant:i,description:a}=e,s={description:a},o=he.object(s).toUint8Array(),c;dt.hasProtocolScope(i.scope)&&(c={protocol:i.scope.protocol});let l={parentContextId:i.id,protocol:dt.uri,protocolPath:dt.revocationPath,dataFormat:"application/json",tags:c},{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([o])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${d.status.detail}`);return{message:{...u,encodedData:he.uint8Array(o).toBase64Url()}}}async clear(){this._cachedPermissions.clear()}static async matchGrantFromArray(e,r,n,i,a=!1){let s;for(let o of i){let{grant:c,message:l}=o;if(a===!0&&c.delegated!==!0)continue;let{messageType:d,protocol:u,protocolPath:f,contextId:h}=n;if(this.matchScopeFromGrant(e,r,d,c,u,f,h)){if(c.scope.interface+c.scope.method===d)return{grant:c,message:l};s||(s={grant:c,message:l})}}return s}static matchScopeFromGrant(e,r,n,i,a,s,o){if(i.grantee!==r||i.grantor!==e)return!1;let c=i.scope,l=c.interface+c.method;if(l===n||l===Re.MessagesRead&&(n===Re.MessagesSync||n===Re.MessagesSubscribe))if(B6(n)){let u=c;if(u.protocol!==a)return!1;if(this.isUnrestrictedProtocolScope(u)||u.protocolPath!==void 0&&u.protocolPath===s||u.contextId!==void 0&&o?.startsWith(u.contextId))return!0}else{let u=c;return u.protocol===void 0?!0:u.protocol!==a?!1:this.isUnrestrictedProtocolScope(u)}return!1}static isUnrestrictedProtocolScope(e){return e.contextId===void 0&&e.protocolPath===void 0}};g();var jH=Tn(VE(),1);Jn();import{Level as Ege}from"level";g();function wge(t){let e=[],r=[];for(let n of t)n.message?n.message.descriptor.interface==="Records"&&n.message.descriptor.method==="Write"&&n.message.descriptor.dataCid&&!n.encodedData?r.push(n.messageCid):e.push(n):r.push(n.messageCid);return{prefetched:e,needsFetchCids:r}}var iS=class{constructor(e){this._deps=e}async reconcile(e,r){let{did:n,dwnUrl:i,delegateDid:a,protocol:s}=e,o=r?.direction,c=r?.verifyConvergence??!1,l=this._deps.shouldContinue,d=await this._deps.getLocalRoot(n,a,s);if(l&&!l())return{aborted:!0,changed:!1,didPull:!1,didPush:!1};let u=await this._deps.getRemoteRoot(n,i,a,s);if(l&&!l())return{aborted:!0,changed:!1,didPull:!1,didPush:!1};let f=!1,h=!1,p;if(d!==u){let v=await this._deps.diffWithRemote(e);if(l&&!l())return{aborted:!0,changed:!0,didPull:!1,didPush:!1,localRoot:d,remoteRoot:u};if((!o||o==="pull")&&v.onlyRemote.length>0){let{prefetched:w,needsFetchCids:S}=wge(v.onlyRemote);if(await this._deps.pullMessages({did:n,dwnUrl:i,delegateDid:a,protocol:s,messageCids:S,prefetched:w}),l&&!l())return{aborted:!0,changed:!0,didPull:!0,didPush:!1,localRoot:d,remoteRoot:u};f=!0}if((!o||o==="push")&&v.onlyLocal.length>0){if(p=await this._deps.pushMessages({did:n,dwnUrl:i,delegateDid:a,protocol:s,messageCids:v.onlyLocal}),l&&!l())return{aborted:!0,changed:!0,didPull:f,didPush:!0,localRoot:d,remoteRoot:u,pushResult:p};h=!0}}if(!c)return{changed:d!==u,didPull:f,didPush:h,localRoot:d,remoteRoot:u,pushResult:p};let m=await this._deps.getLocalRoot(n,a,s);if(l&&!l())return{aborted:!0,changed:d!==u,didPull:f,didPush:h,localRoot:d,remoteRoot:u,pushResult:p};let y=await this._deps.getRemoteRoot(n,i,a,s);return l&&!l()?{aborted:!0,changed:d!==u,didPull:f,didPush:h,localRoot:d,remoteRoot:u,pushResult:p}:{changed:d!==u,didPull:f,didPush:h,localRoot:d,remoteRoot:u,postLocalRoot:m,postRemoteRoot:y,converged:m===y,pushResult:p}}};g();Jn();function IH(t){let e=t.descriptor;return e.interface!==be.Records||e.method!==we.Write?!1:e.dateCreated===e.messageTimestamp}function gg(t){if(t.length<=1)return t;let e=new Map,r=new Map,n=new Map,i=new Map;for(let d=0;d<t.length;d++){let u=t[d];e.set(d,u);let f=u.message.descriptor;if(f.interface===be.Protocols&&f.method===we.Configure){let h=f.definition?.protocol;h&&r.set(h,d)}if(f.interface===be.Records&&f.method===we.Write){let h=u.message.recordId;IH(u.message)&&h&&n.set(h,d),f.protocol===dt.uri&&f.protocolPath===dt.grantPath&&h&&i.set(h,d)}}let a=new Map,s=new Array(t.length).fill(0),o=(d,u)=>{if(d===u)return;a.has(d)||a.set(d,new Set);let f=a.get(d);f.has(u)||(f.add(u),s[u]++)};for(let d=0;d<t.length;d++){let u=t[d].message.descriptor;if(u.interface===be.Records){let h=u.protocol;h&&r.has(h)&&o(r.get(h),d)}if(u.interface===be.Records&&u.parentId){let h=u.parentId;n.has(h)&&o(n.get(h),d)}if(u.interface===be.Records&&u.method===we.Write){let h=t[d].message.recordId;h&&!IH(t[d].message)&&n.has(h)&&o(n.get(h),d)}if(u.interface===be.Records&&u.method===we.Delete){let h=u.recordId;h&&n.has(h)&&o(n.get(h),d)}let f=u.permissionGrantId;f&&i.has(f)&&o(i.get(f),d)}let c=[];for(let d=0;d<t.length;d++)s[d]===0&&c.push(d);let l=[];for(;c.length>0;){let d=c.shift();l.push(e.get(d));let u=a.get(d);if(u)for(let f of u)s[f]--,s[f]===0&&c.push(f)}if(l.length<t.length){let d=new Set(l);for(let u=0;u<t.length;u++){let f=e.get(u);d.has(f)||l.push(f)}}return l}g();var sS="^";function DH(t,e,r){return`${t}${sS}${e}${sS}${r}`}function Ab(t,e,r){let n=`${t}${sS}${e}`;return r?`${n}${sS}${r}`:n}g();Jn();var vge=1048576;function RH(t){return t.status.code===202||t.status.code===204||t.status.code===409||t.entry?.message.descriptor.interface===be.Records&&t.entry?.message.descriptor.method===we.Delete&&t.status.code===404}function bge(t){return t.status.code===400||t.status.code===401||t.status.code===403}async function CH(t){try{return await ge.getCid(t)}catch{return"unknown"}}async function $H({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,prefetched:a,agent:s,permissionsApi:o}){let c=[];if(a)for(let p of a){if(!p.message)continue;let m={message:p.message};if(p.encodedData){let y=De.base64UrlToBytes(p.encodedData);m.bufferedData=y,m.dataStream=new ReadableStream({start(v){v.enqueue(y),v.close()}})}c.push(m)}let l=i.length>0?await oS({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:s,permissionsApi:o}):[],d=[...c,...l],u=gg(d);await Pge(u);let f=3,h=u;for(let p=0;p<=f&&h.length>0;p++){let m=[];for(let y of h){let v=y.bufferedData?new ReadableStream({start(S){S.enqueue(y.bufferedData),S.close()}}):y.dataStream,w=await s.dwn.processRawMessage(t,y.message,{dataStream:v});RH(w)||m.push(y)}if(m.length>0){let y=[],v=[];for(let w of m)if(w.bufferedData||!w.dataStream)v.push(w);else{let S=await CH(w.message);y.push(S)}if(y.length>0){let w=await oS({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:y,agent:s,permissionsApi:o});v.push(...w)}h=gg(v)}else h=[]}}async function Pge(t){for(let e of t){if(!e.dataStream)continue;let r=[],n=0,i=!1,a=e.dataStream.getReader();try{for(;;){let{done:c,value:l}=await a.read();if(c)break;if(n+=l.byteLength,n>vge){i=!0;break}r.push(l)}}finally{a.releaseLock()}if(i){e.dataStream=void 0;continue}let s=new Uint8Array(n),o=0;for(let c of r)s.set(c,o),o+=c.byteLength;e.bufferedData=s,e.dataStream=new ReadableStream({start(c){c.enqueue(s),c.close()}})}}async function oS({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:s}){let o=[],c;r&&(c=(await s.getPermissionForRequest({connectedDid:t,messageType:Re.MessagesRead,delegateDid:r,protocol:n,cached:!0})).grant.id);let l=4,d=0;for(;d<i.length;){let u=i.slice(d,d+l);d+=l;let f=await Promise.all(u.map(async h=>{let p=await a.processDwnRequest({store:!1,author:t,target:t,messageType:Re.MessagesRead,granteeDid:r,messageParams:{messageCid:h,permissionGrantId:c}}),m;try{m=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:t,message:p.message})}catch(w){console.error(`SyncEngineLevel: pull - failed to read ${h} from ${e}:`,w.message??w);return}if(m.status.code!==200||!m.entry?.message)return;let y=m.entry,v;return $d(y)&&y.data&&(v=y.data),{message:y.message,dataStream:v}}));for(let h of f)h&&o.push(h)}return o}async function H6({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:s}){let o=[],c=[],l=[],d=[];for(let f of i){let h=await xge({author:t,messageCid:f,delegateDid:r,protocol:n,agent:a,permissionsApi:s});h?d.push(h):c.push(f)}let u=gg(d);for(let f of u){let h=await CH(f.message);try{let p=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:t,data:f.dataStream,message:f.message});RH(p)?o.push(h):bge(p)?(console.warn(`SyncEngineLevel: push permanently failed for ${h}: ${p.status.code} ${p.status.detail}`),l.push(h)):(console.error(`SyncEngineLevel: push failed for ${h}: ${p.status.code} ${p.status.detail}`),c.push(h))}catch(p){console.error(`SyncEngineLevel: push error for ${h}: ${p.message??p}`),c.push(h)}}return{succeeded:o,failed:c,permanentlyFailed:l}}async function xge({author:t,delegateDid:e,protocol:r,messageCid:n,agent:i,permissionsApi:a}){let s;e&&(s=(await a.getPermissionForRequest({connectedDid:t,messageType:Re.MessagesRead,delegateDid:e,protocol:r,cached:!0})).grant.id);let{reply:o}=await i.dwn.processRequest({author:t,target:t,messageType:Re.MessagesRead,granteeDid:e,messageParams:{messageCid:n,permissionGrantId:s}});if(o.status.code!==200||!o.entry)return;let c=o.entry,l={message:c.message};return $d(c)&&c.data&&(l.dataStream=c.data),l}var Sge=16,BH=8,kge=100;function OH(t,e){if(e.kind==="full"||!e.protocolPathPrefixes&&!e.contextIdPrefixes)return!0;let r=t.descriptor;if(e.protocolPathPrefixes&&e.protocolPathPrefixes.length>0){let n=r.protocolPath;if(!n||!e.protocolPathPrefixes.some(a=>n===a||n.startsWith(a+"/")))return!1}if(e.contextIdPrefixes&&e.contextIdPrefixes.length>0){let n=t.contextId;if(!n||!e.contextIdPrefixes.some(a=>n===a||n.startsWith(a+"/")))return!1}return!0}var ei=class ei{constructor({agent:e,dataPath:r,db:n}){this._syncLock=!1;this._activeLinks=new Map;this._linkRuntimes=new Map;this._syncMode="poll";this._engineGeneration=0;this._liveSubscriptions=[];this._localSubscriptions=[];this._connectivityState="unknown";this._eventListeners=new Set;this._pushRuntimes=new Map;this._recentlyPulledCids=new Map;this._closureContexts=new Map;this._consecutiveFailures=0;this._degradedPollTimers=new Map;this._repairAttempts=new Map;this._activeRepairs=new Map;this._repairRetryTimers=new Map;this._repairContext=new Map;this._reconcileTimers=new Map;this._reconcileInFlight=new Map;this._agent=e,this._permissionsApi=new La({agent:e}),this._db=n||new Ege(r??"DATA/AGENT/SYNC_STORE")}get ledger(){return this._ledger||(this._ledger=new is(this._db)),this._ledger}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 La({agent:e})}get connectivityState(){if(this._activeLinks.size===0)return this._connectivityState;let e=!1,r=!1;for(let n of this._activeLinks.values())n.connectivity==="online"&&(e=!0),n.connectivity==="offline"&&(r=!0);return e?"online":r?"offline":"unknown"}on(e){return this._eventListeners.add(e),()=>{this._eventListeners.delete(e)}}emitEvent(e){for(let r of this._eventListeners)try{r(e)}catch{}}async clear(){await this.teardownLiveSync(),await this._permissionsApi.clear(),await this._db.clear()}async close(){await this.teardownLiveSync(),await this._db.close()}async registerIdentity({did:e,options:r}){let n=this._db.sublevel("registeredIdentities");if(await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is already registered.`);r??={protocols:[]},await n.put(e,JSON.stringify(r))}async unregisterIdentity(e){let r=this._db.sublevel("registeredIdentities");if(!await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);await r.del(e)}async getIdentityOptions(e){let r=this._db.sublevel("registeredIdentities");try{let n=await 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}.`)}}async updateIdentityOptions({did:e,options:r}){let n=this._db.sublevel("registeredIdentities");if(!await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);await n.put(e,JSON.stringify(r))}async sync(e){if(this._syncLock)throw new Error("SyncEngineLevel: Sync operation is already in progress.");this._syncLock=!0;try{let r=await this.getSyncTargets(),n=new Map;for(let o of r){let c=n.get(o.dwnUrl);c||(c=[],n.set(o.dwnUrl,c)),c.push(o)}let i=0,a=0,s=await Promise.allSettled([...n.entries()].map(async([o,c])=>{for(let l of c){let{did:d,delegateDid:u,protocol:f}=l;try{await this.createLinkReconciler().reconcile({did:d,dwnUrl:o,delegateDid:u,protocol:f},{direction:e})}catch(h){a++,console.error(`SyncEngineLevel: Error syncing ${d} with ${o}`,h);return}}i++}));for(let o of s)o.status==="rejected"&&a++;i>0?(this._consecutiveFailures=0,this._connectivityState="online"):a>0?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):r.length>0&&(this._consecutiveFailures=0,this._connectivityState="online")}finally{this._syncLock=!1}}async startSync(e){let r=e.mode??"poll",n=e.interval??(r==="live"?"5m":"2m"),i=(0,jH.default)(n);(this._liveSubscriptions.length>0||this._localSubscriptions.length>0)&&await this.teardownLiveSync(),this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),this._syncMode=r,r==="live"?await this.startLiveSync(i):await this.startPollSync(i)}async stopSync(e=2e3){this._engineGeneration++;let r=0;for(;this._syncLock;){if(r>=e)throw new Error(`SyncEngineLevel: Existing sync operation did not complete within ${e} milliseconds.`);r+=100,await new Promise(n=>{setTimeout(n,e<100?e:100)})}this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),await this.teardownLiveSync()}async startPollSync(e){let r=this._engineGeneration,n=async()=>{if(this._engineGeneration!==r||this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{await this.sync()}catch(s){console.error("SyncEngineLevel: Error during sync operation",s)}let i=Math.min(Math.pow(2,this._consecutiveFailures),ei.MAX_BACKOFF_MULTIPLIER),a=this._consecutiveFailures>0?e*i:e;this._engineGeneration===r&&(this._syncIntervalId||(this._syncIntervalId=setInterval(n,a)))};this._syncIntervalId&&clearInterval(this._syncIntervalId),this._syncIntervalId=setInterval(n,e),this._syncLock||await this.sync()}async startLiveSync(e){try{await this.sync()}catch(i){console.error("SyncEngineLevel: Error during initial live-sync catch-up",i)}let r=await this.getSyncTargets();await Promise.allSettled(r.map(async i=>{let a;try{let s=i.protocol?{kind:"protocol",protocol:i.protocol}:{kind:"full"};a=await this.ledger.getOrCreateLink({tenantDid:i.did,remoteEndpoint:i.dwnUrl,scope:s,delegateDid:i.delegateDid,protocol:i.protocol});let o=this.buildLinkKey(i.did,i.dwnUrl,a.scopeId);if(!a.pull.contiguousAppliedToken){let l=Ab(i.did,i.dwnUrl,i.protocol),d=await this.getCursor(l);d&&(is.resetCheckpoint(a.pull,d),await this.ledger.saveLink(a),await this.deleteLegacyCursor(l))}this._activeLinks.set(o,a);let c={...i,linkKey:o};await this.openLivePullSubscription(c);try{await this.openLocalPushSubscription(c)}catch(l){let d=this._liveSubscriptions.find(u=>u.linkKey===o);if(d){try{await d.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(u=>u!==d)}throw l}this.emitEvent({type:"link:status-change",tenantDid:i.did,remoteEndpoint:i.dwnUrl,protocol:i.protocol,from:"initializing",to:"live"}),await this.ledger.setStatus(a,"live"),a.needsReconcile&&this.scheduleReconcile(o,1e3)}catch(s){let o=a?this.buildLinkKey(i.did,i.dwnUrl,a.scopeId):Ab(i.did,i.dwnUrl,i.protocol);if(s.isProgressGap&&a){console.warn(`SyncEngineLevel: ProgressGap detected for ${i.did} -> ${i.dwnUrl}, initiating repair`),this.emitEvent({type:"gap:detected",tenantDid:i.did,remoteEndpoint:i.dwnUrl,protocol:i.protocol,reason:"ProgressGap"});let c=s.gapInfo;await this.transitionToRepairing(o,a,{resumeToken:c?.latestAvailable});return}console.error(`SyncEngineLevel: Failed to open live subscription for ${i.did} -> ${i.dwnUrl}`,s),this._activeLinks.delete(o),this._linkRuntimes.delete(o),this._liveSubscriptions.length===0&&(this._connectivityState="unknown")}}));let n=async()=>{if(!this._syncLock)try{await this.sync()}catch(i){console.error("SyncEngineLevel: Error during SMT integrity check",i)}};this._syncIntervalId=setInterval(n,e)}getOrCreateRuntime(e){let r=this._linkRuntimes.get(e);return r||(r={nextDeliveryOrdinal:0,nextCommitOrdinal:0,inflight:new Map},this._linkRuntimes.set(e,r)),r}drainCommittedPull(e){let r=this._linkRuntimes.get(e),n=this._activeLinks.get(e);if(!r||!n)return 0;let i=0;for(;;){let a=r.inflight.get(r.nextCommitOrdinal);if(!a||!a.committed)break;is.commitContiguousToken(n.pull,a.token),is.setReceivedToken(n.pull,a.token),r.inflight.delete(r.nextCommitOrdinal),r.nextCommitOrdinal++,i++}return i}async transitionToRepairing(e,r,n){let i=r.status,a=r.connectivity;r.connectivity="offline",await this.ledger.setStatus(r,"repairing"),this.emitEvent({type:"link:status-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:i,to:"repairing"}),a!=="offline"&&this.emitEvent({type:"link:connectivity-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:a,to:"offline"}),n?.resumeToken&&this._repairContext.set(e,{resumeToken:n.resumeToken});let s=this._linkRuntimes.get(e);s&&(s.inflight.clear(),s.nextCommitOrdinal=s.nextDeliveryOrdinal),this.repairLink(e).catch(()=>{this.scheduleRepairRetry(e)})}scheduleRepairRetry(e){let r=this._activeLinks.get(e);if(!r||r.status==="degraded_poll"||this._repairRetryTimers.has(e))return;let n=this._repairAttempts.get(e)??1,i=ei.REPAIR_BACKOFF_MS,a=i[Math.min(n-1,i.length-1)],s=this._engineGeneration,o=setTimeout(async()=>{if(this._repairRetryTimers.delete(e),this._engineGeneration!==s)return;let c=this._activeLinks.get(e);if(!(!c||c.status!=="repairing"))try{await this.repairLink(e)}catch{c.status==="repairing"&&this.scheduleRepairRetry(e)}},a);this._repairRetryTimers.set(e,o)}repairLink(e){let r=this._activeRepairs.get(e);if(r)return r;let n=this.doRepairLink(e).finally(()=>{this._activeRepairs.delete(e);let i=this._activeLinks.get(e);i?.needsReconcile&&i.status==="live"&&this.scheduleReconcile(e,500)});return this._activeRepairs.set(e,n),n}async doRepairLink(e){let r=this._activeLinks.get(e);if(!r)return;let n=this._engineGeneration,{tenantDid:i,remoteEndpoint:a,delegateDid:s,protocol:o}=r;this.emitEvent({type:"repair:started",tenantDid:i,remoteEndpoint:a,protocol:o,attempt:(this._repairAttempts.get(e)??0)+1});let c=(this._repairAttempts.get(e)??0)+1;if(this._repairAttempts.set(e,c),await this.closeLinkSubscriptions(r),this._engineGeneration!==n)return;let l=this.getOrCreateRuntime(e);l.inflight.clear(),l.nextDeliveryOrdinal=0,l.nextCommitOrdinal=0;try{if((await this.createLinkReconciler(()=>this._engineGeneration===n).reconcile({did:i,dwnUrl:a,delegateDid:s,protocol:o})).aborted)return;let f=this._repairContext.get(e)?.resumeToken??r.pull.contiguousAppliedToken;if(is.resetCheckpoint(r.pull,f),await this.ledger.saveLink(r),this._engineGeneration!==n||(r.needsReconcile=!0,await this.ledger.saveLink(r),this._engineGeneration!==n))return;let h={did:i,dwnUrl:a,delegateDid:s,protocol:o,linkKey:e};try{await this.openLivePullSubscription(h)}catch(y){if(y.isProgressGap){if(console.warn(`SyncEngineLevel: Stale pull resume token for ${i} -> ${a}, resetting to start fresh`),is.resetCheckpoint(r.pull),await this.ledger.saveLink(r),this._engineGeneration!==n)return;await this.openLivePullSubscription(h)}else throw y}if(this._engineGeneration!==n)return;try{await this.openLocalPushSubscription(h)}catch(y){let v=this._liveSubscriptions.find(w=>w.linkKey===e);if(v){try{await v.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(w=>w!==v)}throw y}if(this._engineGeneration!==n)return;this._repairContext.delete(e),this._repairAttempts.delete(e);let p=this._repairRetryTimers.get(e);p&&(clearTimeout(p),this._repairRetryTimers.delete(e));let m=r.connectivity;r.connectivity="online",await this.ledger.setStatus(r,"live"),this.emitEvent({type:"repair:completed",tenantDid:i,remoteEndpoint:a,protocol:o}),m!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:i,remoteEndpoint:a,protocol:o,from:m,to:"online"}),this.emitEvent({type:"link:status-change",tenantDid:i,remoteEndpoint:a,protocol:o,from:"repairing",to:"live"})}catch(d){if(this._engineGeneration!==n)return;if(console.error(`SyncEngineLevel: Repair failed for ${i} -> ${a} (attempt ${c})`,d),this.emitEvent({type:"repair:failed",tenantDid:i,remoteEndpoint:a,protocol:o,attempt:c,error:String(d.message??d)}),c>=ei.MAX_REPAIR_ATTEMPTS){console.warn(`SyncEngineLevel: Max repair attempts reached for ${i} -> ${a}, entering degraded_poll`),await this.enterDegradedPoll(e);return}throw d}}async closeLinkSubscriptions(e){let{tenantDid:r,remoteEndpoint:n}=e,i=this.buildLinkKey(r,n,e.scopeId),a=this._liveSubscriptions.find(o=>o.linkKey===i);if(a){try{await a.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(o=>o!==a)}let s=this._localSubscriptions.find(o=>o.linkKey===i);if(s){try{await s.close()}catch{}this._localSubscriptions=this._localSubscriptions.filter(o=>o!==s)}}async enterDegradedPoll(e){let r=this._activeLinks.get(e);if(!r)return;r.connectivity="offline";let n=r.status;await this.ledger.setStatus(r,"degraded_poll"),this._repairAttempts.delete(e),this.emitEvent({type:"link:status-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:n,to:"degraded_poll"}),this.emitEvent({type:"degraded-poll:entered",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol});let i=this._degradedPollTimers.get(e);i&&clearInterval(i);let a=15e3,s=Math.floor(Math.random()*15e3),o=a+s,c=this._engineGeneration,l=setInterval(async()=>{if(this._engineGeneration!==c){clearInterval(l),this._degradedPollTimers.delete(e);return}if(r.status!=="degraded_poll"){clearInterval(l),this._degradedPollTimers.delete(e);return}try{this._repairAttempts.set(e,0),await this.ledger.setStatus(r,"repairing"),await this.repairLink(e),r.status==="live"&&(clearInterval(l),this._degradedPollTimers.delete(e))}catch{await this.ledger.setStatus(r,"degraded_poll")}},o);this._degradedPollTimers.set(e,l)}async teardownLiveSync(){this._engineGeneration++;for(let e of this._pushRuntimes.values())e.timer&&clearTimeout(e.timer);this._pushRuntimes.clear();for(let e of this._liveSubscriptions)try{await e.close()}catch{}this._liveSubscriptions=[];for(let e of this._localSubscriptions)try{await e.close()}catch{}this._localSubscriptions=[];for(let e of this._degradedPollTimers.values())clearInterval(e);this._degradedPollTimers.clear(),this._repairAttempts.clear(),this._activeRepairs.clear();for(let e of this._repairRetryTimers.values())clearTimeout(e);this._repairRetryTimers.clear(),this._repairContext.clear();for(let e of this._reconcileTimers.values())clearTimeout(e);this._reconcileTimers.clear(),this._reconcileInFlight.clear(),this._closureContexts.clear(),this._recentlyPulledCids.clear(),this._activeLinks.clear(),this._linkRuntimes.clear()}async openLivePullSubscription(e){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=e.linkKey,o=this._activeLinks.get(s),c=o?.pull.contiguousAppliedToken;c&&(!c.streamId||!c.messageCid||!c.epoch||!c.position)&&(console.warn(`SyncEngineLevel: Discarding stored cursor with empty field(s) for ${r} -> ${i}`),c=void 0,o&&(is.resetCheckpoint(o.pull),await this.ledger.saveLink(o)));let l=o?.scope.kind==="protocol"?o.scope.protocolPathPrefixes?.[0]:void 0,d=a?[{protocol:a,...l?{protocolPathPrefix:l}:{}}]:[],u;n&&(u=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id);let f=this._engineGeneration,h=async _=>{if(this._engineGeneration===f){if(_.type==="eose"){if(o){if(o.status!=="live"&&o.status!=="initializing")return;if(!is.validateTokenDomain(o.pull,_.cursor)){console.warn(`SyncEngineLevel: Token domain mismatch on EOSE for ${r} -> ${i}, transitioning to repairing`),await this.transitionToRepairing(s,o);return}is.setReceivedToken(o.pull,_.cursor),this.drainCommittedPull(s),await this.ledger.saveLink(o)}if(o){let D=o.connectivity;o.connectivity="online",D!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:r,remoteEndpoint:i,protocol:a,from:D,to:"online"}),o.needsReconcile&&this.scheduleReconcile(s,500)}else this._connectivityState="online";return}if(_.type==="event"){let D=_.event;if(o&&o.status!=="live"&&o.status!=="initializing")return;if(o&&!is.validateTokenDomain(o.pull,_.cursor)){console.warn(`SyncEngineLevel: Token domain mismatch for ${r} -> ${i}, transitioning to repairing`),await this.transitionToRepairing(s,o);return}if(o&&!OH(D.message,o.scope)){is.setReceivedToken(o.pull,_.cursor),is.commitContiguousToken(o.pull,_.cursor),await this.ledger.saveLink(o);return}let N=o?this.getOrCreateRuntime(s):void 0,$=N?N.nextDeliveryOrdinal++:-1;N&&N.inflight.set($,{ordinal:$,token:_.cursor,committed:!1});try{let F=this.extractDataStream(D);if(!F&&$d(D)&&D.message.descriptor.dataCid){let H=await ge.getCid(D.message),X=await oS({did:r,dwnUrl:i,delegateDid:n,protocol:a,messageCids:[H],agent:this.agent,permissionsApi:this._permissionsApi});X.length>0&&X[0].dataStream&&(F=X[0].dataStream)}await this.agent.dwn.processRawMessage(r,D.message,{dataStream:F});let L=this._closureContexts.get(r);if(L&&zG(L,D.message),o&&o.scope.kind==="protocol"){let H=this.agent.dwn.node.storage.messageStore,X=this._closureContexts.get(r);X||(X=mb(r),this._closureContexts.set(r,X));let R=await FE(D.message,H,o.scope,X);if(!R.complete){console.warn(`SyncEngineLevel: Closure incomplete for ${r} -> ${i}: ${R.failure.code} \u2014 ${R.failure.detail}`),await this.transitionToRepairing(s,o);return}}let M=await ge.getCid(D.message);if(this._recentlyPulledCids.set(`${M}|${i}`,Date.now()+ei.ECHO_SUPPRESS_TTL_MS),this.evictExpiredEchoEntries(),o&&N&&o.status==="live"){let H=N.inflight.get($);H&&(H.committed=!0),is.setReceivedToken(o.pull,_.cursor),this.drainCommittedPull(s)>0&&(await this.ledger.saveLink(o),o.pull.contiguousAppliedToken&&this.emitEvent({type:"checkpoint:pull-advance",tenantDid:o.tenantDid,remoteEndpoint:o.remoteEndpoint,protocol:o.protocol,position:o.pull.contiguousAppliedToken.position,messageCid:o.pull.contiguousAppliedToken.messageCid})),N.inflight.size>T6&&(console.warn(`SyncEngineLevel: Pull in-flight overflow for ${r} -> ${i}, transitioning to repairing`),await this.transitionToRepairing(s,o))}}catch(F){console.error(`SyncEngineLevel: Error processing live-pull event for ${r}`,F),o&&await this.transitionToRepairing(s,o)}}}},p={store:!1,author:r,target:r,messageType:Re.MessagesSubscribe,granteeDid:n,messageParams:{filters:d,cursor:c,permissionGrantId:u}},{message:m}=await this.agent.dwn.processRequest(p);if(!m)throw new Error(`SyncEngineLevel: Failed to construct MessagesSubscribe for ${i}`);let y=async _=>{let D=_??o?.pull.contiguousAppliedToken??c;D&&(!D.streamId||!D.messageCid||!D.epoch||!D.position)&&(D=void 0);let N={...p,messageParams:{...p.messageParams,cursor:D}},{message:$}=await this.agent.dwn.processRequest(N);if(!$)throw new Error(`SyncEngineLevel: Failed to construct resume MessagesSubscribe for ${i}`);return $},v=new URL(i);v.protocol=v.protocol==="http:"?"ws:":"wss:";let w=v.toString(),S=await this.agent.rpc.sendDwnRequest({dwnUrl:w,targetDid:r,message:m,subscription:{handler:h,resubscribeFactory:y}});if(S.status.code===410){let _=new Error(`SyncEngineLevel: ProgressGap for ${r} -> ${i}: ${S.status.detail}`);throw _.isProgressGap=!0,_.gapInfo=S.error,_}if(S.status.code!==200||!S.subscription)throw new Error(`SyncEngineLevel: MessagesSubscribe failed for ${r} -> ${i}: ${S.status.code} ${S.status.detail}`);this._liveSubscriptions.push({linkKey:s,did:r,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await S.subscription.close()}});let A=this._activeLinks.get(s);if(A){let _=A.connectivity;A.connectivity="online",_!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:r,remoteEndpoint:i,protocol:a,from:_,to:"online"})}}async openLocalPushSubscription(e){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=a?[{protocol:a}]:[],o;n&&(o=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id);let c=this._engineGeneration,l=async f=>{if(this._engineGeneration!==c||f.type!=="event")return;let h=e.linkKey,p=this._activeLinks.get(h);if(p&&!OH(f.event.message,p.scope))return;let m=h,y=await ge.getCid(f.event.message);if(y===void 0||this.isRecentlyPulled(y,i))return;let v=this.getOrCreatePushRuntime(m,{did:r,dwnUrl:i,delegateDid:n,protocol:a});v.entries.push({cid:y}),!v.flushing&&!v.timer&&this.flushPendingPushesForLink(m)},u=(await this.agent.dwn.processRequest({author:r,target:r,messageType:Re.MessagesSubscribe,granteeDid:n,messageParams:{filters:s,permissionGrantId:o},subscriptionHandler:l})).reply;if(u.status.code!==200||!u.subscription)throw new Error(`SyncEngineLevel: Local MessagesSubscribe failed for ${r}: ${u.status.code} ${u.status.detail}`);this._localSubscriptions.push({linkKey:e.linkKey??Ab(r,i,a),did:r,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await u.subscription.close()}})}async flushPendingPushes(){await Promise.all([...this._pushRuntimes.keys()].map(async e=>{await this.flushPendingPushesForLink(e)}))}async flushPendingPushesForLink(e){let r=this._pushRuntimes.get(e);if(!r)return;let{did:n,dwnUrl:i,delegateDid:a,protocol:s,entries:o,retryCount:c}=r;if(r.entries=[],o.length===0){!r.timer&&!r.flushing&&c===0&&this._pushRuntimes.delete(e);return}let l=o.map(d=>d.cid);r.flushing=!0;try{let d=await H6({did:n,dwnUrl:i,delegateDid:a,protocol:s,messageCids:l,agent:this.agent,permissionsApi:this._permissionsApi});if(d.failed.length>0){let u=new Set(d.failed),f=o.filter(h=>u.has(h.cid));this.requeueOrReconcile(e,{did:n,dwnUrl:i,delegateDid:a,protocol:s,entries:f,retryCount:c+1})}else r.retryCount=0,!r.timer&&r.entries.length===0&&this._pushRuntimes.delete(e)}catch(d){console.error(`SyncEngineLevel: Push batch failed for ${n} -> ${i}`,d),this.requeueOrReconcile(e,{did:n,dwnUrl:i,delegateDid:a,protocol:s,entries:o,retryCount:c+1})}finally{r.flushing=!1;let d=this._pushRuntimes.get(e);d&&d.entries.length>0&&!d.timer&&(d.timer=setTimeout(()=>{d.timer=void 0,this.flushPendingPushesForLink(e)},kge))}}requeueOrReconcile(e,r){let n=ei.PUSH_RETRY_BACKOFF_MS.length,i=this.getOrCreatePushRuntime(e,r);if(r.retryCount>=n){i.timer&&clearTimeout(i.timer),this._pushRuntimes.delete(e);let s=this._activeLinks.get(e);s&&!s.needsReconcile&&(s.needsReconcile=!0,this.ledger.saveLink(s).then(()=>{this.emitEvent({type:"reconcile:needed",tenantDid:r.did,remoteEndpoint:r.dwnUrl,protocol:r.protocol,reason:"push-retry-exhausted"}),this.scheduleReconcile(e)}));return}i.entries.push(...r.entries),i.retryCount=r.retryCount;let a=ei.PUSH_RETRY_BACKOFF_MS[r.retryCount]??2e3;i.timer&&clearTimeout(i.timer),i.timer=setTimeout(()=>{i.timer=void 0,this.flushPendingPushesForLink(e)},a)}createLinkReconciler(e){return new iS({getLocalRoot:async(r,n,i)=>this.getLocalRoot(r,n,i),getRemoteRoot:async(r,n,i,a)=>this.getRemoteRoot(r,n,i,a),diffWithRemote:async r=>this.diffWithRemote(r),pullMessages:async r=>this.pullMessages(r),pushMessages:async r=>this.pushMessages(r),shouldContinue:e})}scheduleReconcile(e,r=1500){if(this._reconcileTimers.has(e)||this._reconcileInFlight.has(e)||this._activeRepairs.has(e))return;let n=this._engineGeneration,i=setTimeout(()=>{this._reconcileTimers.delete(e),this._engineGeneration===n&&this.reconcileLink(e)},r);this._reconcileTimers.set(e,i)}async reconcileLink(e){let r=this._reconcileInFlight.get(e);if(r)return r;let n=this.doReconcileLink(e).finally(()=>{this._reconcileInFlight.delete(e)});return this._reconcileInFlight.set(e,n),n}async doReconcileLink(e){let r=this._activeLinks.get(e);if(!r||r.status!=="live"||this._activeRepairs.has(e))return;let n=this._engineGeneration,{tenantDid:i,remoteEndpoint:a,delegateDid:s,protocol:o}=r;try{let c=await this.createLinkReconciler(()=>this._engineGeneration===n).reconcile({did:i,dwnUrl:a,delegateDid:s,protocol:o},{verifyConvergence:!0});if(c.aborted)return;c.converged?(await this.ledger.clearNeedsReconcile(r),this.emitEvent({type:"reconcile:completed",tenantDid:i,remoteEndpoint:a,protocol:o})):this.scheduleReconcile(e,5e3)}catch(c){console.error(`SyncEngineLevel: Reconciliation failed for ${i} -> ${a}`,c),this.scheduleReconcile(e,5e3)}}getOrCreatePushRuntime(e,r){let n=this._pushRuntimes.get(e);return n||(n={...r,entries:[],retryCount:0},this._pushRuntimes.set(e,n)),n}buildLinkKey(e,r,n){return n?DH(e,r,n):Ab(e,r)}async getCursor(e){let r=this._db.sublevel("syncCursors");try{let n=await r.get(e);try{let i=JSON.parse(n);if(i&&typeof i=="object"&&typeof i.streamId=="string"&&i.streamId.length>0&&typeof i.epoch=="string"&&i.epoch.length>0&&typeof i.position=="string"&&i.position.length>0&&typeof i.messageCid=="string"&&i.messageCid.length>0)return i}catch{}await this.deleteLegacyCursor(e);return}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async deleteLegacyCursor(e){let r=this._db.sublevel("syncCursors");try{await r.del(e)}catch{}}extractDataStream(e){if(!$d(e))return;let r=e.message.encodedData;if(r){delete e.message.encodedData;let n=De.base64UrlToBytes(r);return new ReadableStream({start(i){i.enqueue(n),i.close()}})}if(e.data)return e.data}async getDefaultHashHex(e){if(this._defaultHashHex===void 0){let r=await kl(),n=new Map;for(let i=0;i<=Sge;i++)n.set(i,an(r[i]));this._defaultHashHex=n}return this._defaultHashHex.get(e)??""}static parseBitPrefix(e){return Array.from(e,r=>r==="1")}get stateIndex(){if(!this.agent.dwn.isRemoteMode)return this.agent.dwn.node.storage.stateIndex}async getLocalRoot(e,r,n){let i=this.stateIndex;if(i){let c=n!==void 0?await i.getProtocolRoot(e,n):await i.getRoot(e);return an(c)}let a=await this.getSyncPermissionGrantId(e,r,n);return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:r,messageParams:{action:"root",protocol:n,permissionGrantId:a}})).reply.root??""}async getRemoteRoot(e,r,n,i){let a=await this.getSyncPermissionGrantId(e,n,i),s=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"root",protocol:i,permissionGrantId:a}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:s.message})).root??""}async diffWithRemote({did:e,dwnUrl:r,delegateDid:n,protocol:i}){let a=await this.collectLocalSubtreeHashes(e,i,BH),s=await this.getSyncPermissionGrantId(e,n,i),o=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"diff",protocol:i,hashes:a,depth:BH,permissionGrantId:s}}),c=await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message});if(c.status.code!==200)throw new Error(`SyncEngineLevel: diff failed with ${c.status.code}: ${c.status.detail}`);let l=s,d=[];for(let u of c.onlyLocal??[]){let f=await this.getLocalLeaves(e,u,n,i,l);d.push(...f)}return{onlyRemote:c.onlyRemote??[],onlyLocal:d}}async collectLocalSubtreeHashes(e,r,n){let i={},a=await this.getDefaultHashHex(n),s=this.stateIndex,o=async(c,l)=>{let d;if(s){let u=ei.parseBitPrefix(c),f=r!==void 0?await s.getProtocolSubtreeHash(e,r,u):await s.getSubtreeHash(e,u);d=an(f)}else d=await this.getLocalSubtreeHash(e,c,void 0,r);if(d!==a){if(l>=n){i[c]=d;return}await Promise.all([o(c+"0",l+1),o(c+"1",l+1)])}};return await o("",0),i}async getLocalSubtreeHash(e,r,n,i,a){let s=this.stateIndex;if(s){let l=ei.parseBitPrefix(r),d=i!==void 0?await s.getProtocolSubtreeHash(e,i,l):await s.getSubtreeHash(e,l);return an(d)}return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"subtree",prefix:r,protocol:i,permissionGrantId:a}})).reply.hash??""}async getLocalLeaves(e,r,n,i,a){let s=this.stateIndex;if(s){let l=ei.parseBitPrefix(r);return i!==void 0?await s.getProtocolLeaves(e,i,l):await s.getLeaves(e,l)}return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"leaves",prefix:r,protocol:i,permissionGrantId:a}})).reply.entries??[]}async pullMessages({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s}){return $H({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s,agent:this.agent,permissionsApi:this._permissionsApi})}evictExpiredEchoEntries(){let e=Date.now();for(let[r,n]of this._recentlyPulledCids)e>=n&&this._recentlyPulledCids.delete(r);if(this._recentlyPulledCids.size>ei.ECHO_SUPPRESS_MAX_ENTRIES){let r=this._recentlyPulledCids.size-ei.ECHO_SUPPRESS_MAX_ENTRIES,n=0;for(let i of this._recentlyPulledCids.keys()){if(n>=r)break;this._recentlyPulledCids.delete(i),n++}}}isRecentlyPulled(e,r){let n=`${e}|${r}`,i=this._recentlyPulledCids.get(n);return i===void 0?!1:Date.now()>=i?(this._recentlyPulledCids.delete(n),!1):!0}async pushMessages({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a}){return H6({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:this.agent,permissionsApi:this._permissionsApi})}static topologicalSort(e){return gg(e)}async getSyncTargets(){let e=[];for await(let[r,n]of this._db.sublevel("registeredIdentities").iterator()){let i;try{i=JSON.parse(n)}catch(c){console.warn(`SyncEngineLevel: Corrupt sync options for ${r}, falling back to global sync:`,c),i={protocols:[]}}let{protocols:a,delegateDid:s}=i,o=await this.agent.dwn.getDwnEndpointUrlsForTarget(r);if(o.length!==0)for(let c of o)if(a.length===0)e.push({did:r,delegateDid:s,dwnUrl:c});else for(let l of a)e.push({did:r,delegateDid:s,dwnUrl:c,protocol:l})}return e}async getSyncPermissionGrantId(e,r,n){return r?(await this._permissionsApi.getPermissionForRequest({connectedDid:e,messageType:Re.MessagesSync,delegateDid:r,protocol:n,cached:!0})).grant.id:void 0}};ei.ECHO_SUPPRESS_TTL_MS=6e4,ei.ECHO_SUPPRESS_MAX_ENTRIES=1e4,ei.MAX_CONSECUTIVE_FAILURES=5,ei.MAX_BACKOFF_MULTIPLIER=4,ei.MAX_REPAIR_ATTEMPTS=3,ei.REPAIR_BACKOFF_MS=[1e3,3e3,1e4],ei.PUSH_RETRY_BACKOFF_MS=[0,250,1e3,2e3];var wg=ei;g();Jn();Qo();Sr();import{Level as Mge}from"level";g();g();g();Sr();Pn();g();g();var MH=Tn(VE(),1);Sr();var vg=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},aS=class{constructor({ttl:e="15m"}={}){this.cache=new us.default({ttl:(0,MH.default)(e)})}get(e){return vg(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,r){return vg(this,void 0,void 0,function*(){this.cache.set(e,r)})}delete(e){return vg(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return vg(this,void 0,void 0,function*(){this.cache.clear()})}open(){return vg(this,void 0,void 0,function*(){})}close(){return vg(this,void 0,void 0,function*(){})}};g();Pn();Jn();g();var bg=class extends Error{constructor(e,r){super(r??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};g();var Pg;(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"})(Pg||(Pg={}));var xg=(t,e,r)=>({jsonrpc:"2.0",id:t,method:e,params:r}),cS=(t,e,r,n)=>({jsonrpc:"2.0",id:t,method:e,params:r,subscription:{id:n??null}}),KH=(t,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:t}});function Oh(t){try{return JSON.parse(t)}catch{return null}}var W6=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Age=3,_ge=500,Tge=1e4,Ige=3e4,NH=new Set([408,429,500,502,503,504]);function Dge(t,e){return t instanceof TypeError?!0:e?NH.has(e.status):!1}function Rge(t,e,r){let n=Math.min(e*Math.pow(2,t),r),i=.5+Math.random()*.5;return n*i}function Cge(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 dS=class t{constructor(e,r){var n,i,a;this.serverInfoCache=e??new aS,this._retryOptions={maxRetries:(n=r?.maxRetries)!==null&&n!==void 0?n:Age,baseDelayMs:(i=r?.baseDelayMs)!==null&&i!==void 0?i:_ge,maxDelayMs:(a=r?.maxDelayMs)!==null&&a!==void 0?a:Tge}}static isBunRuntime(){return typeof globalThis.Bun<"u"}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return W6(this,void 0,void 0,function*(){var r,n,i;let a=bn.randomUuid(),s=xg(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),o={"dwn-request":JSON.stringify(s)},c={method:"POST",headers:o};if(e.data){o["content-type"]="application/octet-stream";let h=e.data;if(h instanceof ReadableStream)if(t.isBunRuntime()){let p=yield Xt.toBytes(h);h=new Blob([p],{type:"application/octet-stream"})}else c.duplex="half";c.body=h}let l=yield this.fetchWithRetry(e.dwnUrl,c);if(l.status===429){let h=parseInt((r=l.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new bg(h)}let d,u=l.headers.has("dwn-response");if(u){let h=Oh(l.headers.get("dwn-response"));if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);d=h}else{let h=yield l.text(),p=Oh(h);if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${l.status}`);d=p}if(d.error){let{code:h,message:p}=d.error;if(h===Pg.TooManyRequests){let m=(i=(n=d.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new bg(m)}throw new Error(`(${h}) - ${p}`)}let{reply:f}=d.result;if(u){let h=new Uint8Array(yield l.arrayBuffer()),p=Xt.fromBytes(h);f.record?f.record.data=p:f.entry&&(f.entry.data=p)}return f})}getServerInfo(e){return W6(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 bg(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 W6(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,s,o;for(let c=0;c<=n;c++){try{let f=AbortSignal.timeout(Ige),h=Object.assign(Object.assign({},r),{signal:r?.signal?AbortSignal.any([r.signal,f]):f}),p=yield fetch(e,h);if(!NH.has(p.status)||c===n)return p;o=p}catch(f){if(!Dge(f)||c===n)throw f;s=f}let l=o?Cge(o):void 0,d=Rge(c,i,a),u=l!==void 0?Math.max(l,d):d;yield new Promise(f=>{setTimeout(f,u)})}if(o)return o;throw s})}};g();Pn();var _b=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})};function V6(t){return typeof t=="string"?t:t instanceof ArrayBuffer?new TextDecoder().decode(t):t instanceof Uint8Array?new TextDecoder().decode(t):String(t)}var UH=3e3,$ge=3e4,Bge=1e3,Oge=3e4,jge=1/0,lS=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 _b(this,arguments,void 0,function*(r,n={}){var i;let{connectTimeout:a=UH,responseTimeout:s=$ge}=n,o;try{o=yield t.createWebSocket(r,a)}catch(l){throw(i=n.onerror)===null||i===void 0||i.call(n,l),l}let c=new t(o,s,r,n);return c.wireSocket(o),c})}close(){this.closedByUser=!0,this._isConnected=!1,this.socket.close()}request(e){return _b(this,void 0,void 0,function*(){return new Promise((r,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=bn.randomUuid());let a=s=>{let o=Oh(V6(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 _b(this,void 0,void 0,function*(){if(!e.method.startsWith("rpc.subscribe."))throw new Error("subscribe rpc requests must include the `rpc.subscribe` prefix");if(!e.subscription)throw new Error("subscribe rpc requests must include subscribe options");let n=e.subscription.id,i=this.messageHandlers.get(n),a=c=>{let l=Oh(V6(c.data));l.id===n&&(l.error!==void 0&&(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),this.closeSubscription(n).catch(()=>{})),r(l))};this.messageHandlers.set(n,a),this.subscriptionHandlerIds.add(n);let s=yield this.request(e);return s.error?(i?this.messageHandlers.set(n,i):(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n)),{response:s}):{response:s,close:()=>_b(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let r=bn.randomUuid(),n=cS(r,"rpc.subscribe.close",{},e);return this.request(n)}send(e){this.socket.send(JSON.stringify(e))}static createWebSocket(e,r){return new Promise((n,i)=>{let a=new WebSocket(e),s=()=>{l(),n(a)},o=d=>{l(),i(d)},c=setTimeout(()=>{l(),a.close(),i(new Error("connect timed out"))},r),l=()=>{clearTimeout(c),a.removeEventListener("open",s),a.removeEventListener("error",o)};a.addEventListener("open",s),a.addEventListener("error",o)})}wireSocket(e){e.addEventListener("message",r=>{let n=Oh(V6(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:Pg.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:Bge,s=(r=this.options.maxReconnectDelay)!==null&&r!==void 0?r:Oge,o=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:jge,c=(i=this.options.connectTimeout)!==null&&i!==void 0?i:UH,l=0,d=()=>_b(this,void 0,void 0,function*(){var u,f,h,p;if(this.closedByUser){this.reconnecting=!1;return}if(l++,l>o){this.reconnecting=!1;return}(f=(u=this.options).onreconnecting)===null||f===void 0||f.call(u,l);let y=Math.min(a*Math.pow(2,l-1),s)*(.5+Math.random()*.5);if(yield new Promise(v=>setTimeout(v,y)),this.closedByUser){this.reconnecting=!1;return}try{let v=yield t.createWebSocket(this.url,c);this.socket=v,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(v),(p=(h=this.options).onreconnected)===null||p===void 0||p.call(h)}catch{yield d()}});d()}};g();g();g();Pn();g();Pn();var Eg=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Tb=class t{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return Eg(this,void 0,void 0,function*(){let r=new URL(e.dwnUrl);if(r.protocol!=="ws:"&&r.protocol!=="wss:")throw new Error(`Invalid websocket protocol ${r.protocol}`);if(!t.connections.has(r.host))try{let c=yield t.createConnection(r);t.connections.set(r.host,c)}catch(c){throw new Error(`Error connecting to ${r.host}: ${c.message}`)}let i=t.connections.get(r.host),{targetDid:a,message:s,subscription:o}=e;return o?t.subscriptionRequest(i,a,s,o.handler,o.resubscribeFactory):t.processMessage(i,a,s)})}static createConnection(e){return Eg(this,void 0,void 0,function*(){let r=e.host,n=new Map,i=yield lS.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 Eg(this,void 0,void 0,function*(){let i=bn.randomUuid(),a=xg(i,"dwn.processMessage",{target:r,message:n}),{socket:s}=e,o=yield s.request(a),{error:c,result:l}=o;if(c!==void 0)throw new Error(`error sending DWN request: ${c.message}`);return l.reply})}static subscriptionRequest(e,r,n,i,a){return Eg(this,void 0,void 0,function*(){let s=bn.randomUuid(),o=bn.randomUuid(),c=cS(s,"rpc.subscribe.dwn.processMessage",{target:r,message:n},o),{socket:l,subscriptions:d}=e,{response:u,close:f}=yield l.subscribe(c,y=>{let{result:v,error:w}=y;if(w){let A=d.get(o);A&&A.subscription.close(),d.delete(o);return}let S=v.subscription;if(i(S),"cursor"in S&&S.cursor){let A=d.get(o);A&&(A.lastCursor=S.cursor),l.send(KH(o,S.cursor))}}),{error:h,result:p}=u;if(h)throw new Error(`could not subscribe via jsonrpc socket: ${h.message}`);let{reply:m}=p;if(m.subscription&&f){let y=()=>Eg(this,void 0,void 0,function*(){d.delete(o),yield f()}),v={subscription:Object.assign(Object.assign({},m.subscription),{close:y}),target:r,message:n,handler:i,resubscribeFactory:a};d.set(o,v),m.subscription.close=y}return m})}static resubscribeAll(e){return Eg(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{}})}};Tb.connections=new Map;var Ib=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},LH;(function(t){t.Create="did.create",t.Resolve="did.resolve"})(LH||(LH={}));var Sg=class{constructor(e=[]){this.transportClients=new Map,e=[new J6,new Z6,...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 Ib(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 Ib(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)})}},J6=class extends dS{sendDidRequest(e){return Ib(this,void 0,void 0,function*(){let r=bn.randomUuid(),n=xg(r,e.method,{data:e.data}),i=new Request(e.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a;try{let s=yield fetch(i,{signal:AbortSignal.timeout(3e4)});if(s.ok){if(a=yield s.json(),a.error){let{code:o,message:c}=a.error;throw new Error(`JSON RPC (${o}) - ${c}`)}}else throw new Error(`HTTP (${s.status}) - ${s.statusText}`)}catch(s){throw new Error(`Error encountered while processing response from ${e.url}: ${s.message}`)}return a.result})}},Z6=class extends Tb{sendDidRequest(e){return Ib(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return Ib(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};g();var qH=class t{constructor(e){this.agent=e.agent,this.agentStores=e.agentStores,this.didResolverCache=e.didResolverCache,this.dwn=e.dwn,this.dwnDataStore=e.dwnDataStore,this.dwnStateIndex=e.dwnStateIndex,this.dwnMessageStore=e.dwnMessageStore,this.syncStore=e.syncStore,this.vaultStore=e.vaultStore,this.dwnResumableTaskStore=e.dwnResumableTaskStore,this.dwnStores=e.dwnStores}async clearStorage(){if(await this.agent.sync.stopSync(),this.agent.agentDid=void 0,await this.didResolverCache.clear(),await this.dwnDataStore.clear(),await this.dwnStateIndex.clear(),await this.dwnMessageStore.clear(),await this.dwnResumableTaskStore.clear(),await this.syncStore.clear(),await this.vaultStore.clear(),this.agent.vault._cachedInitialized=void 0,await this.agent.permissions.clear(),this.dwnStores.clear(),this.agentStores==="memory"){let{didApi:e,identityApi:r,permissionsApi:n,keyManager:i}=t.useMemoryStores({agent:this.agent});this.agent.did=e,this.agent.identity=r,this.agent.keyManager=i,this.agent.permissions=n}}async clearDwnStores(){await this.syncStore.clear(),await this.dwnDataStore.clear(),await this.dwnStateIndex.clear(),await this.dwnMessageStore.clear(),await this.dwnResumableTaskStore.clear(),await this.agent.permissions.clear(),this.dwnStores.clear()}async closeStorage(){await this.didResolverCache.close(),await this.dwnDataStore.close(),await this.dwnStateIndex.close(),await this.dwnMessageStore.close(),await this.dwnResumableTaskStore.close(),await this.syncStore.close(),await this.vaultStore.close()}async createAgentDid(){this.agent.agentDid=await go.create({options:{publish:!0,gatewayUri:O.DID_DHT_GATEWAY_URI??"http://localhost:7527",verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]}})}async createIdentity({name:e,testDwnUrls:r}){return await this.agent.identity.create({didMethod:"dht",didOptions:{services:[{id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:r}],verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]},metadata:{name:e}})}static async setup({agentClass:e,agentStores:r,testDataLocation:n}){r??="memory",n??="__TESTDATA__";let i=F=>`${n}/${F}`,a=new bo,s=new Sg,o={keyStore:new pg,identityStore:new mg,didStore:new ug,clear:()=>{o.keyStore._protocolInitializedCache?.clear(),o.identityStore._protocolInitializedCache?.clear(),o.didStore._protocolInitializedCache?.clear()}},{agentVault:c,didApi:l,identityApi:d,keyManager:u,didResolverCache:f,vaultStore:h,permissionsApi:p}=r==="memory"?t.useMemoryStores():t.useDiskStores({testDataLocation:n,stores:o}),m=new Df({blockstoreLocation:i("DWN_DATASTORE")}),y=new Bf({location:i("DWN_STATEINDEX")}),v=new $f,w=new Cf({location:i("DWN_RESUMABLETASKSTORE")}),S=new Rf({blockstoreLocation:i("DWN_MESSAGESTORE"),indexLocation:i("DWN_MESSAGEINDEX")}),A=await Wl.createDwn({dataPath:n,dataStore:m,didResolver:l,stateIndex:y,eventLog:v,messageStore:S,resumableTaskStore:w}),_=new Wl({dwn:A,localDwnStrategy:"off"}),D=new Mge(i("SYNC_STORE")),N=new wg({db:D}),$=new e({agentVault:c,cryptoApi:a,didApi:l,dwnApi:_,identityApi:d,keyManager:u,permissionsApi:p,rpcClient:s,syncApi:N});return new t({agent:$,agentStores:r,didResolverCache:f,dwn:A,dwnDataStore:m,dwnStateIndex:y,dwnMessageStore:S,dwnResumableTaskStore:w,dwnStores:o,syncStore:D,vaultStore:h})}static useDiskStores({agent:e,testDataLocation:r,stores:n}){let i=m=>`${r}/${m}`,a=new Rm({location:i("VAULT_STORE")}),s=new $h({keyDerivationWorkFactor:1,store:a}),{didStore:o,identityStore:c,keyStore:l}=n,d=new Of({location:i("DID_RESOLVERCACHE")}),u=new Ih({agent:e,didMethods:[go,wo],resolverCache:d,store:o}),f=new Bh({agent:e,store:c}),h=new Po({agent:e,keyStore:l}),p=new La({agent:e});return{agentVault:s,didApi:u,didResolverCache:d,identityApi:f,keyManager:h,permissionsApi:p,vaultStore:a}}static useMemoryStores({agent:e}={}){let r=new Eu,n=new $h({keyDerivationWorkFactor:1,store:r}),i=new hE,a=new Ih({agent:e,didMethods:[go,wo],resolverCache:i,store:new fg}),s=new Po({agent:e,keyStore:new hg}),o=new Bh({agent:e,store:new yg}),c=new La({agent:e});return{agentVault:n,didApi:a,didResolverCache:i,identityApi:o,keyManager:s,permissionsApi:c,vaultStore:r}}};g();Qo();Sr();Pn();Jn();function Kge({baseURL:t,endpoint:e,authParam:r,tokenParam:n}){switch(e){case"pushedAuthorizationRequest":return wb(t,"par");case"authorize":if(!r)throw new Error("authParam must be provided when building an authorize URL");return wb(t,`authorize/${r}.jwt`);case"callback":return wb(t,"callback");case"token":if(!n)throw new Error("tokenParam must be provided when building a token URL");return wb(t,`token/${n}.jwt`);default:throw new Error(`Unknown connect endpoint: ${e}`)}}async function Nge({did:t,data:e}){let r=he.object({alg:"EdDSA",kid:t.document.verificationMethod[0].id,typ:"JWT"}).toBase64Url(),n=he.object(e).toBase64Url(),a=await(await t.getSigner()).sign({data:he.string(`${r}.${n}`).toUint8Array()}),s=he.uint8Array(a).toBase64Url();return`${r}.${n}.${s}`}async function zH({jwt:t}){let[e,r,n]=t.split("."),i=he.base64Url(e).toObject();if(!i.kid)throw new Error('Connect: JWT missing required "kid" header value.');let{didDocument:a}=await wo.resolve(i.kid.split("#")[0]);if(!a)throw new Error("Connect: JWT verification failed \u2014 could not resolve DID.");let{publicKeyJwk:s}=a.verificationMethod?.find(l=>l.id===i.kid)??{};if(!s)throw new Error("Connect: JWT verification failed \u2014 public key not found in DID document.");if(!await new Wc().verify({key:s,signature:he.base64Url(n).toUint8Array(),data:he.string(`${e}.${r}`).toUint8Array()}))throw new Error("Connect: JWT verification failed \u2014 invalid signature.");return he.base64Url(r).toObject()}async function Uge({jwt:t,encryptionKey:e}){let r={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT"},n=bn.randomBytes(24),i=he.object(r).toUint8Array(),a=he.string(t).toUint8Array(),s=await Jc.encryptRaw({data:a,keyBytes:e,nonce:n,additionalData:i}),o=s.subarray(0,-16),c=s.subarray(-16);return[he.object(r).toBase64Url(),"",he.uint8Array(n).toBase64Url(),he.uint8Array(o).toBase64Url(),he.uint8Array(c).toBase64Url()].join(".")}async function FH({jwe:t,encryptionKey:e}){let[r,,n,i,a]=t.split("."),s=he.base64Url(e).toUint8Array(),o=he.base64Url(r).toUint8Array(),c=he.base64Url(n).toUint8Array(),l=he.base64Url(i).toUint8Array(),d=he.base64Url(a).toUint8Array(),u=new Uint8Array([...l,...d]),f=await Jc.decryptRaw({data:u,keyBytes:s,nonce:c,additionalData:o});return he.uint8Array(f).toString()}async function Lge(t,e){let r=await t.export(),n=e.verificationMethod?.[0].publicKeyJwk,i=r.privateKeys?.[0];n.alg="EdDSA";let a=await bi.convertPublicKeyToX25519({publicKey:n}),s=await bi.convertPrivateKeyToX25519({privateKey:i}),o=await Ht.sharedSecret({privateKeyA:s,publicKeyB:a});return Mm.deriveKeyBytes({baseKeyBytes:new Uint8Array(o),hash:"SHA-256",salt:new Uint8Array,info:new Uint8Array,length:256})}async function qge({jwt:t,encryptionKey:e,delegateDidKeyId:r,pin:n}){let i={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT",kid:r},a=bn.randomBytes(24),s=n?{...i,pin:n}:{...i},o=he.object(s).toUint8Array(),c=he.string(t).toUint8Array(),l=await Jc.encryptRaw({data:c,keyBytes:e,nonce:a,additionalData:o}),d=l.subarray(0,-16),u=l.subarray(-16);return[he.object(i).toBase64Url(),"",he.uint8Array(a).toBase64Url(),he.uint8Array(d).toBase64Url(),he.uint8Array(u).toBase64Url()].join(".")}async function zge(t,e,r){let[n,,i,a,s]=e.split("."),o=he.base64Url(n).toObject();if(!o.kid)throw new Error('Connect: JWE protected header is missing required "kid" property.');let c=await wo.resolve(o.kid.split("#")[0]),l=await kg.deriveSharedKey(t,c.didDocument),d=r?{...o,pin:r}:{...o},u=he.object(d).toUint8Array(),f=he.base64Url(i).toUint8Array(),h=he.base64Url(a).toUint8Array(),p=he.base64Url(s).toUint8Array(),m=new Uint8Array([...h,...p]),y=await Jc.decryptRaw({data:m,keyBytes:l,nonce:f,additionalData:u});return he.uint8Array(y).toString()}async function Fge(t){let e=bn.randomBytes(16),r=bn.randomBytes(16);return{...t,nonce:he.uint8Array(r).toBase64Url(),responseMode:"direct_post",state:he.uint8Array(e).toBase64Url(),supportedDidMethods:t.supportedDidMethods??["did:dht","did:jwk"]}}async function Gge(t,e){let n=await(await fetch(t,{signal:AbortSignal.timeout(3e4)})).text(),i=await FH({jwe:n,encryptionKey:e});return await zH({jwt:i})}async function Hge(t){let e=Math.floor(Date.now()/1e3);return{...t,iat:e,exp:e+600}}function Wge(t){return O6(t)?!0:t.interface===be.Protocols&&t.method===we.Configure}async function Vge(t,e,r,n){let i=new La({agent:r});Bs.log(`Creating permission grants for ${n.length} scopes...`);let a=await Promise.all(n.map(c=>{let l=Wge(c);return i.createGrant({delegated:l,store:!0,grantedTo:e.uri,scope:c,dateExpires:"2040-06-25T16:09:16.693356Z",author:t})})),s=await r.dwn.getDwnEndpointUrlsForTarget(t);Bs.log(`Sending ${a.length} permission grants to ${s.length} DWN endpoint(s)...`);let o=a.map(async c=>{let{encodedData:l,...d}=c.message,u=he.base64Url(l).toUint8Array(),f=!1;for(let h of s)try{let p=await r.rpc.sendDwnRequest({dwnUrl:h,targetDid:t,message:d,data:new Blob([u])});p.status.code===202||p.status.code===409?f=!0:Bs.error(`Grant send to ${h} returned ${p.status.code}: ${p.status.detail}`)}catch(p){Bs.error(`Grant send to ${h} failed: ${p.message}`)}if(!f)throw new Error("Could not send permission grant to any DWN endpoint.");return c.message});try{return await Promise.all(o)}catch(c){throw Bs.error(`Error during batch-send of permission grants: ${c}`),c}}async function Jge(t,e,r){let n=await e.processDwnRequest({author:t,messageType:Re.ProtocolsQuery,target:t,messageParams:{filter:{protocol:r.protocol}}});if(n.reply.status.code!==200)throw new Error(`Could not fetch protocol: ${n.reply.status.detail}`);if(n.reply.entries===void 0||n.reply.entries.length===0){Bs.log(`Protocol does not exist, creating: ${r.protocol}`);let{reply:i,message:a}=await e.sendDwnRequest({author:t,target:t,messageType:Re.ProtocolsConfigure,messageParams:{definition:r}});if(i.status.code!==202&&i.status.code!==409)throw new Error(`Could not send protocol: ${i.status.detail}`);await e.processDwnRequest({author:t,target:t,messageType:Re.ProtocolsConfigure,rawMessage:a})}else{Bs.log(`Protocol already exists: ${r.protocol}`);let i=n.reply.entries[0],{reply:a}=await e.sendDwnRequest({author:t,target:t,messageType:Re.ProtocolsConfigure,rawMessage:i});if(a.status.code!==202&&a.status.code!==409)throw new Error(`Could not send protocol: ${a.status.detail}`)}}async function Zge(t,e,r,n){let i=await wo.create(),a=await i.export(),s=e.permissionRequests.map(async p=>{let{protocolDefinition:m,permissionScopes:y}=p;if(!y.every(w=>"protocol"in w&&w.protocol===m.protocol))throw new Error("All permission scopes must match the protocol URI they are provided with.");return await Jge(t,n,m),kg.createPermissionGrants(t,i,n,y)}),o=(await Promise.all(s)).flat();Bs.log("Building connect response...");let c=await kg.createConnectResponse({providerDid:t,delegateDid:i.uri,aud:e.clientDid,nonce:e.nonce,delegateGrants:o,delegatePortableDid:a});Bs.log("Signing connect response...");let l=await kg.signJwt({did:i,data:c}),d=await wo.resolve(e.clientDid),u=await kg.deriveSharedKey(i,d?.didDocument);Bs.log("Encrypting connect response...");let f=await kg.encryptResponse({jwt:l,encryptionKey:u,delegateDidKeyId:i.document.verificationMethod[0].id,pin:r}),h=new URLSearchParams({id_token:f,state:e.state}).toString();Bs.log(`Sending connect response to: ${e.callbackUrl}`),await fetch(e.callbackUrl,{body:h,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(3e4)})}var kg={buildConnectUrl:Kge,signJwt:Nge,verifyJwt:zH,encryptRequest:Uge,decryptRequest:FH,encryptResponse:qge,decryptResponse:zge,deriveSharedKey:Lge,createConnectRequest:Fge,getConnectRequest:Gge,createConnectResponse:Hge,createPermissionGrants:Vge,submitConnectResponse:Zge};g();Sr();Qo();var GH=class t{constructor(e){this._agentDid=e.agentDid,this.crypto=e.cryptoApi,this.did=e.didApi,this.dwn=e.dwnApi,this.identity=e.identityApi,this.keyManager=e.keyManager,this.permissions=e.permissionsApi,this.rpc=e.rpcClient,this.sync=e.syncApi,this.vault=e.agentVault,this.did.agent=this,this.dwn.agent=this,this.identity.agent=this,this.keyManager.agent=this,this.permissions.agent=this,this.sync.agent=this}get agentDid(){if(this._agentDid===void 0)throw new Error('EnboxUserAgent: The "agentDid" property is not set. Ensure the agent is properly initialized and a DID is assigned.');return this._agentDid}set agentDid(e){this._agentDid=e}static async create({dataPath:e="DATA/AGENT",localDwnStrategy:r,localDwnEndpoint:n,agentDid:i,agentVault:a,cryptoApi:s,didApi:o,dwnApi:c,identityApi:l,keyManager:d,permissionsApi:u,rpcClient:f,syncApi:h}={}){return a??=new $h({keyDerivationWorkFactor:21e4,store:new Rm({location:`${e}/VAULT_STORE`})}),s??=new bo,o??=new Ih({didMethods:[go,wo],resolverCache:new Of({location:`${e}/DID_RESOLVERCACHE`}),store:new ug}),c||(n?c=new Wl({localDwnEndpoint:n,localDwnStrategy:r??"prefer"}):c=new Wl({dwn:await Wl.createDwn({dataPath:e,didResolver:o}),localDwnStrategy:r??"prefer"})),r&&c.setLocalDwnStrategy(r),l??=new Bh({store:new mg}),d??=new Po({keyStore:new pg}),u??=new La,f??=new Sg,h??=new wg({dataPath:e}),new t({agentDid:i,agentVault:a,cryptoApi:s,didApi:o,dwnApi:c,keyManager:d,permissionsApi:u,identityApi:l,rpcClient:f,syncApi:h})}async firstLaunch(){return await this.vault.isInitialized()===!1}async initialize({password:e,recoveryPhrase:r,dwnEndpoints:n}){return r=await this.vault.initialize({password:e,recoveryPhrase:r,dwnEndpoints:n}),r}async processDidRequest(e){return this.did.processRequest(e)}async processDwnRequest(e){return this.dwn.processRequest(e)}async processVcRequest(e){throw new Error("Not implemented")}async sendDidRequest(e){throw new Error("Not implemented")}async sendDwnRequest(e){return this.dwn.sendRequest(e)}async sendVcRequest(e){throw new Error("Not implemented")}async start({password:e}){this.vault.isLocked()&&await this.vault.unlock({password:e}),this.agentDid=await this.vault.getDid()}};export{bo as AgentCryptoApi,Ih as AgentDidApi,Of as AgentDidResolverCache,Wl as AgentDwnApi,Bh as AgentIdentityApi,La as AgentPermissionsApi,WG as AnonymousDwnApi,ag as BearerIdentity,D6 as ClosureFailureCode,jye as DISCOVERY_DIR,Mye as DISCOVERY_FILENAME,uH as DWN_CONNECT_PATH,lH as DWN_PROTOCOL_SCHEME,$ye as DidInterface,ao as DwnConstant,ai as DwnContentEncryptionAlgorithm,jf as DwnDataStore,Kt as DwnDateSort,ug as DwnDidStore,ZE as DwnDiscoveryFile,mg as DwnIdentityStore,Re as DwnInterface,Wt as DwnKeyDerivationScheme,pg as DwnKeyStore,Ir as DwnPermissionGrant,ud as DwnPermissionRequest,dt as DwnPermissionsProtocol,kg as EnboxConnectProtocol,GH as EnboxUserAgent,$h as HdIdentityVault,Mf as InMemoryDataStore,fg as InMemoryDidStore,yg as InMemoryIdentityStore,hg as InMemoryKeyStore,Dh as LocalDwnDiscovery,Po as LocalKeyManager,T6 as MAX_PENDING_TOKENS,qH as PlatformAgentTestHarness,is as ReplicationLedger,wg as SyncEngineLevel,YG as buildContextKeyDecrypter,_We as buildDwnConnectUrl,IWe as buildDwnDiscoveryRedirectUrl,Rh as buildEncryptionInput,eH as buildKmsDecryptCallback,_6 as computeScopeId,wb as concatenateUrl,mb as createClosureContext,Oye as createNodeDiscoveryFileFs,dH as decodeDwnDiscoveryPayload,QG as deriveContextEncryptionInput,C6 as detectNewParticipants,Cd as dwnMessageConstructors,iH as eagerSendContextKeyRecord,Lye as encodeDwnDiscoveryPayload,XE as encryptAndComputeCid,rH as ensureKeyDeliveryProtocol,FE as evaluateClosure,Sye as evaluateClosureBatch,sH as fetchContextKeyRecord,gb as getDwnServiceEndpointUrls,bb as getEncryptionKeyDeriver,Hl as getEncryptionKeyInfo,Pb as getKeyDecrypter,XGe as getPaginationCursor,ZGe as getRecordAuthor,_ye as getRecordMessageCid,YGe as getRecordProtocolRole,jGe as getRootContextId,FG as getRuleSetAtPath,R6 as hasRelationalReadAccess,ZG as isDidRequest,Nye as isDwnMessage,Od as isDwnRequest,gge as isIdentityMetadata,Uye as isMessagesPermissionScope,yb as isMultiPartyContext,aJe as isPortableIdentity,O6 as isRecordPermissionScope,B6 as isRecordsType,$d as isRecordsWrite,YE as ivLength,Bye as localDwnServerName,tH as maybeDecryptReply,JE as normalizeBaseUrl,TWe as parseDwnConnectUrl,QGe as pollWithTtl,DWe as readDwnDiscoveryPayloadFromUrl,XG as resolveKeyDecrypter,nH as writeContextKeyRecord};
|
|
2060
|
+
'valid, non-empty password.`);if(r??=EH(L6,128),!kH(r,L6))throw new Error("HdIdentityVault: The provided recovery phrase is invalid. Please ensure that the recovery phrase is a correctly formatted series of 12 words.");let i=await AH(r),a=tS.fromMasterSeed(i),s=a.derive("m/44'/0'/0'/0'/0'"),o=await this.crypto.deriveKey({algorithm:"HKDF-512",baseKeyBytes:s.privateKey,salt:"",info:"vault_cek",derivedKeyAlgorithm:"A256GCM"}),c=await this.crypto.deriveKeyBytes({algorithm:"HKDF-512",baseKeyBytes:s.publicKey,salt:"",info:"vault_unlock_salt",length:256}),l={alg:"PBES2-HS512+A256KW",enc:"A256GCM",cty:"text/plain",p2c:this._keyDerivationWorkFactor,p2s:he.uint8Array(c).toBase64Url()},d=await Vl.encrypt({key:he.string(e).toUint8Array(),protectedHeader:l,plaintext:he.object(o).toUint8Array(),crypto:this.crypto,keyManager:new Po});await this._store.set("contentEncryptionKey",d);let u=a.derive("m/44'/0'/1708523827'/0'/0'"),f=await this.crypto.bytesToPrivateKey({algorithm:"Ed25519",privateKeyBytes:u.privateKey}),h=a.derive("m/44'/0'/1708523827'/0'/1'"),p=await this.crypto.bytesToPrivateKey({algorithm:"Ed25519",privateKeyBytes:h.privateKey}),m=a.derive("m/44'/0'/1708523827'/0'/2'"),y=await this.crypto.bytesToPrivateKey({algorithm:"X25519",privateKeyBytes:m.privateKey}),v=new HE;await v.addPredefinedKeys({privateKeys:[f,p,y]});let w={verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]};n&&n.length&&(w.services=[{id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:n}]);let A=await(await go.create({keyManager:v,options:w})).export(),_={alg:"dir",enc:"A256GCM",cty:"json"},D=await Vl.encrypt({key:o,plaintext:he.object(A).toUint8Array(),protectedHeader:_,crypto:this.crypto,keyManager:new Po});return await this._store.set("did",D),this._contentEncryptionKey=o,await this.setStatus({initialized:!0}),r}async isInitialized(){return this._cachedInitialized===!0?!0:this.getStatus().then(({initialized:e})=>e)}isLocked(){return!this._contentEncryptionKey}async lock(){if(await this.isInitialized()===!1)throw new Error("HdIdentityVault: Lock operation failed. Vault has not been initialized.");this._contentEncryptionKey&&(this._contentEncryptionKey.k=""),this._contentEncryptionKey=void 0}async restore({backup:e,password:r}){if(!mge(e))throw new Error("HdIdentityVault: Restore operation failed due to invalid backup object.");let n,i,a;try{a=await this.getStoredDid(),i=await this.getStoredContentEncryptionKey(),n=await this.getStatus()}catch{throw new Error("HdIdentityVault: The restore operation cannot proceed because the existing vault contents are missing or inaccessible. If the problem persists consider re-initializing the vault and retrying the restore.")}try{let s=he.base64Url(e.data).toObject();await this._store.set("did",s.did),await this._store.set("contentEncryptionKey",s.contentEncryptionKey),await this.setStatus(s.status),await this.unlock({password:r})}catch{throw await this.setStatus(n),await this._store.set("contentEncryptionKey",i),await this._store.set("did",a),new Error("HdIdentityVault: Restore operation failed due to invalid backup data or an incorrect password. Please verify the password is correct for the provided backup and try again.")}await this.setStatus({lastRestore:new Date().toISOString()})}async unlock({password:e}){await this.lock();let r=await this.getStoredContentEncryptionKey();try{let{plaintext:n}=await Vl.decrypt({jwe:r,key:he.string(e).toUint8Array(),crypto:this.crypto,keyManager:new Po,options:{minP2cCount:1}}),i=he.uint8Array(n).toObject();this._contentEncryptionKey=i}catch{throw new Error("HdIdentityVault: Unable to unlock the vault due to an incorrect password.")}}async getStoredDid(){let e=await this._store.get("did");if(!e)throw new Error("HdIdentityVault: Unable to retrieve the DID record from the vault. Please check the vault status and if the problem persists consider re-initializing the vault and restoring the contents from a previous backup.");return e}async getStoredContentEncryptionKey(){let e=await this._store.get("contentEncryptionKey");if(!e)throw new Error("HdIdentityVault: Unable to retrieve the Content Encryption Key record from the vault. Please check the vault status and if the problem persists consider re-initializing the vault and restoring the contents from a previous backup.");return e}async setStatus({initialized:e,lastBackup:r,lastRestore:n}){let i=await this.getStatus();return i.initialized=e??i.initialized,i.lastBackup=r??i.lastBackup,i.lastRestore=n??i.lastRestore,await this._store.set("vaultStatus",JSON.stringify(i)),this._cachedInitialized=i.initialized,!0}};g();Qo();g();Sr();function gge(t){return!(!t||typeof t!="object"||t===null)&&"name"in t}var mg=class extends jf{constructor(){super(...arguments);this.name="DwnIdentityStore";this._recordProtocolDefinition=GE;this._recordProperties={dataFormat:"application/json",protocol:this._recordProtocolDefinition.protocol,protocolPath:"identityMetadata",schema:this._recordProtocolDefinition.types.identityMetadata.schema}}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async set(r){return await super.set(r)}async list(r){return await super.list(r)}async getAllRecords({agent:r,tenantDid:n}){this._index.clear();let{reply:i}=await r.dwn.processRequest({author:n,target:n,messageType:Re.RecordsQuery,messageParams:{filter:{...this._recordProperties}}}),a=[];for(let s of i.entries??[]){if(!s.encodedData)throw new Error(`${this.name}: Expected 'encodedData' to be present in the DWN query result entry`);let o=he.base64Url(s.encodedData).toObject();if(gge(o)){let c=`${n}${Ti}${o.uri}`;this._index.set(c,s.recordId),this._cache.set(s.recordId,o),a.push(o)}}return a}},yg=class extends Mf{constructor(){super(...arguments);this.name="InMemoryIdentityStore"}async delete(r){return await super.delete(r)}async get(r){return await super.get(r)}async list(r){return await super.list(r)}async set(r){return await super.set(r)}};function aJe(t){return!(!t||typeof t!="object"||t===null)&&"did"in t&&"metadata"in t&&xh(t.did)}var Bh=class{constructor({agent:e,store:r}={}){this._agent=e,this._store=r??new yg}get agent(){if(this._agent===void 0)throw new Error("AgentIdentityApi: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e}get tenant(){if(!this._agent)throw new Error("AgentIdentityApi: The agent must be set to perform tenant specific actions.");return this._agent.agentDid.uri}async create({metadata:e,didMethod:r="dht",didOptions:n,store:i}){let a=await this.agent.did.create({method:r,options:n,tenant:this.tenant,store:i}),s=new ag({did:a,metadata:{...e,uri:a.uri,tenant:this.tenant}});return(i??!0)&&await this._store.set({id:s.did.uri,data:s.metadata,agent:this.agent,tenant:s.metadata.tenant,preventDuplicates:!1,useCache:!0}),s}async export({didUri:e}){let r=await this.get({didUri:e});if(!r)throw new Error(`AgentIdentityApi: Failed to export due to Identity not found: ${e}`);return await r.export()}async get({didUri:e}){let r=await this._store.get({id:e,agent:this.agent,useCache:!0});if(!r)return;let n=await this.agent.did.get({didUri:e,tenant:r.tenant});if(!n)throw new Error(`AgentIdentityApi: Identity is present in the store but DID is missing: ${e}`);return new ag({did:n,metadata:r})}async import({portableIdentity:e}){e.metadata.tenant=this.tenant;let r=await this.agent.did.import({portableDid:e.portableDid,tenant:e.metadata.tenant});if(!r)throw new Error(`AgentIdentityApi: Failed to import Identity: ${e.metadata.uri}`);let n=new ag({did:r,metadata:e.metadata});return await this._store.set({id:n.did.uri,data:n.metadata,agent:this.agent,tenant:n.metadata.tenant,preventDuplicates:!0,useCache:!0}),n}async list({tenant:e}={}){let r=await this._store.list({agent:this.agent,tenant:e});return(await Promise.all(r.map(i=>this.get({didUri:i.uri})))).filter(i=>typeof i<"u")}async delete({didUri:e}){if(!await this._store.get({id:e,agent:this.agent,useCache:!0}))throw new Error(`AgentIdentityApi: Failed to purge due to Identity not found: ${e}`);await this._store.delete({id:e,agent:this.agent})}getDwnEndpoints({didUri:e}){return this.agent.dwn.getDwnEndpointUrlsForTarget(e)}async setDwnEndpoints({didUri:e,endpoints:r}){let n=await this.agent.did.get({didUri:e});if(!n)throw new Error(`AgentIdentityApi: Failed to set DWN endpoints due to DID not found: ${e}`);let i=await n.export(),a=i.document.service?.find(s=>s.id.endsWith("dwn"));if(a)a.serviceEndpoint=r;else{let s={id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:r};i.document.service?i.document.service.push(s):i.document.service=[s]}await this.agent.did.update({portableDid:i,tenant:this.agent.agentDid.uri})}async setMetadataName({didUri:e,name:r}){if(!r)throw new Error("AgentIdentityApi: Failed to set metadata name due to missing name value.");let n=await this.get({didUri:e});if(!n)throw new Error(`AgentIdentityApi: Failed to set metadata name due to Identity not found: ${e}`);if(n.metadata.name===r)throw new Error("AgentIdentityApi: No changes detected.");await this._store.set({id:n.did.uri,data:{...n.metadata,name:r},agent:this.agent,tenant:n.metadata.tenant,updateExisting:!0,useCache:!0})}async connectedIdentity({connectedDid:e}={}){let r=await this.list();if(!(r.length<1))return e?r.find(n=>n.metadata.connectedDid===e):r.find(n=>n.metadata.connectedDid!==void 0)}};g();Jn();Sr();var La=class t{constructor({agent:e}={}){this._cachedPermissions=new us.default({ttl:60*1e3});this._agent=e}get agent(){if(!this._agent)throw new Error("AgentPermissionsApi: Agent is not set");return this._agent}set agent(e){this._agent=e}async getPermissionForRequest({connectedDid:e,delegateDid:r,delegate:n,messageType:i,protocol:a,cached:s=!1}){let o=[e,r,i,a].join("~"),c=s?this._cachedPermissions.get(o):void 0;if(c)return c;let l=await this.fetchGrants({author:r,target:r,grantor:e,grantee:r}),d=await t.matchGrantFromArray(e,r,{messageType:i,protocol:a},l,n);if(!d)throw new Error(`CachedPermissions: No permissions found for ${i}: ${a}`);return this._cachedPermissions.set(o,d),d}async fetchGrants({author:e,target:r,grantee:n,grantor:i,protocol:a,remote:s=!1,checkRevoked:o=!0}){let c=a?{protocol:a}:void 0,l={author:e,target:r,messageType:Re.RecordsQuery,messageParams:{filter:{author:i,recipient:n,protocol:dt.uri,protocolPath:dt.grantPath,tags:c}}},{reply:d}=s?await this.agent.sendDwnRequest(l):await this.agent.processDwnRequest(l);if(d.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${d.status.detail}`);let u=o?await this.fetchRevokedGrantIds({author:e,target:r,grantor:i,remote:s,tags:c}):new Set,f=[];for(let h of d.entries){if(u.has(h.recordId))continue;let p=Ir.parse(h);f.push({grant:p,message:h})}return f}async fetchRevokedGrantIds({author:e,target:r,grantor:n,remote:i,tags:a}){let s={author:e,target:r,messageType:Re.RecordsQuery,messageParams:{filter:{author:n,protocol:dt.uri,protocolPath:dt.revocationPath,tags:a}}},{reply:o}=i?await this.agent.sendDwnRequest(s):await this.agent.processDwnRequest(s);if(o.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch revocations: ${o.status.detail}`);let c=new Set;for(let l of o.entries)l.descriptor.parentId!==void 0&&c.add(l.descriptor.parentId);return c}async fetchRequests({author:e,target:r,protocol:n,remote:i=!1}){let a=n?{protocol:n}:void 0,s={author:e,target:r,messageType:Re.RecordsQuery,messageParams:{filter:{protocol:dt.uri,protocolPath:dt.requestPath,tags:a}}},{reply:o}=i?await this.agent.sendDwnRequest(s):await this.agent.processDwnRequest(s);if(o.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch requests: ${o.status.detail}`);let c=[];for(let l of o.entries){let d=ud.parse(l);c.push({request:d,message:l})}return c}async isGrantRevoked({author:e,target:r,grantRecordId:n,remote:i=!1}){let a={author:e,target:r,messageType:Re.RecordsRead,messageParams:{filter:{parentId:n,protocol:dt.uri,protocolPath:dt.revocationPath}}},{reply:s}=i?await this.agent.sendDwnRequest(a):await this.agent.processDwnRequest(a);if(s.status.code===404)return!1;if(s.status.code===200)return!0;throw new Error(`PermissionsApi: Failed to check if grant is revoked: ${s.status.detail}`)}async createGrant(e){let{author:r,store:n=!1,delegated:i=!1,...a}=e,s;dt.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={dateExpires:a.dateExpires,requestId:a.requestId,description:a.description,delegated:i,scope:a.scope},c=he.object(o).toUint8Array(),l={recipient:a.grantedTo,protocol:dt.uri,protocolPath:dt.grantPath,dataFormat:"application/json",tags:s},{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([c])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${d.status.detail}`);let f={...u,encodedData:he.uint8Array(c).toBase64Url()};return{grant:Ir.parse(f),message:f}}async createRequest(e){let{author:r,store:n=!1,delegated:i=!1,...a}=e,s;dt.hasProtocolScope(a.scope)&&(s={protocol:a.scope.protocol});let o={description:a.description,delegated:i,scope:a.scope},c=he.object(o).toUint8Array(),l={protocol:dt.uri,protocolPath:dt.requestPath,dataFormat:"application/json",tags:s},{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([c])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${d.status.detail}`);let f={...u,encodedData:he.uint8Array(c).toBase64Url()};return{request:ud.parse(f),message:f}}async createRevocation(e){let{author:r,store:n=!1,grant:i,description:a}=e,s={description:a},o=he.object(s).toUint8Array(),c;dt.hasProtocolScope(i.scope)&&(c={protocol:i.scope.protocol});let l={parentContextId:i.id,protocol:dt.uri,protocolPath:dt.revocationPath,dataFormat:"application/json",tags:c},{reply:d,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([o])});if(d.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${d.status.detail}`);return{message:{...u,encodedData:he.uint8Array(o).toBase64Url()}}}async clear(){this._cachedPermissions.clear()}static async matchGrantFromArray(e,r,n,i,a=!1){let s;for(let o of i){let{grant:c,message:l}=o;if(a===!0&&c.delegated!==!0)continue;let{messageType:d,protocol:u,protocolPath:f,contextId:h}=n;if(this.matchScopeFromGrant(e,r,d,c,u,f,h)){if(c.scope.interface+c.scope.method===d)return{grant:c,message:l};s||(s={grant:c,message:l})}}return s}static matchScopeFromGrant(e,r,n,i,a,s,o){if(i.grantee!==r||i.grantor!==e)return!1;let c=i.scope,l=c.interface+c.method;if(l===n||l===Re.MessagesRead&&(n===Re.MessagesSync||n===Re.MessagesSubscribe))if(B6(n)){let u=c;if(u.protocol!==a)return!1;if(this.isUnrestrictedProtocolScope(u)||u.protocolPath!==void 0&&u.protocolPath===s||u.contextId!==void 0&&o?.startsWith(u.contextId))return!0}else{let u=c;return u.protocol===void 0?!0:u.protocol!==a?!1:this.isUnrestrictedProtocolScope(u)}return!1}static isUnrestrictedProtocolScope(e){return e.contextId===void 0&&e.protocolPath===void 0}};g();var jH=Tn(VE(),1);Jn();import{Level as Ege}from"level";g();function wge(t){let e=[],r=[];for(let n of t)n.message?n.message.descriptor.interface==="Records"&&n.message.descriptor.method==="Write"&&n.message.descriptor.dataCid&&!n.encodedData?r.push(n.messageCid):e.push(n):r.push(n.messageCid);return{prefetched:e,needsFetchCids:r}}var iS=class{constructor(e){this._deps=e}async reconcile(e,r){let{did:n,dwnUrl:i,delegateDid:a,protocol:s}=e,o=r?.direction,c=r?.verifyConvergence??!1,l=this._deps.shouldContinue,d=await this._deps.getLocalRoot(n,a,s);if(l&&!l())return{aborted:!0,changed:!1,didPull:!1,didPush:!1};let u=await this._deps.getRemoteRoot(n,i,a,s);if(l&&!l())return{aborted:!0,changed:!1,didPull:!1,didPush:!1};let f=!1,h=!1,p;if(d!==u){let v=await this._deps.diffWithRemote(e);if(l&&!l())return{aborted:!0,changed:!0,didPull:!1,didPush:!1,localRoot:d,remoteRoot:u};if((!o||o==="pull")&&v.onlyRemote.length>0){let{prefetched:w,needsFetchCids:S}=wge(v.onlyRemote);if(await this._deps.pullMessages({did:n,dwnUrl:i,delegateDid:a,protocol:s,messageCids:S,prefetched:w}),l&&!l())return{aborted:!0,changed:!0,didPull:!0,didPush:!1,localRoot:d,remoteRoot:u};f=!0}if((!o||o==="push")&&v.onlyLocal.length>0){if(p=await this._deps.pushMessages({did:n,dwnUrl:i,delegateDid:a,protocol:s,messageCids:v.onlyLocal}),l&&!l())return{aborted:!0,changed:!0,didPull:f,didPush:!0,localRoot:d,remoteRoot:u,pushResult:p};h=!0}}if(!c)return{changed:d!==u,didPull:f,didPush:h,localRoot:d,remoteRoot:u,pushResult:p};let m=await this._deps.getLocalRoot(n,a,s);if(l&&!l())return{aborted:!0,changed:d!==u,didPull:f,didPush:h,localRoot:d,remoteRoot:u,pushResult:p};let y=await this._deps.getRemoteRoot(n,i,a,s);return l&&!l()?{aborted:!0,changed:d!==u,didPull:f,didPush:h,localRoot:d,remoteRoot:u,pushResult:p}:{changed:d!==u,didPull:f,didPush:h,localRoot:d,remoteRoot:u,postLocalRoot:m,postRemoteRoot:y,converged:m===y,pushResult:p}}};g();Jn();function IH(t){let e=t.descriptor;return e.interface!==be.Records||e.method!==we.Write?!1:e.dateCreated===e.messageTimestamp}function gg(t){if(t.length<=1)return t;let e=new Map,r=new Map,n=new Map,i=new Map;for(let d=0;d<t.length;d++){let u=t[d];e.set(d,u);let f=u.message.descriptor;if(f.interface===be.Protocols&&f.method===we.Configure){let h=f.definition?.protocol;h&&r.set(h,d)}if(f.interface===be.Records&&f.method===we.Write){let h=u.message.recordId;IH(u.message)&&h&&n.set(h,d),f.protocol===dt.uri&&f.protocolPath===dt.grantPath&&h&&i.set(h,d)}}let a=new Map,s=new Array(t.length).fill(0),o=(d,u)=>{if(d===u)return;a.has(d)||a.set(d,new Set);let f=a.get(d);f.has(u)||(f.add(u),s[u]++)};for(let d=0;d<t.length;d++){let u=t[d].message.descriptor;if(u.interface===be.Records){let h=u.protocol;h&&r.has(h)&&o(r.get(h),d)}if(u.interface===be.Records&&u.parentId){let h=u.parentId;n.has(h)&&o(n.get(h),d)}if(u.interface===be.Records&&u.method===we.Write){let h=t[d].message.recordId;h&&!IH(t[d].message)&&n.has(h)&&o(n.get(h),d)}if(u.interface===be.Records&&u.method===we.Delete){let h=u.recordId;h&&n.has(h)&&o(n.get(h),d)}let f=u.permissionGrantId;f&&i.has(f)&&o(i.get(f),d)}let c=[];for(let d=0;d<t.length;d++)s[d]===0&&c.push(d);let l=[];for(;c.length>0;){let d=c.shift();l.push(e.get(d));let u=a.get(d);if(u)for(let f of u)s[f]--,s[f]===0&&c.push(f)}if(l.length<t.length){let d=new Set(l);for(let u=0;u<t.length;u++){let f=e.get(u);d.has(f)||l.push(f)}}return l}g();var sS="^";function DH(t,e,r){return`${t}${sS}${e}${sS}${r}`}function Ab(t,e,r){let n=`${t}${sS}${e}`;return r?`${n}${sS}${r}`:n}g();Jn();var vge=1048576;function RH(t){return t.status.code===202||t.status.code===204||t.status.code===409||t.entry?.message.descriptor.interface===be.Records&&t.entry?.message.descriptor.method===we.Delete&&t.status.code===404}function bge(t){return t.status.code===400||t.status.code===401||t.status.code===403}async function CH(t){try{return await ge.getCid(t)}catch{return"unknown"}}async function $H({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,prefetched:a,agent:s,permissionsApi:o}){let c=[];if(a)for(let p of a){if(!p.message)continue;let m={message:p.message};if(p.encodedData){let y=De.base64UrlToBytes(p.encodedData);m.bufferedData=y,m.dataStream=new ReadableStream({start(v){v.enqueue(y),v.close()}})}c.push(m)}let l=i.length>0?await oS({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:s,permissionsApi:o}):[],d=[...c,...l],u=gg(d);await Pge(u);let f=3,h=u;for(let p=0;p<=f&&h.length>0;p++){let m=[];for(let y of h){let v=y.bufferedData?new ReadableStream({start(S){S.enqueue(y.bufferedData),S.close()}}):y.dataStream,w=await s.dwn.processRawMessage(t,y.message,{dataStream:v});RH(w)||m.push(y)}if(m.length>0){let y=[],v=[];for(let w of m)if(w.bufferedData||!w.dataStream)v.push(w);else{let S=await CH(w.message);y.push(S)}if(y.length>0){let w=await oS({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:y,agent:s,permissionsApi:o});v.push(...w)}h=gg(v)}else h=[]}}async function Pge(t){for(let e of t){if(!e.dataStream)continue;let r=[],n=0,i=!1,a=e.dataStream.getReader();try{for(;;){let{done:c,value:l}=await a.read();if(c)break;if(n+=l.byteLength,n>vge){i=!0;break}r.push(l)}}finally{a.releaseLock()}if(i){e.dataStream=void 0;continue}let s=new Uint8Array(n),o=0;for(let c of r)s.set(c,o),o+=c.byteLength;e.bufferedData=s,e.dataStream=new ReadableStream({start(c){c.enqueue(s),c.close()}})}}async function oS({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:s}){let o=[],c;r&&(c=(await s.getPermissionForRequest({connectedDid:t,messageType:Re.MessagesRead,delegateDid:r,protocol:n,cached:!0})).grant.id);let l=4,d=0;for(;d<i.length;){let u=i.slice(d,d+l);d+=l;let f=await Promise.all(u.map(async h=>{let p=await a.processDwnRequest({store:!1,author:t,target:t,messageType:Re.MessagesRead,granteeDid:r,messageParams:{messageCid:h,permissionGrantId:c}}),m;try{m=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:t,message:p.message})}catch(w){console.error(`SyncEngineLevel: pull - failed to read ${h} from ${e}:`,w.message??w);return}if(m.status.code!==200||!m.entry?.message)return;let y=m.entry,v;return $d(y)&&y.data&&(v=y.data),{message:y.message,dataStream:v}}));for(let h of f)h&&o.push(h)}return o}async function H6({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:s}){let o=[],c=[],l=[],d=[];for(let f of i){let h=await xge({author:t,messageCid:f,delegateDid:r,protocol:n,agent:a,permissionsApi:s});h?d.push(h):c.push(f)}let u=gg(d);for(let f of u){let h=await CH(f.message);try{let p=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:t,data:f.dataStream,message:f.message});RH(p)?o.push(h):bge(p)?(p.status.code===400&&p.status.detail?.includes("record limit")?console.debug(`SyncEngineLevel: singleton already exists on remote, skipping push for ${h}`):console.warn(`SyncEngineLevel: push permanently failed for ${h}: ${p.status.code} ${p.status.detail}`),l.push(h)):(console.error(`SyncEngineLevel: push failed for ${h}: ${p.status.code} ${p.status.detail}`),c.push(h))}catch(p){console.error(`SyncEngineLevel: push error for ${h}: ${p.message??p}`),c.push(h)}}return{succeeded:o,failed:c,permanentlyFailed:l}}async function xge({author:t,delegateDid:e,protocol:r,messageCid:n,agent:i,permissionsApi:a}){let s;e&&(s=(await a.getPermissionForRequest({connectedDid:t,messageType:Re.MessagesRead,delegateDid:e,protocol:r,cached:!0})).grant.id);let{reply:o}=await i.dwn.processRequest({author:t,target:t,messageType:Re.MessagesRead,granteeDid:e,messageParams:{messageCid:n,permissionGrantId:s}});if(o.status.code!==200||!o.entry)return;let c=o.entry,l={message:c.message};return $d(c)&&c.data&&(l.dataStream=c.data),l}var Sge=16,BH=8,kge=100;function OH(t,e){if(e.kind==="full"||!e.protocolPathPrefixes&&!e.contextIdPrefixes)return!0;let r=t.descriptor;if(e.protocolPathPrefixes&&e.protocolPathPrefixes.length>0){let n=r.protocolPath;if(!n||!e.protocolPathPrefixes.some(a=>n===a||n.startsWith(a+"/")))return!1}if(e.contextIdPrefixes&&e.contextIdPrefixes.length>0){let n=t.contextId;if(!n||!e.contextIdPrefixes.some(a=>n===a||n.startsWith(a+"/")))return!1}return!0}var ei=class ei{constructor({agent:e,dataPath:r,db:n}){this._syncLock=!1;this._activeLinks=new Map;this._linkRuntimes=new Map;this._syncMode="poll";this._engineGeneration=0;this._liveSubscriptions=[];this._localSubscriptions=[];this._connectivityState="unknown";this._eventListeners=new Set;this._pushRuntimes=new Map;this._recentlyPulledCids=new Map;this._closureContexts=new Map;this._consecutiveFailures=0;this._degradedPollTimers=new Map;this._repairAttempts=new Map;this._activeRepairs=new Map;this._repairRetryTimers=new Map;this._repairContext=new Map;this._reconcileTimers=new Map;this._reconcileInFlight=new Map;this._agent=e,this._permissionsApi=new La({agent:e}),this._db=n||new Ege(r??"DATA/AGENT/SYNC_STORE")}get ledger(){return this._ledger||(this._ledger=new is(this._db)),this._ledger}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 La({agent:e})}get connectivityState(){if(this._activeLinks.size===0)return this._connectivityState;let e=!1,r=!1;for(let n of this._activeLinks.values())n.connectivity==="online"&&(e=!0),n.connectivity==="offline"&&(r=!0);return e?"online":r?"offline":"unknown"}on(e){return this._eventListeners.add(e),()=>{this._eventListeners.delete(e)}}emitEvent(e){for(let r of this._eventListeners)try{r(e)}catch{}}async clear(){await this.teardownLiveSync(),await this._permissionsApi.clear(),await this._db.clear()}async close(){await this.teardownLiveSync(),await this._db.close()}async registerIdentity({did:e,options:r}){let n=this._db.sublevel("registeredIdentities");if(await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is already registered.`);r??={protocols:[]},await n.put(e,JSON.stringify(r))}async unregisterIdentity(e){let r=this._db.sublevel("registeredIdentities");if(!await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);await r.del(e)}async getIdentityOptions(e){let r=this._db.sublevel("registeredIdentities");try{let n=await 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}.`)}}async updateIdentityOptions({did:e,options:r}){let n=this._db.sublevel("registeredIdentities");if(!await this.getIdentityOptions(e))throw new Error(`SyncEngineLevel: Identity with DID ${e} is not registered.`);await n.put(e,JSON.stringify(r))}async sync(e){if(this._syncLock)throw new Error("SyncEngineLevel: Sync operation is already in progress.");this._syncLock=!0;try{let r=await this.getSyncTargets(),n=new Map;for(let o of r){let c=n.get(o.dwnUrl);c||(c=[],n.set(o.dwnUrl,c)),c.push(o)}let i=0,a=0,s=await Promise.allSettled([...n.entries()].map(async([o,c])=>{for(let l of c){let{did:d,delegateDid:u,protocol:f}=l;try{await this.createLinkReconciler().reconcile({did:d,dwnUrl:o,delegateDid:u,protocol:f},{direction:e})}catch(h){a++,console.error(`SyncEngineLevel: Error syncing ${d} with ${o}`,h);return}}i++}));for(let o of s)o.status==="rejected"&&a++;i>0?(this._consecutiveFailures=0,this._connectivityState="online"):a>0?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):r.length>0&&(this._consecutiveFailures=0,this._connectivityState="online")}finally{this._syncLock=!1}}async startSync(e){let r=e.mode??"poll",n=e.interval??(r==="live"?"5m":"2m"),i=(0,jH.default)(n);(this._liveSubscriptions.length>0||this._localSubscriptions.length>0)&&await this.teardownLiveSync(),this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),this._syncMode=r,r==="live"?await this.startLiveSync(i):await this.startPollSync(i)}async stopSync(e=2e3){this._engineGeneration++;let r=0;for(;this._syncLock;){if(r>=e)throw new Error(`SyncEngineLevel: Existing sync operation did not complete within ${e} milliseconds.`);r+=100,await new Promise(n=>{setTimeout(n,e<100?e:100)})}this._syncIntervalId&&(clearInterval(this._syncIntervalId),this._syncIntervalId=void 0),await this.teardownLiveSync()}async startPollSync(e){let r=this._engineGeneration,n=async()=>{if(this._engineGeneration!==r||this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{await this.sync()}catch(s){console.error("SyncEngineLevel: Error during sync operation",s)}let i=Math.min(Math.pow(2,this._consecutiveFailures),ei.MAX_BACKOFF_MULTIPLIER),a=this._consecutiveFailures>0?e*i:e;this._engineGeneration===r&&(this._syncIntervalId||(this._syncIntervalId=setInterval(n,a)))};this._syncIntervalId&&clearInterval(this._syncIntervalId),this._syncIntervalId=setInterval(n,e),this._syncLock||await this.sync()}async startLiveSync(e){try{await this.sync()}catch(i){console.error("SyncEngineLevel: Error during initial live-sync catch-up",i)}let r=await this.getSyncTargets();await Promise.allSettled(r.map(async i=>{let a;try{let s=i.protocol?{kind:"protocol",protocol:i.protocol}:{kind:"full"};a=await this.ledger.getOrCreateLink({tenantDid:i.did,remoteEndpoint:i.dwnUrl,scope:s,delegateDid:i.delegateDid,protocol:i.protocol});let o=this.buildLinkKey(i.did,i.dwnUrl,a.scopeId);if(!a.pull.contiguousAppliedToken){let l=Ab(i.did,i.dwnUrl,i.protocol),d=await this.getCursor(l);d&&(is.resetCheckpoint(a.pull,d),await this.ledger.saveLink(a),await this.deleteLegacyCursor(l))}this._activeLinks.set(o,a);let c={...i,linkKey:o};await this.openLivePullSubscription(c);try{await this.openLocalPushSubscription(c)}catch(l){let d=this._liveSubscriptions.find(u=>u.linkKey===o);if(d){try{await d.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(u=>u!==d)}throw l}this.emitEvent({type:"link:status-change",tenantDid:i.did,remoteEndpoint:i.dwnUrl,protocol:i.protocol,from:"initializing",to:"live"}),await this.ledger.setStatus(a,"live"),a.needsReconcile&&this.scheduleReconcile(o,1e3)}catch(s){let o=a?this.buildLinkKey(i.did,i.dwnUrl,a.scopeId):Ab(i.did,i.dwnUrl,i.protocol);if(s.isProgressGap&&a){console.warn(`SyncEngineLevel: ProgressGap detected for ${i.did} -> ${i.dwnUrl}, initiating repair`),this.emitEvent({type:"gap:detected",tenantDid:i.did,remoteEndpoint:i.dwnUrl,protocol:i.protocol,reason:"ProgressGap"});let c=s.gapInfo;await this.transitionToRepairing(o,a,{resumeToken:c?.latestAvailable});return}console.error(`SyncEngineLevel: Failed to open live subscription for ${i.did} -> ${i.dwnUrl}`,s),this._activeLinks.delete(o),this._linkRuntimes.delete(o),this._liveSubscriptions.length===0&&(this._connectivityState="unknown")}}));let n=async()=>{if(!this._syncLock)try{await this.sync()}catch(i){console.error("SyncEngineLevel: Error during SMT integrity check",i)}};this._syncIntervalId=setInterval(n,e)}getOrCreateRuntime(e){let r=this._linkRuntimes.get(e);return r||(r={nextDeliveryOrdinal:0,nextCommitOrdinal:0,inflight:new Map},this._linkRuntimes.set(e,r)),r}drainCommittedPull(e){let r=this._linkRuntimes.get(e),n=this._activeLinks.get(e);if(!r||!n)return 0;let i=0;for(;;){let a=r.inflight.get(r.nextCommitOrdinal);if(!a||!a.committed)break;is.commitContiguousToken(n.pull,a.token),is.setReceivedToken(n.pull,a.token),r.inflight.delete(r.nextCommitOrdinal),r.nextCommitOrdinal++,i++}return i}async transitionToRepairing(e,r,n){let i=r.status,a=r.connectivity;r.connectivity="offline",await this.ledger.setStatus(r,"repairing"),this.emitEvent({type:"link:status-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:i,to:"repairing"}),a!=="offline"&&this.emitEvent({type:"link:connectivity-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:a,to:"offline"}),n?.resumeToken&&this._repairContext.set(e,{resumeToken:n.resumeToken});let s=this._linkRuntimes.get(e);s&&(s.inflight.clear(),s.nextCommitOrdinal=s.nextDeliveryOrdinal),this.repairLink(e).catch(()=>{this.scheduleRepairRetry(e)})}scheduleRepairRetry(e){let r=this._activeLinks.get(e);if(!r||r.status==="degraded_poll"||this._repairRetryTimers.has(e))return;let n=this._repairAttempts.get(e)??1,i=ei.REPAIR_BACKOFF_MS,a=i[Math.min(n-1,i.length-1)],s=this._engineGeneration,o=setTimeout(async()=>{if(this._repairRetryTimers.delete(e),this._engineGeneration!==s)return;let c=this._activeLinks.get(e);if(!(!c||c.status!=="repairing"))try{await this.repairLink(e)}catch{c.status==="repairing"&&this.scheduleRepairRetry(e)}},a);this._repairRetryTimers.set(e,o)}repairLink(e){let r=this._activeRepairs.get(e);if(r)return r;let n=this.doRepairLink(e).finally(()=>{this._activeRepairs.delete(e);let i=this._activeLinks.get(e);i?.needsReconcile&&i.status==="live"&&this.scheduleReconcile(e,500)});return this._activeRepairs.set(e,n),n}async doRepairLink(e){let r=this._activeLinks.get(e);if(!r)return;let n=this._engineGeneration,{tenantDid:i,remoteEndpoint:a,delegateDid:s,protocol:o}=r;this.emitEvent({type:"repair:started",tenantDid:i,remoteEndpoint:a,protocol:o,attempt:(this._repairAttempts.get(e)??0)+1});let c=(this._repairAttempts.get(e)??0)+1;if(this._repairAttempts.set(e,c),await this.closeLinkSubscriptions(r),this._engineGeneration!==n)return;let l=this.getOrCreateRuntime(e);l.inflight.clear(),l.nextDeliveryOrdinal=0,l.nextCommitOrdinal=0;try{if((await this.createLinkReconciler(()=>this._engineGeneration===n).reconcile({did:i,dwnUrl:a,delegateDid:s,protocol:o})).aborted)return;let f=this._repairContext.get(e)?.resumeToken??r.pull.contiguousAppliedToken;if(is.resetCheckpoint(r.pull,f),await this.ledger.saveLink(r),this._engineGeneration!==n||(r.needsReconcile=!0,await this.ledger.saveLink(r),this._engineGeneration!==n))return;let h={did:i,dwnUrl:a,delegateDid:s,protocol:o,linkKey:e};try{await this.openLivePullSubscription(h)}catch(y){if(y.isProgressGap){if(console.warn(`SyncEngineLevel: Stale pull resume token for ${i} -> ${a}, resetting to start fresh`),is.resetCheckpoint(r.pull),await this.ledger.saveLink(r),this._engineGeneration!==n)return;await this.openLivePullSubscription(h)}else throw y}if(this._engineGeneration!==n)return;try{await this.openLocalPushSubscription(h)}catch(y){let v=this._liveSubscriptions.find(w=>w.linkKey===e);if(v){try{await v.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(w=>w!==v)}throw y}if(this._engineGeneration!==n)return;this._repairContext.delete(e),this._repairAttempts.delete(e);let p=this._repairRetryTimers.get(e);p&&(clearTimeout(p),this._repairRetryTimers.delete(e));let m=r.connectivity;r.connectivity="online",await this.ledger.setStatus(r,"live"),this.emitEvent({type:"repair:completed",tenantDid:i,remoteEndpoint:a,protocol:o}),m!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:i,remoteEndpoint:a,protocol:o,from:m,to:"online"}),this.emitEvent({type:"link:status-change",tenantDid:i,remoteEndpoint:a,protocol:o,from:"repairing",to:"live"})}catch(d){if(this._engineGeneration!==n)return;if(console.error(`SyncEngineLevel: Repair failed for ${i} -> ${a} (attempt ${c})`,d),this.emitEvent({type:"repair:failed",tenantDid:i,remoteEndpoint:a,protocol:o,attempt:c,error:String(d.message??d)}),c>=ei.MAX_REPAIR_ATTEMPTS){console.warn(`SyncEngineLevel: Max repair attempts reached for ${i} -> ${a}, entering degraded_poll`),await this.enterDegradedPoll(e);return}throw d}}async closeLinkSubscriptions(e){let{tenantDid:r,remoteEndpoint:n}=e,i=this.buildLinkKey(r,n,e.scopeId),a=this._liveSubscriptions.find(o=>o.linkKey===i);if(a){try{await a.close()}catch{}this._liveSubscriptions=this._liveSubscriptions.filter(o=>o!==a)}let s=this._localSubscriptions.find(o=>o.linkKey===i);if(s){try{await s.close()}catch{}this._localSubscriptions=this._localSubscriptions.filter(o=>o!==s)}}async enterDegradedPoll(e){let r=this._activeLinks.get(e);if(!r)return;r.connectivity="offline";let n=r.status;await this.ledger.setStatus(r,"degraded_poll"),this._repairAttempts.delete(e),this.emitEvent({type:"link:status-change",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol,from:n,to:"degraded_poll"}),this.emitEvent({type:"degraded-poll:entered",tenantDid:r.tenantDid,remoteEndpoint:r.remoteEndpoint,protocol:r.protocol});let i=this._degradedPollTimers.get(e);i&&clearInterval(i);let a=15e3,s=Math.floor(Math.random()*15e3),o=a+s,c=this._engineGeneration,l=setInterval(async()=>{if(this._engineGeneration!==c){clearInterval(l),this._degradedPollTimers.delete(e);return}if(r.status!=="degraded_poll"){clearInterval(l),this._degradedPollTimers.delete(e);return}try{this._repairAttempts.set(e,0),await this.ledger.setStatus(r,"repairing"),await this.repairLink(e),r.status==="live"&&(clearInterval(l),this._degradedPollTimers.delete(e))}catch{await this.ledger.setStatus(r,"degraded_poll")}},o);this._degradedPollTimers.set(e,l)}async teardownLiveSync(){this._engineGeneration++;for(let e of this._pushRuntimes.values())e.timer&&clearTimeout(e.timer);this._pushRuntimes.clear();for(let e of this._liveSubscriptions)try{await e.close()}catch{}this._liveSubscriptions=[];for(let e of this._localSubscriptions)try{await e.close()}catch{}this._localSubscriptions=[];for(let e of this._degradedPollTimers.values())clearInterval(e);this._degradedPollTimers.clear(),this._repairAttempts.clear(),this._activeRepairs.clear();for(let e of this._repairRetryTimers.values())clearTimeout(e);this._repairRetryTimers.clear(),this._repairContext.clear();for(let e of this._reconcileTimers.values())clearTimeout(e);this._reconcileTimers.clear(),this._reconcileInFlight.clear(),this._closureContexts.clear(),this._recentlyPulledCids.clear(),this._activeLinks.clear(),this._linkRuntimes.clear()}async openLivePullSubscription(e){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=e.linkKey,o=this._activeLinks.get(s),c=o?.pull.contiguousAppliedToken;c&&(!c.streamId||!c.messageCid||!c.epoch||!c.position)&&(console.warn(`SyncEngineLevel: Discarding stored cursor with empty field(s) for ${r} -> ${i}`),c=void 0,o&&(is.resetCheckpoint(o.pull),await this.ledger.saveLink(o)));let l=o?.scope.kind==="protocol"?o.scope.protocolPathPrefixes?.[0]:void 0,d=a?[{protocol:a,...l?{protocolPathPrefix:l}:{}}]:[],u;n&&(u=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id);let f=this._engineGeneration,h=async _=>{if(this._engineGeneration===f){if(_.type==="eose"){if(o){if(o.status!=="live"&&o.status!=="initializing")return;if(!is.validateTokenDomain(o.pull,_.cursor)){console.warn(`SyncEngineLevel: Token domain mismatch on EOSE for ${r} -> ${i}, transitioning to repairing`),await this.transitionToRepairing(s,o);return}is.setReceivedToken(o.pull,_.cursor),this.drainCommittedPull(s),await this.ledger.saveLink(o)}if(o){let D=o.connectivity;o.connectivity="online",D!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:r,remoteEndpoint:i,protocol:a,from:D,to:"online"}),o.needsReconcile&&this.scheduleReconcile(s,500)}else this._connectivityState="online";return}if(_.type==="event"){let D=_.event;if(o&&o.status!=="live"&&o.status!=="initializing")return;if(o&&!is.validateTokenDomain(o.pull,_.cursor)){console.warn(`SyncEngineLevel: Token domain mismatch for ${r} -> ${i}, transitioning to repairing`),await this.transitionToRepairing(s,o);return}if(o&&!OH(D.message,o.scope)){is.setReceivedToken(o.pull,_.cursor),is.commitContiguousToken(o.pull,_.cursor),await this.ledger.saveLink(o);return}let N=o?this.getOrCreateRuntime(s):void 0,$=N?N.nextDeliveryOrdinal++:-1;N&&N.inflight.set($,{ordinal:$,token:_.cursor,committed:!1});try{let F=this.extractDataStream(D);if(!F&&$d(D)&&D.message.descriptor.dataCid){let H=await ge.getCid(D.message),X=await oS({did:r,dwnUrl:i,delegateDid:n,protocol:a,messageCids:[H],agent:this.agent,permissionsApi:this._permissionsApi});X.length>0&&X[0].dataStream&&(F=X[0].dataStream)}await this.agent.dwn.processRawMessage(r,D.message,{dataStream:F});let L=this._closureContexts.get(r);if(L&&zG(L,D.message),o&&o.scope.kind==="protocol"){let H=this.agent.dwn.node.storage.messageStore,X=this._closureContexts.get(r);X||(X=mb(r),this._closureContexts.set(r,X));let R=await FE(D.message,H,o.scope,X);if(!R.complete){console.warn(`SyncEngineLevel: Closure incomplete for ${r} -> ${i}: ${R.failure.code} \u2014 ${R.failure.detail}`),await this.transitionToRepairing(s,o);return}}let M=await ge.getCid(D.message);if(this._recentlyPulledCids.set(`${M}|${i}`,Date.now()+ei.ECHO_SUPPRESS_TTL_MS),this.evictExpiredEchoEntries(),o&&N&&o.status==="live"){let H=N.inflight.get($);H&&(H.committed=!0),is.setReceivedToken(o.pull,_.cursor),this.drainCommittedPull(s)>0&&(await this.ledger.saveLink(o),o.pull.contiguousAppliedToken&&this.emitEvent({type:"checkpoint:pull-advance",tenantDid:o.tenantDid,remoteEndpoint:o.remoteEndpoint,protocol:o.protocol,position:o.pull.contiguousAppliedToken.position,messageCid:o.pull.contiguousAppliedToken.messageCid})),N.inflight.size>T6&&(console.warn(`SyncEngineLevel: Pull in-flight overflow for ${r} -> ${i}, transitioning to repairing`),await this.transitionToRepairing(s,o))}}catch(F){console.error(`SyncEngineLevel: Error processing live-pull event for ${r}`,F),o&&await this.transitionToRepairing(s,o)}}}},p={store:!1,author:r,target:r,messageType:Re.MessagesSubscribe,granteeDid:n,messageParams:{filters:d,cursor:c,permissionGrantId:u}},{message:m}=await this.agent.dwn.processRequest(p);if(!m)throw new Error(`SyncEngineLevel: Failed to construct MessagesSubscribe for ${i}`);let y=async _=>{let D=_??o?.pull.contiguousAppliedToken??c;D&&(!D.streamId||!D.messageCid||!D.epoch||!D.position)&&(D=void 0);let N={...p,messageParams:{...p.messageParams,cursor:D}},{message:$}=await this.agent.dwn.processRequest(N);if(!$)throw new Error(`SyncEngineLevel: Failed to construct resume MessagesSubscribe for ${i}`);return $},v=new URL(i);v.protocol=v.protocol==="http:"?"ws:":"wss:";let w=v.toString(),S=await this.agent.rpc.sendDwnRequest({dwnUrl:w,targetDid:r,message:m,subscription:{handler:h,resubscribeFactory:y}});if(S.status.code===410){let _=new Error(`SyncEngineLevel: ProgressGap for ${r} -> ${i}: ${S.status.detail}`);throw _.isProgressGap=!0,_.gapInfo=S.error,_}if(S.status.code!==200||!S.subscription)throw new Error(`SyncEngineLevel: MessagesSubscribe failed for ${r} -> ${i}: ${S.status.code} ${S.status.detail}`);this._liveSubscriptions.push({linkKey:s,did:r,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await S.subscription.close()}});let A=this._activeLinks.get(s);if(A){let _=A.connectivity;A.connectivity="online",_!=="online"&&this.emitEvent({type:"link:connectivity-change",tenantDid:r,remoteEndpoint:i,protocol:a,from:_,to:"online"})}}async openLocalPushSubscription(e){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=a?[{protocol:a}]:[],o;n&&(o=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id);let c=this._engineGeneration,l=async f=>{if(this._engineGeneration!==c||f.type!=="event")return;let h=e.linkKey,p=this._activeLinks.get(h);if(p&&!OH(f.event.message,p.scope))return;let m=h,y=await ge.getCid(f.event.message);if(y===void 0||this.isRecentlyPulled(y,i))return;let v=this.getOrCreatePushRuntime(m,{did:r,dwnUrl:i,delegateDid:n,protocol:a});v.entries.push({cid:y}),!v.flushing&&!v.timer&&this.flushPendingPushesForLink(m)},u=(await this.agent.dwn.processRequest({author:r,target:r,messageType:Re.MessagesSubscribe,granteeDid:n,messageParams:{filters:s,permissionGrantId:o},subscriptionHandler:l})).reply;if(u.status.code!==200||!u.subscription)throw new Error(`SyncEngineLevel: Local MessagesSubscribe failed for ${r}: ${u.status.code} ${u.status.detail}`);this._localSubscriptions.push({linkKey:e.linkKey??Ab(r,i,a),did:r,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await u.subscription.close()}})}async flushPendingPushes(){await Promise.all([...this._pushRuntimes.keys()].map(async e=>{await this.flushPendingPushesForLink(e)}))}async flushPendingPushesForLink(e){let r=this._pushRuntimes.get(e);if(!r)return;let{did:n,dwnUrl:i,delegateDid:a,protocol:s,entries:o,retryCount:c}=r;if(r.entries=[],o.length===0){!r.timer&&!r.flushing&&c===0&&this._pushRuntimes.delete(e);return}let l=o.map(d=>d.cid);r.flushing=!0;try{let d=await H6({did:n,dwnUrl:i,delegateDid:a,protocol:s,messageCids:l,agent:this.agent,permissionsApi:this._permissionsApi});if(d.failed.length>0){let u=new Set(d.failed),f=o.filter(h=>u.has(h.cid));this.requeueOrReconcile(e,{did:n,dwnUrl:i,delegateDid:a,protocol:s,entries:f,retryCount:c+1})}else r.retryCount=0,!r.timer&&r.entries.length===0&&this._pushRuntimes.delete(e)}catch(d){console.error(`SyncEngineLevel: Push batch failed for ${n} -> ${i}`,d),this.requeueOrReconcile(e,{did:n,dwnUrl:i,delegateDid:a,protocol:s,entries:o,retryCount:c+1})}finally{r.flushing=!1;let d=this._pushRuntimes.get(e);d&&d.entries.length>0&&!d.timer&&(d.timer=setTimeout(()=>{d.timer=void 0,this.flushPendingPushesForLink(e)},kge))}}requeueOrReconcile(e,r){let n=ei.PUSH_RETRY_BACKOFF_MS.length,i=this.getOrCreatePushRuntime(e,r);if(r.retryCount>=n){i.timer&&clearTimeout(i.timer),this._pushRuntimes.delete(e);let s=this._activeLinks.get(e);s&&!s.needsReconcile&&(s.needsReconcile=!0,this.ledger.saveLink(s).then(()=>{this.emitEvent({type:"reconcile:needed",tenantDid:r.did,remoteEndpoint:r.dwnUrl,protocol:r.protocol,reason:"push-retry-exhausted"}),this.scheduleReconcile(e)}));return}i.entries.push(...r.entries),i.retryCount=r.retryCount;let a=ei.PUSH_RETRY_BACKOFF_MS[r.retryCount]??2e3;i.timer&&clearTimeout(i.timer),i.timer=setTimeout(()=>{i.timer=void 0,this.flushPendingPushesForLink(e)},a)}createLinkReconciler(e){return new iS({getLocalRoot:async(r,n,i)=>this.getLocalRoot(r,n,i),getRemoteRoot:async(r,n,i,a)=>this.getRemoteRoot(r,n,i,a),diffWithRemote:async r=>this.diffWithRemote(r),pullMessages:async r=>this.pullMessages(r),pushMessages:async r=>this.pushMessages(r),shouldContinue:e})}scheduleReconcile(e,r=1500){if(this._reconcileTimers.has(e)||this._reconcileInFlight.has(e)||this._activeRepairs.has(e))return;let n=this._engineGeneration,i=setTimeout(()=>{this._reconcileTimers.delete(e),this._engineGeneration===n&&this.reconcileLink(e)},r);this._reconcileTimers.set(e,i)}async reconcileLink(e){let r=this._reconcileInFlight.get(e);if(r)return r;let n=this.doReconcileLink(e).finally(()=>{this._reconcileInFlight.delete(e)});return this._reconcileInFlight.set(e,n),n}async doReconcileLink(e){let r=this._activeLinks.get(e);if(!r||r.status!=="live"||this._activeRepairs.has(e))return;let n=this._engineGeneration,{tenantDid:i,remoteEndpoint:a,delegateDid:s,protocol:o}=r;try{let c=await this.createLinkReconciler(()=>this._engineGeneration===n).reconcile({did:i,dwnUrl:a,delegateDid:s,protocol:o},{verifyConvergence:!0});if(c.aborted)return;c.converged?(await this.ledger.clearNeedsReconcile(r),this.emitEvent({type:"reconcile:completed",tenantDid:i,remoteEndpoint:a,protocol:o})):this.scheduleReconcile(e,5e3)}catch(c){console.error(`SyncEngineLevel: Reconciliation failed for ${i} -> ${a}`,c),this.scheduleReconcile(e,5e3)}}getOrCreatePushRuntime(e,r){let n=this._pushRuntimes.get(e);return n||(n={...r,entries:[],retryCount:0},this._pushRuntimes.set(e,n)),n}buildLinkKey(e,r,n){return n?DH(e,r,n):Ab(e,r)}async getCursor(e){let r=this._db.sublevel("syncCursors");try{let n=await r.get(e);try{let i=JSON.parse(n);if(i&&typeof i=="object"&&typeof i.streamId=="string"&&i.streamId.length>0&&typeof i.epoch=="string"&&i.epoch.length>0&&typeof i.position=="string"&&i.position.length>0&&typeof i.messageCid=="string"&&i.messageCid.length>0)return i}catch{}await this.deleteLegacyCursor(e);return}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async deleteLegacyCursor(e){let r=this._db.sublevel("syncCursors");try{await r.del(e)}catch{}}extractDataStream(e){if(!$d(e))return;let r=e.message.encodedData;if(r){delete e.message.encodedData;let n=De.base64UrlToBytes(r);return new ReadableStream({start(i){i.enqueue(n),i.close()}})}if(e.data)return e.data}async getDefaultHashHex(e){if(this._defaultHashHex===void 0){let r=await kl(),n=new Map;for(let i=0;i<=Sge;i++)n.set(i,an(r[i]));this._defaultHashHex=n}return this._defaultHashHex.get(e)??""}static parseBitPrefix(e){return Array.from(e,r=>r==="1")}get stateIndex(){if(!this.agent.dwn.isRemoteMode)return this.agent.dwn.node.storage.stateIndex}async getLocalRoot(e,r,n){let i=this.stateIndex;if(i){let c=n!==void 0?await i.getProtocolRoot(e,n):await i.getRoot(e);return an(c)}let a=await this.getSyncPermissionGrantId(e,r,n);return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:r,messageParams:{action:"root",protocol:n,permissionGrantId:a}})).reply.root??""}async getRemoteRoot(e,r,n,i){let a=await this.getSyncPermissionGrantId(e,n,i),s=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"root",protocol:i,permissionGrantId:a}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:s.message})).root??""}async diffWithRemote({did:e,dwnUrl:r,delegateDid:n,protocol:i}){let a=await this.collectLocalSubtreeHashes(e,i,BH),s=await this.getSyncPermissionGrantId(e,n,i),o=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"diff",protocol:i,hashes:a,depth:BH,permissionGrantId:s}}),c=await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message});if(c.status.code!==200)throw new Error(`SyncEngineLevel: diff failed with ${c.status.code}: ${c.status.detail}`);let l=s,d=[];for(let u of c.onlyLocal??[]){let f=await this.getLocalLeaves(e,u,n,i,l);d.push(...f)}return{onlyRemote:c.onlyRemote??[],onlyLocal:d}}async collectLocalSubtreeHashes(e,r,n){let i={},a=await this.getDefaultHashHex(n),s=this.stateIndex,o=async(c,l)=>{let d;if(s){let u=ei.parseBitPrefix(c),f=r!==void 0?await s.getProtocolSubtreeHash(e,r,u):await s.getSubtreeHash(e,u);d=an(f)}else d=await this.getLocalSubtreeHash(e,c,void 0,r);if(d!==a){if(l>=n){i[c]=d;return}await Promise.all([o(c+"0",l+1),o(c+"1",l+1)])}};return await o("",0),i}async getLocalSubtreeHash(e,r,n,i,a){let s=this.stateIndex;if(s){let l=ei.parseBitPrefix(r),d=i!==void 0?await s.getProtocolSubtreeHash(e,i,l):await s.getSubtreeHash(e,l);return an(d)}return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"subtree",prefix:r,protocol:i,permissionGrantId:a}})).reply.hash??""}async getLocalLeaves(e,r,n,i,a){let s=this.stateIndex;if(s){let l=ei.parseBitPrefix(r);return i!==void 0?await s.getProtocolLeaves(e,i,l):await s.getLeaves(e,l)}return(await this.agent.dwn.processRequest({author:e,target:e,messageType:Re.MessagesSync,granteeDid:n,messageParams:{action:"leaves",prefix:r,protocol:i,permissionGrantId:a}})).reply.entries??[]}async pullMessages({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s}){return $H({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s,agent:this.agent,permissionsApi:this._permissionsApi})}evictExpiredEchoEntries(){let e=Date.now();for(let[r,n]of this._recentlyPulledCids)e>=n&&this._recentlyPulledCids.delete(r);if(this._recentlyPulledCids.size>ei.ECHO_SUPPRESS_MAX_ENTRIES){let r=this._recentlyPulledCids.size-ei.ECHO_SUPPRESS_MAX_ENTRIES,n=0;for(let i of this._recentlyPulledCids.keys()){if(n>=r)break;this._recentlyPulledCids.delete(i),n++}}}isRecentlyPulled(e,r){let n=`${e}|${r}`,i=this._recentlyPulledCids.get(n);return i===void 0?!1:Date.now()>=i?(this._recentlyPulledCids.delete(n),!1):!0}async pushMessages({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a}){return H6({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:this.agent,permissionsApi:this._permissionsApi})}static topologicalSort(e){return gg(e)}async getSyncTargets(){let e=[];for await(let[r,n]of this._db.sublevel("registeredIdentities").iterator()){let i;try{i=JSON.parse(n)}catch(c){console.warn(`SyncEngineLevel: Corrupt sync options for ${r}, falling back to global sync:`,c),i={protocols:[]}}let{protocols:a,delegateDid:s}=i,o=await this.agent.dwn.getDwnEndpointUrlsForTarget(r);if(o.length!==0)for(let c of o)if(a.length===0)e.push({did:r,delegateDid:s,dwnUrl:c});else for(let l of a)e.push({did:r,delegateDid:s,dwnUrl:c,protocol:l})}return e}async getSyncPermissionGrantId(e,r,n){return r?(await this._permissionsApi.getPermissionForRequest({connectedDid:e,messageType:Re.MessagesSync,delegateDid:r,protocol:n,cached:!0})).grant.id:void 0}};ei.ECHO_SUPPRESS_TTL_MS=6e4,ei.ECHO_SUPPRESS_MAX_ENTRIES=1e4,ei.MAX_CONSECUTIVE_FAILURES=5,ei.MAX_BACKOFF_MULTIPLIER=4,ei.MAX_REPAIR_ATTEMPTS=3,ei.REPAIR_BACKOFF_MS=[1e3,3e3,1e4],ei.PUSH_RETRY_BACKOFF_MS=[0,250,1e3,2e3];var wg=ei;g();Jn();Qo();Sr();import{Level as Mge}from"level";g();g();g();Sr();Pn();g();g();var MH=Tn(VE(),1);Sr();var vg=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},aS=class{constructor({ttl:e="15m"}={}){this.cache=new us.default({ttl:(0,MH.default)(e)})}get(e){return vg(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,r){return vg(this,void 0,void 0,function*(){this.cache.set(e,r)})}delete(e){return vg(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return vg(this,void 0,void 0,function*(){this.cache.clear()})}open(){return vg(this,void 0,void 0,function*(){})}close(){return vg(this,void 0,void 0,function*(){})}};g();Pn();Jn();g();var bg=class extends Error{constructor(e,r){super(r??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};g();var Pg;(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"})(Pg||(Pg={}));var xg=(t,e,r)=>({jsonrpc:"2.0",id:t,method:e,params:r}),cS=(t,e,r,n)=>({jsonrpc:"2.0",id:t,method:e,params:r,subscription:{id:n??null}}),KH=(t,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:t}});function Oh(t){try{return JSON.parse(t)}catch{return null}}var W6=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Age=3,_ge=500,Tge=1e4,Ige=3e4,NH=new Set([408,429,500,502,503,504]);function Dge(t,e){return t instanceof TypeError?!0:e?NH.has(e.status):!1}function Rge(t,e,r){let n=Math.min(e*Math.pow(2,t),r),i=.5+Math.random()*.5;return n*i}function Cge(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 dS=class t{constructor(e,r){var n,i,a;this.serverInfoCache=e??new aS,this._retryOptions={maxRetries:(n=r?.maxRetries)!==null&&n!==void 0?n:Age,baseDelayMs:(i=r?.baseDelayMs)!==null&&i!==void 0?i:_ge,maxDelayMs:(a=r?.maxDelayMs)!==null&&a!==void 0?a:Tge}}static isBunRuntime(){return typeof globalThis.Bun<"u"}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return W6(this,void 0,void 0,function*(){var r,n,i;let a=bn.randomUuid(),s=xg(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),o={"dwn-request":JSON.stringify(s)},c={method:"POST",headers:o};if(e.data){o["content-type"]="application/octet-stream";let h=e.data;if(h instanceof ReadableStream)if(t.isBunRuntime()){let p=yield Xt.toBytes(h);h=new Blob([p],{type:"application/octet-stream"})}else c.duplex="half";c.body=h}let l=yield this.fetchWithRetry(e.dwnUrl,c);if(l.status===429){let h=parseInt((r=l.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new bg(h)}let d,u=l.headers.has("dwn-response");if(u){let h=Oh(l.headers.get("dwn-response"));if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);d=h}else{let h=yield l.text(),p=Oh(h);if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${l.status}`);d=p}if(d.error){let{code:h,message:p}=d.error;if(h===Pg.TooManyRequests){let m=(i=(n=d.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new bg(m)}throw new Error(`(${h}) - ${p}`)}let{reply:f}=d.result;if(u){let h=new Uint8Array(yield l.arrayBuffer()),p=Xt.fromBytes(h);f.record?f.record.data=p:f.entry&&(f.entry.data=p)}return f})}getServerInfo(e){return W6(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 bg(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 W6(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,s,o;for(let c=0;c<=n;c++){try{let f=AbortSignal.timeout(Ige),h=Object.assign(Object.assign({},r),{signal:r?.signal?AbortSignal.any([r.signal,f]):f}),p=yield fetch(e,h);if(!NH.has(p.status)||c===n)return p;o=p}catch(f){if(!Dge(f)||c===n)throw f;s=f}let l=o?Cge(o):void 0,d=Rge(c,i,a),u=l!==void 0?Math.max(l,d):d;yield new Promise(f=>{setTimeout(f,u)})}if(o)return o;throw s})}};g();Pn();var _b=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})};function V6(t){return typeof t=="string"?t:t instanceof ArrayBuffer?new TextDecoder().decode(t):t instanceof Uint8Array?new TextDecoder().decode(t):String(t)}var UH=3e3,$ge=3e4,Bge=1e3,Oge=3e4,jge=1/0,lS=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 _b(this,arguments,void 0,function*(r,n={}){var i;let{connectTimeout:a=UH,responseTimeout:s=$ge}=n,o;try{o=yield t.createWebSocket(r,a)}catch(l){throw(i=n.onerror)===null||i===void 0||i.call(n,l),l}let c=new t(o,s,r,n);return c.wireSocket(o),c})}close(){this.closedByUser=!0,this._isConnected=!1,this.socket.close()}request(e){return _b(this,void 0,void 0,function*(){return new Promise((r,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=bn.randomUuid());let a=s=>{let o=Oh(V6(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 _b(this,void 0,void 0,function*(){if(!e.method.startsWith("rpc.subscribe."))throw new Error("subscribe rpc requests must include the `rpc.subscribe` prefix");if(!e.subscription)throw new Error("subscribe rpc requests must include subscribe options");let n=e.subscription.id,i=this.messageHandlers.get(n),a=c=>{let l=Oh(V6(c.data));l.id===n&&(l.error!==void 0&&(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),this.closeSubscription(n).catch(()=>{})),r(l))};this.messageHandlers.set(n,a),this.subscriptionHandlerIds.add(n);let s=yield this.request(e);return s.error?(i?this.messageHandlers.set(n,i):(this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n)),{response:s}):{response:s,close:()=>_b(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let r=bn.randomUuid(),n=cS(r,"rpc.subscribe.close",{},e);return this.request(n)}send(e){this.socket.send(JSON.stringify(e))}static createWebSocket(e,r){return new Promise((n,i)=>{let a=new WebSocket(e),s=()=>{l(),n(a)},o=d=>{l(),i(d)},c=setTimeout(()=>{l(),a.close(),i(new Error("connect timed out"))},r),l=()=>{clearTimeout(c),a.removeEventListener("open",s),a.removeEventListener("error",o)};a.addEventListener("open",s),a.addEventListener("error",o)})}wireSocket(e){e.addEventListener("message",r=>{let n=Oh(V6(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:Pg.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:Bge,s=(r=this.options.maxReconnectDelay)!==null&&r!==void 0?r:Oge,o=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:jge,c=(i=this.options.connectTimeout)!==null&&i!==void 0?i:UH,l=0,d=()=>_b(this,void 0,void 0,function*(){var u,f,h,p;if(this.closedByUser){this.reconnecting=!1;return}if(l++,l>o){this.reconnecting=!1;return}(f=(u=this.options).onreconnecting)===null||f===void 0||f.call(u,l);let y=Math.min(a*Math.pow(2,l-1),s)*(.5+Math.random()*.5);if(yield new Promise(v=>setTimeout(v,y)),this.closedByUser){this.reconnecting=!1;return}try{let v=yield t.createWebSocket(this.url,c);this.socket=v,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(v),(p=(h=this.options).onreconnected)===null||p===void 0||p.call(h)}catch{yield d()}});d()}};g();g();g();Pn();g();Pn();var Eg=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},Tb=class t{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return Eg(this,void 0,void 0,function*(){let r=new URL(e.dwnUrl);if(r.protocol!=="ws:"&&r.protocol!=="wss:")throw new Error(`Invalid websocket protocol ${r.protocol}`);if(!t.connections.has(r.host))try{let c=yield t.createConnection(r);t.connections.set(r.host,c)}catch(c){throw new Error(`Error connecting to ${r.host}: ${c.message}`)}let i=t.connections.get(r.host),{targetDid:a,message:s,subscription:o}=e;return o?t.subscriptionRequest(i,a,s,o.handler,o.resubscribeFactory):t.processMessage(i,a,s)})}static createConnection(e){return Eg(this,void 0,void 0,function*(){let r=e.host,n=new Map,i=yield lS.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 Eg(this,void 0,void 0,function*(){let i=bn.randomUuid(),a=xg(i,"dwn.processMessage",{target:r,message:n}),{socket:s}=e,o=yield s.request(a),{error:c,result:l}=o;if(c!==void 0)throw new Error(`error sending DWN request: ${c.message}`);return l.reply})}static subscriptionRequest(e,r,n,i,a){return Eg(this,void 0,void 0,function*(){let s=bn.randomUuid(),o=bn.randomUuid(),c=cS(s,"rpc.subscribe.dwn.processMessage",{target:r,message:n},o),{socket:l,subscriptions:d}=e,{response:u,close:f}=yield l.subscribe(c,y=>{let{result:v,error:w}=y;if(w){let A=d.get(o);A&&A.subscription.close(),d.delete(o);return}let S=v.subscription;if(i(S),"cursor"in S&&S.cursor){let A=d.get(o);A&&(A.lastCursor=S.cursor),l.send(KH(o,S.cursor))}}),{error:h,result:p}=u;if(h)throw new Error(`could not subscribe via jsonrpc socket: ${h.message}`);let{reply:m}=p;if(m.subscription&&f){let y=()=>Eg(this,void 0,void 0,function*(){d.delete(o),yield f()}),v={subscription:Object.assign(Object.assign({},m.subscription),{close:y}),target:r,message:n,handler:i,resubscribeFactory:a};d.set(o,v),m.subscription.close=y}return m})}static resubscribeAll(e){return Eg(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{}})}};Tb.connections=new Map;var Ib=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(d){try{l(n.next(d))}catch(u){s(u)}}function c(d){try{l(n.throw(d))}catch(u){s(u)}}function l(d){d.done?a(d.value):i(d.value).then(o,c)}l((n=n.apply(t,e||[])).next())})},LH;(function(t){t.Create="did.create",t.Resolve="did.resolve"})(LH||(LH={}));var Sg=class{constructor(e=[]){this.transportClients=new Map,e=[new J6,new Z6,...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 Ib(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 Ib(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)})}},J6=class extends dS{sendDidRequest(e){return Ib(this,void 0,void 0,function*(){let r=bn.randomUuid(),n=xg(r,e.method,{data:e.data}),i=new Request(e.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a;try{let s=yield fetch(i,{signal:AbortSignal.timeout(3e4)});if(s.ok){if(a=yield s.json(),a.error){let{code:o,message:c}=a.error;throw new Error(`JSON RPC (${o}) - ${c}`)}}else throw new Error(`HTTP (${s.status}) - ${s.statusText}`)}catch(s){throw new Error(`Error encountered while processing response from ${e.url}: ${s.message}`)}return a.result})}},Z6=class extends Tb{sendDidRequest(e){return Ib(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return Ib(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};g();var qH=class t{constructor(e){this.agent=e.agent,this.agentStores=e.agentStores,this.didResolverCache=e.didResolverCache,this.dwn=e.dwn,this.dwnDataStore=e.dwnDataStore,this.dwnStateIndex=e.dwnStateIndex,this.dwnMessageStore=e.dwnMessageStore,this.syncStore=e.syncStore,this.vaultStore=e.vaultStore,this.dwnResumableTaskStore=e.dwnResumableTaskStore,this.dwnStores=e.dwnStores}async clearStorage(){if(await this.agent.sync.stopSync(),this.agent.agentDid=void 0,await this.didResolverCache.clear(),await this.dwnDataStore.clear(),await this.dwnStateIndex.clear(),await this.dwnMessageStore.clear(),await this.dwnResumableTaskStore.clear(),await this.syncStore.clear(),await this.vaultStore.clear(),this.agent.vault._cachedInitialized=void 0,await this.agent.permissions.clear(),this.dwnStores.clear(),this.agentStores==="memory"){let{didApi:e,identityApi:r,permissionsApi:n,keyManager:i}=t.useMemoryStores({agent:this.agent});this.agent.did=e,this.agent.identity=r,this.agent.keyManager=i,this.agent.permissions=n}}async clearDwnStores(){await this.syncStore.clear(),await this.dwnDataStore.clear(),await this.dwnStateIndex.clear(),await this.dwnMessageStore.clear(),await this.dwnResumableTaskStore.clear(),await this.agent.permissions.clear(),this.dwnStores.clear()}async closeStorage(){await this.didResolverCache.close(),await this.dwnDataStore.close(),await this.dwnStateIndex.close(),await this.dwnMessageStore.close(),await this.dwnResumableTaskStore.close(),await this.syncStore.close(),await this.vaultStore.close()}async createAgentDid(){this.agent.agentDid=await go.create({options:{publish:!0,gatewayUri:O.DID_DHT_GATEWAY_URI??"http://localhost:7527",verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]}})}async createIdentity({name:e,testDwnUrls:r}){return await this.agent.identity.create({didMethod:"dht",didOptions:{services:[{id:"dwn",type:"DecentralizedWebNode",serviceEndpoint:r}],verificationMethods:[{algorithm:"Ed25519",id:"sig",purposes:["assertionMethod","authentication"]},{algorithm:"X25519",id:"enc",purposes:["keyAgreement"]}]},metadata:{name:e}})}static async setup({agentClass:e,agentStores:r,testDataLocation:n}){r??="memory",n??="__TESTDATA__";let i=F=>`${n}/${F}`,a=new bo,s=new Sg,o={keyStore:new pg,identityStore:new mg,didStore:new ug,clear:()=>{o.keyStore._protocolInitializedCache?.clear(),o.identityStore._protocolInitializedCache?.clear(),o.didStore._protocolInitializedCache?.clear()}},{agentVault:c,didApi:l,identityApi:d,keyManager:u,didResolverCache:f,vaultStore:h,permissionsApi:p}=r==="memory"?t.useMemoryStores():t.useDiskStores({testDataLocation:n,stores:o}),m=new Df({blockstoreLocation:i("DWN_DATASTORE")}),y=new Bf({location:i("DWN_STATEINDEX")}),v=new $f,w=new Cf({location:i("DWN_RESUMABLETASKSTORE")}),S=new Rf({blockstoreLocation:i("DWN_MESSAGESTORE"),indexLocation:i("DWN_MESSAGEINDEX")}),A=await Wl.createDwn({dataPath:n,dataStore:m,didResolver:l,stateIndex:y,eventLog:v,messageStore:S,resumableTaskStore:w}),_=new Wl({dwn:A,localDwnStrategy:"off"}),D=new Mge(i("SYNC_STORE")),N=new wg({db:D}),$=new e({agentVault:c,cryptoApi:a,didApi:l,dwnApi:_,identityApi:d,keyManager:u,permissionsApi:p,rpcClient:s,syncApi:N});return new t({agent:$,agentStores:r,didResolverCache:f,dwn:A,dwnDataStore:m,dwnStateIndex:y,dwnMessageStore:S,dwnResumableTaskStore:w,dwnStores:o,syncStore:D,vaultStore:h})}static useDiskStores({agent:e,testDataLocation:r,stores:n}){let i=m=>`${r}/${m}`,a=new Rm({location:i("VAULT_STORE")}),s=new $h({keyDerivationWorkFactor:1,store:a}),{didStore:o,identityStore:c,keyStore:l}=n,d=new Of({location:i("DID_RESOLVERCACHE")}),u=new Ih({agent:e,didMethods:[go,wo],resolverCache:d,store:o}),f=new Bh({agent:e,store:c}),h=new Po({agent:e,keyStore:l}),p=new La({agent:e});return{agentVault:s,didApi:u,didResolverCache:d,identityApi:f,keyManager:h,permissionsApi:p,vaultStore:a}}static useMemoryStores({agent:e}={}){let r=new Eu,n=new $h({keyDerivationWorkFactor:1,store:r}),i=new hE,a=new Ih({agent:e,didMethods:[go,wo],resolverCache:i,store:new fg}),s=new Po({agent:e,keyStore:new hg}),o=new Bh({agent:e,store:new yg}),c=new La({agent:e});return{agentVault:n,didApi:a,didResolverCache:i,identityApi:o,keyManager:s,permissionsApi:c,vaultStore:r}}};g();Qo();Sr();Pn();Jn();function Kge({baseURL:t,endpoint:e,authParam:r,tokenParam:n}){switch(e){case"pushedAuthorizationRequest":return wb(t,"par");case"authorize":if(!r)throw new Error("authParam must be provided when building an authorize URL");return wb(t,`authorize/${r}.jwt`);case"callback":return wb(t,"callback");case"token":if(!n)throw new Error("tokenParam must be provided when building a token URL");return wb(t,`token/${n}.jwt`);default:throw new Error(`Unknown connect endpoint: ${e}`)}}async function Nge({did:t,data:e}){let r=he.object({alg:"EdDSA",kid:t.document.verificationMethod[0].id,typ:"JWT"}).toBase64Url(),n=he.object(e).toBase64Url(),a=await(await t.getSigner()).sign({data:he.string(`${r}.${n}`).toUint8Array()}),s=he.uint8Array(a).toBase64Url();return`${r}.${n}.${s}`}async function zH({jwt:t}){let[e,r,n]=t.split("."),i=he.base64Url(e).toObject();if(!i.kid)throw new Error('Connect: JWT missing required "kid" header value.');let{didDocument:a}=await wo.resolve(i.kid.split("#")[0]);if(!a)throw new Error("Connect: JWT verification failed \u2014 could not resolve DID.");let{publicKeyJwk:s}=a.verificationMethod?.find(l=>l.id===i.kid)??{};if(!s)throw new Error("Connect: JWT verification failed \u2014 public key not found in DID document.");if(!await new Wc().verify({key:s,signature:he.base64Url(n).toUint8Array(),data:he.string(`${e}.${r}`).toUint8Array()}))throw new Error("Connect: JWT verification failed \u2014 invalid signature.");return he.base64Url(r).toObject()}async function Uge({jwt:t,encryptionKey:e}){let r={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT"},n=bn.randomBytes(24),i=he.object(r).toUint8Array(),a=he.string(t).toUint8Array(),s=await Jc.encryptRaw({data:a,keyBytes:e,nonce:n,additionalData:i}),o=s.subarray(0,-16),c=s.subarray(-16);return[he.object(r).toBase64Url(),"",he.uint8Array(n).toBase64Url(),he.uint8Array(o).toBase64Url(),he.uint8Array(c).toBase64Url()].join(".")}async function FH({jwe:t,encryptionKey:e}){let[r,,n,i,a]=t.split("."),s=he.base64Url(e).toUint8Array(),o=he.base64Url(r).toUint8Array(),c=he.base64Url(n).toUint8Array(),l=he.base64Url(i).toUint8Array(),d=he.base64Url(a).toUint8Array(),u=new Uint8Array([...l,...d]),f=await Jc.decryptRaw({data:u,keyBytes:s,nonce:c,additionalData:o});return he.uint8Array(f).toString()}async function Lge(t,e){let r=await t.export(),n=e.verificationMethod?.[0].publicKeyJwk,i=r.privateKeys?.[0];n.alg="EdDSA";let a=await bi.convertPublicKeyToX25519({publicKey:n}),s=await bi.convertPrivateKeyToX25519({privateKey:i}),o=await Ht.sharedSecret({privateKeyA:s,publicKeyB:a});return Mm.deriveKeyBytes({baseKeyBytes:new Uint8Array(o),hash:"SHA-256",salt:new Uint8Array,info:new Uint8Array,length:256})}async function qge({jwt:t,encryptionKey:e,delegateDidKeyId:r,pin:n}){let i={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT",kid:r},a=bn.randomBytes(24),s=n?{...i,pin:n}:{...i},o=he.object(s).toUint8Array(),c=he.string(t).toUint8Array(),l=await Jc.encryptRaw({data:c,keyBytes:e,nonce:a,additionalData:o}),d=l.subarray(0,-16),u=l.subarray(-16);return[he.object(i).toBase64Url(),"",he.uint8Array(a).toBase64Url(),he.uint8Array(d).toBase64Url(),he.uint8Array(u).toBase64Url()].join(".")}async function zge(t,e,r){let[n,,i,a,s]=e.split("."),o=he.base64Url(n).toObject();if(!o.kid)throw new Error('Connect: JWE protected header is missing required "kid" property.');let c=await wo.resolve(o.kid.split("#")[0]),l=await kg.deriveSharedKey(t,c.didDocument),d=r?{...o,pin:r}:{...o},u=he.object(d).toUint8Array(),f=he.base64Url(i).toUint8Array(),h=he.base64Url(a).toUint8Array(),p=he.base64Url(s).toUint8Array(),m=new Uint8Array([...h,...p]),y=await Jc.decryptRaw({data:m,keyBytes:l,nonce:f,additionalData:u});return he.uint8Array(y).toString()}async function Fge(t){let e=bn.randomBytes(16),r=bn.randomBytes(16);return{...t,nonce:he.uint8Array(r).toBase64Url(),responseMode:"direct_post",state:he.uint8Array(e).toBase64Url(),supportedDidMethods:t.supportedDidMethods??["did:dht","did:jwk"]}}async function Gge(t,e){let n=await(await fetch(t,{signal:AbortSignal.timeout(3e4)})).text(),i=await FH({jwe:n,encryptionKey:e});return await zH({jwt:i})}async function Hge(t){let e=Math.floor(Date.now()/1e3);return{...t,iat:e,exp:e+600}}function Wge(t){return O6(t)?!0:t.interface===be.Protocols&&t.method===we.Configure}async function Vge(t,e,r,n){let i=new La({agent:r});Bs.log(`Creating permission grants for ${n.length} scopes...`);let a=await Promise.all(n.map(c=>{let l=Wge(c);return i.createGrant({delegated:l,store:!0,grantedTo:e.uri,scope:c,dateExpires:"2040-06-25T16:09:16.693356Z",author:t})})),s=await r.dwn.getDwnEndpointUrlsForTarget(t);Bs.log(`Sending ${a.length} permission grants to ${s.length} DWN endpoint(s)...`);let o=a.map(async c=>{let{encodedData:l,...d}=c.message,u=he.base64Url(l).toUint8Array(),f=!1;for(let h of s)try{let p=await r.rpc.sendDwnRequest({dwnUrl:h,targetDid:t,message:d,data:new Blob([u])});p.status.code===202||p.status.code===409?f=!0:Bs.error(`Grant send to ${h} returned ${p.status.code}: ${p.status.detail}`)}catch(p){Bs.error(`Grant send to ${h} failed: ${p.message}`)}if(!f)throw new Error("Could not send permission grant to any DWN endpoint.");return c.message});try{return await Promise.all(o)}catch(c){throw Bs.error(`Error during batch-send of permission grants: ${c}`),c}}async function Jge(t,e,r){let n=await e.processDwnRequest({author:t,messageType:Re.ProtocolsQuery,target:t,messageParams:{filter:{protocol:r.protocol}}});if(n.reply.status.code!==200)throw new Error(`Could not fetch protocol: ${n.reply.status.detail}`);if(n.reply.entries===void 0||n.reply.entries.length===0){Bs.log(`Protocol does not exist, creating: ${r.protocol}`);let{reply:i,message:a}=await e.sendDwnRequest({author:t,target:t,messageType:Re.ProtocolsConfigure,messageParams:{definition:r}});if(i.status.code!==202&&i.status.code!==409)throw new Error(`Could not send protocol: ${i.status.detail}`);await e.processDwnRequest({author:t,target:t,messageType:Re.ProtocolsConfigure,rawMessage:a})}else{Bs.log(`Protocol already exists: ${r.protocol}`);let i=n.reply.entries[0],{reply:a}=await e.sendDwnRequest({author:t,target:t,messageType:Re.ProtocolsConfigure,rawMessage:i});if(a.status.code!==202&&a.status.code!==409)throw new Error(`Could not send protocol: ${a.status.detail}`)}}async function Zge(t,e,r,n){let i=await wo.create(),a=await i.export(),s=e.permissionRequests.map(async p=>{let{protocolDefinition:m,permissionScopes:y}=p;if(!y.every(w=>"protocol"in w&&w.protocol===m.protocol))throw new Error("All permission scopes must match the protocol URI they are provided with.");return await Jge(t,n,m),kg.createPermissionGrants(t,i,n,y)}),o=(await Promise.all(s)).flat();Bs.log("Building connect response...");let c=await kg.createConnectResponse({providerDid:t,delegateDid:i.uri,aud:e.clientDid,nonce:e.nonce,delegateGrants:o,delegatePortableDid:a});Bs.log("Signing connect response...");let l=await kg.signJwt({did:i,data:c}),d=await wo.resolve(e.clientDid),u=await kg.deriveSharedKey(i,d?.didDocument);Bs.log("Encrypting connect response...");let f=await kg.encryptResponse({jwt:l,encryptionKey:u,delegateDidKeyId:i.document.verificationMethod[0].id,pin:r}),h=new URLSearchParams({id_token:f,state:e.state}).toString();Bs.log(`Sending connect response to: ${e.callbackUrl}`),await fetch(e.callbackUrl,{body:h,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:AbortSignal.timeout(3e4)})}var kg={buildConnectUrl:Kge,signJwt:Nge,verifyJwt:zH,encryptRequest:Uge,decryptRequest:FH,encryptResponse:qge,decryptResponse:zge,deriveSharedKey:Lge,createConnectRequest:Fge,getConnectRequest:Gge,createConnectResponse:Hge,createPermissionGrants:Vge,submitConnectResponse:Zge};g();Sr();Qo();var GH=class t{constructor(e){this._agentDid=e.agentDid,this.crypto=e.cryptoApi,this.did=e.didApi,this.dwn=e.dwnApi,this.identity=e.identityApi,this.keyManager=e.keyManager,this.permissions=e.permissionsApi,this.rpc=e.rpcClient,this.sync=e.syncApi,this.vault=e.agentVault,this.did.agent=this,this.dwn.agent=this,this.identity.agent=this,this.keyManager.agent=this,this.permissions.agent=this,this.sync.agent=this}get agentDid(){if(this._agentDid===void 0)throw new Error('EnboxUserAgent: The "agentDid" property is not set. Ensure the agent is properly initialized and a DID is assigned.');return this._agentDid}set agentDid(e){this._agentDid=e}static async create({dataPath:e="DATA/AGENT",localDwnStrategy:r,localDwnEndpoint:n,agentDid:i,agentVault:a,cryptoApi:s,didApi:o,dwnApi:c,identityApi:l,keyManager:d,permissionsApi:u,rpcClient:f,syncApi:h}={}){return a??=new $h({keyDerivationWorkFactor:21e4,store:new Rm({location:`${e}/VAULT_STORE`})}),s??=new bo,o??=new Ih({didMethods:[go,wo],resolverCache:new Of({location:`${e}/DID_RESOLVERCACHE`}),store:new ug}),c||(n?c=new Wl({localDwnEndpoint:n,localDwnStrategy:r??"prefer"}):c=new Wl({dwn:await Wl.createDwn({dataPath:e,didResolver:o}),localDwnStrategy:r??"prefer"})),r&&c.setLocalDwnStrategy(r),l??=new Bh({store:new mg}),d??=new Po({keyStore:new pg}),u??=new La,f??=new Sg,h??=new wg({dataPath:e}),new t({agentDid:i,agentVault:a,cryptoApi:s,didApi:o,dwnApi:c,keyManager:d,permissionsApi:u,identityApi:l,rpcClient:f,syncApi:h})}async firstLaunch(){return await this.vault.isInitialized()===!1}async initialize({password:e,recoveryPhrase:r,dwnEndpoints:n}){return r=await this.vault.initialize({password:e,recoveryPhrase:r,dwnEndpoints:n}),r}async processDidRequest(e){return this.did.processRequest(e)}async processDwnRequest(e){return this.dwn.processRequest(e)}async processVcRequest(e){throw new Error("Not implemented")}async sendDidRequest(e){throw new Error("Not implemented")}async sendDwnRequest(e){return this.dwn.sendRequest(e)}async sendVcRequest(e){throw new Error("Not implemented")}async start({password:e}){this.vault.isLocked()&&await this.vault.unlock({password:e}),this.agentDid=await this.vault.getDid()}};export{bo as AgentCryptoApi,Ih as AgentDidApi,Of as AgentDidResolverCache,Wl as AgentDwnApi,Bh as AgentIdentityApi,La as AgentPermissionsApi,WG as AnonymousDwnApi,ag as BearerIdentity,D6 as ClosureFailureCode,jye as DISCOVERY_DIR,Mye as DISCOVERY_FILENAME,uH as DWN_CONNECT_PATH,lH as DWN_PROTOCOL_SCHEME,$ye as DidInterface,ao as DwnConstant,ai as DwnContentEncryptionAlgorithm,jf as DwnDataStore,Kt as DwnDateSort,ug as DwnDidStore,ZE as DwnDiscoveryFile,mg as DwnIdentityStore,Re as DwnInterface,Wt as DwnKeyDerivationScheme,pg as DwnKeyStore,Ir as DwnPermissionGrant,ud as DwnPermissionRequest,dt as DwnPermissionsProtocol,kg as EnboxConnectProtocol,GH as EnboxUserAgent,$h as HdIdentityVault,Mf as InMemoryDataStore,fg as InMemoryDidStore,yg as InMemoryIdentityStore,hg as InMemoryKeyStore,Dh as LocalDwnDiscovery,Po as LocalKeyManager,T6 as MAX_PENDING_TOKENS,qH as PlatformAgentTestHarness,is as ReplicationLedger,wg as SyncEngineLevel,YG as buildContextKeyDecrypter,_We as buildDwnConnectUrl,IWe as buildDwnDiscoveryRedirectUrl,Rh as buildEncryptionInput,eH as buildKmsDecryptCallback,_6 as computeScopeId,wb as concatenateUrl,mb as createClosureContext,Oye as createNodeDiscoveryFileFs,dH as decodeDwnDiscoveryPayload,QG as deriveContextEncryptionInput,C6 as detectNewParticipants,Cd as dwnMessageConstructors,iH as eagerSendContextKeyRecord,Lye as encodeDwnDiscoveryPayload,XE as encryptAndComputeCid,rH as ensureKeyDeliveryProtocol,FE as evaluateClosure,Sye as evaluateClosureBatch,sH as fetchContextKeyRecord,gb as getDwnServiceEndpointUrls,bb as getEncryptionKeyDeriver,Hl as getEncryptionKeyInfo,Pb as getKeyDecrypter,XGe as getPaginationCursor,ZGe as getRecordAuthor,_ye as getRecordMessageCid,YGe as getRecordProtocolRole,jGe as getRootContextId,FG as getRuleSetAtPath,R6 as hasRelationalReadAccess,ZG as isDidRequest,Nye as isDwnMessage,Od as isDwnRequest,gge as isIdentityMetadata,Uye as isMessagesPermissionScope,yb as isMultiPartyContext,aJe as isPortableIdentity,O6 as isRecordPermissionScope,B6 as isRecordsType,$d as isRecordsWrite,YE as ivLength,Bye as localDwnServerName,tH as maybeDecryptReply,JE as normalizeBaseUrl,TWe as parseDwnConnectUrl,QGe as pollWithTtl,DWe as readDwnDiscoveryPayloadFromUrl,XG as resolveKeyDecrypter,nH as writeContextKeyRecord};
|
|
2061
2061
|
/*! Bundled license information:
|
|
2062
2062
|
|
|
2063
2063
|
ieee754/index.js:
|