solid-logic 4.0.7 → 4.0.8-test.0

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.
Files changed (79) hide show
  1. package/README.md +3 -1
  2. package/dist/2729812e0bfc062ee77a.js +1 -0
  3. package/dist/a9c30b64ceaae48b72f0.js +2045 -0
  4. package/dist/authSession/authSession.d.ts +41 -2
  5. package/dist/authSession/authSession.d.ts.map +1 -1
  6. package/dist/authSession/events.d.ts +24 -0
  7. package/dist/authSession/events.d.ts.map +1 -0
  8. package/dist/authSession/issuer.d.ts +8 -0
  9. package/dist/authSession/issuer.d.ts.map +1 -0
  10. package/dist/authSession/session.d.ts +45 -0
  11. package/dist/authSession/session.d.ts.map +1 -0
  12. package/dist/authn/SolidAuthnLogic.d.ts +15 -6
  13. package/dist/authn/SolidAuthnLogic.d.ts.map +1 -1
  14. package/dist/authn/serverLogout.d.ts +6 -0
  15. package/dist/authn/serverLogout.d.ts.map +1 -0
  16. package/dist/index.d.ts +2 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/logic/solidLogic.d.ts +3 -3
  19. package/dist/logic/solidLogic.d.ts.map +1 -1
  20. package/dist/logic/solidLogicSingleton.d.ts.map +1 -1
  21. package/dist/solid-logic.esm.js +492 -9622
  22. package/dist/solid-logic.esm.js.map +1 -1
  23. package/dist/solid-logic.esm.min.js +1 -1
  24. package/dist/solid-logic.esm.min.js.map +1 -1
  25. package/dist/solid-logic.js +4082 -8082
  26. package/dist/solid-logic.js.map +1 -1
  27. package/dist/solid-logic.min.js +1 -1
  28. package/dist/solid-logic.min.js.map +1 -1
  29. package/dist/types.d.ts +2 -2
  30. package/dist/types.d.ts.map +1 -1
  31. package/package.json +11 -9
  32. package/dist/acl/aclLogic.js +0 -117
  33. package/dist/acl/aclLogic.js.map +0 -1
  34. package/dist/authSession/authSession.js +0 -3
  35. package/dist/authSession/authSession.js.map +0 -1
  36. package/dist/authn/SolidAuthnLogic.js +0 -109
  37. package/dist/authn/SolidAuthnLogic.js.map +0 -1
  38. package/dist/authn/authUtil.js +0 -64
  39. package/dist/authn/authUtil.js.map +0 -1
  40. package/dist/chat/chatLogic.js +0 -157
  41. package/dist/chat/chatLogic.js.map +0 -1
  42. package/dist/inbox/inboxLogic.js +0 -51
  43. package/dist/inbox/inboxLogic.js.map +0 -1
  44. package/dist/index.js +0 -14
  45. package/dist/index.js.map +0 -1
  46. package/dist/issuer/issuerLogic.js +0 -37
  47. package/dist/issuer/issuerLogic.js.map +0 -1
  48. package/dist/logic/CustomError.js +0 -27
  49. package/dist/logic/CustomError.js.map +0 -1
  50. package/dist/logic/solidLogic.js +0 -64
  51. package/dist/logic/solidLogic.js.map +0 -1
  52. package/dist/logic/solidLogicSingleton.js +0 -31
  53. package/dist/logic/solidLogicSingleton.js.map +0 -1
  54. package/dist/profile/profileAclDocuments.js +0 -13
  55. package/dist/profile/profileAclDocuments.js.map +0 -1
  56. package/dist/profile/profileDocuments.js +0 -11
  57. package/dist/profile/profileDocuments.js.map +0 -1
  58. package/dist/profile/profileLogic.js +0 -344
  59. package/dist/profile/profileLogic.js.map +0 -1
  60. package/dist/typeIndex/typeIndexAclDocuments.js +0 -31
  61. package/dist/typeIndex/typeIndexAclDocuments.js.map +0 -1
  62. package/dist/typeIndex/typeIndexDocuments.js +0 -17
  63. package/dist/typeIndex/typeIndexDocuments.js.map +0 -1
  64. package/dist/typeIndex/typeIndexLogic.js +0 -248
  65. package/dist/typeIndex/typeIndexLogic.js.map +0 -1
  66. package/dist/types.js +0 -2
  67. package/dist/types.js.map +0 -1
  68. package/dist/util/containerLogic.js +0 -49
  69. package/dist/util/containerLogic.js.map +0 -1
  70. package/dist/util/debug.js +0 -13
  71. package/dist/util/debug.js.map +0 -1
  72. package/dist/util/ns.js +0 -5
  73. package/dist/util/ns.js.map +0 -1
  74. package/dist/util/utilityLogic.js +0 -201
  75. package/dist/util/utilityLogic.js.map +0 -1
  76. package/dist/util/utils.js +0 -39
  77. package/dist/util/utils.js.map +0 -1
  78. package/dist/versionInfo.js +0 -36
  79. package/dist/versionInfo.js.map +0 -1
package/README.md CHANGED
@@ -29,7 +29,9 @@ console.log('Current user:', authn.currentUser());
29
29
 
30
30
  ## 🌐 Use directly in a browser
31
31
 
32
- Both UMD and ESM bundles externalize rdflib to keep bundle sizes small and avoid version conflicts.
32
+ The UMD bundles externalize `rdflib` only.
33
+
34
+ The ESM bundles externalize both `rdflib` and the auth library packages `@uvdsl/solid-oidc-client-browser` / `@uvdsl/solid-oidc-client-browser/core`.
33
35
 
34
36
  ## Available Files
35
37
 
@@ -0,0 +1 @@
1
+ var crypto$1=crypto;const isCryptoKey=e=>e instanceof CryptoKey,digest=async(e,t)=>{const r=`SHA-${e.slice(-3)}`;return new Uint8Array(await crypto$1.subtle.digest(r,t))};var digest$1=digest;const encoder=new TextEncoder,decoder=new TextDecoder;function concat(...e){const t=e.reduce((e,{length:t})=>e+t,0),r=new Uint8Array(t);let a=0;for(const t of e)r.set(t,a),a+=t.length;return r}const encodeBase64=e=>{let t=e;"string"==typeof t&&(t=encoder.encode(t));const r=[];for(let e=0;e<t.length;e+=32768)r.push(String.fromCharCode.apply(null,t.subarray(e,e+32768)));return btoa(r.join(""))},encode=e=>encodeBase64(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),decodeBase64=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r},decode$1=e=>{let t=e;t instanceof Uint8Array&&(t=decoder.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return decodeBase64(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class JOSEError extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}JOSEError.code="ERR_JOSE_GENERIC";class JWTClaimValidationFailed extends JOSEError{constructor(e,t,r="unspecified",a="unspecified"){super(e,{cause:{claim:r,reason:a,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=a,this.payload=t}}JWTClaimValidationFailed.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class JWTExpired extends JOSEError{constructor(e,t,r="unspecified",a="unspecified"){super(e,{cause:{claim:r,reason:a,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=a,this.payload=t}}JWTExpired.code="ERR_JWT_EXPIRED";class JOSEAlgNotAllowed extends JOSEError{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}JOSEAlgNotAllowed.code="ERR_JOSE_ALG_NOT_ALLOWED";class JOSENotSupported extends JOSEError{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}JOSENotSupported.code="ERR_JOSE_NOT_SUPPORTED";class JWEDecryptionFailed extends JOSEError{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}JWEDecryptionFailed.code="ERR_JWE_DECRYPTION_FAILED";class JWEInvalid extends JOSEError{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}JWEInvalid.code="ERR_JWE_INVALID";class JWSInvalid extends JOSEError{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}JWSInvalid.code="ERR_JWS_INVALID";class JWTInvalid extends JOSEError{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}JWTInvalid.code="ERR_JWT_INVALID";class JWKInvalid extends JOSEError{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}JWKInvalid.code="ERR_JWK_INVALID";class JWKSInvalid extends JOSEError{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}JWKSInvalid.code="ERR_JWKS_INVALID";class JWKSNoMatchingKey extends JOSEError{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}JWKSNoMatchingKey.code="ERR_JWKS_NO_MATCHING_KEY";class JWKSMultipleMatchingKeys extends JOSEError{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}JWKSMultipleMatchingKeys.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class JWKSTimeout extends JOSEError{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}JWKSTimeout.code="ERR_JWKS_TIMEOUT";class JWSSignatureVerificationFailed extends JOSEError{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function unusable(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function isAlgorithm(e,t){return e.name===t}function getHashLength(e){return parseInt(e.name.slice(4),10)}function getNamedCurve(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function checkUsage(e,t){if(t.length&&!t.some(t=>e.usages.includes(t))){let e="CryptoKey does not support this operation, its usages must include ";if(t.length>2){const r=t.pop();e+=`one of ${t.join(", ")}, or ${r}.`}else 2===t.length?e+=`one of ${t[0]} or ${t[1]}.`:e+=`${t[0]}.`;throw new TypeError(e)}}function checkSigCryptoKey(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!isAlgorithm(e.algorithm,"HMAC"))throw unusable("HMAC");const r=parseInt(t.slice(2),10);if(getHashLength(e.algorithm.hash)!==r)throw unusable(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!isAlgorithm(e.algorithm,"RSASSA-PKCS1-v1_5"))throw unusable("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(getHashLength(e.algorithm.hash)!==r)throw unusable(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!isAlgorithm(e.algorithm,"RSA-PSS"))throw unusable("RSA-PSS");const r=parseInt(t.slice(2),10);if(getHashLength(e.algorithm.hash)!==r)throw unusable(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw unusable("Ed25519 or Ed448");break;case"Ed25519":if(!isAlgorithm(e.algorithm,"Ed25519"))throw unusable("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!isAlgorithm(e.algorithm,"ECDSA"))throw unusable("ECDSA");const r=getNamedCurve(t);if(e.algorithm.namedCurve!==r)throw unusable(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}checkUsage(e,r)}function message(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else 2===r.length?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return null==t?e+=` Received ${t}`:"function"==typeof t&&t.name?e+=` Received function ${t.name}`:"object"==typeof t&&null!=t&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}JWSSignatureVerificationFailed.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";var invalidKeyInput=(e,...t)=>message("Key must be ",e,...t);function withAlg(e,t,...r){return message(`Key for the ${e} algorithm must be `,t,...r)}var isKeyLike=e=>!!isCryptoKey(e)||"KeyObject"===e?.[Symbol.toStringTag];const types=["CryptoKey"],isDisjoint=(...e)=>{const t=e.filter(Boolean);if(0===t.length||1===t.length)return!0;let r;for(const e of t){const t=Object.keys(e);if(r&&0!==r.size)for(const e of t){if(r.has(e))return!1;r.add(e)}else r=new Set(t)}return!0};var isDisjoint$1=isDisjoint;function isObjectLike(e){return"object"==typeof e&&null!==e}function isObject(e){if(!isObjectLike(e)||"[object Object]"!==Object.prototype.toString.call(e))return!1;if(null===Object.getPrototypeOf(e))return!0;let t=e;for(;null!==Object.getPrototypeOf(t);)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var checkKeyLength=(e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){const{modulusLength:r}=t.algorithm;if("number"!=typeof r||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}};function isJWK(e){return isObject(e)&&"string"==typeof e.kty}function isPrivateJWK(e){return"oct"!==e.kty&&"string"==typeof e.d}function isPublicJWK(e){return"oct"!==e.kty&&void 0===e.d}function isSecretJWK(e){return isJWK(e)&&"oct"===e.kty&&"string"==typeof e.k}function subtleMapping(e){let t,r;switch(e.kty){case"RSA":switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"EC":switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;case"OKP":switch(e.alg){case"Ed25519":t={name:"Ed25519"},r=e.d?["sign"]:["verify"];break;case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}const parse=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=subtleMapping(e),a=[t,e.ext??!1,e.key_ops??r],o={...e};return delete o.alg,delete o.use,crypto$1.subtle.importKey("jwk",o,...a)};var asKeyObject=parse;const exportKeyValue=e=>decode$1(e);let privCache,pubCache;const isKeyObject=e=>"KeyObject"===e?.[Symbol.toStringTag],importAndCache=async(e,t,r,a,o=!1)=>{let s=e.get(t);if(s?.[a])return s[a];const i=await asKeyObject({...r,alg:a});return o&&Object.freeze(t),s?s[a]=i:e.set(t,{[a]:i}),i},normalizePublicKey=(e,t)=>{if(isKeyObject(e)){let r=e.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?exportKeyValue(r.k):(pubCache||(pubCache=new WeakMap),importAndCache(pubCache,e,r,t))}if(isJWK(e)){if(e.k)return decode$1(e.k);pubCache||(pubCache=new WeakMap);return importAndCache(pubCache,e,e,t,!0)}return e},normalizePrivateKey=(e,t)=>{if(isKeyObject(e)){let r=e.export({format:"jwk"});return r.k?exportKeyValue(r.k):(privCache||(privCache=new WeakMap),importAndCache(privCache,e,r,t))}if(isJWK(e)){if(e.k)return decode$1(e.k);privCache||(privCache=new WeakMap);return importAndCache(privCache,e,e,t,!0)}return e};var normalize={normalizePublicKey,normalizePrivateKey};async function importJWK(e,t){if(!isObject(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if("string"!=typeof e.k||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return decode$1(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return asKeyObject({...e,alg:t});default:throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value')}}const tag=e=>e?.[Symbol.toStringTag],jwkMatchesOp=(e,t,r)=>{if(void 0!==t.use&&"sig"!==t.use)throw new TypeError("Invalid key for this operation, when present its use must be sig");if(void 0!==t.key_ops&&!0!==t.key_ops.includes?.(r))throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(void 0!==t.alg&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},symmetricTypeCheck=(e,t,r,a)=>{if(!(t instanceof Uint8Array)){if(a&&isJWK(t)){if(isSecretJWK(t)&&jwkMatchesOp(e,t,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!isKeyLike(t))throw new TypeError(withAlg(e,t,...types,"Uint8Array",a?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${tag(t)} instances for symmetric algorithms must be of type "secret"`)}},asymmetricTypeCheck=(e,t,r,a)=>{if(a&&isJWK(t))switch(r){case"sign":if(isPrivateJWK(t)&&jwkMatchesOp(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(isPublicJWK(t)&&jwkMatchesOp(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!isKeyLike(t))throw new TypeError(withAlg(e,t,...types,a?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${tag(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${tag(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${tag(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${tag(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${tag(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function checkKeyType(e,t,r,a){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?symmetricTypeCheck(t,r,a,e):asymmetricTypeCheck(t,r,a,e)}checkKeyType.bind(void 0,!1);const checkKeyTypeWithJwk=checkKeyType.bind(void 0,!0);function validateCrit(e,t,r,a,o){if(void 0!==o.crit&&void 0===a?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!a||void 0===a.crit)return new Set;if(!Array.isArray(a.crit)||0===a.crit.length||a.crit.some(e=>"string"!=typeof e||0===e.length))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;s=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of a.crit){if(!s.has(t))throw new JOSENotSupported(`Extension Header Parameter "${t}" is not recognized`);if(void 0===o[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(s.get(t)&&void 0===a[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(a.crit)}const validateAlgorithms=(e,t)=>{if(void 0!==t&&(!Array.isArray(t)||t.some(e=>"string"!=typeof e)))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)};var validateAlgorithms$1=validateAlgorithms;const keyToJWK=async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:encode(e)};if(!isCryptoKey(e))throw new TypeError(invalidKeyInput(e,...types,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");const{ext:t,key_ops:r,alg:a,use:o,...s}=await crypto$1.subtle.exportKey("jwk",e);return s};var keyToJWK$1=keyToJWK;async function exportJWK(e){return keyToJWK$1(e)}function subtleDsa(e,t){const r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:t.name};default:throw new JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function getCryptoKey(e,t,r){if("sign"===r&&(t=await normalize.normalizePrivateKey(t,e)),"verify"===r&&(t=await normalize.normalizePublicKey(t,e)),isCryptoKey(t))return checkSigCryptoKey(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(invalidKeyInput(t,...types));return crypto$1.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(invalidKeyInput(t,...types,"Uint8Array","JSON Web Key"))}const verify=async(e,t,r,a)=>{const o=await getCryptoKey(e,t,"verify");checkKeyLength(e,o);const s=subtleDsa(e,o.algorithm);try{return await crypto$1.subtle.verify(s,o,r,a)}catch{return!1}};var verify$1=verify;async function flattenedVerify(e,t,r){if(!isObject(e))throw new JWSInvalid("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new JWSInvalid("JWS Protected Header incorrect type");if(void 0===e.payload)throw new JWSInvalid("JWS Payload missing");if("string"!=typeof e.signature)throw new JWSInvalid("JWS Signature missing or incorrect type");if(void 0!==e.header&&!isObject(e.header))throw new JWSInvalid("JWS Unprotected Header incorrect type");let a={};if(e.protected)try{const t=decode$1(e.protected);a=JSON.parse(decoder.decode(t))}catch{throw new JWSInvalid("JWS Protected Header is invalid")}if(!isDisjoint$1(a,e.header))throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const o={...a,...e.header};let s=!0;if(validateCrit(JWSInvalid,new Map([["b64",!0]]),r?.crit,a,o).has("b64")&&(s=a.b64,"boolean"!=typeof s))throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:i}=o;if("string"!=typeof i||!i)throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');const n=r&&validateAlgorithms$1("algorithms",r.algorithms);if(n&&!n.has(i))throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');if(s){if("string"!=typeof e.payload)throw new JWSInvalid("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");let c=!1;"function"==typeof t?(t=await t(a,e),c=!0,checkKeyTypeWithJwk(i,t,"verify"),isJWK(t)&&(t=await importJWK(t,i))):checkKeyTypeWithJwk(i,t,"verify");const d=concat(encoder.encode(e.protected??""),encoder.encode("."),"string"==typeof e.payload?encoder.encode(e.payload):e.payload);let l;try{l=decode$1(e.signature)}catch{throw new JWSInvalid("Failed to base64url decode the signature")}if(!await verify$1(i,t,l,d))throw new JWSSignatureVerificationFailed;let h;if(s)try{h=decode$1(e.payload)}catch{throw new JWSInvalid("Failed to base64url decode the payload")}else h="string"==typeof e.payload?encoder.encode(e.payload):e.payload;const p={payload:h};return void 0!==e.protected&&(p.protectedHeader=a),void 0!==e.header&&(p.unprotectedHeader=e.header),c?{...p,key:t}:p}async function compactVerify(e,t,r){if(e instanceof Uint8Array&&(e=decoder.decode(e)),"string"!=typeof e)throw new JWSInvalid("Compact JWS must be a string or Uint8Array");const{0:a,1:o,2:s,length:i}=e.split(".");if(3!==i)throw new JWSInvalid("Invalid Compact JWS");const n=await flattenedVerify({payload:o,protected:a,signature:s},t,r),c={payload:n.payload,protectedHeader:n.protectedHeader};return"function"==typeof t?{...c,key:n.key}:c}var epoch=e=>Math.floor(e.getTime()/1e3);const minute=60,hour=3600,day=86400,week=7*day,year=31557600,REGEX=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;var secs=e=>{const t=REGEX.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let a;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":a=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":a=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":a=Math.round(3600*r);break;case"day":case"days":case"d":a=Math.round(r*day);break;case"week":case"weeks":case"w":a=Math.round(r*week);break;default:a=Math.round(r*year)}return"-"===t[1]||"ago"===t[4]?-a:a};const normalizeTyp=e=>e.toLowerCase().replace(/^application\//,""),checkAudiencePresence=(e,t)=>"string"==typeof e?t.includes(e):!!Array.isArray(e)&&t.some(Set.prototype.has.bind(new Set(e)));var jwtPayload=(e,t,r={})=>{let a;try{a=JSON.parse(decoder.decode(t))}catch{}if(!isObject(a))throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");const{typ:o}=r;if(o&&("string"!=typeof e.typ||normalizeTyp(e.typ)!==normalizeTyp(o)))throw new JWTClaimValidationFailed('unexpected "typ" JWT header value',a,"typ","check_failed");const{requiredClaims:s=[],issuer:i,subject:n,audience:c,maxTokenAge:d}=r,l=[...s];void 0!==d&&l.push("iat"),void 0!==c&&l.push("aud"),void 0!==n&&l.push("sub"),void 0!==i&&l.push("iss");for(const e of new Set(l.reverse()))if(!(e in a))throw new JWTClaimValidationFailed(`missing required "${e}" claim`,a,e,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(a.iss))throw new JWTClaimValidationFailed('unexpected "iss" claim value',a,"iss","check_failed");if(n&&a.sub!==n)throw new JWTClaimValidationFailed('unexpected "sub" claim value',a,"sub","check_failed");if(c&&!checkAudiencePresence(a.aud,"string"==typeof c?[c]:c))throw new JWTClaimValidationFailed('unexpected "aud" claim value',a,"aud","check_failed");let h;switch(typeof r.clockTolerance){case"string":h=secs(r.clockTolerance);break;case"number":h=r.clockTolerance;break;case"undefined":h=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:p}=r,u=epoch(p||new Date);if((void 0!==a.iat||d)&&"number"!=typeof a.iat)throw new JWTClaimValidationFailed('"iat" claim must be a number',a,"iat","invalid");if(void 0!==a.nbf){if("number"!=typeof a.nbf)throw new JWTClaimValidationFailed('"nbf" claim must be a number',a,"nbf","invalid");if(a.nbf>u+h)throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed',a,"nbf","check_failed")}if(void 0!==a.exp){if("number"!=typeof a.exp)throw new JWTClaimValidationFailed('"exp" claim must be a number',a,"exp","invalid");if(a.exp<=u-h)throw new JWTExpired('"exp" claim timestamp check failed',a,"exp","check_failed")}if(d){const e=u-a.iat;if(e-h>("number"==typeof d?d:secs(d)))throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)',a,"iat","check_failed");if(e<0-h)throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)',a,"iat","check_failed")}return a};async function jwtVerify(e,t,r){const a=await compactVerify(e,t,r);if(a.protectedHeader.crit?.includes("b64")&&!1===a.protectedHeader.b64)throw new JWTInvalid("JWTs MUST NOT use unencoded payload");const o={payload:jwtPayload(a.protectedHeader,a.payload,r),protectedHeader:a.protectedHeader};return"function"==typeof t?{...o,key:a.key}:o}const sign=async(e,t,r)=>{const a=await getCryptoKey(e,t,"sign");checkKeyLength(e,a);const o=await crypto$1.subtle.sign(subtleDsa(e,a.algorithm),a,r);return new Uint8Array(o)};var sign$1=sign;class FlattenedSign{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,t){if(!this._protectedHeader&&!this._unprotectedHeader)throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!isDisjoint$1(this._protectedHeader,this._unprotectedHeader))throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let a=!0;if(validateCrit(JWSInvalid,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(a=this._protectedHeader.b64,"boolean"!=typeof a))throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:o}=r;if("string"!=typeof o||!o)throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');checkKeyTypeWithJwk(o,e,"sign");let s,i=this._payload;a&&(i=encoder.encode(encode(i))),s=this._protectedHeader?encoder.encode(encode(JSON.stringify(this._protectedHeader))):encoder.encode("");const n=concat(s,encoder.encode("."),i),c=await sign$1(o,e,n),d={signature:encode(c),payload:""};return a&&(d.payload=decoder.decode(i)),this._unprotectedHeader&&(d.header=this._unprotectedHeader),this._protectedHeader&&(d.protected=decoder.decode(s)),d}}class CompactSign{constructor(e){this._flattened=new FlattenedSign(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,t){const r=await this._flattened.sign(e,t);if(void 0===r.payload)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}}function validateInput(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class ProduceJWT{constructor(e={}){if(!isObject(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return"number"==typeof e?this._payload={...this._payload,nbf:validateInput("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:validateInput("setNotBefore",epoch(e))}:this._payload={...this._payload,nbf:epoch(new Date)+secs(e)},this}setExpirationTime(e){return"number"==typeof e?this._payload={...this._payload,exp:validateInput("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:validateInput("setExpirationTime",epoch(e))}:this._payload={...this._payload,exp:epoch(new Date)+secs(e)},this}setIssuedAt(e){return void 0===e?this._payload={...this._payload,iat:epoch(new Date)}:e instanceof Date?this._payload={...this._payload,iat:validateInput("setIssuedAt",epoch(e))}:this._payload="string"==typeof e?{...this._payload,iat:validateInput("setIssuedAt",epoch(new Date)+secs(e))}:{...this._payload,iat:validateInput("setIssuedAt",e)},this}}class SignJWT extends ProduceJWT{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new CompactSign(encoder.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&!1===this._protectedHeader.b64)throw new JWTInvalid("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}const check=(e,t)=>{if("string"!=typeof e||!e)throw new JWKInvalid(`${t} missing or invalid`)};async function calculateJwkThumbprint(e,t){if(!isObject(e))throw new TypeError("JWK must be an object");if(t??(t="sha256"),"sha256"!==t&&"sha384"!==t&&"sha512"!==t)throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":check(e.crv,'"crv" (Curve) Parameter'),check(e.x,'"x" (X Coordinate) Parameter'),check(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":check(e.crv,'"crv" (Subtype of Key Pair) Parameter'),check(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":check(e.e,'"e" (Exponent) Parameter'),check(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":check(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported')}const a=encoder.encode(JSON.stringify(r));return encode(await digest$1(t,a))}function getKtyFromAlg(e){switch("string"==typeof e&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set')}}function isJWKSLike(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(isJWKLike)}function isJWKLike(e){return isObject(e)}function clone(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}class LocalJWKSet{constructor(e){if(this._cached=new WeakMap,!isJWKSLike(e))throw new JWKSInvalid("JSON Web Key Set malformed");this._jwks=clone(e)}async getKey(e,t){const{alg:r,kid:a}={...e,...t?.header},o=getKtyFromAlg(r),s=this._jwks.keys.filter(e=>{let t=o===e.kty;if(t&&"string"==typeof a&&(t=a===e.kid),t&&"string"==typeof e.alg&&(t=r===e.alg),t&&"string"==typeof e.use&&(t="sig"===e.use),t&&Array.isArray(e.key_ops)&&(t=e.key_ops.includes("verify")),t)switch(r){case"ES256":t="P-256"===e.crv;break;case"ES256K":t="secp256k1"===e.crv;break;case"ES384":t="P-384"===e.crv;break;case"ES512":t="P-521"===e.crv;break;case"Ed25519":t="Ed25519"===e.crv;break;case"EdDSA":t="Ed25519"===e.crv||"Ed448"===e.crv}return t}),{0:i,length:n}=s;if(0===n)throw new JWKSNoMatchingKey;if(1!==n){const e=new JWKSMultipleMatchingKeys,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of s)try{yield await importWithAlgCache(t,e,r)}catch{}},e}return importWithAlgCache(this._cached,i,r)}}async function importWithAlgCache(e,t,r){const a=e.get(t)||e.set(t,{}).get(t);if(void 0===a[r]){const e=await importJWK({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new JWKSInvalid("JSON Web Key Set members must be public keys");a[r]=e}return a[r]}function createLocalJWKSet(e){const t=new LocalJWKSet(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>clone(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}const fetchJwks=async(e,t,r)=>{let a,o,s=!1;"function"==typeof AbortController&&(a=new AbortController,o=setTimeout(()=>{s=!0,a.abort()},t));const i=await fetch(e.href,{signal:a?a.signal:void 0,redirect:"manual",headers:r.headers}).catch(e=>{if(s)throw new JWKSTimeout;throw e});if(void 0!==o&&clearTimeout(o),200!==i.status)throw new JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON")}};var fetchJwks$1=fetchJwks;function isCloudflareWorkers(){return"undefined"!=typeof WebSocketPair||"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"undefined"!=typeof EdgeRuntime&&"vercel"===EdgeRuntime}let USER_AGENT;if("undefined"==typeof navigator||!navigator.userAgent?.startsWith?.("Mozilla/5.0 ")){USER_AGENT=`${"jose"}/${"v5.10.0"}`}const jwksCache=Symbol();function isFreshJwksCache(e,t){return"object"==typeof e&&null!==e&&("uat"in e&&"number"==typeof e.uat&&!(Date.now()-e.uat>=t)&&!!("jwks"in e&&isObject(e.jwks)&&Array.isArray(e.jwks.keys)&&Array.prototype.every.call(e.jwks.keys,isObject)))}class RemoteJWKSet{constructor(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:t?.agent,headers:t?.headers},this._timeoutDuration="number"==typeof t?.timeoutDuration?t?.timeoutDuration:5e3,this._cooldownDuration="number"==typeof t?.cooldownDuration?t?.cooldownDuration:3e4,this._cacheMaxAge="number"==typeof t?.cacheMaxAge?t?.cacheMaxAge:6e5,void 0!==t?.[jwksCache]&&(this._cache=t?.[jwksCache],isFreshJwksCache(t?.[jwksCache],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=createLocalJWKSet(this._cache.jwks)))}coolingDown(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cooldownDuration}fresh(){return"number"==typeof this._jwksTimestamp&&Date.now()<this._jwksTimestamp+this._cacheMaxAge}async getKey(e,t){this._local&&this.fresh()||await this.reload();try{return await this._local(e,t)}catch(r){if(r instanceof JWKSNoMatchingKey&&!1===this.coolingDown())return await this.reload(),this._local(e,t);throw r}}async reload(){this._pendingFetch&&isCloudflareWorkers()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);USER_AGENT&&!e.has("User-Agent")&&(e.set("User-Agent",USER_AGENT),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=fetchJwks$1(this._url,this._timeoutDuration,this._options).then(e=>{this._local=createLocalJWKSet(e),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=e),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(e=>{throw this._pendingFetch=void 0,e})),await this._pendingFetch}}function createRemoteJWKSet(e,t){const r=new RemoteJWKSet(e,t),a=async(e,t)=>r.getKey(e,t);return Object.defineProperties(a,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>r._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),a}const decode=decode$1;function decodeJwt(e){if("string"!=typeof e)throw new JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(5===r)throw new JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");if(3!==r)throw new JWTInvalid("Invalid JWT");if(!t)throw new JWTInvalid("JWTs must contain a payload");let a,o;try{a=decode(t)}catch{throw new JWTInvalid("Failed to base64url decode the payload")}try{o=JSON.parse(decoder.decode(a))}catch{throw new JWTInvalid("Failed to parse the decoded payload as JSON")}if(!isObject(o))throw new JWTInvalid("Invalid JWT Claims Set");return o}const renewTokens=async e=>{try{await e.init();const t=await e.getItem("client_id"),r=await e.getItem("token_endpoint"),a=await e.getItem("dpop_keypair"),o=await e.getItem("refresh_token");if(null===t||null===r||null===a||null===o)throw new Error("Could not refresh tokens: details missing from database.");const s=await requestFreshTokens(o,t,r,a).then(e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}),i=s.access_token,n=await e.getItem("idp");if(null===n)throw new Error("Access Token validation preparation - Could not find in sessionDatabase: idp");const c=await e.getItem("jwks_uri");if(null===c)throw new Error("Access Token validation preparation - Could not find in sessionDatabase: jwks_uri");const d=createRemoteJWKSet(new URL(c)),{payload:l}=await jwtVerify(i,d,{issuer:n,audience:"solid"}),h=await calculateJwkThumbprint(await exportJWK(a.publicKey));if(l.cnf.jkt!==h)throw new Error("Access Token validation failed on `jkt`: jkt !== DPoP thumbprint - "+l.cnf.jkt+" !== "+h);if(l.client_id!==t)throw new Error("Access Token validation failed on `client_id`: JWT payload !== client_id - "+l.client_id+" !== "+t);return await e.setItem("refresh_token",s.refresh_token),{...s,dpop_key_pair:a}}finally{e.close()}},requestFreshTokens=async(e,t,r,a)=>{const o=await exportJWK(a.publicKey);o.alg="ES256";const s=await new SignJWT({htu:r,htm:"POST"}).setIssuedAt().setJti(self.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:o}).sign(a.privateKey);return fetch(r,{method:"POST",headers:{dpop:s,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:t})})};class SessionIDB{dbName;storeName;dbVersion;db=null;constructor(e="soidc",t="session",r=1){this.dbName=e,this.storeName=t,this.dbVersion=r}async init(){return new Promise((e,t)=>{const r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=e=>{t(new Error(`Database error: ${e.target.error}`))},r.onsuccess=t=>{this.db=t.target.result,e(this)},r.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(this.storeName)||t.createObjectStore(this.storeName)}})}async setItem(e,t){return this.db||await this.init(),new Promise((r,a)=>{const o=this.db.transaction(this.storeName,"readwrite");o.oncomplete=()=>{r()},o.onerror=t=>{a(new Error(`Transaction error for setItem(${e},...): ${t.target.error}`))},o.onabort=t=>{a(new Error(`Transaction aborted for setItem(${e},...): ${t.target.error}`))};o.objectStore(this.storeName).put(t,e)})}async getItem(e){return this.db||await this.init(),new Promise((t,r)=>{const a=this.db.transaction(this.storeName,"readonly");a.onerror=t=>{r(new Error(`Transaction error for getItem(${e}): ${t.target.error}`))},a.onabort=t=>{r(new Error(`Transaction aborted for getItem(${e}): ${t.target.error}`))};const o=a.objectStore(this.storeName).get(e);o.onsuccess=()=>{t(o.result||null)}})}async deleteItem(e){return this.db||await this.init(),new Promise((t,r)=>{const a=this.db.transaction(this.storeName,"readwrite");a.oncomplete=()=>{t()},a.onerror=t=>{r(new Error(`Transaction error for deleteItem(${e}): ${t.target.error}`))},a.onabort=t=>{r(new Error(`Transaction aborted for deleteItem(${e}): ${t.target.error}`))};a.objectStore(this.storeName).delete(e)})}async clear(){return this.db||await this.init(),new Promise((e,t)=>{const r=this.db.transaction(this.storeName,"readwrite");r.oncomplete=()=>{e()},r.onerror=e=>{t(new Error(`Transaction error for clear(): ${e.target.error}`))},r.onabort=e=>{t(new Error(`Transaction aborted for clear(): ${e.target.error}`))};r.objectStore(this.storeName).clear()})}close(){this.db&&(this.db.close(),this.db=null)}}var RefreshMessageTypes;!function(e){e.SCHEDULE="SCHEDULE",e.REFRESH="REFRESH",e.STOP="STOP",e.DISCONNECT="DISCONNECT",e.TOKEN_DETAILS="TOKEN_DETAILS",e.ERROR_ON_REFRESH="ERROR_ON_REFRESH",e.EXPIRED="EXPIRED"}(RefreshMessageTypes||(RefreshMessageTypes={}));const ports=new Set,broadcast=e=>{for(const t of ports)t.postMessage(e)};let refresher;self.onconnect=e=>{const t=e.ports[0];ports.add(t),refresher||(refresher=new Refresher(broadcast,new SessionIDB)),t.onmessage=e=>{const{type:r,payload:a}=e.data;switch(r){case RefreshMessageTypes.SCHEDULE:refresher.handleSchedule(a);break;case RefreshMessageTypes.REFRESH:refresher.handleRefresh(t);break;case RefreshMessageTypes.STOP:refresher.handleStop();break;case RefreshMessageTypes.DISCONNECT:ports.delete(t)}},t.onmessageerror=()=>ports.delete(t),t.start()};class Refresher{tokenDetails;exp;refreshTimeout;finalLogoutTimeout;timersAreRunning=!1;broadcast;database;refreshPromise;constructor(e,t){this.broadcast=e,this.database=t}async handleSchedule(e){this.tokenDetails=e,this.exp=decodeJwt(this.tokenDetails.access_token).exp,this.broadcast({type:RefreshMessageTypes.TOKEN_DETAILS,payload:{tokenDetails:this.tokenDetails}}),console.log(`[RefreshWorker] Scheduling timers, expiry in ${this.tokenDetails.expires_in}s`),this.scheduleTimers(this.tokenDetails.expires_in),this.timersAreRunning=!0}async handleRefresh(e){this.tokenDetails&&this.exp&&!this.isTokenExpired(this.exp)?(console.log("[RefreshWorker] Providing current tokens"),e.postMessage({type:RefreshMessageTypes.TOKEN_DETAILS,payload:{tokenDetails:this.tokenDetails}})):(console.log("[RefreshWorker] Refreshing tokens"),this.performRefresh())}handleStop(){this.tokenDetails?(this.broadcast({type:RefreshMessageTypes.EXPIRED}),this.tokenDetails=void 0,this.exp=void 0,this.refreshPromise=void 0,console.log("[RefreshWorker] Received STOP, clearing timers"),this.clearAllTimers()):console.log("[RefreshWorker] Received STOP, being idle")}async performRefresh(){return this.refreshPromise?(console.log("[RefreshWorker] Refresh already in progress, waiting..."),this.refreshPromise):(this.refreshPromise=this.doRefresh(),this.refreshPromise)}async doRefresh(){try{this.tokenDetails=await renewTokens(this.database),this.exp=decodeJwt(this.tokenDetails.access_token).exp,this.broadcast({type:RefreshMessageTypes.TOKEN_DETAILS,payload:{tokenDetails:this.tokenDetails}}),console.log("[RefreshWorker] Token refreshed"),console.log(`[RefreshWorker] Scheduling timers, expiry in ${this.tokenDetails.expires_in}s`),this.scheduleTimers(this.tokenDetails.expires_in)}catch(e){this.broadcast({type:RefreshMessageTypes.ERROR_ON_REFRESH,error:e.message}),console.log("[RefreshWorker]",e.message)}finally{this.refreshPromise=void 0}}clearAllTimers(){this.refreshTimeout&&clearTimeout(this.refreshTimeout),this.finalLogoutTimeout&&clearTimeout(this.finalLogoutTimeout),this.timersAreRunning=!1}scheduleTimers(e){this.clearAllTimers(),this.timersAreRunning=!0;const t=1e3*e,r=.8*t;r>3e4&&(this.refreshTimeout=setTimeout(()=>this.performRefresh(),r));const a=t-5e3;this.finalLogoutTimeout=setTimeout(()=>{this.tokenDetails=void 0,this.broadcast({type:RefreshMessageTypes.EXPIRED})},a)}isTokenExpired(e,t=0){if("number"!=typeof e||isNaN(e))return!0;return e<Math.floor(Date.now()/1e3)+t}setTokenDetails(e){this.tokenDetails=e}getTimersAreRunning(){return this.timersAreRunning}getTokenDetails(){return this.tokenDetails}}export{Refresher};