@enbox/agent 0.5.4 → 0.5.5

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
  `);Jo();Er();g();Zh();g();Zh();Gb();za();function $ye(t,e,r,n){qb(t);let i=g8({dkLen:32,asyncTick:10},n),{c:a,dkLen:s,asyncTick:o}=i;if(Zl(a),Zl(s),Zl(o),a<1)throw new Error("PBKDF2: iterations (c) should be >= 1");let d=Yl(e),l=Yl(r),c=new Uint8Array(s),u=Xl.create(t,d),f=u._cloneInto().update(l);return{c:a,dkLen:s,asyncTick:o,DK:c,PRF:u,PRFSalt:f}}function Bye(t,e,r,n,i){return t.destroy(),e.destroy(),n&&n.destroy(),i.fill(0),r}async function iH(t,e,r,n){let{c:i,dkLen:a,asyncTick:s,DK:o,PRF:d,PRFSalt:l}=$ye(t,e,r,n),c,u=new Uint8Array(4),f=Nd(u),h=new Uint8Array(d.outputLen);for(let p=1,m=0;m<a;p++,m+=d.outputLen){let y=o.subarray(m,m+d.outputLen);f.setInt32(0,p,!1),(c=l._cloneInto(c)).update(u).digestInto(h),y.set(h.subarray(0,y.length)),await y8(i-1,s,()=>{d._cloneInto(c).update(h).digestInto(h);for(let b=0;b<y.length;b++)y[b]^=h[b]})}return Bye(d,l,o,c,h)}Gg();iP();za();g();function Dh(t){if(!Number.isSafeInteger(t))throw new Error(`Wrong integer: ${t}`)}function ZE(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Oye(...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 jye(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 Mye(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 Kye(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 D5(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 d=n;d<a.length;d++){let l=a[d],c=e*s+l;if(!Number.isSafeInteger(c)||e*s/e!==s||c-l!==e*s)throw new Error("convertRadix: carry overflow");s=c%r;let u=Math.floor(c/r);if(a[d]=u,!Number.isSafeInteger(u)||u*r+s!==c)throw new Error("convertRadix: carry overflow");if(o)u?o=!1:n=d;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 sH=(t,e)=>e?sH(e,t%e):t,YE=(t,e)=>t+(e-sH(t,e));function R5(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(YE(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${YE(e,r)}`);let i=0,a=0,s=2**r-1,o=[];for(let d of t){if(d>=2**e)throw new Error(`convertRadix2: invalid data word=${d} from=${e}`);if(i=i<<e|d,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 Nye(t){return{encode:e=>{if(!ZE(e))throw new Error("radix.encode input should be Uint8Array");return D5(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(D5(e,t,2**8))}}}function Uye(t,e=!1){if(t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(YE(8,t)>32||YE(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!ZE(r))throw new Error("radix2.encode input should be Uint8Array");return R5(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(R5(r,t,8,e))}}}function Lye(t,e){if(typeof e!="function")throw new Error("checksum fn should be function");return{encode(r){if(!ZE(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(!ZE(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 wb={alphabet:jye,chain:Oye,checksum:Lye,convertRadix:D5,convertRadix2:R5,radix:Nye,radix2:Uye,join:Mye,padding:Kye};var qye=t=>t[0]==="\u3042\u3044\u3053\u304F\u3057\u3093";function oH(t){if(typeof t!="string")throw new TypeError(`Invalid mnemonic type: ${typeof t}`);return t.normalize("NFKD")}function aH(t){let e=oH(t),r=e.split(" ");if(![12,15,18,21,24].includes(r.length))throw new Error("Invalid mnemonic");return{nfkd:e,words:r}}function cH(t){Md(t,16,20,24,28,32)}function dH(t,e=128){if(Zl(e),e%32!==0||e>256)throw new TypeError("Invalid entropy");return Gye(Hf(e/8),t)}var zye=t=>{let e=8-t.length/4;return new Uint8Array([nu(t)[0]>>e<<e])};function lH(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}`)}),wb.chain(wb.checksum(1,zye),wb.radix2(11,!0),wb.alphabet(t))}function Fye(t,e){let{words:r}=aH(t),n=lH(e).decode(r);return cH(n),n}function Gye(t,e){return cH(t),lH(e).encode(t).join(qye(e)?"\u3000":" ")}function uH(t,e){try{Fye(t,e)}catch{return!1}return!0}var Hye=t=>oH(`mnemonic${t}`);function fH(t,e=""){return iH(ku,aH(t).nfkd,Hye(e),{c:2048,dkLen:64})}g();wn();g();Er();wn();g();Er();wn();function bb(t){return typeof t=="object"&&t!==null&&"alg"in t&&t.alg!==void 0&&"enc"in t&&t.enc!==void 0}var vb=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 d=await i.deriveKey({algorithm:n.alg,baseKeyBytes:e,iterations:n.p2c,salt:o});if(!(d.alg&&["A128KW","A192KW","A256KW"].includes(d.alg)))throw new Fe(Le.AlgorithmNotSupported,`Unsupported Key Encryption Algorithm (alg) value: ${d.alg}`);return await i.unwrapKey({decryptionKey:d,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 C5(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 Pb=class t{constructor(e){this.ciphertext="";Object.assign(this,e)}static async decrypt({jwe:e,key:r,keyManager:n=new Gc,crypto:i=new yo,options:a={}}){if(!Yw(i))throw new Fe(Le.OperationNotSupported,'Crypto API does not support the "encrypt" operation.');if(!Yw(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(pH(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(!bb(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 d;try{let p=e.encrypted_key?he.base64Url(e.encrypted_key).toUint8Array():void 0;d=await vb.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;d=typeof r=="string"?await n.generateKey({algorithm:o.enc}):await i.generateKey({algorithm:o.enc})}let l=C5("iv",e.iv),c=C5("tag",e.tag),u=c!==void 0?new Uint8Array([...he.base64Url(e.ciphertext).toUint8Array(),...c??[]]):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 d=="string"?await n.decrypt({keyUri:d,data:u,iv:l,additionalData:f}):await i.decrypt({key:d,data:u,iv:l,additionalData:f}),protectedHeader:s,additionalAuthenticatedData:C5("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 Gc,crypto:d=new yo}){if(!Yw(d))throw new Fe(Le.OperationNotSupported,'Crypto API does not support the "encrypt" operation.');if(!Yw(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(pH(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(!bb(l))throw new Error('JWE Header is missing required "alg" (Algorithm) and/or "enc" (Encryption) Header Parameters');let{cek:c,encryptedKey:u}=await vb.encrypt({key:e,joseHeader:l,keyManager:o,crypto:d}),f;switch(l.enc){case"A128GCM":case"A192GCM":case"A256GCM":f=gn.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 c=="string"?await o.encrypt({keyUri:c,data:r,iv:f,additionalData:p}):await d.encrypt({key:c,data:r,iv:f,additionalData:p}),b=y.slice(0,-16),w=y.slice(-16),S=new t({ciphertext:he.uint8Array(b).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 pH(...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 Gl=class{static async decrypt({jwe:e,key:r,keyManager:n=new Gc,crypto:i=new yo,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:d,3:l,4:c,length:u}=e.split(".");if(u!==5)throw new Fe(Le.InvalidJwe,"Invalid JWE format. JWE must have 5 parts.");let f=await Pb.decrypt({jwe:{ciphertext:l,encrypted_key:o||void 0,iv:d||void 0,protected:s,tag:c||void 0},key:r,keyManager:n,crypto:i,options:a});if(!bb(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 Gc,crypto:a=new yo,options:s={}}){let o=await Pb.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();wn();wn();Yn();g();Er();wn();var lg=class extends $f{constructor(){super(...arguments);this.name="DwnKeyStore";this._recordProtocolDefinition=$G;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:d}=await r.dwn.processRequest({author:n,target:n,messageType:Re.RecordsRead,messageParams:{filter:{recordId:s.recordId}},encryption:!0}),l=d;if(!l.entry?.data)throw new Error(`${this.name}: Failed to read encrypted key record: ${s.recordId}`);o=await Dm.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(vp(o)){let d=`${n}${ki}${wp}${o.kid}`;this._index.set(d,s.recordId),this._cache.set(s.recordId,o),a.push(o)}}return a}},ug=class extends Bf{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 $5={"AES-GCM":{implementation:$m,names:["A128GCM","A192GCM","A256GCM"]},"AES-KW":{implementation:Bm,names:["A128KW","A192KW","A256KW"]},Ed25519:{implementation:Fc,names:["Ed25519"]},secp256k1:{implementation:oc,names:["ES256K","secp256k1"]},secp256r1:{implementation:oc,names:["ES256","secp256r1"]},"SHA-256":{implementation:_u,names:["SHA-256"]},X25519:{implementation:Iu,names:["X25519"]}},go=class{constructor({agent:e,keyStore:r}={}){this._algorithmInstances=new Map;this._agent=e,this._keyStore=r??new ug}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`${wp}${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 $s.derivePrivateKeyBytes(n,r),a=await Gt.bytesToPrivateKey({privateKeyBytes:i});return await Gt.getPublicKey({key:a})}async jweKeyUnwrap({keyUri:e,derivationPath:r,encryptedKey:n,ephemeralPublicKey:i}){let a=await this.getX25519PrivateKeyBytes({keyUri:e}),s=await $s.derivePrivateKeyBytes(a,r),o=await Gt.bytesToPrivateKey({privateKeyBytes:s});return Bi.ecdhEsUnwrapKey(o,i,n)}async derivePrivateKeyBytes({keyUri:e,derivationPath:r}){let n=await this.getX25519PrivateKeyBytes({keyUri:e});return $s.derivePrivateKeyBytes(n,r)}async importKey({key:e}){if(!vp(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=$5[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($5)){let a=$5[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 Gt.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&&vp(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 hH(t){return typeof t!="string"||t.trim().length===0}function Vye(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 Wye(t){return typeof t=="object"&&t!==null&&"initialized"in t&&typeof t.initialized=="boolean"&&"lastBackup"in t&&"lastRestore"in t}var Rh=class{constructor({keyDerivationWorkFactor:e,store:r}={}){this.crypto=new yo;this._keyDerivationWorkFactor=e??21e4,this._store=r??new bu}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 Gl.decrypt({jwe:n,key:he.string(e).toUint8Array(),crypto:this.crypto,keyManager:new go,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 Gl.encrypt({key:he.string(r).toUint8Array(),protectedHeader:i,plaintext:he.object(a).toUint8Array(),crypto:this.crypto,keyManager:new go});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 Gl.decrypt({jwe:e,key:this._contentEncryptionKey,crypto:this.crypto,keyManager:new go,options:{minP2cCount:1}}),n=he.uint8Array(r).toObject();if(!bh(n))throw new Error("HdIdentityVault: Unable to decode malformed DID in identity vault");return await bs.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(!Wye(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(hH(e))throw new Error(`HdIdentityVault: The password is required and cannot be blank. Please provide a ' +
2059
2059
  'valid, non-empty password.`);if(r&&hH(r))throw new Error(`HdIdentityVault: The password is required and cannot be blank. Please provide a ' +
2060
- 'valid, non-empty password.`);if(r??=dH(I5,128),!uH(r,I5))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 fH(r),a=JE.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"}),d=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(d).toBase64Url()},c=await Gl.encrypt({key:he.string(e).toUint8Array(),protectedHeader:l,plaintext:he.object(o).toUint8Array(),crypto:this.crypto,keyManager:new go});await this._store.set("contentEncryptionKey",c);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}),b=new UE;await b.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 k=await(await po.create({keyManager:b,options:w})).export(),T={alg:"dir",enc:"A256GCM",cty:"json"},D=await Gl.encrypt({key:o,plaintext:he.object(k).toUint8Array(),protectedHeader:T,crypto:this.crypto,keyManager:new go});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(!Vye(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 Gl.decrypt({jwe:r,key:he.string(e).toUint8Array(),crypto:this.crypto,keyManager:new go,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();Jo();g();Er();function Jye(t){return!(!t||typeof t!="object"||t===null)&&"name"in t}var fg=class extends $f{constructor(){super(...arguments);this.name="DwnIdentityStore";this._recordProtocolDefinition=NE;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(Jye(o)){let d=`${n}${ki}${o.uri}`;this._index.set(d,s.recordId),this._cache.set(s.recordId,o),a.push(o)}}return a}},pg=class extends Bf{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 SWe(t){return!(!t||typeof t!="object"||t===null)&&"did"in t&&"metadata"in t&&bh(t.did)}var Ch=class{constructor({agent:e,store:r}={}){this._agent=e,this._store=r??new pg}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 ig({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 ig({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 ig({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();Yn();Er();var Ka=class t{constructor({agent:e}={}){this._cachedPermissions=new cs.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("~"),d=s?this._cachedPermissions.get(o):void 0;if(d)return d;let l=await this.fetchGrants({author:r,target:r,grantor:e,grantee:r}),c=await t.matchGrantFromArray(e,r,{messageType:i,protocol:a},l,n);if(!c)throw new Error(`CachedPermissions: No permissions found for ${i}: ${a}`);return this._cachedPermissions.set(o,c),c}async fetchGrants({author:e,target:r,grantee:n,grantor:i,protocol:a,remote:s=!1,checkRevoked:o=!0}){let d=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:d}}},{reply:c}=s?await this.agent.sendDwnRequest(l):await this.agent.processDwnRequest(l);if(c.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${c.status.detail}`);let u=o?await this.fetchRevokedGrantIds({author:e,target:r,grantor:i,remote:s,tags:d}):new Set,f=[];for(let h of c.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 d=new Set;for(let l of o.entries)l.descriptor.parentId!==void 0&&d.add(l.descriptor.parentId);return d}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 d=[];for(let l of o.entries){let c=cd.parse(l);d.push({request:c,message:l})}return d}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},d=he.object(o).toUint8Array(),l={recipient:a.grantedTo,protocol:dt.uri,protocolPath:dt.grantPath,dataFormat:"application/json",tags:s},{reply:c,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${c.status.detail}`);let f={...u,encodedData:he.uint8Array(d).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},d=he.object(o).toUint8Array(),l={protocol:dt.uri,protocolPath:dt.requestPath,dataFormat:"application/json",tags:s},{reply:c,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${c.status.detail}`);let f={...u,encodedData:he.uint8Array(d).toBase64Url()};return{request:cd.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(),d;dt.hasProtocolScope(i.scope)&&(d={protocol:i.scope.protocol});let l={parentContextId:i.id,protocol:dt.uri,protocolPath:dt.revocationPath,dataFormat:"application/json",tags:d},{reply:c,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([o])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${c.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:d,message:l}=o;if(a===!0&&d.delegated!==!0)continue;let{messageType:c,protocol:u,protocolPath:f,contextId:h}=n;if(this.matchScopeFromGrant(e,r,c,d,u,f,h)){if(d.scope.interface+d.scope.method===c)return{grant:d,message:l};s||(s={grant:d,message:l})}}return s}static matchScopeFromGrant(e,r,n,i,a,s,o){if(i.grantee!==r||i.grantor!==e)return!1;let d=i.scope,l=d.interface+d.method;if(l===n||l===Re.MessagesRead&&(n===Re.MessagesSync||n===Re.MessagesSubscribe))if(v5(n)){let u=d;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=d;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 EH=An(qE(),1);Yn();import{Level as Qye}from"level";g();Yn();function mH(t){let e=t.descriptor;return e.interface!==be.Records||e.method!==ge.Write?!1:e.dateCreated===e.messageTimestamp}function hg(t){if(t.length<=1)return t;let e=new Map,r=new Map,n=new Map,i=new Map;for(let c=0;c<t.length;c++){let u=t[c];e.set(c,u);let f=u.message.descriptor;if(f.interface===be.Protocols&&f.method===ge.Configure){let h=f.definition?.protocol;h&&r.set(h,c)}if(f.interface===be.Records&&f.method===ge.Write){let h=u.message.recordId;mH(u.message)&&h&&n.set(h,c),f.protocol===dt.uri&&f.protocolPath===dt.grantPath&&h&&i.set(h,c)}}let a=new Map,s=new Array(t.length).fill(0),o=(c,u)=>{if(c===u)return;a.has(c)||a.set(c,new Set);let f=a.get(c);f.has(u)||(f.add(u),s[u]++)};for(let c=0;c<t.length;c++){let u=t[c].message.descriptor;if(u.interface===be.Records){let h=u.protocol;h&&r.has(h)&&o(r.get(h),c)}if(u.interface===be.Records&&u.parentId){let h=u.parentId;n.has(h)&&o(n.get(h),c)}if(u.interface===be.Records&&u.method===ge.Write){let h=t[c].message.recordId;h&&!mH(t[c].message)&&n.has(h)&&o(n.get(h),c)}if(u.interface===be.Records&&u.method===ge.Delete){let h=u.recordId;h&&n.has(h)&&o(n.get(h),c)}let f=u.permissionGrantId;f&&i.has(f)&&o(i.get(f),c)}let d=[];for(let c=0;c<t.length;c++)s[c]===0&&d.push(c);let l=[];for(;d.length>0;){let c=d.shift();l.push(e.get(c));let u=a.get(c);if(u)for(let f of u)s[f]--,s[f]===0&&d.push(f)}if(l.length<t.length){let c=new Set(l);for(let u=0;u<t.length;u++){let f=e.get(u);c.has(f)||l.push(f)}}return l}g();Yn();var Zye=1048576;function gH(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===ge.Delete&&t.status.code===404}async function wH(t){try{return await we.getCid(t)}catch{return"unknown"}}async function vH({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,prefetched:a,agent:s,permissionsApi:o}){let d=[];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(b){b.enqueue(y),b.close()}})}d.push(m)}let l=i.length>0?await yH({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:s,permissionsApi:o}):[],c=[...d,...l],u=hg(c);await Yye(u);let f=3,h=u;for(let p=0;p<=f&&h.length>0;p++){let m=[];for(let y of h){let b=y.bufferedData?new ReadableStream({start(S){S.enqueue(y.bufferedData),S.close()}}):y.dataStream,w=await s.dwn.processRawMessage(t,y.message,{dataStream:b});gH(w)||m.push(y)}if(m.length>0){let y=[],b=[];for(let w of m)if(w.bufferedData||!w.dataStream)b.push(w);else{let S=await wH(w.message);y.push(S)}if(y.length>0){let w=await yH({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:y,agent:s,permissionsApi:o});b.push(...w)}h=hg(b)}else h=[]}}async function Yye(t){for(let e of t){if(!e.dataStream)continue;let r=[],n=0,i=!1,a=e.dataStream.getReader();try{for(;;){let{done:d,value:l}=await a.read();if(d)break;if(n+=l.byteLength,n>Zye){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 d of r)s.set(d,o),o+=d.byteLength;e.bufferedData=s,e.dataStream=new ReadableStream({start(d){d.enqueue(s),d.close()}})}}async function yH({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:s}){let o=[],d;if(r)try{d=(await s.getPermissionForRequest({connectedDid:t,messageType:Re.MessagesRead,delegateDid:r,protocol:n,cached:!0})).grant.id}catch(u){return console.error("SyncEngineLevel: pull - Error fetching MessagesRead permission grant for delegate DID",u),o}let l=4,c=0;for(;c<i.length;){let u=i.slice(c,c+l);c+=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:d}}),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,b;return Ll(y)&&y.data&&(b=y.data),{message:y.message,dataStream:b}}));for(let h of f)h&&o.push(h)}return o}async function B5({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:s}){let o=[];for(let l of i){let c=await Xye({author:t,messageCid:l,delegateDid:r,protocol:n,agent:a,permissionsApi:s});c&&o.push(c)}let d=hg(o);for(let l of d)try{let c=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:t,data:l.dataStream,message:l.message});if(!gH(c)){let u=await wH(l.message);console.error(`SyncEngineLevel: push failed for ${u}: ${c.status.code} ${c.status.detail}`)}}catch(c){let u=c.message??c;throw new Error(`SyncEngineLevel: push to ${e} failed: ${u}`)}}async function Xye({author:t,delegateDid:e,protocol:r,messageCid:n,agent:i,permissionsApi:a}){let s;if(e)try{s=(await a.getPermissionForRequest({connectedDid:t,messageType:Re.MessagesRead,delegateDid:e,protocol:r,cached:!0})).grant.id}catch(c){console.error("SyncEngineLevel: push - Error fetching MessagesRead permission grant for delegate DID",c);return}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 d=o.entry,l={message:d.message};return Ll(d)&&d.data&&(l.dataStream=d.data),l}var bH=16,PH=8,ege=4,O5=class{constructor(e){this._waiting=[];this._permits=e}async acquire(){if(this._permits>0){this._permits--;return}return new Promise(e=>{this._waiting.push(e)})}release(){let e=this._waiting.shift();e?e():this._permits++}async run(e){await this.acquire();try{return await e()}finally{this.release()}}},xH="^",tge=250,Of=class Of{constructor({agent:e,dataPath:r,db:n}){this._syncLock=!1;this._syncMode="poll";this._liveSubscriptions=[];this._localSubscriptions=[];this._connectivityState="unknown";this._pendingPushCids=new Map;this._consecutiveFailures=0;this._agent=e,this._permissionsApi=new Ka({agent:e}),this._db=n||new Qye(r??"DATA/AGENT/SYNC_STORE")}get agent(){if(this._agent===void 0)throw new Error("SyncEngineLevel: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,this._permissionsApi=new Ka({agent:e})}get connectivityState(){return this._connectivityState}async clear(){await this._permissionsApi.clear(),await this._db.clear()}async close(){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 Set,i=!1;for(let a of r){let{did:s,delegateDid:o,dwnUrl:d,protocol:l}=a;if(!n.has(d))try{let c=await this.getLocalRoot(s,o,l),u=await this.getRemoteRoot(s,d,o,l);if(c===u)continue;let f=await this.diffWithRemote({did:s,dwnUrl:d,delegateDid:o,protocol:l});if((!e||e==="pull")&&f.onlyRemote.length>0){let h=[],p=[];for(let m of f.onlyRemote)m.message?m.message.descriptor.interface==="Records"&&m.message.descriptor.method==="Write"&&m.message.descriptor.dataCid&&!m.encodedData?p.push(m.messageCid):h.push(m):p.push(m.messageCid);await this.pullMessages({did:s,dwnUrl:d,delegateDid:o,protocol:l,messageCids:p,prefetched:h})}(!e||e==="push")&&f.onlyLocal.length>0&&await this.pushMessages({did:s,dwnUrl:d,delegateDid:o,protocol:l,messageCids:f.onlyLocal})}catch(c){n.add(d),i=!0,console.error(`SyncEngineLevel: Error syncing ${s} with ${d}`,c)}}i?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):(this._consecutiveFailures=0,r.length>0&&(this._connectivityState="online"))}finally{this._syncLock=!1}}async startSync(e){let r=e.mode??"poll",n=e.interval??(r==="live"?"5m":"2m"),i=(0,EH.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){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=async()=>{if(this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{await this.sync()}catch(a){console.error("SyncEngineLevel: Error during sync operation",a)}let n=Math.min(Math.pow(2,this._consecutiveFailures),Of.MAX_BACKOFF_MULTIPLIER),i=this._consecutiveFailures>0?e*n:e;this._syncIntervalId||(this._syncIntervalId=setInterval(r,i))};this._syncIntervalId&&clearInterval(this._syncIntervalId),this._syncIntervalId=setInterval(r,e),this._syncLock||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();for(let i of r)try{await this.openLivePullSubscription(i),await this.openLocalPushSubscription(i)}catch(a){console.error(`SyncEngineLevel: Failed to open live subscription for ${i.did} -> ${i.dwnUrl}`,a)}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)}async teardownLiveSync(){this._pushDebounceTimer&&(clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=void 0),this._pendingPushCids.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=[]}async openLivePullSubscription(e){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=this.buildCursorKey(r,i,a),o=await this.getCursor(s),d=a?[{protocol:a}]:[],l;if(n)try{l=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{try{l=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}catch(h){console.error("SyncEngineLevel: Could not find permission grant for live pull subscription",h);return}}let c=async h=>{if(h.type==="eose"){await this.setCursor(s,h.cursor),this._connectivityState="online";return}if(h.type==="event"){let p=h.event;try{let m=this.extractDataStream(p);await this.agent.dwn.processRawMessage(r,p.message,{dataStream:m})}catch(m){console.error(`SyncEngineLevel: Error processing live-pull event for ${r}`,m)}await this.setCursor(s,h.cursor)}},f=(await this.agent.dwn.sendRequest({author:r,target:r,messageType:Re.MessagesSubscribe,granteeDid:n,messageParams:{filters:d,cursor:o,permissionGrantId:l},subscriptionHandler:c})).reply;if(f.status.code!==200||!f.subscription){console.error(`SyncEngineLevel: MessagesSubscribe failed for ${r} -> ${i}: ${f.status.code} ${f.status.detail}`);return}this._liveSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await f.subscription.close()}}),this._connectivityState="online"}async openLocalPushSubscription(e){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=a?[{protocol:a}]:[],o;if(n)try{o=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{return}let d=u=>{if(u.type!=="event")return;let f=this.buildCursorKey(r,i,a),h=this.tryGetCidSync(u.event.message);if(h===void 0)return;let p=this._pendingPushCids.get(f);p||(p={did:r,dwnUrl:i,delegateDid:n,protocol:a,cids:[]},this._pendingPushCids.set(f,p)),p.cids.push(h),this._pushDebounceTimer&&clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=setTimeout(()=>{this.flushPendingPushes()},tge)},c=(await this.agent.dwn.processRequest({author:r,target:r,messageType:Re.MessagesSubscribe,granteeDid:n,messageParams:{filters:s,permissionGrantId:o},subscriptionHandler:d})).reply;if(c.status.code!==200||!c.subscription){console.error(`SyncEngineLevel: Local MessagesSubscribe failed for ${r}: ${c.status.code} ${c.status.detail}`);return}this._localSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await c.subscription.close()}})}async flushPendingPushes(){this._pushDebounceTimer=void 0;let e=[...this._pendingPushCids.entries()];this._pendingPushCids.clear();for(let[,r]of e){let{did:n,dwnUrl:i,delegateDid:a,protocol:s,cids:o}=r;if(o.length!==0)try{await B5({did:n,dwnUrl:i,delegateDid:a,protocol:s,messageCids:o,agent:this.agent,permissionsApi:this._permissionsApi})}catch(d){console.error(`SyncEngineLevel: Push-on-write failed for ${n} -> ${i}`,d)}}}buildCursorKey(e,r,n){let i=`${e}${xH}${r}`;return n?`${i}${xH}${n}`:i}async getCursor(e){let r=this._db.sublevel("syncCursors");try{return await r.get(e)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async setCursor(e,r){await this._db.sublevel("syncCursors").put(e,r)}extractDataStream(e){if(Ll(e)&&e.data)return e.data}tryGetCidSync(e){let r;return we.getCid(e).then(n=>{r=n}),r??e.messageCid??void 0}async getDefaultHashHex(e){if(this._defaultHashHex===void 0){let r=await Pl(),n=new Map;for(let i=0;i<=bH;i++)n.set(i,sn(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 d=n!==void 0?await i.getProtocolRoot(e,n):await i.getRoot(e);return sn(d)}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 walkTreeDiff({did:e,dwnUrl:r,delegateDid:n,protocol:i}){let a=[],s=[],o=await this.getSyncPermissionGrantId(e,n,i),d=new O5(ege),l=async c=>{let[u,f]=await Promise.all([this.getLocalSubtreeHash(e,c,n,i,o),d.run(()=>this.getRemoteSubtreeHash(e,r,c,n,i,o))]);if(u===f)return;let h=await this.getDefaultHashHex(c.length);if(f===h&&u!==h){let p=await this.getLocalLeaves(e,c,n,i,o);a.push(...p);return}if(u===h&&f!==h){let p=await d.run(()=>this.getRemoteLeaves(e,r,c,n,i,o));s.push(...p);return}if(c.length>=bH){let[p,m]=await Promise.all([this.getLocalLeaves(e,c,n,i,o),d.run(()=>this.getRemoteLeaves(e,r,c,n,i,o))]),y=new Set(p),b=new Set(m);for(let w of p)b.has(w)||a.push(w);for(let w of m)y.has(w)||s.push(w);return}await Promise.all([l(c+"0"),l(c+"1")])};return await l(""),{onlyLocal:a,onlyRemote:s}}async diffWithRemote({did:e,dwnUrl:r,delegateDid:n,protocol:i}){let a=await this.collectLocalSubtreeHashes(e,i,PH),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:PH,permissionGrantId:s}}),d=await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message});if(d.status.code!==200)throw new Error(`SyncEngineLevel: diff failed with ${d.status.code}: ${d.status.detail}`);let l=await this.getSyncPermissionGrantId(e,n,i),c=[];for(let u of d.onlyLocal??[]){let f=await this.getLocalLeaves(e,u,n,i,l);c.push(...f)}return{onlyRemote:d.onlyRemote??[],onlyLocal:c}}async collectLocalSubtreeHashes(e,r,n){let i={},a=await this.getDefaultHashHex(n),s=this.stateIndex,o=async(d,l)=>{let c;if(s){let u=Of.parseBitPrefix(d),f=r!==void 0?await s.getProtocolSubtreeHash(e,r,u):await s.getSubtreeHash(e,u);c=sn(f)}else c=await this.getLocalSubtreeHash(e,d,void 0,r);if(c!==a){if(l>=n){i[d]=c;return}await Promise.all([o(d+"0",l+1),o(d+"1",l+1)])}};return await o("",0),i}async getLocalSubtreeHash(e,r,n,i,a){let s=this.stateIndex;if(s){let l=Of.parseBitPrefix(r),c=i!==void 0?await s.getProtocolSubtreeHash(e,i,l):await s.getSubtreeHash(e,l);return sn(c)}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 getRemoteSubtreeHash(e,r,n,i,a,s){let o=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:i,messageParams:{action:"subtree",prefix:n,protocol:a,permissionGrantId:s}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message})).hash??""}async getLocalLeaves(e,r,n,i,a){let s=this.stateIndex;if(s){let l=Of.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 getRemoteLeaves(e,r,n,i,a,s){let o=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:i,messageParams:{action:"leaves",prefix:n,protocol:a,permissionGrantId:s}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message})).entries??[]}async pullMessages({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s}){return vH({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s,agent:this.agent,permissionsApi:this._permissionsApi})}async pushMessages({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a}){return B5({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:this.agent,permissionsApi:this._permissionsApi})}static topologicalSort(e){return hg(e)}async getSyncTargets(){let e=[];for await(let[r,n]of this._db.sublevel("registeredIdentities").iterator()){let i;try{i=JSON.parse(n)}catch{i={protocols:[]}}let{protocols:a,delegateDid:s}=i,o=await this.agent.dwn.getDwnEndpointUrlsForTarget(r);if(o.length!==0)for(let d of o)if(a.length===0)e.push({did:r,delegateDid:s,dwnUrl:d});else for(let l of a)e.push({did:r,delegateDid:s,dwnUrl:d,protocol:l})}return e}async getSyncPermissionGrantId(e,r,n){if(r)try{return(await this._permissionsApi.getPermissionForRequest({connectedDid:e,messageType:Re.MessagesSync,delegateDid:r,protocol:n,cached:!0})).grant.id}catch(i){console.error("SyncEngineLevel: Error fetching MessagesSync permission grant for delegate DID",i);return}}};Of.MAX_CONSECUTIVE_FAILURES=5,Of.MAX_BACKOFF_MULTIPLIER=4;var mg=Of;g();Yn();Jo();Er();import{Level as pge}from"level";g();g();g();Er();wn();g();g();var SH=An(qE(),1);Er();var yg=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},XE=class{constructor({ttl:e="15m"}={}){this.cache=new cs.default({ttl:(0,SH.default)(e)})}get(e){return yg(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,r){return yg(this,void 0,void 0,function*(){this.cache.set(e,r)})}delete(e){return yg(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return yg(this,void 0,void 0,function*(){this.cache.clear()})}open(){return yg(this,void 0,void 0,function*(){})}close(){return yg(this,void 0,void 0,function*(){})}};g();wn();Yn();g();var gg=class extends Error{constructor(e,r){super(r??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};g();var wg;(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"})(wg||(wg={}));var vg=(t,e,r)=>({jsonrpc:"2.0",id:t,method:e,params:r}),QE=(t,e,r,n)=>({jsonrpc:"2.0",id:t,method:e,params:r,subscription:{id:n??null}}),AH=(t,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:t}});function $h(t){try{return JSON.parse(t)}catch{return null}}var j5=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},rge=3,nge=500,ige=1e4,sge=3e4,kH=new Set([408,429,500,502,503,504]);function oge(t,e){return t instanceof TypeError?!0:e?kH.has(e.status):!1}function age(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 eS=class t{constructor(e,r){var n,i,a;this.serverInfoCache=e??new XE,this._retryOptions={maxRetries:(n=r?.maxRetries)!==null&&n!==void 0?n:rge,baseDelayMs:(i=r?.baseDelayMs)!==null&&i!==void 0?i:nge,maxDelayMs:(a=r?.maxDelayMs)!==null&&a!==void 0?a:ige}}static isBunRuntime(){return typeof globalThis.Bun<"u"}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return j5(this,void 0,void 0,function*(){var r,n,i;let a=gn.randomUuid(),s=vg(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),o={"dwn-request":JSON.stringify(s)},d={method:"POST",headers:o};if(e.data){o["content-type"]="application/octet-stream";let h=e.data;if(h instanceof ReadableStream)if(t.isBunRuntime()){let p=yield Yt.toBytes(h);h=new Blob([p],{type:"application/octet-stream"})}else d.duplex="half";d.body=h}let l=yield this.fetchWithRetry(e.dwnUrl,d);if(l.status===429){let h=parseInt((r=l.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new gg(h)}let c,u=l.headers.has("dwn-response");if(u){let h=$h(l.headers.get("dwn-response"));if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);c=h}else{let h=yield l.text(),p=$h(h);if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${l.status}`);c=p}if(c.error){let{code:h,message:p}=c.error;if(h===wg.TooManyRequests){let m=(i=(n=c.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new gg(m)}throw new Error(`(${h}) - ${p}`)}let{reply:f}=c.result;if(u){let h=new Uint8Array(yield l.arrayBuffer()),p=Yt.fromBytes(h);f.record?f.record.data=p:f.entry&&(f.entry.data=p)}return f})}getServerInfo(e){return j5(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 gg(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 j5(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,s,o;for(let d=0;d<=n;d++){try{let f=AbortSignal.timeout(sge),h=Object.assign(Object.assign({},r),{signal:r?.signal?AbortSignal.any([r.signal,f]):f}),p=yield fetch(e,h);if(!kH.has(p.status)||d===n)return p;o=p}catch(f){if(!oge(f)||d===n)throw f;s=f}let l=o?cge(o):void 0,c=age(d,i,a),u=l!==void 0?Math.max(l,c):c;yield new Promise(f=>{setTimeout(f,u)})}if(o)return o;throw s})}};g();wn();var xb=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})};function M5(t){return typeof t=="string"?t:t instanceof ArrayBuffer?new TextDecoder().decode(t):t instanceof Uint8Array?new TextDecoder().decode(t):String(t)}var _H=3e3,dge=3e4,lge=1e3,uge=3e4,fge=1/0,tS=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 xb(this,arguments,void 0,function*(r,n={}){var i;let{connectTimeout:a=_H,responseTimeout:s=dge}=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 d=new t(o,s,r,n);return d.wireSocket(o),d})}close(){this.closedByUser=!0,this._isConnected=!1,this.socket.close()}request(e){return xb(this,void 0,void 0,function*(){return new Promise((r,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=gn.randomUuid());let a=s=>{let o=$h(M5(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 xb(this,void 0,void 0,function*(){if(!e.method.startsWith("rpc.subscribe."))throw new Error("subscribe rpc requests must include the `rpc.subscribe` prefix");if(!e.subscription)throw new Error("subscribe rpc requests must include subscribe options");let n=e.subscription.id,i=this.messageHandlers.get(n),a=d=>{let l=$h(M5(d.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:()=>xb(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let r=gn.randomUuid(),n=QE(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=c=>{l(),i(c)},d=setTimeout(()=>{l(),a.close(),i(new Error("connect timed out"))},r),l=()=>{clearTimeout(d),a.removeEventListener("open",s),a.removeEventListener("error",o)};a.addEventListener("open",s),a.addEventListener("error",o)})}wireSocket(e){e.addEventListener("message",r=>{let n=$h(M5(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:wg.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:lge,s=(r=this.options.maxReconnectDelay)!==null&&r!==void 0?r:uge,o=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:fge,d=(i=this.options.connectTimeout)!==null&&i!==void 0?i:_H,l=0,c=()=>xb(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(b=>setTimeout(b,y)),this.closedByUser){this.reconnecting=!1;return}try{let b=yield t.createWebSocket(this.url,d);this.socket=b,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(b),(p=(h=this.options).onreconnected)===null||p===void 0||p.call(h)}catch{yield c()}});c()}};g();g();g();wn();g();wn();var bg=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},Eb=class t{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return bg(this,void 0,void 0,function*(){let r=new URL(e.dwnUrl);if(r.protocol!=="ws:"&&r.protocol!=="wss:")throw new Error(`Invalid websocket protocol ${r.protocol}`);if(!t.connections.has(r.host))try{let d=yield t.createConnection(r);t.connections.set(r.host,d)}catch(d){throw new Error(`Error connecting to ${r.host}: ${d.message}`)}let i=t.connections.get(r.host),{targetDid:a,message:s,subscription:o}=e;return o?t.subscriptionRequest(i,a,s,o.handler,o.resubscribeFactory):t.processMessage(i,a,s)})}static createConnection(e){return bg(this,void 0,void 0,function*(){let r=e.host,n=new Map,i=yield tS.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 bg(this,void 0,void 0,function*(){let i=gn.randomUuid(),a=vg(i,"dwn.processMessage",{target:r,message:n}),{socket:s}=e,o=yield s.request(a),{error:d,result:l}=o;if(d!==void 0)throw new Error(`error sending DWN request: ${d.message}`);return l.reply})}static subscriptionRequest(e,r,n,i,a){return bg(this,void 0,void 0,function*(){let s=gn.randomUuid(),o=gn.randomUuid(),d=QE(s,"rpc.subscribe.dwn.processMessage",{target:r,message:n},o),{socket:l,subscriptions:c}=e,{response:u,close:f}=yield l.subscribe(d,y=>{let{result:b,error:w}=y;if(w){let k=c.get(o);k&&k.subscription.close(),c.delete(o);return}let S=b.subscription;if(i(S),"cursor"in S&&S.cursor){let k=c.get(o);k&&(k.lastCursor=S.cursor),l.send(AH(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=()=>bg(this,void 0,void 0,function*(){c.delete(o),yield f()}),b={subscription:Object.assign(Object.assign({},m.subscription),{close:y}),target:r,message:n,handler:i,resubscribeFactory:a};c.set(o,b),m.subscription.close=y}return m})}static resubscribeAll(e){return bg(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{}})}};Eb.connections=new Map;var Sb=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},TH;(function(t){t.Create="did.create",t.Resolve="did.resolve"})(TH||(TH={}));var Pg=class{constructor(e=[]){this.transportClients=new Map,e=[new K5,new N5,...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 Sb(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 Sb(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)})}},K5=class extends eS{sendDidRequest(e){return Sb(this,void 0,void 0,function*(){let r=gn.randomUuid(),n=vg(r,e.method,{data:e.data}),i=new Request(e.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a;try{let s=yield fetch(i,{signal:AbortSignal.timeout(3e4)});if(s.ok){if(a=yield s.json(),a.error){let{code:o,message:d}=a.error;throw new Error(`JSON RPC (${o}) - ${d}`)}}else throw new Error(`HTTP (${s.status}) - ${s.statusText}`)}catch(s){throw new Error(`Error encountered while processing response from ${e.url}: ${s.message}`)}return a.result})}},N5=class extends Eb{sendDidRequest(e){return Sb(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return Sb(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};g();var IH=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 po.create({options:{publish:!0,gatewayUri:j.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=G=>`${n}/${G}`,a=new yo,s=new Pg,o={keyStore:new lg,identityStore:new fg,didStore:new cg,clear:()=>{o.keyStore._protocolInitializedCache?.clear(),o.identityStore._protocolInitializedCache?.clear(),o.didStore._protocolInitializedCache?.clear()}},{agentVault:d,didApi:l,identityApi:c,keyManager:u,didResolverCache:f,vaultStore:h,permissionsApi:p}=r==="memory"?t.useMemoryStores():t.useDiskStores({testDataLocation:n,stores:o}),m=new _f({blockstoreLocation:i("DWN_DATASTORE")}),y=new Rf({location:i("DWN_STATEINDEX")}),b=new Df,w=new If({location:i("DWN_RESUMABLETASKSTORE")}),S=new Tf({blockstoreLocation:i("DWN_MESSAGESTORE"),indexLocation:i("DWN_MESSAGEINDEX")}),k=await Fl.createDwn({dataPath:n,dataStore:m,didResolver:l,stateIndex:y,eventLog:b,messageStore:S,resumableTaskStore:w}),T=new Fl({dwn:k,localDwnStrategy:"off"}),D=new pge(i("SYNC_STORE")),K=new mg({db:D}),C=new e({agentVault:d,cryptoApi:a,didApi:l,dwnApi:T,identityApi:c,keyManager:u,permissionsApi:p,rpcClient:s,syncApi:K});return new t({agent:C,agentStores:r,didResolverCache:f,dwn:k,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 Im({location:i("VAULT_STORE")}),s=new Rh({keyDerivationWorkFactor:1,store:a}),{didStore:o,identityStore:d,keyStore:l}=n,c=new Cf({location:i("DID_RESOLVERCACHE")}),u=new _h({agent:e,didMethods:[po,ho],resolverCache:c,store:o}),f=new Ch({agent:e,store:d}),h=new go({agent:e,keyStore:l}),p=new Ka({agent:e});return{agentVault:s,didApi:u,didResolverCache:c,identityApi:f,keyManager:h,permissionsApi:p,vaultStore:a}}static useMemoryStores({agent:e}={}){let r=new bu,n=new Rh({keyDerivationWorkFactor:1,store:r}),i=new dE,a=new _h({agent:e,didMethods:[po,ho],resolverCache:i,store:new dg}),s=new go({agent:e,keyStore:new ug}),o=new Ch({agent:e,store:new pg}),d=new Ka({agent:e});return{agentVault:n,didApi:a,didResolverCache:i,identityApi:o,keyManager:s,permissionsApi:d,vaultStore:r}}};g();Jo();Er();wn();Yn();function hge({baseURL:t,endpoint:e,authParam:r,tokenParam:n}){switch(e){case"pushedAuthorizationRequest":return hb(t,"par");case"authorize":if(!r)throw new Error("authParam must be provided when building an authorize URL");return hb(t,`authorize/${r}.jwt`);case"callback":return hb(t,"callback");case"token":if(!n)throw new Error("tokenParam must be provided when building a token URL");return hb(t,`token/${n}.jwt`);default:throw new Error(`Unknown connect endpoint: ${e}`)}}async function mge({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 DH({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 ho.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 Fc().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 yge({jwt:t,encryptionKey:e}){let r={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT"},n=gn.randomBytes(24),i=he.object(r).toUint8Array(),a=he.string(t).toUint8Array(),s=await Hc.encryptRaw({data:a,keyBytes:e,nonce:n,additionalData:i}),o=s.subarray(0,-16),d=s.subarray(-16);return[he.object(r).toBase64Url(),"",he.uint8Array(n).toBase64Url(),he.uint8Array(o).toBase64Url(),he.uint8Array(d).toBase64Url()].join(".")}async function RH({jwe:t,encryptionKey:e}){let[r,,n,i,a]=t.split("."),s=he.base64Url(e).toUint8Array(),o=he.base64Url(r).toUint8Array(),d=he.base64Url(n).toUint8Array(),l=he.base64Url(i).toUint8Array(),c=he.base64Url(a).toUint8Array(),u=new Uint8Array([...l,...c]),f=await Hc.decryptRaw({data:u,keyBytes:s,nonce:d,additionalData:o});return he.uint8Array(f).toString()}async function gge(t,e){let r=await t.export(),n=e.verificationMethod?.[0].publicKeyJwk,i=r.privateKeys?.[0];n.alg="EdDSA";let a=await wi.convertPublicKeyToX25519({publicKey:n}),s=await wi.convertPrivateKeyToX25519({privateKey:i}),o=await Gt.sharedSecret({privateKeyA:s,publicKeyB:a});return Om.deriveKeyBytes({baseKeyBytes:new Uint8Array(o),hash:"SHA-256",salt:new Uint8Array,info:new Uint8Array,length:256})}async function wge({jwt:t,encryptionKey:e,delegateDidKeyId:r,pin:n}){let i={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT",kid:r},a=gn.randomBytes(24),s=n?{...i,pin:n}:{...i},o=he.object(s).toUint8Array(),d=he.string(t).toUint8Array(),l=await Hc.encryptRaw({data:d,keyBytes:e,nonce:a,additionalData:o}),c=l.subarray(0,-16),u=l.subarray(-16);return[he.object(i).toBase64Url(),"",he.uint8Array(a).toBase64Url(),he.uint8Array(c).toBase64Url(),he.uint8Array(u).toBase64Url()].join(".")}async function vge(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 d=await ho.resolve(o.kid.split("#")[0]),l=await xg.deriveSharedKey(t,d.didDocument),c=r?{...o,pin:r}:{...o},u=he.object(c).toUint8Array(),f=he.base64Url(i).toUint8Array(),h=he.base64Url(a).toUint8Array(),p=he.base64Url(s).toUint8Array(),m=new Uint8Array([...h,...p]),y=await Hc.decryptRaw({data:m,keyBytes:l,nonce:f,additionalData:u});return he.uint8Array(y).toString()}async function bge(t){let e=gn.randomBytes(16),r=gn.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 Pge(t,e){let n=await(await fetch(t,{signal:AbortSignal.timeout(3e4)})).text(),i=await RH({jwe:n,encryptionKey:e});return await DH({jwt:i})}async function xge(t){let e=Math.floor(Date.now()/1e3);return{...t,iat:e,exp:e+600}}function Ege(t){return b5(t)?!0:t.interface===be.Protocols&&t.method===ge.Configure}async function Sge(t,e,r,n){let i=new Ka({agent:r});Rs.log(`Creating permission grants for ${n.length} scopes...`);let a=await Promise.all(n.map(d=>{let l=Ege(d);return i.createGrant({delegated:l,store:!0,grantedTo:e.uri,scope:d,dateExpires:"2040-06-25T16:09:16.693356Z",author:t})})),s=await r.dwn.getDwnEndpointUrlsForTarget(t);Rs.log(`Sending ${a.length} permission grants to ${s.length} DWN endpoint(s)...`);let o=a.map(async d=>{let{encodedData:l,...c}=d.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:c,data:new Blob([u])});p.status.code===202||p.status.code===409?f=!0:Rs.error(`Grant send to ${h} returned ${p.status.code}: ${p.status.detail}`)}catch(p){Rs.error(`Grant send to ${h} failed: ${p.message}`)}if(!f)throw new Error("Could not send permission grant to any DWN endpoint.");return d.message});try{return await Promise.all(o)}catch(d){throw Rs.error(`Error during batch-send of permission grants: ${d}`),d}}async function Age(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){Rs.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{Rs.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 kge(t,e,r,n){let i=await ho.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 Age(t,n,m),xg.createPermissionGrants(t,i,n,y)}),o=(await Promise.all(s)).flat();Rs.log("Building connect response...");let d=await xg.createConnectResponse({providerDid:t,delegateDid:i.uri,aud:e.clientDid,nonce:e.nonce,delegateGrants:o,delegatePortableDid:a});Rs.log("Signing connect response...");let l=await xg.signJwt({did:i,data:d}),c=await ho.resolve(e.clientDid),u=await xg.deriveSharedKey(i,c?.didDocument);Rs.log("Encrypting connect response...");let f=await xg.encryptResponse({jwt:l,encryptionKey:u,delegateDidKeyId:i.document.verificationMethod[0].id,pin:r}),h=new URLSearchParams({id_token:f,state:e.state}).toString();Rs.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 xg={buildConnectUrl:hge,signJwt:mge,verifyJwt:DH,encryptRequest:yge,decryptRequest:RH,encryptResponse:wge,decryptResponse:vge,deriveSharedKey:gge,createConnectRequest:bge,getConnectRequest:Pge,createConnectResponse:xge,createPermissionGrants:Sge,submitConnectResponse:kge};g();Er();Jo();var CH=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:d,identityApi:l,keyManager:c,permissionsApi:u,rpcClient:f,syncApi:h}={}){return a??=new Rh({keyDerivationWorkFactor:21e4,store:new Im({location:`${e}/VAULT_STORE`})}),s??=new yo,o??=new _h({didMethods:[po,ho],resolverCache:new Cf({location:`${e}/DID_RESOLVERCACHE`}),store:new cg}),d||(n?d=new Fl({localDwnEndpoint:n,localDwnStrategy:r??"prefer"}):d=new Fl({dwn:await Fl.createDwn({dataPath:e,didResolver:o}),localDwnStrategy:r??"prefer"})),r&&d.setLocalDwnStrategy(r),l??=new Ch({store:new fg}),c??=new go({keyStore:new lg}),u??=new Ka,f??=new Pg,h??=new mg({dataPath:e}),new t({agentDid:i,agentVault:a,cryptoApi:s,didApi:o,dwnApi:d,keyManager:c,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{yo as AgentCryptoApi,_h as AgentDidApi,Cf as AgentDidResolverCache,Fl as AgentDwnApi,Ch as AgentIdentityApi,Ka as AgentPermissionsApi,CG as AnonymousDwnApi,ig as BearerIdentity,hye as DISCOVERY_DIR,mye as DISCOVERY_FILENAME,YG as DWN_CONNECT_PATH,ZG as DWN_PROTOCOL_SCHEME,uye as DidInterface,ma as DwnConstant,ii as DwnContentEncryptionAlgorithm,$f as DwnDataStore,Kt as DwnDateSort,cg as DwnDidStore,FE as DwnDiscoveryFile,fg as DwnIdentityStore,Re as DwnInterface,Ht as DwnKeyDerivationScheme,lg as DwnKeyStore,Ir as DwnPermissionGrant,cd as DwnPermissionRequest,dt as DwnPermissionsProtocol,xg as EnboxConnectProtocol,CH as EnboxUserAgent,Rh as HdIdentityVault,Bf as InMemoryDataStore,dg as InMemoryDidStore,pg as InMemoryIdentityStore,ug as InMemoryKeyStore,Th as LocalDwnDiscovery,go as LocalKeyManager,IH as PlatformAgentTestHarness,mg as SyncEngineLevel,jG as buildContextKeyDecrypter,FHe as buildDwnConnectUrl,HHe as buildDwnDiscoveryRedirectUrl,Ih as buildEncryptionInput,NG as buildKmsDecryptCallback,hb as concatenateUrl,pye as createNodeDiscoveryFileFs,JG as decodeDwnDiscoveryPayload,KG as deriveContextEncryptionInput,E5 as detectNewParticipants,Id as dwnMessageConstructors,FG as eagerSendContextKeyRecord,vye as encodeDwnDiscoveryPayload,HE as encryptAndComputeCid,qG as ensureKeyDeliveryProtocol,GG as fetchContextKeyRecord,pb as getDwnServiceEndpointUrls,yb as getEncryptionKeyDeriver,zl as getEncryptionKeyInfo,gb as getKeyDecrypter,fGe as getPaginationCursor,lGe as getRecordAuthor,sye as getRecordMessageCid,uGe as getRecordProtocolRole,hHe as getRootContextId,LG as getRuleSetAtPath,P5 as hasRelationalReadAccess,OG as isDidRequest,gye as isDwnMessage,Rd as isDwnRequest,Jye as isIdentityMetadata,wye as isMessagesPermissionScope,x5 as isMultiPartyContext,SWe as isPortableIdentity,b5 as isRecordPermissionScope,v5 as isRecordsType,Ll as isRecordsWrite,GE as ivLength,fye as localDwnServerName,UG as maybeDecryptReply,zE as normalizeBaseUrl,GHe as parseDwnConnectUrl,pGe as pollWithTtl,VHe as readDwnDiscoveryPayloadFromUrl,MG as resolveKeyDecrypter,zG as writeContextKeyRecord};
2060
+ 'valid, non-empty password.`);if(r??=dH(I5,128),!uH(r,I5))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 fH(r),a=JE.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"}),d=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(d).toBase64Url()},c=await Gl.encrypt({key:he.string(e).toUint8Array(),protectedHeader:l,plaintext:he.object(o).toUint8Array(),crypto:this.crypto,keyManager:new go});await this._store.set("contentEncryptionKey",c);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}),b=new UE;await b.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 k=await(await po.create({keyManager:b,options:w})).export(),T={alg:"dir",enc:"A256GCM",cty:"json"},D=await Gl.encrypt({key:o,plaintext:he.object(k).toUint8Array(),protectedHeader:T,crypto:this.crypto,keyManager:new go});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(!Vye(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 Gl.decrypt({jwe:r,key:he.string(e).toUint8Array(),crypto:this.crypto,keyManager:new go,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();Jo();g();Er();function Jye(t){return!(!t||typeof t!="object"||t===null)&&"name"in t}var fg=class extends $f{constructor(){super(...arguments);this.name="DwnIdentityStore";this._recordProtocolDefinition=NE;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(Jye(o)){let d=`${n}${ki}${o.uri}`;this._index.set(d,s.recordId),this._cache.set(s.recordId,o),a.push(o)}}return a}},pg=class extends Bf{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 SWe(t){return!(!t||typeof t!="object"||t===null)&&"did"in t&&"metadata"in t&&bh(t.did)}var Ch=class{constructor({agent:e,store:r}={}){this._agent=e,this._store=r??new pg}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 ig({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 ig({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 ig({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();Yn();Er();var Ka=class t{constructor({agent:e}={}){this._cachedPermissions=new cs.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("~"),d=s?this._cachedPermissions.get(o):void 0;if(d)return d;let l=await this.fetchGrants({author:r,target:r,grantor:e,grantee:r}),c=await t.matchGrantFromArray(e,r,{messageType:i,protocol:a},l,n);if(!c)throw new Error(`CachedPermissions: No permissions found for ${i}: ${a}`);return this._cachedPermissions.set(o,c),c}async fetchGrants({author:e,target:r,grantee:n,grantor:i,protocol:a,remote:s=!1,checkRevoked:o=!0}){let d=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:d}}},{reply:c}=s?await this.agent.sendDwnRequest(l):await this.agent.processDwnRequest(l);if(c.status.code!==200)throw new Error(`PermissionsApi: Failed to fetch grants: ${c.status.detail}`);let u=o?await this.fetchRevokedGrantIds({author:e,target:r,grantor:i,remote:s,tags:d}):new Set,f=[];for(let h of c.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 d=new Set;for(let l of o.entries)l.descriptor.parentId!==void 0&&d.add(l.descriptor.parentId);return d}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 d=[];for(let l of o.entries){let c=cd.parse(l);d.push({request:c,message:l})}return d}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},d=he.object(o).toUint8Array(),l={recipient:a.grantedTo,protocol:dt.uri,protocolPath:dt.grantPath,dataFormat:"application/json",tags:s},{reply:c,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create grant: ${c.status.detail}`);let f={...u,encodedData:he.uint8Array(d).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},d=he.object(o).toUint8Array(),l={protocol:dt.uri,protocolPath:dt.requestPath,dataFormat:"application/json",tags:s},{reply:c,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([d])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create request: ${c.status.detail}`);let f={...u,encodedData:he.uint8Array(d).toBase64Url()};return{request:cd.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(),d;dt.hasProtocolScope(i.scope)&&(d={protocol:i.scope.protocol});let l={parentContextId:i.id,protocol:dt.uri,protocolPath:dt.revocationPath,dataFormat:"application/json",tags:d},{reply:c,message:u}=await this.agent.processDwnRequest({store:n,author:r,target:r,messageType:Re.RecordsWrite,messageParams:l,dataStream:new Blob([o])});if(c.status.code!==202)throw new Error(`PermissionsApi: Failed to create revocation: ${c.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:d,message:l}=o;if(a===!0&&d.delegated!==!0)continue;let{messageType:c,protocol:u,protocolPath:f,contextId:h}=n;if(this.matchScopeFromGrant(e,r,c,d,u,f,h)){if(d.scope.interface+d.scope.method===c)return{grant:d,message:l};s||(s={grant:d,message:l})}}return s}static matchScopeFromGrant(e,r,n,i,a,s,o){if(i.grantee!==r||i.grantor!==e)return!1;let d=i.scope,l=d.interface+d.method;if(l===n||l===Re.MessagesRead&&(n===Re.MessagesSync||n===Re.MessagesSubscribe))if(v5(n)){let u=d;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=d;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 EH=An(qE(),1);Yn();import{Level as Qye}from"level";g();Yn();function mH(t){let e=t.descriptor;return e.interface!==be.Records||e.method!==ge.Write?!1:e.dateCreated===e.messageTimestamp}function hg(t){if(t.length<=1)return t;let e=new Map,r=new Map,n=new Map,i=new Map;for(let c=0;c<t.length;c++){let u=t[c];e.set(c,u);let f=u.message.descriptor;if(f.interface===be.Protocols&&f.method===ge.Configure){let h=f.definition?.protocol;h&&r.set(h,c)}if(f.interface===be.Records&&f.method===ge.Write){let h=u.message.recordId;mH(u.message)&&h&&n.set(h,c),f.protocol===dt.uri&&f.protocolPath===dt.grantPath&&h&&i.set(h,c)}}let a=new Map,s=new Array(t.length).fill(0),o=(c,u)=>{if(c===u)return;a.has(c)||a.set(c,new Set);let f=a.get(c);f.has(u)||(f.add(u),s[u]++)};for(let c=0;c<t.length;c++){let u=t[c].message.descriptor;if(u.interface===be.Records){let h=u.protocol;h&&r.has(h)&&o(r.get(h),c)}if(u.interface===be.Records&&u.parentId){let h=u.parentId;n.has(h)&&o(n.get(h),c)}if(u.interface===be.Records&&u.method===ge.Write){let h=t[c].message.recordId;h&&!mH(t[c].message)&&n.has(h)&&o(n.get(h),c)}if(u.interface===be.Records&&u.method===ge.Delete){let h=u.recordId;h&&n.has(h)&&o(n.get(h),c)}let f=u.permissionGrantId;f&&i.has(f)&&o(i.get(f),c)}let d=[];for(let c=0;c<t.length;c++)s[c]===0&&d.push(c);let l=[];for(;d.length>0;){let c=d.shift();l.push(e.get(c));let u=a.get(c);if(u)for(let f of u)s[f]--,s[f]===0&&d.push(f)}if(l.length<t.length){let c=new Set(l);for(let u=0;u<t.length;u++){let f=e.get(u);c.has(f)||l.push(f)}}return l}g();Yn();var Zye=1048576;function gH(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===ge.Delete&&t.status.code===404}async function wH(t){try{return await we.getCid(t)}catch{return"unknown"}}async function vH({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,prefetched:a,agent:s,permissionsApi:o}){let d=[];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(b){b.enqueue(y),b.close()}})}d.push(m)}let l=i.length>0?await yH({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:s,permissionsApi:o}):[],c=[...d,...l],u=hg(c);await Yye(u);let f=3,h=u;for(let p=0;p<=f&&h.length>0;p++){let m=[];for(let y of h){let b=y.bufferedData?new ReadableStream({start(S){S.enqueue(y.bufferedData),S.close()}}):y.dataStream,w=await s.dwn.processRawMessage(t,y.message,{dataStream:b});gH(w)||m.push(y)}if(m.length>0){let y=[],b=[];for(let w of m)if(w.bufferedData||!w.dataStream)b.push(w);else{let S=await wH(w.message);y.push(S)}if(y.length>0){let w=await yH({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:y,agent:s,permissionsApi:o});b.push(...w)}h=hg(b)}else h=[]}}async function Yye(t){for(let e of t){if(!e.dataStream)continue;let r=[],n=0,i=!1,a=e.dataStream.getReader();try{for(;;){let{done:d,value:l}=await a.read();if(d)break;if(n+=l.byteLength,n>Zye){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 d of r)s.set(d,o),o+=d.byteLength;e.bufferedData=s,e.dataStream=new ReadableStream({start(d){d.enqueue(s),d.close()}})}}async function yH({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:s}){let o=[],d;r&&(d=(await s.getPermissionForRequest({connectedDid:t,messageType:Re.MessagesRead,delegateDid:r,protocol:n,cached:!0})).grant.id);let l=4,c=0;for(;c<i.length;){let u=i.slice(c,c+l);c+=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:d}}),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,b;return Ll(y)&&y.data&&(b=y.data),{message:y.message,dataStream:b}}));for(let h of f)h&&o.push(h)}return o}async function B5({did:t,dwnUrl:e,delegateDid:r,protocol:n,messageCids:i,agent:a,permissionsApi:s}){let o=[];for(let l of i){let c=await Xye({author:t,messageCid:l,delegateDid:r,protocol:n,agent:a,permissionsApi:s});c&&o.push(c)}let d=hg(o);for(let l of d)try{let c=await a.rpc.sendDwnRequest({dwnUrl:e,targetDid:t,data:l.dataStream,message:l.message});if(!gH(c)){let u=await wH(l.message);console.error(`SyncEngineLevel: push failed for ${u}: ${c.status.code} ${c.status.detail}`)}}catch(c){let u=c.message??c;throw new Error(`SyncEngineLevel: push to ${e} failed: ${u}`)}}async function Xye({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 d=o.entry,l={message:d.message};return Ll(d)&&d.data&&(l.dataStream=d.data),l}var bH=16,PH=8,ege=4,O5=class{constructor(e){this._waiting=[];this._permits=e}async acquire(){if(this._permits>0){this._permits--;return}return new Promise(e=>{this._waiting.push(e)})}release(){let e=this._waiting.shift();e?e():this._permits++}async run(e){await this.acquire();try{return await e()}finally{this.release()}}},xH="^",tge=250,Of=class Of{constructor({agent:e,dataPath:r,db:n}){this._syncLock=!1;this._syncMode="poll";this._liveSubscriptions=[];this._localSubscriptions=[];this._connectivityState="unknown";this._pendingPushCids=new Map;this._consecutiveFailures=0;this._agent=e,this._permissionsApi=new Ka({agent:e}),this._db=n||new Qye(r??"DATA/AGENT/SYNC_STORE")}get agent(){if(this._agent===void 0)throw new Error("SyncEngineLevel: Unable to determine agent execution context.");return this._agent}set agent(e){this._agent=e,this._permissionsApi=new Ka({agent:e})}get connectivityState(){return this._connectivityState}async clear(){await this._permissionsApi.clear(),await this._db.clear()}async close(){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 Set,i=!1;for(let a of r){let{did:s,delegateDid:o,dwnUrl:d,protocol:l}=a;if(!n.has(d))try{let c=await this.getLocalRoot(s,o,l),u=await this.getRemoteRoot(s,d,o,l);if(c===u)continue;let f=await this.diffWithRemote({did:s,dwnUrl:d,delegateDid:o,protocol:l});if((!e||e==="pull")&&f.onlyRemote.length>0){let h=[],p=[];for(let m of f.onlyRemote)m.message?m.message.descriptor.interface==="Records"&&m.message.descriptor.method==="Write"&&m.message.descriptor.dataCid&&!m.encodedData?p.push(m.messageCid):h.push(m):p.push(m.messageCid);await this.pullMessages({did:s,dwnUrl:d,delegateDid:o,protocol:l,messageCids:p,prefetched:h})}(!e||e==="push")&&f.onlyLocal.length>0&&await this.pushMessages({did:s,dwnUrl:d,delegateDid:o,protocol:l,messageCids:f.onlyLocal})}catch(c){n.add(d),i=!0,console.error(`SyncEngineLevel: Error syncing ${s} with ${d}`,c)}}i?(this._consecutiveFailures++,this._connectivityState==="online"&&(this._connectivityState="offline")):(this._consecutiveFailures=0,r.length>0&&(this._connectivityState="online"))}finally{this._syncLock=!1}}async startSync(e){let r=e.mode??"poll",n=e.interval??(r==="live"?"5m":"2m"),i=(0,EH.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){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=async()=>{if(this._syncLock)return;clearInterval(this._syncIntervalId),this._syncIntervalId=void 0;try{await this.sync()}catch(a){console.error("SyncEngineLevel: Error during sync operation",a)}let n=Math.min(Math.pow(2,this._consecutiveFailures),Of.MAX_BACKOFF_MULTIPLIER),i=this._consecutiveFailures>0?e*n:e;this._syncIntervalId||(this._syncIntervalId=setInterval(r,i))};this._syncIntervalId&&clearInterval(this._syncIntervalId),this._syncIntervalId=setInterval(r,e),this._syncLock||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();for(let i of r)try{await this.openLivePullSubscription(i),await this.openLocalPushSubscription(i)}catch(a){console.error(`SyncEngineLevel: Failed to open live subscription for ${i.did} -> ${i.dwnUrl}`,a)}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)}async teardownLiveSync(){this._pushDebounceTimer&&(clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=void 0),this._pendingPushCids.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=[]}async openLivePullSubscription(e){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=this.buildCursorKey(r,i,a),o=await this.getCursor(s),d=a?[{protocol:a}]:[],l;if(n)try{l=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesSubscribe,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{try{l=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}catch(h){console.error("SyncEngineLevel: Could not find permission grant for live pull subscription",h);return}}let c=async h=>{if(h.type==="eose"){await this.setCursor(s,h.cursor),this._connectivityState="online";return}if(h.type==="event"){let p=h.event;try{let m=this.extractDataStream(p);await this.agent.dwn.processRawMessage(r,p.message,{dataStream:m})}catch(m){console.error(`SyncEngineLevel: Error processing live-pull event for ${r}`,m)}await this.setCursor(s,h.cursor)}},f=(await this.agent.dwn.sendRequest({author:r,target:r,messageType:Re.MessagesSubscribe,granteeDid:n,messageParams:{filters:d,cursor:o,permissionGrantId:l},subscriptionHandler:c})).reply;if(f.status.code!==200||!f.subscription){console.error(`SyncEngineLevel: MessagesSubscribe failed for ${r} -> ${i}: ${f.status.code} ${f.status.detail}`);return}this._liveSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await f.subscription.close()}}),this._connectivityState="online"}async openLocalPushSubscription(e){let{did:r,delegateDid:n,dwnUrl:i,protocol:a}=e,s=a?[{protocol:a}]:[],o;if(n)try{o=(await this._permissionsApi.getPermissionForRequest({connectedDid:r,messageType:Re.MessagesRead,delegateDid:n,protocol:a,cached:!0})).grant.id}catch{return}let d=u=>{if(u.type!=="event")return;let f=this.buildCursorKey(r,i,a),h=this.tryGetCidSync(u.event.message);if(h===void 0)return;let p=this._pendingPushCids.get(f);p||(p={did:r,dwnUrl:i,delegateDid:n,protocol:a,cids:[]},this._pendingPushCids.set(f,p)),p.cids.push(h),this._pushDebounceTimer&&clearTimeout(this._pushDebounceTimer),this._pushDebounceTimer=setTimeout(()=>{this.flushPendingPushes()},tge)},c=(await this.agent.dwn.processRequest({author:r,target:r,messageType:Re.MessagesSubscribe,granteeDid:n,messageParams:{filters:s,permissionGrantId:o},subscriptionHandler:d})).reply;if(c.status.code!==200||!c.subscription){console.error(`SyncEngineLevel: Local MessagesSubscribe failed for ${r}: ${c.status.code} ${c.status.detail}`);return}this._localSubscriptions.push({did:r,dwnUrl:i,delegateDid:n,protocol:a,close:async()=>{await c.subscription.close()}})}async flushPendingPushes(){this._pushDebounceTimer=void 0;let e=[...this._pendingPushCids.entries()];this._pendingPushCids.clear();for(let[,r]of e){let{did:n,dwnUrl:i,delegateDid:a,protocol:s,cids:o}=r;if(o.length!==0)try{await B5({did:n,dwnUrl:i,delegateDid:a,protocol:s,messageCids:o,agent:this.agent,permissionsApi:this._permissionsApi})}catch(d){console.error(`SyncEngineLevel: Push-on-write failed for ${n} -> ${i}`,d)}}}buildCursorKey(e,r,n){let i=`${e}${xH}${r}`;return n?`${i}${xH}${n}`:i}async getCursor(e){let r=this._db.sublevel("syncCursors");try{return await r.get(e)}catch(n){if(n.code==="LEVEL_NOT_FOUND")return;throw n}}async setCursor(e,r){await this._db.sublevel("syncCursors").put(e,r)}extractDataStream(e){if(Ll(e)&&e.data)return e.data}tryGetCidSync(e){let r;return we.getCid(e).then(n=>{r=n}),r??e.messageCid??void 0}async getDefaultHashHex(e){if(this._defaultHashHex===void 0){let r=await Pl(),n=new Map;for(let i=0;i<=bH;i++)n.set(i,sn(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 d=n!==void 0?await i.getProtocolRoot(e,n):await i.getRoot(e);return sn(d)}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 walkTreeDiff({did:e,dwnUrl:r,delegateDid:n,protocol:i}){let a=[],s=[],o=await this.getSyncPermissionGrantId(e,n,i),d=new O5(ege),l=async c=>{let[u,f]=await Promise.all([this.getLocalSubtreeHash(e,c,n,i,o),d.run(()=>this.getRemoteSubtreeHash(e,r,c,n,i,o))]);if(u===f)return;let h=await this.getDefaultHashHex(c.length);if(f===h&&u!==h){let p=await this.getLocalLeaves(e,c,n,i,o);a.push(...p);return}if(u===h&&f!==h){let p=await d.run(()=>this.getRemoteLeaves(e,r,c,n,i,o));s.push(...p);return}if(c.length>=bH){let[p,m]=await Promise.all([this.getLocalLeaves(e,c,n,i,o),d.run(()=>this.getRemoteLeaves(e,r,c,n,i,o))]),y=new Set(p),b=new Set(m);for(let w of p)b.has(w)||a.push(w);for(let w of m)y.has(w)||s.push(w);return}await Promise.all([l(c+"0"),l(c+"1")])};return await l(""),{onlyLocal:a,onlyRemote:s}}async diffWithRemote({did:e,dwnUrl:r,delegateDid:n,protocol:i}){let a=await this.collectLocalSubtreeHashes(e,i,PH),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:PH,permissionGrantId:s}}),d=await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message});if(d.status.code!==200)throw new Error(`SyncEngineLevel: diff failed with ${d.status.code}: ${d.status.detail}`);let l=await this.getSyncPermissionGrantId(e,n,i),c=[];for(let u of d.onlyLocal??[]){let f=await this.getLocalLeaves(e,u,n,i,l);c.push(...f)}return{onlyRemote:d.onlyRemote??[],onlyLocal:c}}async collectLocalSubtreeHashes(e,r,n){let i={},a=await this.getDefaultHashHex(n),s=this.stateIndex,o=async(d,l)=>{let c;if(s){let u=Of.parseBitPrefix(d),f=r!==void 0?await s.getProtocolSubtreeHash(e,r,u):await s.getSubtreeHash(e,u);c=sn(f)}else c=await this.getLocalSubtreeHash(e,d,void 0,r);if(c!==a){if(l>=n){i[d]=c;return}await Promise.all([o(d+"0",l+1),o(d+"1",l+1)])}};return await o("",0),i}async getLocalSubtreeHash(e,r,n,i,a){let s=this.stateIndex;if(s){let l=Of.parseBitPrefix(r),c=i!==void 0?await s.getProtocolSubtreeHash(e,i,l):await s.getSubtreeHash(e,l);return sn(c)}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 getRemoteSubtreeHash(e,r,n,i,a,s){let o=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:i,messageParams:{action:"subtree",prefix:n,protocol:a,permissionGrantId:s}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message})).hash??""}async getLocalLeaves(e,r,n,i,a){let s=this.stateIndex;if(s){let l=Of.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 getRemoteLeaves(e,r,n,i,a,s){let o=await this.agent.dwn.processRequest({store:!1,author:e,target:e,messageType:Re.MessagesSync,granteeDid:i,messageParams:{action:"leaves",prefix:n,protocol:a,permissionGrantId:s}});return(await this.agent.rpc.sendDwnRequest({dwnUrl:r,targetDid:e,message:o.message})).entries??[]}async pullMessages({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s}){return vH({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,prefetched:s,agent:this.agent,permissionsApi:this._permissionsApi})}async pushMessages({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a}){return B5({did:e,dwnUrl:r,delegateDid:n,protocol:i,messageCids:a,agent:this.agent,permissionsApi:this._permissionsApi})}static topologicalSort(e){return hg(e)}async getSyncTargets(){let e=[];for await(let[r,n]of this._db.sublevel("registeredIdentities").iterator()){let i;try{i=JSON.parse(n)}catch{i={protocols:[]}}let{protocols:a,delegateDid:s}=i,o=await this.agent.dwn.getDwnEndpointUrlsForTarget(r);if(o.length!==0)for(let d of o)if(a.length===0)e.push({did:r,delegateDid:s,dwnUrl:d});else for(let l of a)e.push({did:r,delegateDid:s,dwnUrl:d,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}};Of.MAX_CONSECUTIVE_FAILURES=5,Of.MAX_BACKOFF_MULTIPLIER=4;var mg=Of;g();Yn();Jo();Er();import{Level as pge}from"level";g();g();g();Er();wn();g();g();var SH=An(qE(),1);Er();var yg=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},XE=class{constructor({ttl:e="15m"}={}){this.cache=new cs.default({ttl:(0,SH.default)(e)})}get(e){return yg(this,void 0,void 0,function*(){return this.cache.get(e)})}set(e,r){return yg(this,void 0,void 0,function*(){this.cache.set(e,r)})}delete(e){return yg(this,void 0,void 0,function*(){this.cache.delete(e)})}clear(){return yg(this,void 0,void 0,function*(){this.cache.clear()})}open(){return yg(this,void 0,void 0,function*(){})}close(){return yg(this,void 0,void 0,function*(){})}};g();wn();Yn();g();var gg=class extends Error{constructor(e,r){super(r??`Rate limit exceeded, retry after ${e}s`),this.name="RateLimitError",this.retryAfterSec=e}};g();var wg;(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"})(wg||(wg={}));var vg=(t,e,r)=>({jsonrpc:"2.0",id:t,method:e,params:r}),QE=(t,e,r,n)=>({jsonrpc:"2.0",id:t,method:e,params:r,subscription:{id:n??null}}),AH=(t,e)=>({jsonrpc:"2.0",method:"rpc.ack",params:{cursor:e},subscription:{id:t}});function $h(t){try{return JSON.parse(t)}catch{return null}}var j5=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},rge=3,nge=500,ige=1e4,sge=3e4,kH=new Set([408,429,500,502,503,504]);function oge(t,e){return t instanceof TypeError?!0:e?kH.has(e.status):!1}function age(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 eS=class t{constructor(e,r){var n,i,a;this.serverInfoCache=e??new XE,this._retryOptions={maxRetries:(n=r?.maxRetries)!==null&&n!==void 0?n:rge,baseDelayMs:(i=r?.baseDelayMs)!==null&&i!==void 0?i:nge,maxDelayMs:(a=r?.maxDelayMs)!==null&&a!==void 0?a:ige}}static isBunRuntime(){return typeof globalThis.Bun<"u"}get transportProtocols(){return["http:","https:"]}sendDwnRequest(e){return j5(this,void 0,void 0,function*(){var r,n,i;let a=gn.randomUuid(),s=vg(a,"dwn.processMessage",{target:e.targetDid,message:e.message}),o={"dwn-request":JSON.stringify(s)},d={method:"POST",headers:o};if(e.data){o["content-type"]="application/octet-stream";let h=e.data;if(h instanceof ReadableStream)if(t.isBunRuntime()){let p=yield Yt.toBytes(h);h=new Blob([p],{type:"application/octet-stream"})}else d.duplex="half";d.body=h}let l=yield this.fetchWithRetry(e.dwnUrl,d);if(l.status===429){let h=parseInt((r=l.headers.get("retry-after"))!==null&&r!==void 0?r:"1",10);throw new gg(h)}let c,u=l.headers.has("dwn-response");if(u){let h=$h(l.headers.get("dwn-response"));if(h==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}`);c=h}else{let h=yield l.text(),p=$h(h);if(p==null)throw new Error(`failed to parse json rpc response. dwn url: ${e.dwnUrl}, status: ${l.status}`);c=p}if(c.error){let{code:h,message:p}=c.error;if(h===wg.TooManyRequests){let m=(i=(n=c.error.data)===null||n===void 0?void 0:n.retryAfterSec)!==null&&i!==void 0?i:1;throw new gg(m)}throw new Error(`(${h}) - ${p}`)}let{reply:f}=c.result;if(u){let h=new Uint8Array(yield l.arrayBuffer()),p=Yt.fromBytes(h);f.record?f.record.data=p:f.entry&&(f.entry.data=p)}return f})}getServerInfo(e){return j5(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 gg(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 j5(this,void 0,void 0,function*(){let{maxRetries:n,baseDelayMs:i,maxDelayMs:a}=this._retryOptions,s,o;for(let d=0;d<=n;d++){try{let f=AbortSignal.timeout(sge),h=Object.assign(Object.assign({},r),{signal:r?.signal?AbortSignal.any([r.signal,f]):f}),p=yield fetch(e,h);if(!kH.has(p.status)||d===n)return p;o=p}catch(f){if(!oge(f)||d===n)throw f;s=f}let l=o?cge(o):void 0,c=age(d,i,a),u=l!==void 0?Math.max(l,c):c;yield new Promise(f=>{setTimeout(f,u)})}if(o)return o;throw s})}};g();wn();var xb=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})};function M5(t){return typeof t=="string"?t:t instanceof ArrayBuffer?new TextDecoder().decode(t):t instanceof Uint8Array?new TextDecoder().decode(t):String(t)}var _H=3e3,dge=3e4,lge=1e3,uge=3e4,fge=1/0,tS=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 xb(this,arguments,void 0,function*(r,n={}){var i;let{connectTimeout:a=_H,responseTimeout:s=dge}=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 d=new t(o,s,r,n);return d.wireSocket(o),d})}close(){this.closedByUser=!0,this._isConnected=!1,this.socket.close()}request(e){return xb(this,void 0,void 0,function*(){return new Promise((r,n)=>{var i;(i=e.id)!==null&&i!==void 0||(e.id=gn.randomUuid());let a=s=>{let o=$h(M5(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 xb(this,void 0,void 0,function*(){if(!e.method.startsWith("rpc.subscribe."))throw new Error("subscribe rpc requests must include the `rpc.subscribe` prefix");if(!e.subscription)throw new Error("subscribe rpc requests must include subscribe options");let n=e.subscription.id,i=this.messageHandlers.get(n),a=d=>{let l=$h(M5(d.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:()=>xb(this,void 0,void 0,function*(){this.messageHandlers.delete(n),this.subscriptionHandlerIds.delete(n),yield this.closeSubscription(n)})}})}closeSubscription(e){let r=gn.randomUuid(),n=QE(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=c=>{l(),i(c)},d=setTimeout(()=>{l(),a.close(),i(new Error("connect timed out"))},r),l=()=>{clearTimeout(d),a.removeEventListener("open",s),a.removeEventListener("error",o)};a.addEventListener("open",s),a.addEventListener("error",o)})}wireSocket(e){e.addEventListener("message",r=>{let n=$h(M5(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:wg.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:lge,s=(r=this.options.maxReconnectDelay)!==null&&r!==void 0?r:uge,o=(n=this.options.maxReconnectAttempts)!==null&&n!==void 0?n:fge,d=(i=this.options.connectTimeout)!==null&&i!==void 0?i:_H,l=0,c=()=>xb(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(b=>setTimeout(b,y)),this.closedByUser){this.reconnecting=!1;return}try{let b=yield t.createWebSocket(this.url,d);this.socket=b,this._isConnected=!0,this.reconnecting=!1,this.wireSocket(b),(p=(h=this.options).onreconnected)===null||p===void 0||p.call(h)}catch{yield c()}});c()}};g();g();g();wn();g();wn();var bg=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},Eb=class t{get transportProtocols(){return["ws:","wss:"]}sendDwnRequest(e){return bg(this,void 0,void 0,function*(){let r=new URL(e.dwnUrl);if(r.protocol!=="ws:"&&r.protocol!=="wss:")throw new Error(`Invalid websocket protocol ${r.protocol}`);if(!t.connections.has(r.host))try{let d=yield t.createConnection(r);t.connections.set(r.host,d)}catch(d){throw new Error(`Error connecting to ${r.host}: ${d.message}`)}let i=t.connections.get(r.host),{targetDid:a,message:s,subscription:o}=e;return o?t.subscriptionRequest(i,a,s,o.handler,o.resubscribeFactory):t.processMessage(i,a,s)})}static createConnection(e){return bg(this,void 0,void 0,function*(){let r=e.host,n=new Map,i=yield tS.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 bg(this,void 0,void 0,function*(){let i=gn.randomUuid(),a=vg(i,"dwn.processMessage",{target:r,message:n}),{socket:s}=e,o=yield s.request(a),{error:d,result:l}=o;if(d!==void 0)throw new Error(`error sending DWN request: ${d.message}`);return l.reply})}static subscriptionRequest(e,r,n,i,a){return bg(this,void 0,void 0,function*(){let s=gn.randomUuid(),o=gn.randomUuid(),d=QE(s,"rpc.subscribe.dwn.processMessage",{target:r,message:n},o),{socket:l,subscriptions:c}=e,{response:u,close:f}=yield l.subscribe(d,y=>{let{result:b,error:w}=y;if(w){let k=c.get(o);k&&k.subscription.close(),c.delete(o);return}let S=b.subscription;if(i(S),"cursor"in S&&S.cursor){let k=c.get(o);k&&(k.lastCursor=S.cursor),l.send(AH(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=()=>bg(this,void 0,void 0,function*(){c.delete(o),yield f()}),b={subscription:Object.assign(Object.assign({},m.subscription),{close:y}),target:r,message:n,handler:i,resubscribeFactory:a};c.set(o,b),m.subscription.close=y}return m})}static resubscribeAll(e){return bg(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{}})}};Eb.connections=new Map;var Sb=function(t,e,r,n){function i(a){return a instanceof r?a:new r(function(s){s(a)})}return new(r||(r=Promise))(function(a,s){function o(c){try{l(n.next(c))}catch(u){s(u)}}function d(c){try{l(n.throw(c))}catch(u){s(u)}}function l(c){c.done?a(c.value):i(c.value).then(o,d)}l((n=n.apply(t,e||[])).next())})},TH;(function(t){t.Create="did.create",t.Resolve="did.resolve"})(TH||(TH={}));var Pg=class{constructor(e=[]){this.transportClients=new Map,e=[new K5,new N5,...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 Sb(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 Sb(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)})}},K5=class extends eS{sendDidRequest(e){return Sb(this,void 0,void 0,function*(){let r=gn.randomUuid(),n=vg(r,e.method,{data:e.data}),i=new Request(e.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)}),a;try{let s=yield fetch(i,{signal:AbortSignal.timeout(3e4)});if(s.ok){if(a=yield s.json(),a.error){let{code:o,message:d}=a.error;throw new Error(`JSON RPC (${o}) - ${d}`)}}else throw new Error(`HTTP (${s.status}) - ${s.statusText}`)}catch(s){throw new Error(`Error encountered while processing response from ${e.url}: ${s.message}`)}return a.result})}},N5=class extends Eb{sendDidRequest(e){return Sb(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}getServerInfo(e){return Sb(this,void 0,void 0,function*(){throw new Error(`not implemented for transports [${this.transportProtocols.join(", ")}]`)})}};g();var IH=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 po.create({options:{publish:!0,gatewayUri:j.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=G=>`${n}/${G}`,a=new yo,s=new Pg,o={keyStore:new lg,identityStore:new fg,didStore:new cg,clear:()=>{o.keyStore._protocolInitializedCache?.clear(),o.identityStore._protocolInitializedCache?.clear(),o.didStore._protocolInitializedCache?.clear()}},{agentVault:d,didApi:l,identityApi:c,keyManager:u,didResolverCache:f,vaultStore:h,permissionsApi:p}=r==="memory"?t.useMemoryStores():t.useDiskStores({testDataLocation:n,stores:o}),m=new _f({blockstoreLocation:i("DWN_DATASTORE")}),y=new Rf({location:i("DWN_STATEINDEX")}),b=new Df,w=new If({location:i("DWN_RESUMABLETASKSTORE")}),S=new Tf({blockstoreLocation:i("DWN_MESSAGESTORE"),indexLocation:i("DWN_MESSAGEINDEX")}),k=await Fl.createDwn({dataPath:n,dataStore:m,didResolver:l,stateIndex:y,eventLog:b,messageStore:S,resumableTaskStore:w}),T=new Fl({dwn:k,localDwnStrategy:"off"}),D=new pge(i("SYNC_STORE")),K=new mg({db:D}),C=new e({agentVault:d,cryptoApi:a,didApi:l,dwnApi:T,identityApi:c,keyManager:u,permissionsApi:p,rpcClient:s,syncApi:K});return new t({agent:C,agentStores:r,didResolverCache:f,dwn:k,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 Im({location:i("VAULT_STORE")}),s=new Rh({keyDerivationWorkFactor:1,store:a}),{didStore:o,identityStore:d,keyStore:l}=n,c=new Cf({location:i("DID_RESOLVERCACHE")}),u=new _h({agent:e,didMethods:[po,ho],resolverCache:c,store:o}),f=new Ch({agent:e,store:d}),h=new go({agent:e,keyStore:l}),p=new Ka({agent:e});return{agentVault:s,didApi:u,didResolverCache:c,identityApi:f,keyManager:h,permissionsApi:p,vaultStore:a}}static useMemoryStores({agent:e}={}){let r=new bu,n=new Rh({keyDerivationWorkFactor:1,store:r}),i=new dE,a=new _h({agent:e,didMethods:[po,ho],resolverCache:i,store:new dg}),s=new go({agent:e,keyStore:new ug}),o=new Ch({agent:e,store:new pg}),d=new Ka({agent:e});return{agentVault:n,didApi:a,didResolverCache:i,identityApi:o,keyManager:s,permissionsApi:d,vaultStore:r}}};g();Jo();Er();wn();Yn();function hge({baseURL:t,endpoint:e,authParam:r,tokenParam:n}){switch(e){case"pushedAuthorizationRequest":return hb(t,"par");case"authorize":if(!r)throw new Error("authParam must be provided when building an authorize URL");return hb(t,`authorize/${r}.jwt`);case"callback":return hb(t,"callback");case"token":if(!n)throw new Error("tokenParam must be provided when building a token URL");return hb(t,`token/${n}.jwt`);default:throw new Error(`Unknown connect endpoint: ${e}`)}}async function mge({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 DH({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 ho.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 Fc().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 yge({jwt:t,encryptionKey:e}){let r={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT"},n=gn.randomBytes(24),i=he.object(r).toUint8Array(),a=he.string(t).toUint8Array(),s=await Hc.encryptRaw({data:a,keyBytes:e,nonce:n,additionalData:i}),o=s.subarray(0,-16),d=s.subarray(-16);return[he.object(r).toBase64Url(),"",he.uint8Array(n).toBase64Url(),he.uint8Array(o).toBase64Url(),he.uint8Array(d).toBase64Url()].join(".")}async function RH({jwe:t,encryptionKey:e}){let[r,,n,i,a]=t.split("."),s=he.base64Url(e).toUint8Array(),o=he.base64Url(r).toUint8Array(),d=he.base64Url(n).toUint8Array(),l=he.base64Url(i).toUint8Array(),c=he.base64Url(a).toUint8Array(),u=new Uint8Array([...l,...c]),f=await Hc.decryptRaw({data:u,keyBytes:s,nonce:d,additionalData:o});return he.uint8Array(f).toString()}async function gge(t,e){let r=await t.export(),n=e.verificationMethod?.[0].publicKeyJwk,i=r.privateKeys?.[0];n.alg="EdDSA";let a=await wi.convertPublicKeyToX25519({publicKey:n}),s=await wi.convertPrivateKeyToX25519({privateKey:i}),o=await Gt.sharedSecret({privateKeyA:s,publicKeyB:a});return Om.deriveKeyBytes({baseKeyBytes:new Uint8Array(o),hash:"SHA-256",salt:new Uint8Array,info:new Uint8Array,length:256})}async function wge({jwt:t,encryptionKey:e,delegateDidKeyId:r,pin:n}){let i={alg:"dir",cty:"JWT",enc:"XC20P",typ:"JWT",kid:r},a=gn.randomBytes(24),s=n?{...i,pin:n}:{...i},o=he.object(s).toUint8Array(),d=he.string(t).toUint8Array(),l=await Hc.encryptRaw({data:d,keyBytes:e,nonce:a,additionalData:o}),c=l.subarray(0,-16),u=l.subarray(-16);return[he.object(i).toBase64Url(),"",he.uint8Array(a).toBase64Url(),he.uint8Array(c).toBase64Url(),he.uint8Array(u).toBase64Url()].join(".")}async function vge(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 d=await ho.resolve(o.kid.split("#")[0]),l=await xg.deriveSharedKey(t,d.didDocument),c=r?{...o,pin:r}:{...o},u=he.object(c).toUint8Array(),f=he.base64Url(i).toUint8Array(),h=he.base64Url(a).toUint8Array(),p=he.base64Url(s).toUint8Array(),m=new Uint8Array([...h,...p]),y=await Hc.decryptRaw({data:m,keyBytes:l,nonce:f,additionalData:u});return he.uint8Array(y).toString()}async function bge(t){let e=gn.randomBytes(16),r=gn.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 Pge(t,e){let n=await(await fetch(t,{signal:AbortSignal.timeout(3e4)})).text(),i=await RH({jwe:n,encryptionKey:e});return await DH({jwt:i})}async function xge(t){let e=Math.floor(Date.now()/1e3);return{...t,iat:e,exp:e+600}}function Ege(t){return b5(t)?!0:t.interface===be.Protocols&&t.method===ge.Configure}async function Sge(t,e,r,n){let i=new Ka({agent:r});Rs.log(`Creating permission grants for ${n.length} scopes...`);let a=await Promise.all(n.map(d=>{let l=Ege(d);return i.createGrant({delegated:l,store:!0,grantedTo:e.uri,scope:d,dateExpires:"2040-06-25T16:09:16.693356Z",author:t})})),s=await r.dwn.getDwnEndpointUrlsForTarget(t);Rs.log(`Sending ${a.length} permission grants to ${s.length} DWN endpoint(s)...`);let o=a.map(async d=>{let{encodedData:l,...c}=d.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:c,data:new Blob([u])});p.status.code===202||p.status.code===409?f=!0:Rs.error(`Grant send to ${h} returned ${p.status.code}: ${p.status.detail}`)}catch(p){Rs.error(`Grant send to ${h} failed: ${p.message}`)}if(!f)throw new Error("Could not send permission grant to any DWN endpoint.");return d.message});try{return await Promise.all(o)}catch(d){throw Rs.error(`Error during batch-send of permission grants: ${d}`),d}}async function Age(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){Rs.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{Rs.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 kge(t,e,r,n){let i=await ho.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 Age(t,n,m),xg.createPermissionGrants(t,i,n,y)}),o=(await Promise.all(s)).flat();Rs.log("Building connect response...");let d=await xg.createConnectResponse({providerDid:t,delegateDid:i.uri,aud:e.clientDid,nonce:e.nonce,delegateGrants:o,delegatePortableDid:a});Rs.log("Signing connect response...");let l=await xg.signJwt({did:i,data:d}),c=await ho.resolve(e.clientDid),u=await xg.deriveSharedKey(i,c?.didDocument);Rs.log("Encrypting connect response...");let f=await xg.encryptResponse({jwt:l,encryptionKey:u,delegateDidKeyId:i.document.verificationMethod[0].id,pin:r}),h=new URLSearchParams({id_token:f,state:e.state}).toString();Rs.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 xg={buildConnectUrl:hge,signJwt:mge,verifyJwt:DH,encryptRequest:yge,decryptRequest:RH,encryptResponse:wge,decryptResponse:vge,deriveSharedKey:gge,createConnectRequest:bge,getConnectRequest:Pge,createConnectResponse:xge,createPermissionGrants:Sge,submitConnectResponse:kge};g();Er();Jo();var CH=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:d,identityApi:l,keyManager:c,permissionsApi:u,rpcClient:f,syncApi:h}={}){return a??=new Rh({keyDerivationWorkFactor:21e4,store:new Im({location:`${e}/VAULT_STORE`})}),s??=new yo,o??=new _h({didMethods:[po,ho],resolverCache:new Cf({location:`${e}/DID_RESOLVERCACHE`}),store:new cg}),d||(n?d=new Fl({localDwnEndpoint:n,localDwnStrategy:r??"prefer"}):d=new Fl({dwn:await Fl.createDwn({dataPath:e,didResolver:o}),localDwnStrategy:r??"prefer"})),r&&d.setLocalDwnStrategy(r),l??=new Ch({store:new fg}),c??=new go({keyStore:new lg}),u??=new Ka,f??=new Pg,h??=new mg({dataPath:e}),new t({agentDid:i,agentVault:a,cryptoApi:s,didApi:o,dwnApi:d,keyManager:c,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{yo as AgentCryptoApi,_h as AgentDidApi,Cf as AgentDidResolverCache,Fl as AgentDwnApi,Ch as AgentIdentityApi,Ka as AgentPermissionsApi,CG as AnonymousDwnApi,ig as BearerIdentity,hye as DISCOVERY_DIR,mye as DISCOVERY_FILENAME,YG as DWN_CONNECT_PATH,ZG as DWN_PROTOCOL_SCHEME,uye as DidInterface,ma as DwnConstant,ii as DwnContentEncryptionAlgorithm,$f as DwnDataStore,Kt as DwnDateSort,cg as DwnDidStore,FE as DwnDiscoveryFile,fg as DwnIdentityStore,Re as DwnInterface,Ht as DwnKeyDerivationScheme,lg as DwnKeyStore,Ir as DwnPermissionGrant,cd as DwnPermissionRequest,dt as DwnPermissionsProtocol,xg as EnboxConnectProtocol,CH as EnboxUserAgent,Rh as HdIdentityVault,Bf as InMemoryDataStore,dg as InMemoryDidStore,pg as InMemoryIdentityStore,ug as InMemoryKeyStore,Th as LocalDwnDiscovery,go as LocalKeyManager,IH as PlatformAgentTestHarness,mg as SyncEngineLevel,jG as buildContextKeyDecrypter,FHe as buildDwnConnectUrl,HHe as buildDwnDiscoveryRedirectUrl,Ih as buildEncryptionInput,NG as buildKmsDecryptCallback,hb as concatenateUrl,pye as createNodeDiscoveryFileFs,JG as decodeDwnDiscoveryPayload,KG as deriveContextEncryptionInput,E5 as detectNewParticipants,Id as dwnMessageConstructors,FG as eagerSendContextKeyRecord,vye as encodeDwnDiscoveryPayload,HE as encryptAndComputeCid,qG as ensureKeyDeliveryProtocol,GG as fetchContextKeyRecord,pb as getDwnServiceEndpointUrls,yb as getEncryptionKeyDeriver,zl as getEncryptionKeyInfo,gb as getKeyDecrypter,fGe as getPaginationCursor,lGe as getRecordAuthor,sye as getRecordMessageCid,uGe as getRecordProtocolRole,hHe as getRootContextId,LG as getRuleSetAtPath,P5 as hasRelationalReadAccess,OG as isDidRequest,gye as isDwnMessage,Rd as isDwnRequest,Jye as isIdentityMetadata,wye as isMessagesPermissionScope,x5 as isMultiPartyContext,SWe as isPortableIdentity,b5 as isRecordPermissionScope,v5 as isRecordsType,Ll as isRecordsWrite,GE as ivLength,fye as localDwnServerName,UG as maybeDecryptReply,zE as normalizeBaseUrl,GHe as parseDwnConnectUrl,pGe as pollWithTtl,VHe as readDwnDiscoveryPayloadFromUrl,MG as resolveKeyDecrypter,zG as writeContextKeyRecord};
2061
2061
  /*! Bundled license information:
2062
2062
 
2063
2063
  ieee754/index.js: