@pod-os/elements 0.37.0 → 0.38.0-rc.4b2b787.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 (52) hide show
  1. package/dist/cjs/elements.cjs.js +1 -1
  2. package/dist/cjs/{index-OR1wNkjG.js → index-CmQJab4P.js} +70 -19
  3. package/dist/cjs/{jsonld-V2RB47OZ-B82QNsYZ.js → jsonld-V2RB47OZ-BpANcb5R.js} +1 -1
  4. package/dist/cjs/loader.cjs.js +1 -1
  5. package/dist/cjs/pos-add-literal-value_3.cjs.entry.js +1 -1
  6. package/dist/cjs/pos-add-new-thing_32.cjs.entry.js +2 -2
  7. package/dist/cjs/pos-container-contents.cjs.entry.js +3 -3
  8. package/dist/cjs/pos-list.cjs.entry.js +1 -1
  9. package/dist/cjs/pos-markdown-document.cjs.entry.js +2 -2
  10. package/dist/cjs/pos-subjects.cjs.entry.js +1 -1
  11. package/dist/cjs/pos-switch.cjs.entry.js +41 -7
  12. package/dist/collection/components/pos-app/pos-app.js +1 -1
  13. package/dist/collection/components/pos-container-contents/pos-container-contents.js +2 -2
  14. package/dist/collection/components/pos-list/pos-list.js +1 -1
  15. package/dist/collection/components/pos-markdown-document/pos-markdown-document.js +2 -2
  16. package/dist/collection/components/pos-switch/pos-case/pos-case.js +38 -0
  17. package/dist/collection/components/pos-switch/pos-switch.js +44 -8
  18. package/dist/components/index2.js +2 -2
  19. package/dist/components/pos-app2.js +1 -1
  20. package/dist/components/pos-case.js +1 -1
  21. package/dist/components/pos-container-contents2.js +1 -1
  22. package/dist/components/pos-list.js +1 -1
  23. package/dist/components/pos-markdown-document2.js +1 -1
  24. package/dist/components/pos-switch.js +1 -1
  25. package/dist/elements/elements.esm.js +1 -1
  26. package/dist/elements/p-07f69d8c.entry.js +1 -0
  27. package/dist/elements/{p-dc4c38c8.entry.js → p-59e18120.entry.js} +1 -1
  28. package/dist/elements/{p-c7032012.entry.js → p-935e8df7.entry.js} +1 -1
  29. package/dist/elements/{p-ab4eba43.entry.js → p-9899cefb.entry.js} +2 -2
  30. package/dist/elements/{p-8e76e9dc.entry.js → p-9ac2654c.entry.js} +1 -1
  31. package/dist/elements/{p-a1dd6b42.entry.js → p-9dbe8f72.entry.js} +1 -1
  32. package/dist/elements/{p-BLUiM5OK.js → p-DUt7ij35.js} +1 -1
  33. package/dist/elements/p-Dzr3lPEW.js +67 -0
  34. package/dist/elements/p-cfa86eeb.entry.js +1 -0
  35. package/dist/esm/elements.js +1 -1
  36. package/dist/esm/{index-CXK32bJz.js → index-DymdXook.js} +70 -19
  37. package/dist/esm/{jsonld-V2RB47OZ-BbN7F0s8.js → jsonld-V2RB47OZ-CtbtC7fM.js} +1 -1
  38. package/dist/esm/loader.js +1 -1
  39. package/dist/esm/pos-add-literal-value_3.entry.js +1 -1
  40. package/dist/esm/pos-add-new-thing_32.entry.js +2 -2
  41. package/dist/esm/pos-container-contents.entry.js +3 -3
  42. package/dist/esm/pos-list.entry.js +1 -1
  43. package/dist/esm/pos-markdown-document.entry.js +2 -2
  44. package/dist/esm/pos-subjects.entry.js +1 -1
  45. package/dist/esm/pos-switch.entry.js +41 -7
  46. package/dist/types/components/pos-switch/pos-case/pos-case.d.ts +8 -0
  47. package/dist/types/components/pos-switch/pos-switch.d.ts +7 -3
  48. package/dist/types/components.d.ts +18 -0
  49. package/package.json +2 -2
  50. package/dist/elements/p-3a890f5f.entry.js +0 -1
  51. package/dist/elements/p-53610ccd.entry.js +0 -1
  52. package/dist/elements/p-DHl0QGLf.js +0 -67
@@ -1 +1 @@
1
- import{proxyCustomElement as e,HTMLElement as t,createEvent as r,h as n,transformTag as s}from"@stencil/core/internal/client";import{s as i}from"./session.js";import{l as o}from"./settings.js";import{P as a,N as c}from"./index2.js";import{c as h}from"./index3.js";import"./chunk.3XI76F3K.js";import"./chunk.6CTB5ZDJ.js";import"./chunk.4TUIT776.js";const u=(e,t)=>t.some((t=>e instanceof t));let d,w;const l=new WeakMap,f=new WeakMap,p=new WeakMap;let y={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return l.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return b(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function m(e){y=e(y)}function S(e){return"function"==typeof e?(t=e,(w||(w=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(E(this),e),b(this.request)}:function(...e){return b(t.apply(E(this),e))}):(e instanceof IDBTransaction&&function(e){if(l.has(e))return;const t=new Promise(((t,r)=>{const n=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",i),e.removeEventListener("abort",i)},s=()=>{t(),n()},i=()=>{r(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",s),e.addEventListener("error",i),e.addEventListener("abort",i)}));l.set(e,t)}(e),u(e,d||(d=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,y):e);var t}function b(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,r)=>{const n=()=>{e.removeEventListener("success",s),e.removeEventListener("error",i)},s=()=>{t(b(e.result)),n()},i=()=>{r(e.error),n()};e.addEventListener("success",s),e.addEventListener("error",i)}));return p.set(t,e),t}(e);if(f.has(e))return f.get(e);const t=S(e);return t!==e&&(f.set(e,t),p.set(t,e)),t}const E=e=>p.get(e),g=["get","getKey","getAll","getAllKeys","count"],v=["put","add","delete","clear"],_=new Map;function k(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(_.get(t))return _.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,s=v.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!s&&!g.includes(r))return;const i=async function(e,...t){const i=this.transaction(e,s?"readwrite":"readonly");let o=i.store;return n&&(o=o.index(t.shift())),(await Promise.all([o[r](...t),s&&i.done]))[0]};return _.set(t,i),i}m((e=>({...e,get:(t,r,n)=>k(t,r)||e.get(t,r,n),has:(t,r)=>!!k(t,r)||e.has(t,r)})));const A=["continue","continuePrimaryKey","advance"],T={},P=new WeakMap,R=new WeakMap,I={get(e,t){if(!A.includes(t))return e[t];let r=T[t];return r||(r=T[t]=function(...e){P.set(this,R.get(this)[t](...e))}),r}};async function*D(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const r=new Proxy(t,I);for(R.set(r,t),p.set(r,E(t));t;)yield r,t=await(P.get(r)||t.continue()),P.delete(r)}function W(e,t){return t===Symbol.asyncIterator&&u(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&u(e,[IDBIndex,IDBObjectStore])}m((e=>({...e,get:(t,r,n)=>W(t,r)?D:e.get(t,r,n),has:(t,r)=>W(t,r)||e.has(t,r)})));class C{constructor(){this.dbPromise=function(e,t,{blocked:r,upgrade:n,blocking:s,terminated:i}={}){const o=indexedDB.open(e,t),a=b(o);return n&&o.addEventListener("upgradeneeded",(e=>{n(b(o.result),e.oldVersion,e.newVersion,b(o.transaction),e)})),r&&o.addEventListener("blocked",(e=>r(e.oldVersion,e.newVersion,e))),a.then((e=>{i&&e.addEventListener("close",(()=>i())),s&&e.addEventListener("versionchange",(e=>s(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),a}("OfflineCacheDB",1,{upgrade(e){e.objectStoreNames.contains("documents")||e.createObjectStore("documents",{keyPath:"url"}).createIndex("url-revision",["url","revision"])}})}async clear(){return(await this.dbPromise).clear("documents")}async get(e){const t=await this.dbPromise;return await t.get("documents",e)}async put(e){const t=await this.dbPromise;await t.getFromIndex("documents","url-revision",[e.url,e.revision])||await t.put("documents",e)}}class J{isOnline(){return navigator.onLine}}const O=(e,t)=>new a({session:e,offlineCache:t.offlineCache?new C:new c,onlineStatus:new J});var K=crypto;const $=e=>e instanceof CryptoKey;const H=new TextEncoder,j=new TextDecoder;function x(...e){const t=e.reduce(((e,{length:t})=>e+t),0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}const U=e=>(e=>{let t=e;"string"==typeof t&&(t=H.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(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),N=e=>{let t=e;t instanceof Uint8Array&&(t=j.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(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})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class L extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}L.code="ERR_JOSE_GENERIC";class M extends L{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n,this.payload=t}}M.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class B extends L{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n,this.payload=t}}B.code="ERR_JWT_EXPIRED";class F extends L{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}F.code="ERR_JOSE_ALG_NOT_ALLOWED";class V extends L{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}V.code="ERR_JOSE_NOT_SUPPORTED",class extends L{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}.code="ERR_JWE_DECRYPTION_FAILED",class extends L{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}.code="ERR_JWE_INVALID";class q extends L{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}q.code="ERR_JWS_INVALID";class G extends L{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}G.code="ERR_JWT_INVALID";class z extends L{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}z.code="ERR_JWK_INVALID";class X extends L{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}X.code="ERR_JWKS_INVALID";class Y extends L{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Y.code="ERR_JWKS_NO_MATCHING_KEY";class Z extends L{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Z.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class Q extends L{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}Q.code="ERR_JWKS_TIMEOUT";class ee extends L{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function te(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function re(e,t){return e.name===t}function ne(e){return parseInt(e.name.slice(4),10)}function se(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else e+=2===r.length?`one of type ${r[0]} or ${r[1]}.`:`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}ee.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";var ie=(e,...t)=>se("Key must be ",e,...t);function oe(e,t,...r){return se(`Key for the ${e} algorithm must be `,t,...r)}var ae=e=>!!$(e)||"KeyObject"===e?.[Symbol.toStringTag];const ce=["CryptoKey"];var he=(...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};function ue(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}var de=(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 we(e){return ue(e)&&"string"==typeof e.kty}var le=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=function(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 V('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 V('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 V('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new V('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n=[t,e.ext??!1,e.key_ops??r],s={...e};return delete s.alg,delete s.use,K.subtle.importKey("jwk",s,...n)};const fe=e=>N(e);let pe,ye;const me=e=>"KeyObject"===e?.[Symbol.toStringTag],Se=async(e,t,r,n,s=!1)=>{let i=e.get(t);if(i?.[n])return i[n];const o=await le({...r,alg:n});return s&&Object.freeze(t),i?i[n]=o:e.set(t,{[n]:o}),o};async function be(e,t){if(!ue(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 N(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new V('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return le({...e,alg:t});default:throw new V('Unsupported "kty" (Key Type) Parameter value')}}const Ee=e=>e?.[Symbol.toStringTag],ge=(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};function ve(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?((e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&we(t)){if(function(e){return we(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&ge(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(!ae(t))throw new TypeError(oe(e,t,...ce,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${Ee(t)} instances for symmetric algorithms must be of type "secret"`)}})(t,r,n,e):((e,t,r,n)=>{if(n&&we(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&ge(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&ge(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!ae(t))throw new TypeError(oe(e,t,...ce,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${Ee(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${Ee(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${Ee(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${Ee(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${Ee(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}ve.bind(void 0,!1);const _e=ve.bind(void 0,!0);function ke(e,t,r,n,s){if(void 0!==s.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.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 i;i=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!i.has(t))throw new V(`Extension Header Parameter "${t}" is not recognized`);if(void 0===s[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(i.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)}async function Ae(e){return(async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:U(e)};if(!$(e))throw new TypeError(ie(e,...ce,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");const{ext:t,key_ops:r,alg:n,use:s,...i}=await K.subtle.exportKey("jwk",e);return i})(e)}function Te(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 V(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Pe(e,t,r){if("sign"===r&&(t=await((e,t)=>{if(me(e)){let r=e.export({format:"jwk"});return r.k?fe(r.k):(pe||(pe=new WeakMap),Se(pe,e,r,t))}return we(e)?e.k?N(e.k):(pe||(pe=new WeakMap),Se(pe,e,e,t,!0)):e})(t,e)),"verify"===r&&(t=await((e,t)=>{if(me(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?fe(r.k):(ye||(ye=new WeakMap),Se(ye,e,r,t))}return we(e)?e.k?N(e.k):(ye||(ye=new WeakMap),Se(ye,e,e,t,!0)):e})(t,e)),$(t))return function(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!re(e.algorithm,"HMAC"))throw te("HMAC");const r=parseInt(t.slice(2),10);if(ne(e.algorithm.hash)!==r)throw te(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!re(e.algorithm,"RSASSA-PKCS1-v1_5"))throw te("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(ne(e.algorithm.hash)!==r)throw te(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!re(e.algorithm,"RSA-PSS"))throw te("RSA-PSS");const r=parseInt(t.slice(2),10);if(ne(e.algorithm.hash)!==r)throw te(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw te("Ed25519 or Ed448");break;case"Ed25519":if(!re(e.algorithm,"Ed25519"))throw te("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!re(e.algorithm,"ECDSA"))throw te("ECDSA");const r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw te(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(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 e+=2===t.length?`one of ${t[0]} or ${t[1]}.`:`${t[0]}.`;throw new TypeError(e)}}(e,r)}(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(ie(t,...ce));return K.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(ie(t,...ce,"Uint8Array","JSON Web Key"))}async function Re(e,t,r){if(e instanceof Uint8Array&&(e=j.decode(e)),"string"!=typeof e)throw new q("Compact JWS must be a string or Uint8Array");const{0:n,1:s,2:i,length:o}=e.split(".");if(3!==o)throw new q("Invalid Compact JWS");const a=await async function(e,t,r){if(!ue(e))throw new q("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new q('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new q("JWS Protected Header incorrect type");if(void 0===e.payload)throw new q("JWS Payload missing");if("string"!=typeof e.signature)throw new q("JWS Signature missing or incorrect type");if(void 0!==e.header&&!ue(e.header))throw new q("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const t=N(e.protected);n=JSON.parse(j.decode(t))}catch{throw new q("JWS Protected Header is invalid")}if(!he(n,e.header))throw new q("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...n,...e.header};let i=!0;if(ke(q,new Map([["b64",!0]]),r?.crit,n,s).has("b64")&&(i=n.b64,"boolean"!=typeof i))throw new q('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:o}=s;if("string"!=typeof o||!o)throw new q('JWS "alg" (Algorithm) Header Parameter missing or invalid');const a=r&&((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)})("algorithms",r.algorithms);if(a&&!a.has(o))throw new F('"alg" (Algorithm) Header Parameter value not allowed');if(i){if("string"!=typeof e.payload)throw new q("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new q("JWS Payload must be a string or an Uint8Array instance");let c=!1;"function"==typeof t?(t=await t(n,e),c=!0,_e(o,t,"verify"),we(t)&&(t=await be(t,o))):_e(o,t,"verify");const h=x(H.encode(e.protected??""),H.encode("."),"string"==typeof e.payload?H.encode(e.payload):e.payload);let u,d;try{u=N(e.signature)}catch{throw new q("Failed to base64url decode the signature")}if(!await(async(e,t,r,n)=>{const s=await Pe(e,t,"verify");de(e,s);const i=Te(e,s.algorithm);try{return await K.subtle.verify(i,s,r,n)}catch{return!1}})(o,t,u,h))throw new ee;if(i)try{d=N(e.payload)}catch{throw new q("Failed to base64url decode the payload")}else d="string"==typeof e.payload?H.encode(e.payload):e.payload;const w={payload:d};return void 0!==e.protected&&(w.protectedHeader=n),void 0!==e.header&&(w.unprotectedHeader=e.header),c?{...w,key:t}:w}({payload:s,protected:n,signature:i},t,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return"function"==typeof t?{...c,key:a.key}:c}var Ie=e=>Math.floor(e.getTime()/1e3);const De=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;var We=e=>{const t=De.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*r);break;case"day":case"days":case"d":n=Math.round(86400*r);break;case"week":case"weeks":case"w":n=Math.round(604800*r);break;default:n=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-n:n};const Ce=e=>e.toLowerCase().replace(/^application\//,"");var Je=(e,t,r={})=>{let n;try{n=JSON.parse(j.decode(t))}catch{}if(!ue(n))throw new G("JWT Claims Set must be a top-level JSON object");const{typ:s}=r;if(s&&("string"!=typeof e.typ||Ce(e.typ)!==Ce(s)))throw new M('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:h}=r,u=[...i];void 0!==h&&u.push("iat"),void 0!==c&&u.push("aud"),void 0!==a&&u.push("sub"),void 0!==o&&u.push("iss");for(const e of new Set(u.reverse()))if(!(e in n))throw new M(`missing required "${e}" claim`,n,e,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(n.iss))throw new M('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new M('unexpected "sub" claim value',n,"sub","check_failed");if(c&&(w="string"==typeof c?[c]:c,!("string"==typeof(d=n.aud)?w.includes(d):Array.isArray(d)&&w.some(Set.prototype.has.bind(new Set(d))))))throw new M('unexpected "aud" claim value',n,"aud","check_failed");var d,w;let l;switch(typeof r.clockTolerance){case"string":l=We(r.clockTolerance);break;case"number":l=r.clockTolerance;break;case"undefined":l=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:f}=r,p=Ie(f||new Date);if((void 0!==n.iat||h)&&"number"!=typeof n.iat)throw new M('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new M('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>p+l)throw new M('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new M('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=p-l)throw new B('"exp" claim timestamp check failed',n,"exp","check_failed")}if(h){const e=p-n.iat;if(e-l>("number"==typeof h?h:We(h)))throw new B('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-l)throw new M('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};async function Oe(e,t,r){const n=await Re(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new G("JWTs MUST NOT use unencoded payload");const s={payload:Je(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...s,key:n.key}:s}class Ke{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 q("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!he(this._protectedHeader,this._unprotectedHeader))throw new q("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let n=!0;if(ke(q,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(n=this._protectedHeader.b64,"boolean"!=typeof n))throw new q('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=r;if("string"!=typeof s||!s)throw new q('JWS "alg" (Algorithm) Header Parameter missing or invalid');_e(s,e,"sign");let i,o=this._payload;n&&(o=H.encode(U(o))),i=H.encode(this._protectedHeader?U(JSON.stringify(this._protectedHeader)):"");const a=x(i,H.encode("."),o),c=await(async(e,t,r)=>{const n=await Pe(e,t,"sign");de(e,n);const s=await K.subtle.sign(Te(e,n.algorithm),n,r);return new Uint8Array(s)})(s,e,a),h={signature:U(c),payload:""};return n&&(h.payload=j.decode(o)),this._unprotectedHeader&&(h.header=this._unprotectedHeader),this._protectedHeader&&(h.protected=j.decode(i)),h}}class $e{constructor(e){this._flattened=new Ke(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 He(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class je{constructor(e={}){if(!ue(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 this._payload="number"==typeof e?{...this._payload,nbf:He("setNotBefore",e)}:e instanceof Date?{...this._payload,nbf:He("setNotBefore",Ie(e))}:{...this._payload,nbf:Ie(new Date)+We(e)},this}setExpirationTime(e){return this._payload="number"==typeof e?{...this._payload,exp:He("setExpirationTime",e)}:e instanceof Date?{...this._payload,exp:He("setExpirationTime",Ie(e))}:{...this._payload,exp:Ie(new Date)+We(e)},this}setIssuedAt(e){return this._payload=void 0===e?{...this._payload,iat:Ie(new Date)}:e instanceof Date?{...this._payload,iat:He("setIssuedAt",Ie(e))}:"string"==typeof e?{...this._payload,iat:He("setIssuedAt",Ie(new Date)+We(e))}:{...this._payload,iat:He("setIssuedAt",e)},this}}class xe extends je{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new $e(H.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 G("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}const Ue=(e,t)=>{if("string"!=typeof e||!e)throw new z(`${t} missing or invalid`)};async function Ne(e,t){if(!ue(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":Ue(e.crv,'"crv" (Curve) Parameter'),Ue(e.x,'"x" (X Coordinate) Parameter'),Ue(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":Ue(e.crv,'"crv" (Subtype of Key Pair) Parameter'),Ue(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":Ue(e.e,'"e" (Exponent) Parameter'),Ue(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":Ue(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new V('"kty" (Key Type) Parameter missing or unsupported')}const n=H.encode(JSON.stringify(r));return U(await(async(e,t)=>{const r=`SHA-${e.slice(-3)}`;return new Uint8Array(await K.subtle.digest(r,t))})(t,n))}function Le(e){return ue(e)}function Me(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}class Be{constructor(e){if(this._cached=new WeakMap,!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(Le)}(e))throw new X("JSON Web Key Set malformed");this._jwks=Me(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...t?.header},s=function(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 V('Unsupported "alg" value for a JSON Web Key Set')}}(r),i=this._jwks.keys.filter((e=>{let t=s===e.kty;if(t&&"string"==typeof n&&(t=n===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:o,length:a}=i;if(0===a)throw new Y;if(1!==a){const e=new Z,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of i)try{yield await Fe(t,e,r)}catch{}},e}return Fe(this._cached,o,r)}}async function Fe(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await be({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new X("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function Ve(e){const t=new Be(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>Me(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}let qe;"undefined"!=typeof navigator&&navigator.userAgent?.startsWith?.("Mozilla/5.0 ")||(qe="jose/v5.10.0");const Ge=Symbol();class ze{constructor(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");var r,n;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?.[Ge]&&(this._cache=t?.[Ge],r=t?.[Ge],n=this._cacheMaxAge,"object"==typeof r&&null!==r&&"uat"in r&&"number"==typeof r.uat&&!(Date.now()-r.uat>=n)&&"jwks"in r&&ue(r.jwks)&&Array.isArray(r.jwks.keys)&&Array.prototype.every.call(r.jwks.keys,ue)&&(this._jwksTimestamp=this._cache.uat,this._local=Ve(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 Y&&!1===this.coolingDown())return await this.reload(),this._local(e,t);throw r}}async reload(){this._pendingFetch&&("undefined"!=typeof WebSocketPair||"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"undefined"!=typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);qe&&!e.has("User-Agent")&&(e.set("User-Agent",qe),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=(async(e,t,r)=>{let n,s,i=!1;"function"==typeof AbortController&&(n=new AbortController,s=setTimeout((()=>{i=!0,n.abort()}),t));const o=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch((e=>{if(i)throw new Q;throw e}));if(void 0!==s&&clearTimeout(s),200!==o.status)throw new L("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new L("Failed to parse the JSON Web Key Set HTTP response as JSON")}})(this._url,this._timeoutDuration,this._options).then((e=>{this._local=Ve(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 Xe(e,t){const r=new ze(e,t),n=async(e,t)=>r.getKey(e,t);return Object.defineProperties(n,{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}}),n}const Ye=N;function Ze(e){const t=e?.modulusLength??2048;if("number"!=typeof t||t<2048)throw new V("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}class Qe{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,n)=>{const s=this.db.transaction(this.storeName,"readwrite");s.oncomplete=()=>{r()},s.onerror=t=>{n(new Error(`Transaction error for setItem(${e},...): ${t.target.error}`))},s.onabort=t=>{n(new Error(`Transaction aborted for setItem(${e},...): ${t.target.error}`))},s.objectStore(this.storeName).put(t,e)}))}async getItem(e){return this.db||await this.init(),new Promise(((t,r)=>{const n=this.db.transaction(this.storeName,"readonly");n.onerror=t=>{r(new Error(`Transaction error for getItem(${e}): ${t.target.error}`))},n.onabort=t=>{r(new Error(`Transaction aborted for getItem(${e}): ${t.target.error}`))};const s=n.objectStore(this.storeName).get(e);s.onsuccess=()=>{t(s.result||null)}}))}async deleteItem(e){return this.db||await this.init(),new Promise(((t,r)=>{const n=this.db.transaction(this.storeName,"readwrite");n.oncomplete=()=>{t()},n.onerror=t=>{r(new Error(`Transaction error for deleteItem(${e}): ${t.target.error}`))},n.onabort=t=>{r(new Error(`Transaction aborted for deleteItem(${e}): ${t.target.error}`))},n.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)}}const et=async()=>{const e=window.crypto.randomUUID()+"-"+window.crypto.randomUUID(),t=new Uint8Array(await window.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)));return{pkce_code_verifier:e,pkce_code_challenge:btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}},tt=async()=>{const e=await(new Qe).init(),t=await e.getItem("client_id"),r=await e.getItem("token_endpoint"),n=await e.getItem("dpop_keypair"),s=await e.getItem("refresh_token");if(null===t||null===r||null===n||null===s)throw new Error("Could not refresh tokens: details missing from database.");const i=await rt(s,t,r,n).then((e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()})),o=i.access_token,a=await e.getItem("idp");if(null===a)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 h=Xe(new URL(c)),{payload:u}=await Oe(o,h,{issuer:a,audience:"solid"}),d=await Ne(await Ae(n.publicKey));if(u.cnf.jkt!=d)throw new Error("Access Token validation failed on `jkt`: jkt != DPoP thumbprint - "+u.cnf.jkt+" != "+d);if(u.client_id!=t)throw new Error("Access Token validation failed on `client_id`: JWT payload != client_id - "+u.client_id+" != "+t);return await e.setItem("refresh_token",i.refresh_token),e.close(),{...i,dpop_key_pair:n}},rt=async(e,t,r,n)=>{const s=await Ae(n.publicKey);s.alg="ES256";const i=await new xe({htu:r,htm:"POST"}).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:s}).sign(n.privateKey);return fetch(r,{method:"POST",headers:{dpop:i,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:t})})};class nt{sessionInformation;isActive_=!1;webId_=void 0;currentAth_=void 0;tokenRefreshTimeout;sessionDeactivateTimeout;onSessionExpirationWarning;constructor(e,t){this.sessionInformation={clientDetails:e},this.onSessionExpirationWarning=t?.onSessionExpirationWarning}async login(e,t){await(async(e,t,r)=>{const n=new URL(t),s=n.origin+n.pathname+n.search,i=new URL(e).origin,o=await fetch(`${i}/.well-known/openid-configuration`).then((e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()})),a=o.issuer,c=e=>e.endsWith("/")?e.slice(0,-1):e;if(c(e)!==c(a))throw new Error("RFC 9207 - iss != idp - "+a+" != "+e);sessionStorage.setItem("idp",a),sessionStorage.setItem("token_endpoint",o.token_endpoint),sessionStorage.setItem("jwks_uri",o.jwks_uri);let h=r?.client_id;if(!h){const e=o.registration_endpoint,t=await(async(e,t)=>{const r={...t,grant_types:["authorization_code","refresh_token"],id_token_signed_response_alg:"ES256",token_endpoint_auth_method:"none",application_type:"web",subject_type:"public"};return fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})})(e,r??{redirect_uris:[s]}).then((e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}));h=t.client_id,sessionStorage.setItem("client_id",h)}const{pkce_code_verifier:u,pkce_code_challenge:d}=await et();sessionStorage.setItem("pkce_code_verifier",u);const w=window.crypto.randomUUID();sessionStorage.setItem("csrf_token",w);const l=o.authorization_endpoint+"?response_type=code"+`&redirect_uri=${encodeURIComponent(s)}&scope=openid offline_access webid`+`&client_id=${encodeURIComponent(h)}&code_challenge_method=S256`+`&code_challenge=${d}`+`&state=${w}&prompt=consent`;window.location.href=l})(e,t,this.sessionInformation.clientDetails)}async logout(){if(this.sessionDeactivateTimeout&&clearTimeout(this.sessionDeactivateTimeout),this.sessionDeactivateTimeout=void 0,this.tokenRefreshTimeout&&clearTimeout(this.tokenRefreshTimeout),this.tokenRefreshTimeout=void 0,this.sessionInformation.idpDetails=void 0,this.sessionInformation.tokenDetails=void 0,this.isActive_=!1,this.webId_=void 0,this.sessionInformation.clientDetails?.client_id)try{new URL(this.sessionInformation.clientDetails.client_id)}catch(e){this.sessionInformation.clientDetails.client_id=void 0}const e=await(new Qe).init();await e.clear(),e.close()}async handleRedirectFromLogin(){const e=await(async e=>{const t=new URL(window.location.href),r=t.searchParams.get("code");if(null===r)return{clientDetails:e};const n=sessionStorage.getItem("idp");if(null===n||t.searchParams.get("iss")!=n)throw new Error("RFC 9207 - iss != idp - "+t.searchParams.get("iss")+" != "+n);if(t.searchParams.get("state")!=sessionStorage.getItem("csrf_token"))throw new Error("RFC 6749 - state != csrf_token - "+t.searchParams.get("state")+" != "+sessionStorage.getItem("csrf_token"));t.searchParams.delete("iss"),t.searchParams.delete("state"),t.searchParams.delete("code"),window.history.pushState({},document.title,t.toString());const s=sessionStorage.getItem("pkce_code_verifier");if(null===s)throw new Error("Access Token Request preparation - Could not find in sessionStorage: pkce_code_verifier");const i=e?.client_id||sessionStorage.getItem("client_id");if(!i)throw new Error("Access Token Request preparation - Could not find in sessionStorage: client_id (dynamic registration)");const o=sessionStorage.getItem("token_endpoint");if(null===o)throw new Error("Access Token Request preparation - Could not find in sessionStorage: token_endpoint");const a=await async function(e,t){return async function(e,t){let r,n;switch(e){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ze(t)},n=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ze(t)},n=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ze(t)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"Ed25519":r={name:"Ed25519"},n=["sign","verify"];break;case"EdDSA":{n=["sign","verify"];const e="Ed25519";switch(e){case"Ed25519":case"Ed448":r={name:e};break;default:throw new V("Invalid or unsupported crv option provided")}break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveKey","deriveBits"];const e="P-256";switch(e){case"P-256":case"P-384":case"P-521":r={name:"ECDH",namedCurve:e};break;case"X25519":case"X448":r={name:e};break;default:throw new V("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new V('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return K.subtle.generateKey(r,!1,n)}(e,t)}("ES256"),c=await(async(e,t,r,n,s,i)=>{const o=await Ae(i.publicKey);o.alg="ES256";const a=await new xe({htu:s,htm:"POST"}).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:o}).sign(i.privateKey);return fetch(s,{method:"POST",headers:{dpop:a,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:r,client_id:n})})})(r,s,t.toString(),i,o,a).then((e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()})),h=c.access_token,u=sessionStorage.getItem("jwks_uri");if(null===u)throw new Error("Access Token validation preparation - Could not find in sessionStorage: jwks_uri");const d=Xe(new URL(u)),{payload:w}=await Oe(h,d,{issuer:n,audience:"solid"}),l=await Ne(await Ae(a.publicKey));if(w.cnf.jkt!=l)throw new Error("Access Token validation failed on `jkt`: jkt != DPoP thumbprint - "+w.cnf.jkt+" != "+l);if(w.client_id!=i)throw new Error("Access Token validation failed on `client_id`: JWT payload != client_id - "+w.client_id+" != "+i);const f={...c,dpop_key_pair:a},p={idp:n,jwks_uri:u,token_endpoint:o};e||(e={redirect_uris:[window.location.href]}),e.client_id=i;const y=await(new Qe).init();return await Promise.all([y.setItem("idp",n),y.setItem("jwks_uri",u),y.setItem("token_endpoint",o),y.setItem("client_id",i),y.setItem("dpop_keypair",a),y.setItem("refresh_token",c.refresh_token)]),y.close(),sessionStorage.removeItem("csrf_token"),sessionStorage.removeItem("pkce_code_verifier"),sessionStorage.removeItem("idp"),sessionStorage.removeItem("jwks_uri"),sessionStorage.removeItem("token_endpoint"),sessionStorage.removeItem("client_id"),{clientDetails:e,idpDetails:p,tokenDetails:f}})(this.sessionInformation.clientDetails);e.tokenDetails&&(this.sessionInformation=e,await this.setSessionDetails())}async restore(){await tt().then((e=>(this.sessionInformation.tokenDetails=e,this.setSessionDetails()))).catch((()=>{}))}async createSignedDPoPToken(e){if(!this.sessionInformation.tokenDetails||!this.currentAth_)throw new Error("Session not established.");e.ath=this.currentAth_;const t=await Ae(this.sessionInformation.tokenDetails.dpop_key_pair.publicKey);return new xe(e).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:t}).sign(this.sessionInformation.tokenDetails.dpop_key_pair.privateKey)}async authFetch(e,t,r){let n,s,i;if(e instanceof Request?(n=new URL(e.url),s=t?.method||e?.method||"GET",i=new Headers(e.headers)):(t=t||{},n=new URL(e.toString()),s=t.method||"GET",i=t.headers?new Headers(t.headers):new Headers),this.sessionInformation.tokenDetails){r=r??{htu:`${n.origin}${n.pathname}`,htm:s.toUpperCase()};const e=await this.createSignedDPoPToken(r);i.set("dpop",e),i.set("authorization",`DPoP ${this.sessionInformation.tokenDetails.access_token}`)}return e instanceof Request?fetch(new Request(e,{...t,headers:i})):fetch(n,{...t,headers:i})}get isActive(){return this.isActive_}get webId(){return this.webId_}async setSessionDetails(){this.sessionInformation.tokenDetails?.access_token||this.logout(),this.currentAth_=await this.computeAth(this.sessionInformation.tokenDetails.access_token),this.webId_=function(e){if("string"!=typeof e)throw new G("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(5===r)throw new G("Only JWTs using Compact JWS serialization can be decoded");if(3!==r)throw new G("Invalid JWT");if(!t)throw new G("JWTs must contain a payload");let n,s;try{n=Ye(t)}catch{throw new G("Failed to base64url decode the payload")}try{s=JSON.parse(j.decode(n))}catch{throw new G("Failed to parse the decoded payload as JSON")}if(!ue(s))throw new G("Invalid JWT Claims Set");return s}(this.sessionInformation.tokenDetails.access_token).webid,this.isActive_=void 0!==this.webId,this.setSessionDeactivateTimeout(),this.setTokenRefreshTimeout()}setSessionDeactivateTimeout(){const e=1e3*(this.sessionInformation.tokenDetails.expires_in-5);this.sessionDeactivateTimeout&&clearTimeout(this.sessionDeactivateTimeout),this.sessionDeactivateTimeout=setTimeout((()=>this.logout()),e)}setTokenRefreshTimeout(){const e=1e3*(this.sessionInformation.tokenDetails.expires_in-95);this.tokenRefreshTimeout&&clearTimeout(this.tokenRefreshTimeout),this.tokenRefreshTimeout=setTimeout((async()=>{const e=await tt().catch((()=>{this.onSessionExpirationWarning&&this.onSessionExpirationWarning()}));e&&(this.sessionInformation.tokenDetails=e,this.setSessionDetails())}),e)}async computeAth(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t),n=Array.from(new Uint8Array(r));return btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}}class st{get authenticatedFetch(){return this._authenticatedFetch}constructor(){this.onSessionRestoreCallback=()=>{},this.sessionInfo$=new h.BehaviorSubject({isLoggedIn:!1,webId:void 0}),this.session=new nt,this._authenticatedFetch=this.session.authFetch.bind(this.session)}async handleIncomingRedirect(e=!1){await this.session.handleRedirectFromLogin(),e&&(await this.session.restore(),this.session.isActive&&this.onSessionRestoreCallback(window.location.href)),this.sessionInfo$.next({isLoggedIn:this.session.isActive,webId:this.session.webId})}async login(e){return this.session.login(e,window.location.href)}async logout(){await this.session.logout(),this.sessionInfo$.next({isLoggedIn:!1,webId:void 0})}observeSession(){return this.sessionInfo$}onSessionRestore(e){this.onSessionRestoreCallback=e}}const it=e(class extends t{constructor(e){super(),!1!==e&&this.__registerHost(),this.__attachShadow(),this.sessionRestoredEmitter=r(this,"pod-os:session-restored",7),this.podOsLoadedEmitter=r(this,"pod-os:loaded",7),this.restorePreviousSession=!1,this.disconnected$=new h.Subject,this.loading=!0}async componentWillLoad(){const e=new st;this.unsubscribeSettings=o.on("set",(()=>{this.os=O(e,o.state)})),this.os=O(e,o.state),e.onSessionRestore((e=>{this.sessionRestoredEmitter.emit({url:e})}));try{await e.handleIncomingRedirect(this.restorePreviousSession)}catch(e){console.error(e)}this.os.observeSession().pipe(h.takeUntil(this.disconnected$)).subscribe((async e=>{if(i.state.webId=e.webId,e.isLoggedIn){const t=await this.os.fetchProfile(e.webId);i.state.profile=t}i.state.isLoggedIn=e.isLoggedIn,this.loading=!1})),this.podOsLoadedEmitter.emit({os:this.os,authenticatedFetch:e.authenticatedFetch})}disconnectedCallback(){this.unsubscribeSettings(),this.disconnected$.next(),this.disconnected$.unsubscribe()}async initializeOs(e){e.stopPropagation(),e.detail(this.os)}async loadModule(e){e.stopPropagation();const t=await this.os.loadModule(e.detail.module);e.detail.receiver(t)}render(){return this.loading?n("sl-progress-bar",{indeterminate:!0}):n("slot",null)}},[257,"pos-app",{restorePreviousSession:[4,"restore-previous-session"],os:[32],unsubscribeSettings:[32],loading:[32]},[[0,"pod-os:init","initializeOs"],[0,"pod-os:module","loadModule"]]]);function ot(){"undefined"!=typeof customElements&&["pos-app"].forEach((e=>{"pos-app"===e&&(customElements.get(s(e))||customElements.define(s(e),it))}))}export{it as P,ot as d}
1
+ import{proxyCustomElement as e,HTMLElement as t,createEvent as r,h as n,transformTag as s}from"@stencil/core/internal/client";import{s as i}from"./session.js";import{l as o}from"./settings.js";import{P as a,N as c}from"./index2.js";import{c as h}from"./index3.js";import"./chunk.3XI76F3K.js";import"./chunk.6CTB5ZDJ.js";import"./chunk.4TUIT776.js";const u=(e,t)=>t.some((t=>e instanceof t));let d,w;const l=new WeakMap,f=new WeakMap,p=new WeakMap;let y={get(e,t,r){if(e instanceof IDBTransaction){if("done"===t)return l.get(e);if("store"===t)return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return b(e[t])},set:(e,t,r)=>(e[t]=r,!0),has:(e,t)=>e instanceof IDBTransaction&&("done"===t||"store"===t)||t in e};function m(e){y=e(y)}function S(e){return"function"==typeof e?(t=e,(w||(w=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])).includes(t)?function(...e){return t.apply(E(this),e),b(this.request)}:function(...e){return b(t.apply(E(this),e))}):(e instanceof IDBTransaction&&function(e){if(l.has(e))return;const t=new Promise(((t,r)=>{const n=()=>{e.removeEventListener("complete",s),e.removeEventListener("error",i),e.removeEventListener("abort",i)},s=()=>{t(),n()},i=()=>{r(e.error||new DOMException("AbortError","AbortError")),n()};e.addEventListener("complete",s),e.addEventListener("error",i),e.addEventListener("abort",i)}));l.set(e,t)}(e),u(e,d||(d=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction]))?new Proxy(e,y):e);var t}function b(e){if(e instanceof IDBRequest)return function(e){const t=new Promise(((t,r)=>{const n=()=>{e.removeEventListener("success",s),e.removeEventListener("error",i)},s=()=>{t(b(e.result)),n()},i=()=>{r(e.error),n()};e.addEventListener("success",s),e.addEventListener("error",i)}));return p.set(t,e),t}(e);if(f.has(e))return f.get(e);const t=S(e);return t!==e&&(f.set(e,t),p.set(t,e)),t}const E=e=>p.get(e),g=["get","getKey","getAll","getAllKeys","count"],v=["put","add","delete","clear"],_=new Map;function k(e,t){if(!(e instanceof IDBDatabase)||t in e||"string"!=typeof t)return;if(_.get(t))return _.get(t);const r=t.replace(/FromIndex$/,""),n=t!==r,s=v.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!s&&!g.includes(r))return;const i=async function(e,...t){const i=this.transaction(e,s?"readwrite":"readonly");let o=i.store;return n&&(o=o.index(t.shift())),(await Promise.all([o[r](...t),s&&i.done]))[0]};return _.set(t,i),i}m((e=>({...e,get:(t,r,n)=>k(t,r)||e.get(t,r,n),has:(t,r)=>!!k(t,r)||e.has(t,r)})));const A=["continue","continuePrimaryKey","advance"],T={},P=new WeakMap,R=new WeakMap,I={get(e,t){if(!A.includes(t))return e[t];let r=T[t];return r||(r=T[t]=function(...e){P.set(this,R.get(this)[t](...e))}),r}};async function*D(...e){let t=this;if(t instanceof IDBCursor||(t=await t.openCursor(...e)),!t)return;const r=new Proxy(t,I);for(R.set(r,t),p.set(r,E(t));t;)yield r,t=await(P.get(r)||t.continue()),P.delete(r)}function W(e,t){return t===Symbol.asyncIterator&&u(e,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===t&&u(e,[IDBIndex,IDBObjectStore])}m((e=>({...e,get:(t,r,n)=>W(t,r)?D:e.get(t,r,n),has:(t,r)=>W(t,r)||e.has(t,r)})));class C{constructor(){this.dbPromise=function(e,t,{blocked:r,upgrade:n,blocking:s,terminated:i}={}){const o=indexedDB.open(e,t),a=b(o);return n&&o.addEventListener("upgradeneeded",(e=>{n(b(o.result),e.oldVersion,e.newVersion,b(o.transaction),e)})),r&&o.addEventListener("blocked",(e=>r(e.oldVersion,e.newVersion,e))),a.then((e=>{i&&e.addEventListener("close",(()=>i())),s&&e.addEventListener("versionchange",(e=>s(e.oldVersion,e.newVersion,e)))})).catch((()=>{})),a}("OfflineCacheDB",1,{upgrade(e){e.objectStoreNames.contains("documents")||e.createObjectStore("documents",{keyPath:"url"}).createIndex("url-revision",["url","revision"])}})}async clear(){return(await this.dbPromise).clear("documents")}async get(e){const t=await this.dbPromise;return await t.get("documents",e)}async put(e){const t=await this.dbPromise;await t.getFromIndex("documents","url-revision",[e.url,e.revision])||await t.put("documents",e)}}class J{isOnline(){return navigator.onLine}}const O=(e,t)=>new a({session:e,offlineCache:t.offlineCache?new C:new c,onlineStatus:new J});var K=crypto;const $=e=>e instanceof CryptoKey;const H=new TextEncoder,j=new TextDecoder;function x(...e){const t=e.reduce(((e,{length:t})=>e+t),0),r=new Uint8Array(t);let n=0;for(const t of e)r.set(t,n),n+=t.length;return r}const U=e=>(e=>{let t=e;"string"==typeof t&&(t=H.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(""))})(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),N=e=>{let t=e;t instanceof Uint8Array&&(t=j.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return(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})(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class L extends Error{constructor(e,t){super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}}L.code="ERR_JOSE_GENERIC";class M extends L{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n,this.payload=t}}M.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class B extends L{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n,this.payload=t}}B.code="ERR_JWT_EXPIRED";class F extends L{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}F.code="ERR_JOSE_ALG_NOT_ALLOWED";class V extends L{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}V.code="ERR_JOSE_NOT_SUPPORTED",class extends L{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}.code="ERR_JWE_DECRYPTION_FAILED",class extends L{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}.code="ERR_JWE_INVALID";class q extends L{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}q.code="ERR_JWS_INVALID";class G extends L{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}G.code="ERR_JWT_INVALID";class z extends L{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}z.code="ERR_JWK_INVALID";class X extends L{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}X.code="ERR_JWKS_INVALID";class Y extends L{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Y.code="ERR_JWKS_NO_MATCHING_KEY";class Z extends L{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Z.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class Q extends L{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}Q.code="ERR_JWKS_TIMEOUT";class ee extends L{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}function te(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function re(e,t){return e.name===t}function ne(e){return parseInt(e.name.slice(4),10)}function se(e,t,...r){if((r=r.filter(Boolean)).length>2){const t=r.pop();e+=`one of type ${r.join(", ")}, or ${t}.`}else e+=2===r.length?`one of type ${r[0]} or ${r[1]}.`:`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}ee.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";var ie=(e,...t)=>se("Key must be ",e,...t);function oe(e,t,...r){return se(`Key for the ${e} algorithm must be `,t,...r)}var ae=e=>!!$(e)||"KeyObject"===e?.[Symbol.toStringTag];const ce=["CryptoKey"];var he=(...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};function ue(e){if("object"!=typeof(t=e)||null===t||"[object Object]"!==Object.prototype.toString.call(e))return!1;var t;if(null===Object.getPrototypeOf(e))return!0;let r=e;for(;null!==Object.getPrototypeOf(r);)r=Object.getPrototypeOf(r);return Object.getPrototypeOf(e)===r}var de=(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 we(e){return ue(e)&&"string"==typeof e.kty}var le=async e=>{if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:t,keyUsages:r}=function(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 V('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 V('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 V('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break;default:throw new V('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}(e),n=[t,e.ext??!1,e.key_ops??r],s={...e};return delete s.alg,delete s.use,K.subtle.importKey("jwk",s,...n)};const fe=e=>N(e);let pe,ye;const me=e=>"KeyObject"===e?.[Symbol.toStringTag],Se=async(e,t,r,n,s=!1)=>{let i=e.get(t);if(i?.[n])return i[n];const o=await le({...r,alg:n});return s&&Object.freeze(t),i?i[n]=o:e.set(t,{[n]:o}),o};async function be(e,t){if(!ue(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 N(e.k);case"RSA":if("oth"in e&&void 0!==e.oth)throw new V('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return le({...e,alg:t});default:throw new V('Unsupported "kty" (Key Type) Parameter value')}}const Ee=e=>e?.[Symbol.toStringTag],ge=(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};function ve(e,t,r,n){t.startsWith("HS")||"dir"===t||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?((e,t,r,n)=>{if(!(t instanceof Uint8Array)){if(n&&we(t)){if(function(e){return we(e)&&"oct"===e.kty&&"string"==typeof e.k}(t)&&ge(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(!ae(t))throw new TypeError(oe(e,t,...ce,"Uint8Array",n?"JSON Web Key":null));if("secret"!==t.type)throw new TypeError(`${Ee(t)} instances for symmetric algorithms must be of type "secret"`)}})(t,r,n,e):((e,t,r,n)=>{if(n&&we(t))switch(r){case"sign":if(function(e){return"oct"!==e.kty&&"string"==typeof e.d}(t)&&ge(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(function(e){return"oct"!==e.kty&&void 0===e.d}(t)&&ge(e,t,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!ae(t))throw new TypeError(oe(e,t,...ce,n?"JSON Web Key":null));if("secret"===t.type)throw new TypeError(`${Ee(t)} instances for asymmetric algorithms must not be of type "secret"`);if("sign"===r&&"public"===t.type)throw new TypeError(`${Ee(t)} instances for asymmetric algorithm signing must be of type "private"`);if("decrypt"===r&&"public"===t.type)throw new TypeError(`${Ee(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&"verify"===r&&"private"===t.type)throw new TypeError(`${Ee(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&"encrypt"===r&&"private"===t.type)throw new TypeError(`${Ee(t)} instances for asymmetric algorithm encryption must be of type "public"`)})(t,r,n,e)}ve.bind(void 0,!1);const _e=ve.bind(void 0,!0);function ke(e,t,r,n,s){if(void 0!==s.crit&&void 0===n?.crit)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||void 0===n.crit)return new Set;if(!Array.isArray(n.crit)||0===n.crit.length||n.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 i;i=void 0!==r?new Map([...Object.entries(r),...t.entries()]):t;for(const t of n.crit){if(!i.has(t))throw new V(`Extension Header Parameter "${t}" is not recognized`);if(void 0===s[t])throw new e(`Extension Header Parameter "${t}" is missing`);if(i.get(t)&&void 0===n[t])throw new e(`Extension Header Parameter "${t}" MUST be integrity protected`)}return new Set(n.crit)}async function Ae(e){return(async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:U(e)};if(!$(e))throw new TypeError(ie(e,...ce,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");const{ext:t,key_ops:r,alg:n,use:s,...i}=await K.subtle.exportKey("jwk",e);return i})(e)}function Te(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 V(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}async function Pe(e,t,r){if("sign"===r&&(t=await((e,t)=>{if(me(e)){let r=e.export({format:"jwk"});return r.k?fe(r.k):(pe||(pe=new WeakMap),Se(pe,e,r,t))}return we(e)?e.k?N(e.k):(pe||(pe=new WeakMap),Se(pe,e,e,t,!0)):e})(t,e)),"verify"===r&&(t=await((e,t)=>{if(me(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?fe(r.k):(ye||(ye=new WeakMap),Se(ye,e,r,t))}return we(e)?e.k?N(e.k):(ye||(ye=new WeakMap),Se(ye,e,e,t,!0)):e})(t,e)),$(t))return function(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!re(e.algorithm,"HMAC"))throw te("HMAC");const r=parseInt(t.slice(2),10);if(ne(e.algorithm.hash)!==r)throw te(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!re(e.algorithm,"RSASSA-PKCS1-v1_5"))throw te("RSASSA-PKCS1-v1_5");const r=parseInt(t.slice(2),10);if(ne(e.algorithm.hash)!==r)throw te(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!re(e.algorithm,"RSA-PSS"))throw te("RSA-PSS");const r=parseInt(t.slice(2),10);if(ne(e.algorithm.hash)!==r)throw te(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":if("Ed25519"!==e.algorithm.name&&"Ed448"!==e.algorithm.name)throw te("Ed25519 or Ed448");break;case"Ed25519":if(!re(e.algorithm,"Ed25519"))throw te("Ed25519");break;case"ES256":case"ES384":case"ES512":{if(!re(e.algorithm,"ECDSA"))throw te("ECDSA");const r=function(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}(t);if(e.algorithm.namedCurve!==r)throw te(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}!function(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 e+=2===t.length?`one of ${t[0]} or ${t[1]}.`:`${t[0]}.`;throw new TypeError(e)}}(e,r)}(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(ie(t,...ce));return K.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(ie(t,...ce,"Uint8Array","JSON Web Key"))}async function Re(e,t,r){if(e instanceof Uint8Array&&(e=j.decode(e)),"string"!=typeof e)throw new q("Compact JWS must be a string or Uint8Array");const{0:n,1:s,2:i,length:o}=e.split(".");if(3!==o)throw new q("Invalid Compact JWS");const a=await async function(e,t,r){if(!ue(e))throw new q("Flattened JWS must be an object");if(void 0===e.protected&&void 0===e.header)throw new q('Flattened JWS must have either of the "protected" or "header" members');if(void 0!==e.protected&&"string"!=typeof e.protected)throw new q("JWS Protected Header incorrect type");if(void 0===e.payload)throw new q("JWS Payload missing");if("string"!=typeof e.signature)throw new q("JWS Signature missing or incorrect type");if(void 0!==e.header&&!ue(e.header))throw new q("JWS Unprotected Header incorrect type");let n={};if(e.protected)try{const t=N(e.protected);n=JSON.parse(j.decode(t))}catch{throw new q("JWS Protected Header is invalid")}if(!he(n,e.header))throw new q("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const s={...n,...e.header};let i=!0;if(ke(q,new Map([["b64",!0]]),r?.crit,n,s).has("b64")&&(i=n.b64,"boolean"!=typeof i))throw new q('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:o}=s;if("string"!=typeof o||!o)throw new q('JWS "alg" (Algorithm) Header Parameter missing or invalid');const a=r&&((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)})("algorithms",r.algorithms);if(a&&!a.has(o))throw new F('"alg" (Algorithm) Header Parameter value not allowed');if(i){if("string"!=typeof e.payload)throw new q("JWS Payload must be a string")}else if("string"!=typeof e.payload&&!(e.payload instanceof Uint8Array))throw new q("JWS Payload must be a string or an Uint8Array instance");let c=!1;"function"==typeof t?(t=await t(n,e),c=!0,_e(o,t,"verify"),we(t)&&(t=await be(t,o))):_e(o,t,"verify");const h=x(H.encode(e.protected??""),H.encode("."),"string"==typeof e.payload?H.encode(e.payload):e.payload);let u,d;try{u=N(e.signature)}catch{throw new q("Failed to base64url decode the signature")}if(!await(async(e,t,r,n)=>{const s=await Pe(e,t,"verify");de(e,s);const i=Te(e,s.algorithm);try{return await K.subtle.verify(i,s,r,n)}catch{return!1}})(o,t,u,h))throw new ee;if(i)try{d=N(e.payload)}catch{throw new q("Failed to base64url decode the payload")}else d="string"==typeof e.payload?H.encode(e.payload):e.payload;const w={payload:d};return void 0!==e.protected&&(w.protectedHeader=n),void 0!==e.header&&(w.unprotectedHeader=e.header),c?{...w,key:t}:w}({payload:s,protected:n,signature:i},t,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return"function"==typeof t?{...c,key:a.key}:c}var Ie=e=>Math.floor(e.getTime()/1e3);const De=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;var We=e=>{const t=De.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");const r=parseFloat(t[2]);let n;switch(t[3].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(60*r);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(3600*r);break;case"day":case"days":case"d":n=Math.round(86400*r);break;case"week":case"weeks":case"w":n=Math.round(604800*r);break;default:n=Math.round(31557600*r)}return"-"===t[1]||"ago"===t[4]?-n:n};const Ce=e=>e.toLowerCase().replace(/^application\//,"");var Je=(e,t,r={})=>{let n;try{n=JSON.parse(j.decode(t))}catch{}if(!ue(n))throw new G("JWT Claims Set must be a top-level JSON object");const{typ:s}=r;if(s&&("string"!=typeof e.typ||Ce(e.typ)!==Ce(s)))throw new M('unexpected "typ" JWT header value',n,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:h}=r,u=[...i];void 0!==h&&u.push("iat"),void 0!==c&&u.push("aud"),void 0!==a&&u.push("sub"),void 0!==o&&u.push("iss");for(const e of new Set(u.reverse()))if(!(e in n))throw new M(`missing required "${e}" claim`,n,e,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(n.iss))throw new M('unexpected "iss" claim value',n,"iss","check_failed");if(a&&n.sub!==a)throw new M('unexpected "sub" claim value',n,"sub","check_failed");if(c&&(w="string"==typeof c?[c]:c,!("string"==typeof(d=n.aud)?w.includes(d):Array.isArray(d)&&w.some(Set.prototype.has.bind(new Set(d))))))throw new M('unexpected "aud" claim value',n,"aud","check_failed");var d,w;let l;switch(typeof r.clockTolerance){case"string":l=We(r.clockTolerance);break;case"number":l=r.clockTolerance;break;case"undefined":l=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:f}=r,p=Ie(f||new Date);if((void 0!==n.iat||h)&&"number"!=typeof n.iat)throw new M('"iat" claim must be a number',n,"iat","invalid");if(void 0!==n.nbf){if("number"!=typeof n.nbf)throw new M('"nbf" claim must be a number',n,"nbf","invalid");if(n.nbf>p+l)throw new M('"nbf" claim timestamp check failed',n,"nbf","check_failed")}if(void 0!==n.exp){if("number"!=typeof n.exp)throw new M('"exp" claim must be a number',n,"exp","invalid");if(n.exp<=p-l)throw new B('"exp" claim timestamp check failed',n,"exp","check_failed")}if(h){const e=p-n.iat;if(e-l>("number"==typeof h?h:We(h)))throw new B('"iat" claim timestamp check failed (too far in the past)',n,"iat","check_failed");if(e<0-l)throw new M('"iat" claim timestamp check failed (it should be in the past)',n,"iat","check_failed")}return n};async function Oe(e,t,r){const n=await Re(e,t,r);if(n.protectedHeader.crit?.includes("b64")&&!1===n.protectedHeader.b64)throw new G("JWTs MUST NOT use unencoded payload");const s={payload:Je(n.protectedHeader,n.payload,r),protectedHeader:n.protectedHeader};return"function"==typeof t?{...s,key:n.key}:s}class Ke{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 q("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!he(this._protectedHeader,this._unprotectedHeader))throw new q("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const r={...this._protectedHeader,...this._unprotectedHeader};let n=!0;if(ke(q,new Map([["b64",!0]]),t?.crit,this._protectedHeader,r).has("b64")&&(n=this._protectedHeader.b64,"boolean"!=typeof n))throw new q('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:s}=r;if("string"!=typeof s||!s)throw new q('JWS "alg" (Algorithm) Header Parameter missing or invalid');_e(s,e,"sign");let i,o=this._payload;n&&(o=H.encode(U(o))),i=H.encode(this._protectedHeader?U(JSON.stringify(this._protectedHeader)):"");const a=x(i,H.encode("."),o),c=await(async(e,t,r)=>{const n=await Pe(e,t,"sign");de(e,n);const s=await K.subtle.sign(Te(e,n.algorithm),n,r);return new Uint8Array(s)})(s,e,a),h={signature:U(c),payload:""};return n&&(h.payload=j.decode(o)),this._unprotectedHeader&&(h.header=this._unprotectedHeader),this._protectedHeader&&(h.protected=j.decode(i)),h}}class $e{constructor(e){this._flattened=new Ke(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 He(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}class je{constructor(e={}){if(!ue(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 this._payload="number"==typeof e?{...this._payload,nbf:He("setNotBefore",e)}:e instanceof Date?{...this._payload,nbf:He("setNotBefore",Ie(e))}:{...this._payload,nbf:Ie(new Date)+We(e)},this}setExpirationTime(e){return this._payload="number"==typeof e?{...this._payload,exp:He("setExpirationTime",e)}:e instanceof Date?{...this._payload,exp:He("setExpirationTime",Ie(e))}:{...this._payload,exp:Ie(new Date)+We(e)},this}setIssuedAt(e){return this._payload=void 0===e?{...this._payload,iat:Ie(new Date)}:e instanceof Date?{...this._payload,iat:He("setIssuedAt",Ie(e))}:"string"==typeof e?{...this._payload,iat:He("setIssuedAt",Ie(new Date)+We(e))}:{...this._payload,iat:He("setIssuedAt",e)},this}}class xe extends je{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,t){const r=new $e(H.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 G("JWTs MUST NOT use unencoded payload");return r.sign(e,t)}}const Ue=(e,t)=>{if("string"!=typeof e||!e)throw new z(`${t} missing or invalid`)};async function Ne(e,t){if(!ue(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":Ue(e.crv,'"crv" (Curve) Parameter'),Ue(e.x,'"x" (X Coordinate) Parameter'),Ue(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":Ue(e.crv,'"crv" (Subtype of Key Pair) Parameter'),Ue(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":Ue(e.e,'"e" (Exponent) Parameter'),Ue(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":Ue(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new V('"kty" (Key Type) Parameter missing or unsupported')}const n=H.encode(JSON.stringify(r));return U(await(async(e,t)=>{const r=`SHA-${e.slice(-3)}`;return new Uint8Array(await K.subtle.digest(r,t))})(t,n))}function Le(e){return ue(e)}function Me(e){return"function"==typeof structuredClone?structuredClone(e):JSON.parse(JSON.stringify(e))}class Be{constructor(e){if(this._cached=new WeakMap,!function(e){return e&&"object"==typeof e&&Array.isArray(e.keys)&&e.keys.every(Le)}(e))throw new X("JSON Web Key Set malformed");this._jwks=Me(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...t?.header},s=function(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 V('Unsupported "alg" value for a JSON Web Key Set')}}(r),i=this._jwks.keys.filter((e=>{let t=s===e.kty;if(t&&"string"==typeof n&&(t=n===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:o,length:a}=i;if(0===a)throw new Y;if(1!==a){const e=new Z,{_cached:t}=this;throw e[Symbol.asyncIterator]=async function*(){for(const e of i)try{yield await Fe(t,e,r)}catch{}},e}return Fe(this._cached,o,r)}}async function Fe(e,t,r){const n=e.get(t)||e.set(t,{}).get(t);if(void 0===n[r]){const e=await be({...t,ext:!0},r);if(e instanceof Uint8Array||"public"!==e.type)throw new X("JSON Web Key Set members must be public keys");n[r]=e}return n[r]}function Ve(e){const t=new Be(e),r=async(e,r)=>t.getKey(e,r);return Object.defineProperties(r,{jwks:{value:()=>Me(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}let qe;"undefined"!=typeof navigator&&navigator.userAgent?.startsWith?.("Mozilla/5.0 ")||(qe="jose/v5.10.0");const Ge=Symbol();class ze{constructor(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");var r,n;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?.[Ge]&&(this._cache=t?.[Ge],r=t?.[Ge],n=this._cacheMaxAge,"object"==typeof r&&null!==r&&"uat"in r&&"number"==typeof r.uat&&!(Date.now()-r.uat>=n)&&"jwks"in r&&ue(r.jwks)&&Array.isArray(r.jwks.keys)&&Array.prototype.every.call(r.jwks.keys,ue)&&(this._jwksTimestamp=this._cache.uat,this._local=Ve(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 Y&&!1===this.coolingDown())return await this.reload(),this._local(e,t);throw r}}async reload(){this._pendingFetch&&("undefined"!=typeof WebSocketPair||"undefined"!=typeof navigator&&"Cloudflare-Workers"===navigator.userAgent||"undefined"!=typeof EdgeRuntime&&"vercel"===EdgeRuntime)&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);qe&&!e.has("User-Agent")&&(e.set("User-Agent",qe),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=(async(e,t,r)=>{let n,s,i=!1;"function"==typeof AbortController&&(n=new AbortController,s=setTimeout((()=>{i=!0,n.abort()}),t));const o=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch((e=>{if(i)throw new Q;throw e}));if(void 0!==s&&clearTimeout(s),200!==o.status)throw new L("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new L("Failed to parse the JSON Web Key Set HTTP response as JSON")}})(this._url,this._timeoutDuration,this._options).then((e=>{this._local=Ve(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 Xe(e,t){const r=new ze(e,t),n=async(e,t)=>r.getKey(e,t);return Object.defineProperties(n,{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}}),n}const Ye=N;function Ze(e){const t=e?.modulusLength??2048;if("number"!=typeof t||t<2048)throw new V("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return t}class Qe{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,n)=>{const s=this.db.transaction(this.storeName,"readwrite");s.oncomplete=()=>{r()},s.onerror=t=>{n(new Error(`Transaction error for setItem(${e},...): ${t.target.error}`))},s.onabort=t=>{n(new Error(`Transaction aborted for setItem(${e},...): ${t.target.error}`))},s.objectStore(this.storeName).put(t,e)}))}async getItem(e){return this.db||await this.init(),new Promise(((t,r)=>{const n=this.db.transaction(this.storeName,"readonly");n.onerror=t=>{r(new Error(`Transaction error for getItem(${e}): ${t.target.error}`))},n.onabort=t=>{r(new Error(`Transaction aborted for getItem(${e}): ${t.target.error}`))};const s=n.objectStore(this.storeName).get(e);s.onsuccess=()=>{t(s.result||null)}}))}async deleteItem(e){return this.db||await this.init(),new Promise(((t,r)=>{const n=this.db.transaction(this.storeName,"readwrite");n.oncomplete=()=>{t()},n.onerror=t=>{r(new Error(`Transaction error for deleteItem(${e}): ${t.target.error}`))},n.onabort=t=>{r(new Error(`Transaction aborted for deleteItem(${e}): ${t.target.error}`))},n.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)}}const et=async()=>{const e=window.crypto.randomUUID()+"-"+window.crypto.randomUUID(),t=new Uint8Array(await window.crypto.subtle.digest("SHA-256",(new TextEncoder).encode(e)));return{pkce_code_verifier:e,pkce_code_challenge:btoa(String.fromCharCode(...t)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}},tt=async()=>{const e=await(new Qe).init(),t=await e.getItem("client_id"),r=await e.getItem("token_endpoint"),n=await e.getItem("dpop_keypair"),s=await e.getItem("refresh_token");if(null===t||null===r||null===n||null===s)throw new Error("Could not refresh tokens: details missing from database.");const i=await rt(s,t,r,n).then((e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()})),o=i.access_token,a=await e.getItem("idp");if(null===a)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 h=Xe(new URL(c)),{payload:u}=await Oe(o,h,{issuer:a,audience:"solid"}),d=await Ne(await Ae(n.publicKey));if(u.cnf.jkt!=d)throw new Error("Access Token validation failed on `jkt`: jkt != DPoP thumbprint - "+u.cnf.jkt+" != "+d);if(u.client_id!=t)throw new Error("Access Token validation failed on `client_id`: JWT payload != client_id - "+u.client_id+" != "+t);return await e.setItem("refresh_token",i.refresh_token),e.close(),{...i,dpop_key_pair:n}},rt=async(e,t,r,n)=>{const s=await Ae(n.publicKey);s.alg="ES256";const i=await new xe({htu:r,htm:"POST"}).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:s}).sign(n.privateKey);return fetch(r,{method:"POST",headers:{dpop:i,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:t})})};class nt{sessionInformation;isActive_=!1;webId_=void 0;currentAth_=void 0;tokenRefreshTimeout;sessionDeactivateTimeout;onSessionExpirationWarning;constructor(e,t){this.sessionInformation={clientDetails:e},this.onSessionExpirationWarning=t?.onSessionExpirationWarning}async login(e,t){await(async(e,t,r)=>{const n=new URL(t),s=n.origin+n.pathname+n.search,i=new URL(e).origin,o=await fetch(`${i}/.well-known/openid-configuration`).then((e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()})),a=o.issuer,c=e=>e.endsWith("/")?e.slice(0,-1):e;if(c(e)!==c(a))throw new Error("RFC 9207 - iss != idp - "+a+" != "+e);sessionStorage.setItem("idp",a),sessionStorage.setItem("token_endpoint",o.token_endpoint),sessionStorage.setItem("jwks_uri",o.jwks_uri);let h=r?.client_id;if(!h){const e=o.registration_endpoint,t=await(async(e,t)=>{const r={...t,grant_types:["authorization_code","refresh_token"],id_token_signed_response_alg:"ES256",token_endpoint_auth_method:"none",application_type:"web",subject_type:"public"};return fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})})(e,r??{redirect_uris:[s]}).then((e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()}));h=t.client_id,sessionStorage.setItem("client_id",h)}const{pkce_code_verifier:u,pkce_code_challenge:d}=await et();sessionStorage.setItem("pkce_code_verifier",u);const w=window.crypto.randomUUID();sessionStorage.setItem("csrf_token",w);const l=o.authorization_endpoint+"?response_type=code"+`&redirect_uri=${encodeURIComponent(s)}&scope=openid offline_access webid`+`&client_id=${encodeURIComponent(h)}&code_challenge_method=S256`+`&code_challenge=${d}`+`&state=${w}&prompt=consent`;window.location.href=l})(e,t,this.sessionInformation.clientDetails)}async logout(){if(this.sessionDeactivateTimeout&&clearTimeout(this.sessionDeactivateTimeout),this.sessionDeactivateTimeout=void 0,this.tokenRefreshTimeout&&clearTimeout(this.tokenRefreshTimeout),this.tokenRefreshTimeout=void 0,this.sessionInformation.idpDetails=void 0,this.sessionInformation.tokenDetails=void 0,this.isActive_=!1,this.webId_=void 0,this.sessionInformation.clientDetails?.client_id)try{new URL(this.sessionInformation.clientDetails.client_id)}catch(e){this.sessionInformation.clientDetails.client_id=void 0}const e=await(new Qe).init();await e.clear(),e.close()}async handleRedirectFromLogin(){const e=await(async e=>{const t=new URL(window.location.href),r=t.searchParams.get("code");if(null===r)return{clientDetails:e};const n=sessionStorage.getItem("idp");if(null===n||t.searchParams.get("iss")!=n)throw new Error("RFC 9207 - iss != idp - "+t.searchParams.get("iss")+" != "+n);if(t.searchParams.get("state")!=sessionStorage.getItem("csrf_token"))throw new Error("RFC 6749 - state != csrf_token - "+t.searchParams.get("state")+" != "+sessionStorage.getItem("csrf_token"));t.searchParams.delete("iss"),t.searchParams.delete("state"),t.searchParams.delete("code"),window.history.pushState({},document.title,t.toString());const s=sessionStorage.getItem("pkce_code_verifier");if(null===s)throw new Error("Access Token Request preparation - Could not find in sessionStorage: pkce_code_verifier");const i=e?.client_id||sessionStorage.getItem("client_id");if(!i)throw new Error("Access Token Request preparation - Could not find in sessionStorage: client_id (dynamic registration)");const o=sessionStorage.getItem("token_endpoint");if(null===o)throw new Error("Access Token Request preparation - Could not find in sessionStorage: token_endpoint");const a=await async function(e,t){return async function(e,t){let r,n;switch(e){case"PS256":case"PS384":case"PS512":r={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ze(t)},n=["sign","verify"];break;case"RS256":case"RS384":case"RS512":r={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ze(t)},n=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":r={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ze(t)},n=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":r={name:"ECDSA",namedCurve:"P-256"},n=["sign","verify"];break;case"ES384":r={name:"ECDSA",namedCurve:"P-384"},n=["sign","verify"];break;case"ES512":r={name:"ECDSA",namedCurve:"P-521"},n=["sign","verify"];break;case"Ed25519":r={name:"Ed25519"},n=["sign","verify"];break;case"EdDSA":{n=["sign","verify"];const e="Ed25519";switch(e){case"Ed25519":case"Ed448":r={name:e};break;default:throw new V("Invalid or unsupported crv option provided")}break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{n=["deriveKey","deriveBits"];const e="P-256";switch(e){case"P-256":case"P-384":case"P-521":r={name:"ECDH",namedCurve:e};break;case"X25519":case"X448":r={name:e};break;default:throw new V("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new V('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return K.subtle.generateKey(r,!1,n)}(e,t)}("ES256"),c=await(async(e,t,r,n,s,i)=>{const o=await Ae(i.publicKey);o.alg="ES256";const a=await new xe({htu:s,htm:"POST"}).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:o}).sign(i.privateKey);return fetch(s,{method:"POST",headers:{dpop:a,"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:r,client_id:n})})})(r,s,t.toString(),i,o,a).then((e=>{if(!e.ok)throw new Error(`HTTP error! Status: ${e.status}`);return e.json()})),h=c.access_token,u=sessionStorage.getItem("jwks_uri");if(null===u)throw new Error("Access Token validation preparation - Could not find in sessionStorage: jwks_uri");const d=Xe(new URL(u)),{payload:w}=await Oe(h,d,{issuer:n,audience:"solid"}),l=await Ne(await Ae(a.publicKey));if(w.cnf.jkt!=l)throw new Error("Access Token validation failed on `jkt`: jkt != DPoP thumbprint - "+w.cnf.jkt+" != "+l);if(w.client_id!=i)throw new Error("Access Token validation failed on `client_id`: JWT payload != client_id - "+w.client_id+" != "+i);const f={...c,dpop_key_pair:a},p={idp:n,jwks_uri:u,token_endpoint:o};e||(e={redirect_uris:[window.location.href]}),e.client_id=i;const y=await(new Qe).init();return await Promise.all([y.setItem("idp",n),y.setItem("jwks_uri",u),y.setItem("token_endpoint",o),y.setItem("client_id",i),y.setItem("dpop_keypair",a),y.setItem("refresh_token",c.refresh_token)]),y.close(),sessionStorage.removeItem("csrf_token"),sessionStorage.removeItem("pkce_code_verifier"),sessionStorage.removeItem("idp"),sessionStorage.removeItem("jwks_uri"),sessionStorage.removeItem("token_endpoint"),sessionStorage.removeItem("client_id"),{clientDetails:e,idpDetails:p,tokenDetails:f}})(this.sessionInformation.clientDetails);e.tokenDetails&&(this.sessionInformation=e,await this.setSessionDetails())}async restore(){await tt().then((e=>(this.sessionInformation.tokenDetails=e,this.setSessionDetails()))).catch((()=>{}))}async createSignedDPoPToken(e){if(!this.sessionInformation.tokenDetails||!this.currentAth_)throw new Error("Session not established.");e.ath=this.currentAth_;const t=await Ae(this.sessionInformation.tokenDetails.dpop_key_pair.publicKey);return new xe(e).setIssuedAt().setJti(window.crypto.randomUUID()).setProtectedHeader({alg:"ES256",typ:"dpop+jwt",jwk:t}).sign(this.sessionInformation.tokenDetails.dpop_key_pair.privateKey)}async authFetch(e,t,r){let n,s,i;if(e instanceof Request?(n=new URL(e.url),s=t?.method||e?.method||"GET",i=new Headers(e.headers)):(t=t||{},n=new URL(e.toString()),s=t.method||"GET",i=t.headers?new Headers(t.headers):new Headers),this.sessionInformation.tokenDetails){r=r??{htu:`${n.origin}${n.pathname}`,htm:s.toUpperCase()};const e=await this.createSignedDPoPToken(r);i.set("dpop",e),i.set("authorization",`DPoP ${this.sessionInformation.tokenDetails.access_token}`)}return e instanceof Request?fetch(new Request(e,{...t,headers:i})):fetch(n,{...t,headers:i})}get isActive(){return this.isActive_}get webId(){return this.webId_}async setSessionDetails(){this.sessionInformation.tokenDetails?.access_token||this.logout(),this.currentAth_=await this.computeAth(this.sessionInformation.tokenDetails.access_token),this.webId_=function(e){if("string"!=typeof e)throw new G("JWTs must use Compact JWS serialization, JWT must be a string");const{1:t,length:r}=e.split(".");if(5===r)throw new G("Only JWTs using Compact JWS serialization can be decoded");if(3!==r)throw new G("Invalid JWT");if(!t)throw new G("JWTs must contain a payload");let n,s;try{n=Ye(t)}catch{throw new G("Failed to base64url decode the payload")}try{s=JSON.parse(j.decode(n))}catch{throw new G("Failed to parse the decoded payload as JSON")}if(!ue(s))throw new G("Invalid JWT Claims Set");return s}(this.sessionInformation.tokenDetails.access_token).webid,this.isActive_=void 0!==this.webId,this.setSessionDeactivateTimeout(),this.setTokenRefreshTimeout()}setSessionDeactivateTimeout(){const e=1e3*(this.sessionInformation.tokenDetails.expires_in-5);this.sessionDeactivateTimeout&&clearTimeout(this.sessionDeactivateTimeout),this.sessionDeactivateTimeout=setTimeout((()=>this.logout()),e)}setTokenRefreshTimeout(){const e=1e3*(this.sessionInformation.tokenDetails.expires_in-95);this.tokenRefreshTimeout&&clearTimeout(this.tokenRefreshTimeout),this.tokenRefreshTimeout=setTimeout((async()=>{const e=await tt().catch((()=>{this.onSessionExpirationWarning&&this.onSessionExpirationWarning()}));e&&(this.sessionInformation.tokenDetails=e,this.setSessionDetails())}),e)}async computeAth(e){const t=(new TextEncoder).encode(e),r=await crypto.subtle.digest("SHA-256",t),n=Array.from(new Uint8Array(r));return btoa(String.fromCharCode(...n)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}}class st{get authenticatedFetch(){return this._authenticatedFetch}constructor(){this.onSessionRestoreCallback=()=>{},this.sessionInfo$=new h.BehaviorSubject({isLoggedIn:!1,webId:void 0}),this.session=new nt,this._authenticatedFetch=this.session.authFetch.bind(this.session)}async handleIncomingRedirect(e=!1){await this.session.handleRedirectFromLogin(),e&&(await this.session.restore(),this.session.isActive&&this.onSessionRestoreCallback(window.location.href)),this.sessionInfo$.next({isLoggedIn:this.session.isActive,webId:this.session.webId})}async login(e){return this.session.login(e,window.location.href)}async logout(){await this.session.logout(),this.sessionInfo$.next({isLoggedIn:!1,webId:void 0})}observeSession(){return this.sessionInfo$}onSessionRestore(e){this.onSessionRestoreCallback=e}}const it=e(class extends t{constructor(e){super(),!1!==e&&this.__registerHost(),this.__attachShadow(),this.sessionRestoredEmitter=r(this,"pod-os:session-restored",7),this.podOsLoadedEmitter=r(this,"pod-os:loaded",7),this.restorePreviousSession=!1,this.disconnected$=new h.Subject,this.loading=!0}async componentWillLoad(){const e=new st;this.unsubscribeSettings=o.on("set",(()=>{this.os=O(e,o.state)})),this.os=O(e,o.state),e.onSessionRestore((e=>{this.sessionRestoredEmitter.emit({url:e})}));try{await e.handleIncomingRedirect(this.restorePreviousSession)}catch(e){console.error(e)}this.os.observeSession().pipe(h.takeUntil(this.disconnected$)).subscribe((async e=>{if(i.state.webId=e.webId,e.isLoggedIn){const t=await this.os.fetchProfile(e.webId);i.state.profile=t}i.state.isLoggedIn=e.isLoggedIn,this.loading=!1})),this.podOsLoadedEmitter.emit({os:this.os,authenticatedFetch:e.authenticatedFetch})}disconnectedCallback(){this.unsubscribeSettings(),this.disconnected$.next(),this.disconnected$.complete()}async initializeOs(e){e.stopPropagation(),e.detail(this.os)}async loadModule(e){e.stopPropagation();const t=await this.os.loadModule(e.detail.module);e.detail.receiver(t)}render(){return this.loading?n("sl-progress-bar",{indeterminate:!0}):n("slot",null)}},[257,"pos-app",{restorePreviousSession:[4,"restore-previous-session"],os:[32],unsubscribeSettings:[32],loading:[32]},[[0,"pod-os:init","initializeOs"],[0,"pod-os:module","loadModule"]]]);function ot(){"undefined"!=typeof customElements&&["pos-app"].forEach((e=>{"pos-app"===e&&(customElements.get(s(e))||customElements.define(s(e),it))}))}export{it as P,ot as d}
@@ -1 +1 @@
1
- import{proxyCustomElement as e,HTMLElement as t,transformTag as s}from"@stencil/core/internal/client";const n=e(class extends t{constructor(e){super(),!1!==e&&this.__registerHost(),this.error=null}componentWillLoad(){null==this.host.querySelector("template")&&(this.error="No template element found")}render(){return this.error?this.error:null}get host(){return this}},[0,"pos-case",{ifTypeof:[1,"if-typeof"],not:[4],else:[4],error:[32]}]),o=n,l=function(){"undefined"!=typeof customElements&&["pos-case"].forEach((e=>{"pos-case"===e&&(customElements.get(s(e))||customElements.define(s(e),n))}))};export{o as PosCase,l as defineCustomElement}
1
+ import{proxyCustomElement as e,HTMLElement as t,transformTag as s}from"@stencil/core/internal/client";const o=e(class extends t{constructor(e){super(),!1!==e&&this.__registerHost(),this.error=null}componentWillLoad(){null==this.host.querySelector("template")&&(this.error="No template element found")}render(){return this.error?this.error:null}get host(){return this}},[0,"pos-case",{ifTypeof:[1,"if-typeof"],ifProperty:[1,"if-property"],ifRev:[1,"if-rev"],not:[4],else:[4],error:[32]}]),n=o,r=function(){"undefined"!=typeof customElements&&["pos-case"].forEach((e=>{"pos-case"===e&&(customElements.get(s(e))||customElements.define(s(e),o))}))};export{n as PosCase,r as defineCustomElement}
@@ -1 +1 @@
1
- import{proxyCustomElement as e,HTMLElement as t,createEvent as s,h as o,Host as n,transformTag as i}from"@stencil/core/internal/client";import{L as r}from"./index2.js";import{s as a}from"./ResourceAware.js";import{c}from"./index3.js";import{d as l}from"./pos-container-item2.js";import{d as m}from"./pos-container-toolbar2.js";import{d as p}from"./pos-create-new-container-item2.js";import{d as h}from"./pos-resource2.js";const u=e(class extends t{constructor(e){super(),!1!==e&&this.__registerHost(),this.__attachShadow(),this.subscribeResource=s(this,"pod-os:resource",7),this.contents=[],this.loading=!0,this.createNewItem=null,this.disconnected$=new c.Subject,this.receiveResource=e=>{this.container=e.assume(r),this.loading=!1,this.container.observeContains().pipe(c.takeUntil(this.disconnected$)).subscribe((e=>this.contents=e.sort(((e,t)=>e.name.localeCompare(t.name)))))}}onCreateNewFile(){this.createNewItem="file"}onCreateNewFolder(){this.createNewItem="folder"}componentWillLoad(){a(this)}handleKeyDown(e){"Escape"===e.key&&(this.createNewItem=null)}render(){if(this.loading)return null;const e=this.contents.map((e=>o("li",{key:e.uri},o("pos-resource",{lazy:!0,uri:e.uri},o("pos-container-item",null,e.name)))));return null!==this.createNewItem&&e.unshift(o("li",{key:"new-item"},o("pos-create-new-container-item",{type:this.createNewItem,container:this.container}))),o(n,null,o("pos-container-toolbar",{"onPod-os:create-new-file":()=>this.onCreateNewFile(),"onPod-os:create-new-folder":()=>this.onCreateNewFolder()}),e.length>0?o("ul",{"aria-label":"Container contents"},e):o("p",null,"The container is empty"))}disconnectedCallback(){this.disconnected$.next(),this.disconnected$.unsubscribe()}static get style(){return"ul{list-style:none;padding:0;margin:0}li{padding:0;margin:0}"}},[1,"pos-container-contents",{container:[32],contents:[32],loading:[32],createNewItem:[32]},[[0,"keydown","handleKeyDown"]]]);function d(){"undefined"!=typeof customElements&&["pos-container-contents","pos-container-item","pos-container-toolbar","pos-create-new-container-item","pos-resource"].forEach((e=>{switch(e){case"pos-container-contents":customElements.get(i(e))||customElements.define(i(e),u);break;case"pos-container-item":customElements.get(i(e))||l();break;case"pos-container-toolbar":customElements.get(i(e))||m();break;case"pos-create-new-container-item":customElements.get(i(e))||p();break;case"pos-resource":customElements.get(i(e))||h()}}))}export{u as P,d}
1
+ import{proxyCustomElement as e,HTMLElement as t,createEvent as s,h as o,Host as n,transformTag as i}from"@stencil/core/internal/client";import{L as r}from"./index2.js";import{s as a}from"./ResourceAware.js";import{c}from"./index3.js";import{d as l}from"./pos-container-item2.js";import{d as m}from"./pos-container-toolbar2.js";import{d as p}from"./pos-create-new-container-item2.js";import{d as h}from"./pos-resource2.js";const u=e(class extends t{constructor(e){super(),!1!==e&&this.__registerHost(),this.__attachShadow(),this.subscribeResource=s(this,"pod-os:resource",7),this.contents=[],this.loading=!0,this.createNewItem=null,this.disconnected$=new c.Subject,this.receiveResource=e=>{this.container=e.assume(r),this.loading=!1,this.container.observeContains().pipe(c.takeUntil(this.disconnected$)).subscribe((e=>this.contents=e.toSorted(((e,t)=>e.name.localeCompare(t.name)))))}}onCreateNewFile(){this.createNewItem="file"}onCreateNewFolder(){this.createNewItem="folder"}componentWillLoad(){a(this)}handleKeyDown(e){"Escape"===e.key&&(this.createNewItem=null)}render(){if(this.loading)return null;const e=this.contents.map((e=>o("li",{key:e.uri},o("pos-resource",{lazy:!0,uri:e.uri},o("pos-container-item",null,e.name)))));return null!==this.createNewItem&&e.unshift(o("li",{key:"new-item"},o("pos-create-new-container-item",{type:this.createNewItem,container:this.container}))),o(n,null,o("pos-container-toolbar",{"onPod-os:create-new-file":()=>this.onCreateNewFile(),"onPod-os:create-new-folder":()=>this.onCreateNewFolder()}),e.length>0?o("ul",{"aria-label":"Container contents"},e):o("p",null,"The container is empty"))}disconnectedCallback(){this.disconnected$.next(),this.disconnected$.complete()}static get style(){return"ul{list-style:none;padding:0;margin:0}li{padding:0;margin:0}"}},[1,"pos-container-contents",{container:[32],contents:[32],loading:[32],createNewItem:[32]},[[0,"keydown","handleKeyDown"]]]);function d(){"undefined"!=typeof customElements&&["pos-container-contents","pos-container-item","pos-container-toolbar","pos-create-new-container-item","pos-resource"].forEach((e=>{switch(e){case"pos-container-contents":customElements.get(i(e))||customElements.define(i(e),u);break;case"pos-container-item":customElements.get(i(e))||l();break;case"pos-container-toolbar":customElements.get(i(e))||m();break;case"pos-create-new-container-item":customElements.get(i(e))||p();break;case"pos-resource":customElements.get(i(e))||h()}}))}export{u as P,d}
@@ -1 +1 @@
1
- import{proxyCustomElement as s,HTMLElement as t,createEvent as e,h as i,transformTag as o}from"@stencil/core/internal/client";import{s as r}from"./ResourceAware.js";import{s as h}from"./PodOsAware.js";import{c as n}from"./index3.js";import{d as c}from"./pos-resource2.js";const l=s(class extends t{constructor(s){super(),!1!==s&&this.__registerHost(),this.subscribeResource=e(this,"pod-os:resource",7),this.subscribePodOs=e(this,"pod-os:init",7),this.fetch=!1,this.error=null,this.items=[],this.disconnected$=new n.Subject,this.receiveResource=s=>{this.items=[],this.rel&&(this.items=s.relations(this.rel).flatMap((s=>s.uris)))},this.receivePodOs=async s=>{s.store.observeFindMembers(this.ifTypeof).pipe(n.takeUntil(this.disconnected$)).subscribe((s=>this.items=s))}}componentWillLoad(){this.rel&&r(this),this.ifTypeof&&h(this);const s=this.host.querySelector("template");null==s?this.error="No template element found":this.templateString=s.innerHTML}render(){if(this.error)return this.error;const s=this.items.map((s=>i("pos-resource",{uri:s,lazy:!this.fetch,innerHTML:this.templateString,about:s})));return this.items.length>0?s:null}disconnectedCallback(){this.disconnected$.next(),this.disconnected$.unsubscribe()}get host(){return this}},[0,"pos-list",{rel:[1],ifTypeof:[1,"if-typeof"],fetch:[4],error:[32],os:[32],resource:[32],items:[32],templateString:[32]}]),m=l,u=function(){"undefined"!=typeof customElements&&["pos-list","pos-resource"].forEach((s=>{switch(s){case"pos-list":customElements.get(o(s))||customElements.define(o(s),l);break;case"pos-resource":customElements.get(o(s))||c()}}))};export{m as PosList,u as defineCustomElement}
1
+ import{proxyCustomElement as s,HTMLElement as t,createEvent as e,h as i,transformTag as o}from"@stencil/core/internal/client";import{s as r}from"./ResourceAware.js";import{s as h}from"./PodOsAware.js";import{c as n}from"./index3.js";import{d as c}from"./pos-resource2.js";const l=s(class extends t{constructor(s){super(),!1!==s&&this.__registerHost(),this.subscribeResource=e(this,"pod-os:resource",7),this.subscribePodOs=e(this,"pod-os:init",7),this.fetch=!1,this.error=null,this.items=[],this.disconnected$=new n.Subject,this.receiveResource=s=>{this.items=[],this.rel&&(this.items=s.relations(this.rel).flatMap((s=>s.uris)))},this.receivePodOs=async s=>{s.store.observeFindMembers(this.ifTypeof).pipe(n.takeUntil(this.disconnected$)).subscribe((s=>this.items=s))}}componentWillLoad(){this.rel&&r(this),this.ifTypeof&&h(this);const s=this.host.querySelector("template");null==s?this.error="No template element found":this.templateString=s.innerHTML}render(){if(this.error)return this.error;const s=this.items.map((s=>i("pos-resource",{uri:s,lazy:!this.fetch,innerHTML:this.templateString,about:s})));return this.items.length>0?s:null}disconnectedCallback(){this.disconnected$.next(),this.disconnected$.complete()}get host(){return this}},[0,"pos-list",{rel:[1],ifTypeof:[1,"if-typeof"],fetch:[4],error:[32],os:[32],resource:[32],items:[32],templateString:[32]}]),m=l,u=function(){"undefined"!=typeof customElements&&["pos-list","pos-resource"].forEach((s=>{switch(s){case"pos-list":customElements.get(o(s))||customElements.define(o(s),l);break;case"pos-resource":customElements.get(o(s))||c()}}))};export{m as PosList,u as defineCustomElement}